ffmpeg_demux.c 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898
  1. /*
  2. * This file is part of FFmpeg.
  3. *
  4. * FFmpeg is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * FFmpeg is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with FFmpeg; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include <float.h>
  19. #include <stdint.h>
  20. #include "ffmpeg.h"
  21. #include "ffmpeg_sched.h"
  22. #include "ffmpeg_utils.h"
  23. #include "libavutil/avassert.h"
  24. #include "libavutil/avstring.h"
  25. #include "libavutil/display.h"
  26. #include "libavutil/error.h"
  27. #include "libavutil/intreadwrite.h"
  28. #include "libavutil/mem.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/parseutils.h"
  31. #include "libavutil/pixdesc.h"
  32. #include "libavutil/time.h"
  33. #include "libavutil/timestamp.h"
  34. #include "libavcodec/bsf.h"
  35. #include "libavcodec/packet.h"
  36. #include "libavformat/avformat.h"
  37. typedef struct DemuxStream {
  38. InputStream ist;
  39. // name used for logging
  40. char log_name[32];
  41. int sch_idx_stream;
  42. int sch_idx_dec;
  43. double ts_scale;
  44. /* non zero if the packets must be decoded in 'raw_fifo', see DECODING_FOR_* */
  45. int decoding_needed;
  46. #define DECODING_FOR_OST 1
  47. #define DECODING_FOR_FILTER 2
  48. /* true if stream data should be discarded */
  49. int discard;
  50. // scheduler returned EOF for this stream
  51. int finished;
  52. int streamcopy_needed;
  53. int have_sub2video;
  54. int reinit_filters;
  55. int autorotate;
  56. int apply_cropping;
  57. int wrap_correction_done;
  58. int saw_first_ts;
  59. ///< dts of the first packet read for this stream (in AV_TIME_BASE units)
  60. int64_t first_dts;
  61. /* predicted dts of the next packet read for this stream or (when there are
  62. * several frames in a packet) of the next frame in current packet (in AV_TIME_BASE units) */
  63. int64_t next_dts;
  64. ///< dts of the last packet read for this stream (in AV_TIME_BASE units)
  65. int64_t dts;
  66. const AVCodecDescriptor *codec_desc;
  67. AVDictionary *decoder_opts;
  68. DecoderOpts dec_opts;
  69. char dec_name[16];
  70. // decoded media properties, as estimated by opening the decoder
  71. AVFrame *decoded_params;
  72. AVBSFContext *bsf;
  73. /* number of packets successfully read for this stream */
  74. uint64_t nb_packets;
  75. // combined size of all the packets read
  76. uint64_t data_size;
  77. } DemuxStream;
  78. typedef struct Demuxer {
  79. InputFile f;
  80. // name used for logging
  81. char log_name[32];
  82. int64_t wallclock_start;
  83. /**
  84. * Extra timestamp offset added by discontinuity handling.
  85. */
  86. int64_t ts_offset_discont;
  87. int64_t last_ts;
  88. int64_t recording_time;
  89. int accurate_seek;
  90. /* number of times input stream should be looped */
  91. int loop;
  92. int have_audio_dec;
  93. /* duration of the looped segment of the input file */
  94. Timestamp duration;
  95. /* pts with the smallest/largest values ever seen */
  96. Timestamp min_pts;
  97. Timestamp max_pts;
  98. /* number of streams that the user was warned of */
  99. int nb_streams_warn;
  100. float readrate;
  101. double readrate_initial_burst;
  102. Scheduler *sch;
  103. AVPacket *pkt_heartbeat;
  104. int read_started;
  105. int nb_streams_used;
  106. int nb_streams_finished;
  107. } Demuxer;
  108. typedef struct DemuxThreadContext {
  109. // packet used for reading from the demuxer
  110. AVPacket *pkt_demux;
  111. // packet for reading from BSFs
  112. AVPacket *pkt_bsf;
  113. } DemuxThreadContext;
  114. static DemuxStream *ds_from_ist(InputStream *ist)
  115. {
  116. return (DemuxStream*)ist;
  117. }
  118. static Demuxer *demuxer_from_ifile(InputFile *f)
  119. {
  120. return (Demuxer*)f;
  121. }
  122. InputStream *ist_find_unused(enum AVMediaType type)
  123. {
  124. for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
  125. DemuxStream *ds = ds_from_ist(ist);
  126. if (ist->par->codec_type == type && ds->discard &&
  127. ist->user_set_discard != AVDISCARD_ALL)
  128. return ist;
  129. }
  130. return NULL;
  131. }
  132. static void report_new_stream(Demuxer *d, const AVPacket *pkt)
  133. {
  134. const AVStream *st = d->f.ctx->streams[pkt->stream_index];
  135. if (pkt->stream_index < d->nb_streams_warn)
  136. return;
  137. av_log(d, AV_LOG_WARNING,
  138. "New %s stream with index %d at pos:%"PRId64" and DTS:%ss\n",
  139. av_get_media_type_string(st->codecpar->codec_type),
  140. pkt->stream_index, pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  141. d->nb_streams_warn = pkt->stream_index + 1;
  142. }
  143. static int seek_to_start(Demuxer *d, Timestamp end_pts)
  144. {
  145. InputFile *ifile = &d->f;
  146. AVFormatContext *is = ifile->ctx;
  147. int ret;
  148. ret = avformat_seek_file(is, -1, INT64_MIN, is->start_time, is->start_time, 0);
  149. if (ret < 0)
  150. return ret;
  151. if (end_pts.ts != AV_NOPTS_VALUE &&
  152. (d->max_pts.ts == AV_NOPTS_VALUE ||
  153. av_compare_ts(d->max_pts.ts, d->max_pts.tb, end_pts.ts, end_pts.tb) < 0))
  154. d->max_pts = end_pts;
  155. if (d->max_pts.ts != AV_NOPTS_VALUE) {
  156. int64_t min_pts = d->min_pts.ts == AV_NOPTS_VALUE ? 0 : d->min_pts.ts;
  157. d->duration.ts = d->max_pts.ts - av_rescale_q(min_pts, d->min_pts.tb, d->max_pts.tb);
  158. }
  159. d->duration.tb = d->max_pts.tb;
  160. if (d->loop > 0)
  161. d->loop--;
  162. return ret;
  163. }
  164. static void ts_discontinuity_detect(Demuxer *d, InputStream *ist,
  165. AVPacket *pkt)
  166. {
  167. InputFile *ifile = &d->f;
  168. DemuxStream *ds = ds_from_ist(ist);
  169. const int fmt_is_discont = ifile->ctx->iformat->flags & AVFMT_TS_DISCONT;
  170. int disable_discontinuity_correction = copy_ts;
  171. int64_t pkt_dts = av_rescale_q_rnd(pkt->dts, pkt->time_base, AV_TIME_BASE_Q,
  172. AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
  173. if (copy_ts && ds->next_dts != AV_NOPTS_VALUE &&
  174. fmt_is_discont && ist->st->pts_wrap_bits < 60) {
  175. int64_t wrap_dts = av_rescale_q_rnd(pkt->dts + (1LL<<ist->st->pts_wrap_bits),
  176. pkt->time_base, AV_TIME_BASE_Q,
  177. AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
  178. if (FFABS(wrap_dts - ds->next_dts) < FFABS(pkt_dts - ds->next_dts)/10)
  179. disable_discontinuity_correction = 0;
  180. }
  181. if (ds->next_dts != AV_NOPTS_VALUE && !disable_discontinuity_correction) {
  182. int64_t delta = pkt_dts - ds->next_dts;
  183. if (fmt_is_discont) {
  184. if (FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE ||
  185. pkt_dts + AV_TIME_BASE/10 < ds->dts) {
  186. d->ts_offset_discont -= delta;
  187. av_log(ist, AV_LOG_WARNING,
  188. "timestamp discontinuity "
  189. "(stream id=%d): %"PRId64", new offset= %"PRId64"\n",
  190. ist->st->id, delta, d->ts_offset_discont);
  191. pkt->dts -= av_rescale_q(delta, AV_TIME_BASE_Q, pkt->time_base);
  192. if (pkt->pts != AV_NOPTS_VALUE)
  193. pkt->pts -= av_rescale_q(delta, AV_TIME_BASE_Q, pkt->time_base);
  194. }
  195. } else {
  196. if (FFABS(delta) > 1LL * dts_error_threshold * AV_TIME_BASE) {
  197. av_log(ist, AV_LOG_WARNING,
  198. "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n",
  199. pkt->dts, ds->next_dts, pkt->stream_index);
  200. pkt->dts = AV_NOPTS_VALUE;
  201. }
  202. if (pkt->pts != AV_NOPTS_VALUE){
  203. int64_t pkt_pts = av_rescale_q(pkt->pts, pkt->time_base, AV_TIME_BASE_Q);
  204. delta = pkt_pts - ds->next_dts;
  205. if (FFABS(delta) > 1LL * dts_error_threshold * AV_TIME_BASE) {
  206. av_log(ist, AV_LOG_WARNING,
  207. "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n",
  208. pkt->pts, ds->next_dts, pkt->stream_index);
  209. pkt->pts = AV_NOPTS_VALUE;
  210. }
  211. }
  212. }
  213. } else if (ds->next_dts == AV_NOPTS_VALUE && !copy_ts &&
  214. fmt_is_discont && d->last_ts != AV_NOPTS_VALUE) {
  215. int64_t delta = pkt_dts - d->last_ts;
  216. if (FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE) {
  217. d->ts_offset_discont -= delta;
  218. av_log(ist, AV_LOG_DEBUG,
  219. "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  220. delta, d->ts_offset_discont);
  221. pkt->dts -= av_rescale_q(delta, AV_TIME_BASE_Q, pkt->time_base);
  222. if (pkt->pts != AV_NOPTS_VALUE)
  223. pkt->pts -= av_rescale_q(delta, AV_TIME_BASE_Q, pkt->time_base);
  224. }
  225. }
  226. d->last_ts = av_rescale_q(pkt->dts, pkt->time_base, AV_TIME_BASE_Q);
  227. }
  228. static void ts_discontinuity_process(Demuxer *d, InputStream *ist,
  229. AVPacket *pkt)
  230. {
  231. int64_t offset = av_rescale_q(d->ts_offset_discont, AV_TIME_BASE_Q,
  232. pkt->time_base);
  233. // apply previously-detected timestamp-discontinuity offset
  234. // (to all streams, not just audio/video)
  235. if (pkt->dts != AV_NOPTS_VALUE)
  236. pkt->dts += offset;
  237. if (pkt->pts != AV_NOPTS_VALUE)
  238. pkt->pts += offset;
  239. // detect timestamp discontinuities for audio/video
  240. if ((ist->par->codec_type == AVMEDIA_TYPE_VIDEO ||
  241. ist->par->codec_type == AVMEDIA_TYPE_AUDIO) &&
  242. pkt->dts != AV_NOPTS_VALUE)
  243. ts_discontinuity_detect(d, ist, pkt);
  244. }
  245. static int ist_dts_update(DemuxStream *ds, AVPacket *pkt, FrameData *fd)
  246. {
  247. InputStream *ist = &ds->ist;
  248. const AVCodecParameters *par = ist->par;
  249. if (!ds->saw_first_ts) {
  250. ds->first_dts =
  251. ds->dts = ist->st->avg_frame_rate.num ? - ist->par->video_delay * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
  252. if (pkt->pts != AV_NOPTS_VALUE) {
  253. ds->first_dts =
  254. ds->dts += av_rescale_q(pkt->pts, pkt->time_base, AV_TIME_BASE_Q);
  255. }
  256. ds->saw_first_ts = 1;
  257. }
  258. if (ds->next_dts == AV_NOPTS_VALUE)
  259. ds->next_dts = ds->dts;
  260. if (pkt->dts != AV_NOPTS_VALUE)
  261. ds->next_dts = ds->dts = av_rescale_q(pkt->dts, pkt->time_base, AV_TIME_BASE_Q);
  262. ds->dts = ds->next_dts;
  263. switch (par->codec_type) {
  264. case AVMEDIA_TYPE_AUDIO:
  265. av_assert1(pkt->duration >= 0);
  266. if (par->sample_rate) {
  267. ds->next_dts += ((int64_t)AV_TIME_BASE * par->frame_size) /
  268. par->sample_rate;
  269. } else {
  270. ds->next_dts += av_rescale_q(pkt->duration, pkt->time_base, AV_TIME_BASE_Q);
  271. }
  272. break;
  273. case AVMEDIA_TYPE_VIDEO:
  274. if (ist->framerate.num) {
  275. // TODO: Remove work-around for c99-to-c89 issue 7
  276. AVRational time_base_q = AV_TIME_BASE_Q;
  277. int64_t next_dts = av_rescale_q(ds->next_dts, time_base_q, av_inv_q(ist->framerate));
  278. ds->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
  279. } else if (pkt->duration) {
  280. ds->next_dts += av_rescale_q(pkt->duration, pkt->time_base, AV_TIME_BASE_Q);
  281. } else if (ist->par->framerate.num != 0) {
  282. AVRational field_rate = av_mul_q(ist->par->framerate,
  283. (AVRational){ 2, 1 });
  284. int fields = 2;
  285. if (ds->codec_desc &&
  286. (ds->codec_desc->props & AV_CODEC_PROP_FIELDS) &&
  287. av_stream_get_parser(ist->st))
  288. fields = 1 + av_stream_get_parser(ist->st)->repeat_pict;
  289. ds->next_dts += av_rescale_q(fields, av_inv_q(field_rate), AV_TIME_BASE_Q);
  290. }
  291. break;
  292. }
  293. fd->dts_est = ds->dts;
  294. return 0;
  295. }
  296. static int ts_fixup(Demuxer *d, AVPacket *pkt, FrameData *fd)
  297. {
  298. InputFile *ifile = &d->f;
  299. InputStream *ist = ifile->streams[pkt->stream_index];
  300. DemuxStream *ds = ds_from_ist(ist);
  301. const int64_t start_time = ifile->start_time_effective;
  302. int64_t duration;
  303. int ret;
  304. pkt->time_base = ist->st->time_base;
  305. #define SHOW_TS_DEBUG(tag_) \
  306. if (debug_ts) { \
  307. av_log(ist, AV_LOG_INFO, "%s -> ist_index:%d:%d type:%s " \
  308. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s duration:%s duration_time:%s\n", \
  309. tag_, ifile->index, pkt->stream_index, \
  310. av_get_media_type_string(ist->st->codecpar->codec_type), \
  311. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &pkt->time_base), \
  312. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &pkt->time_base), \
  313. av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, &pkt->time_base)); \
  314. }
  315. SHOW_TS_DEBUG("demuxer");
  316. if (!ds->wrap_correction_done && start_time != AV_NOPTS_VALUE &&
  317. ist->st->pts_wrap_bits < 64) {
  318. int64_t stime, stime2;
  319. stime = av_rescale_q(start_time, AV_TIME_BASE_Q, pkt->time_base);
  320. stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
  321. ds->wrap_correction_done = 1;
  322. if(stime2 > stime && pkt->dts != AV_NOPTS_VALUE && pkt->dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  323. pkt->dts -= 1ULL<<ist->st->pts_wrap_bits;
  324. ds->wrap_correction_done = 0;
  325. }
  326. if(stime2 > stime && pkt->pts != AV_NOPTS_VALUE && pkt->pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  327. pkt->pts -= 1ULL<<ist->st->pts_wrap_bits;
  328. ds->wrap_correction_done = 0;
  329. }
  330. }
  331. if (pkt->dts != AV_NOPTS_VALUE)
  332. pkt->dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, pkt->time_base);
  333. if (pkt->pts != AV_NOPTS_VALUE)
  334. pkt->pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, pkt->time_base);
  335. if (pkt->pts != AV_NOPTS_VALUE)
  336. pkt->pts *= ds->ts_scale;
  337. if (pkt->dts != AV_NOPTS_VALUE)
  338. pkt->dts *= ds->ts_scale;
  339. duration = av_rescale_q(d->duration.ts, d->duration.tb, pkt->time_base);
  340. if (pkt->pts != AV_NOPTS_VALUE) {
  341. // audio decoders take precedence for estimating total file duration
  342. int64_t pkt_duration = d->have_audio_dec ? 0 : pkt->duration;
  343. pkt->pts += duration;
  344. // update max/min pts that will be used to compute total file duration
  345. // when using -stream_loop
  346. if (d->max_pts.ts == AV_NOPTS_VALUE ||
  347. av_compare_ts(d->max_pts.ts, d->max_pts.tb,
  348. pkt->pts + pkt_duration, pkt->time_base) < 0) {
  349. d->max_pts = (Timestamp){ .ts = pkt->pts + pkt_duration,
  350. .tb = pkt->time_base };
  351. }
  352. if (d->min_pts.ts == AV_NOPTS_VALUE ||
  353. av_compare_ts(d->min_pts.ts, d->min_pts.tb,
  354. pkt->pts, pkt->time_base) > 0) {
  355. d->min_pts = (Timestamp){ .ts = pkt->pts,
  356. .tb = pkt->time_base };
  357. }
  358. }
  359. if (pkt->dts != AV_NOPTS_VALUE)
  360. pkt->dts += duration;
  361. SHOW_TS_DEBUG("demuxer+tsfixup");
  362. // detect and try to correct for timestamp discontinuities
  363. ts_discontinuity_process(d, ist, pkt);
  364. // update estimated/predicted dts
  365. ret = ist_dts_update(ds, pkt, fd);
  366. if (ret < 0)
  367. return ret;
  368. return 0;
  369. }
  370. static int input_packet_process(Demuxer *d, AVPacket *pkt, unsigned *send_flags)
  371. {
  372. InputFile *f = &d->f;
  373. InputStream *ist = f->streams[pkt->stream_index];
  374. DemuxStream *ds = ds_from_ist(ist);
  375. FrameData *fd;
  376. int ret = 0;
  377. fd = packet_data(pkt);
  378. if (!fd)
  379. return AVERROR(ENOMEM);
  380. ret = ts_fixup(d, pkt, fd);
  381. if (ret < 0)
  382. return ret;
  383. if (d->recording_time != INT64_MAX) {
  384. int64_t start_time = 0;
  385. if (copy_ts) {
  386. start_time += f->start_time != AV_NOPTS_VALUE ? f->start_time : 0;
  387. start_time += start_at_zero ? 0 : f->start_time_effective;
  388. }
  389. if (ds->dts >= d->recording_time + start_time)
  390. *send_flags |= DEMUX_SEND_STREAMCOPY_EOF;
  391. }
  392. ds->data_size += pkt->size;
  393. ds->nb_packets++;
  394. fd->wallclock[LATENCY_PROBE_DEMUX] = av_gettime_relative();
  395. if (debug_ts) {
  396. av_log(ist, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s duration:%s duration_time:%s off:%s off_time:%s\n",
  397. f->index, pkt->stream_index,
  398. av_get_media_type_string(ist->par->codec_type),
  399. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &pkt->time_base),
  400. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &pkt->time_base),
  401. av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, &pkt->time_base),
  402. av_ts2str(f->ts_offset), av_ts2timestr(f->ts_offset, &AV_TIME_BASE_Q));
  403. }
  404. return 0;
  405. }
  406. static void readrate_sleep(Demuxer *d)
  407. {
  408. InputFile *f = &d->f;
  409. int64_t file_start = copy_ts * (
  410. (f->start_time_effective != AV_NOPTS_VALUE ? f->start_time_effective * !start_at_zero : 0) +
  411. (f->start_time != AV_NOPTS_VALUE ? f->start_time : 0)
  412. );
  413. int64_t burst_until = AV_TIME_BASE * d->readrate_initial_burst;
  414. for (int i = 0; i < f->nb_streams; i++) {
  415. InputStream *ist = f->streams[i];
  416. DemuxStream *ds = ds_from_ist(ist);
  417. int64_t stream_ts_offset, pts, now;
  418. stream_ts_offset = FFMAX(ds->first_dts != AV_NOPTS_VALUE ? ds->first_dts : 0, file_start);
  419. pts = av_rescale(ds->dts, 1000000, AV_TIME_BASE);
  420. now = (av_gettime_relative() - d->wallclock_start) * d->readrate + stream_ts_offset;
  421. if (pts - burst_until > now)
  422. av_usleep(pts - burst_until - now);
  423. }
  424. }
  425. static int do_send(Demuxer *d, DemuxStream *ds, AVPacket *pkt, unsigned flags,
  426. const char *pkt_desc)
  427. {
  428. int ret;
  429. pkt->stream_index = ds->sch_idx_stream;
  430. ret = sch_demux_send(d->sch, d->f.index, pkt, flags);
  431. if (ret == AVERROR_EOF) {
  432. av_packet_unref(pkt);
  433. av_log(ds, AV_LOG_VERBOSE, "All consumers of this stream are done\n");
  434. ds->finished = 1;
  435. if (++d->nb_streams_finished == d->nb_streams_used) {
  436. av_log(d, AV_LOG_VERBOSE, "All consumers are done\n");
  437. return AVERROR_EOF;
  438. }
  439. } else if (ret < 0) {
  440. if (ret != AVERROR_EXIT)
  441. av_log(d, AV_LOG_ERROR,
  442. "Unable to send %s packet to consumers: %s\n",
  443. pkt_desc, av_err2str(ret));
  444. return ret;
  445. }
  446. return 0;
  447. }
  448. static int demux_send(Demuxer *d, DemuxThreadContext *dt, DemuxStream *ds,
  449. AVPacket *pkt, unsigned flags)
  450. {
  451. InputFile *f = &d->f;
  452. int ret;
  453. // pkt can be NULL only when flushing BSFs
  454. av_assert0(ds->bsf || pkt);
  455. // send heartbeat for sub2video streams
  456. if (d->pkt_heartbeat && pkt && pkt->pts != AV_NOPTS_VALUE) {
  457. for (int i = 0; i < f->nb_streams; i++) {
  458. DemuxStream *ds1 = ds_from_ist(f->streams[i]);
  459. if (ds1->finished || !ds1->have_sub2video)
  460. continue;
  461. d->pkt_heartbeat->pts = pkt->pts;
  462. d->pkt_heartbeat->time_base = pkt->time_base;
  463. d->pkt_heartbeat->opaque = (void*)(intptr_t)PKT_OPAQUE_SUB_HEARTBEAT;
  464. ret = do_send(d, ds1, d->pkt_heartbeat, 0, "heartbeat");
  465. if (ret < 0)
  466. return ret;
  467. }
  468. }
  469. if (ds->bsf) {
  470. if (pkt)
  471. av_packet_rescale_ts(pkt, pkt->time_base, ds->bsf->time_base_in);
  472. ret = av_bsf_send_packet(ds->bsf, pkt);
  473. if (ret < 0) {
  474. if (pkt)
  475. av_packet_unref(pkt);
  476. av_log(ds, AV_LOG_ERROR, "Error submitting a packet for filtering: %s\n",
  477. av_err2str(ret));
  478. return ret;
  479. }
  480. while (1) {
  481. ret = av_bsf_receive_packet(ds->bsf, dt->pkt_bsf);
  482. if (ret == AVERROR(EAGAIN))
  483. return 0;
  484. else if (ret < 0) {
  485. if (ret != AVERROR_EOF)
  486. av_log(ds, AV_LOG_ERROR,
  487. "Error applying bitstream filters to a packet: %s\n",
  488. av_err2str(ret));
  489. return ret;
  490. }
  491. dt->pkt_bsf->time_base = ds->bsf->time_base_out;
  492. ret = do_send(d, ds, dt->pkt_bsf, 0, "filtered");
  493. if (ret < 0) {
  494. av_packet_unref(dt->pkt_bsf);
  495. return ret;
  496. }
  497. }
  498. } else {
  499. ret = do_send(d, ds, pkt, flags, "demuxed");
  500. if (ret < 0)
  501. return ret;
  502. }
  503. return 0;
  504. }
  505. static int demux_bsf_flush(Demuxer *d, DemuxThreadContext *dt)
  506. {
  507. InputFile *f = &d->f;
  508. int ret;
  509. for (unsigned i = 0; i < f->nb_streams; i++) {
  510. DemuxStream *ds = ds_from_ist(f->streams[i]);
  511. if (!ds->bsf)
  512. continue;
  513. ret = demux_send(d, dt, ds, NULL, 0);
  514. ret = (ret == AVERROR_EOF) ? 0 : (ret < 0) ? ret : AVERROR_BUG;
  515. if (ret < 0) {
  516. av_log(ds, AV_LOG_ERROR, "Error flushing BSFs: %s\n",
  517. av_err2str(ret));
  518. return ret;
  519. }
  520. av_bsf_flush(ds->bsf);
  521. }
  522. return 0;
  523. }
  524. static void discard_unused_programs(InputFile *ifile)
  525. {
  526. for (int j = 0; j < ifile->ctx->nb_programs; j++) {
  527. AVProgram *p = ifile->ctx->programs[j];
  528. int discard = AVDISCARD_ALL;
  529. for (int k = 0; k < p->nb_stream_indexes; k++) {
  530. DemuxStream *ds = ds_from_ist(ifile->streams[p->stream_index[k]]);
  531. if (!ds->discard) {
  532. discard = AVDISCARD_DEFAULT;
  533. break;
  534. }
  535. }
  536. p->discard = discard;
  537. }
  538. }
  539. static void thread_set_name(InputFile *f)
  540. {
  541. char name[16];
  542. snprintf(name, sizeof(name), "dmx%d:%s", f->index, f->ctx->iformat->name);
  543. ff_thread_setname(name);
  544. }
  545. static void demux_thread_uninit(DemuxThreadContext *dt)
  546. {
  547. av_packet_free(&dt->pkt_demux);
  548. av_packet_free(&dt->pkt_bsf);
  549. memset(dt, 0, sizeof(*dt));
  550. }
  551. static int demux_thread_init(DemuxThreadContext *dt)
  552. {
  553. memset(dt, 0, sizeof(*dt));
  554. dt->pkt_demux = av_packet_alloc();
  555. if (!dt->pkt_demux)
  556. return AVERROR(ENOMEM);
  557. dt->pkt_bsf = av_packet_alloc();
  558. if (!dt->pkt_bsf)
  559. return AVERROR(ENOMEM);
  560. return 0;
  561. }
  562. static int input_thread(void *arg)
  563. {
  564. Demuxer *d = arg;
  565. InputFile *f = &d->f;
  566. DemuxThreadContext dt;
  567. int ret = 0;
  568. ret = demux_thread_init(&dt);
  569. if (ret < 0)
  570. goto finish;
  571. thread_set_name(f);
  572. discard_unused_programs(f);
  573. d->read_started = 1;
  574. d->wallclock_start = av_gettime_relative();
  575. while (1) {
  576. DemuxStream *ds;
  577. unsigned send_flags = 0;
  578. ret = av_read_frame(f->ctx, dt.pkt_demux);
  579. if (ret == AVERROR(EAGAIN)) {
  580. av_usleep(10000);
  581. continue;
  582. }
  583. if (ret < 0) {
  584. int ret_bsf;
  585. if (ret == AVERROR_EOF)
  586. av_log(d, AV_LOG_VERBOSE, "EOF while reading input\n");
  587. else {
  588. av_log(d, AV_LOG_ERROR, "Error during demuxing: %s\n",
  589. av_err2str(ret));
  590. ret = exit_on_error ? ret : 0;
  591. }
  592. ret_bsf = demux_bsf_flush(d, &dt);
  593. ret = err_merge(ret == AVERROR_EOF ? 0 : ret, ret_bsf);
  594. if (d->loop) {
  595. /* signal looping to our consumers */
  596. dt.pkt_demux->stream_index = -1;
  597. ret = sch_demux_send(d->sch, f->index, dt.pkt_demux, 0);
  598. if (ret >= 0)
  599. ret = seek_to_start(d, (Timestamp){ .ts = dt.pkt_demux->pts,
  600. .tb = dt.pkt_demux->time_base });
  601. if (ret >= 0)
  602. continue;
  603. /* fallthrough to the error path */
  604. }
  605. break;
  606. }
  607. if (do_pkt_dump) {
  608. av_pkt_dump_log2(NULL, AV_LOG_INFO, dt.pkt_demux, do_hex_dump,
  609. f->ctx->streams[dt.pkt_demux->stream_index]);
  610. }
  611. /* the following test is needed in case new streams appear
  612. dynamically in stream : we ignore them */
  613. ds = dt.pkt_demux->stream_index < f->nb_streams ?
  614. ds_from_ist(f->streams[dt.pkt_demux->stream_index]) : NULL;
  615. if (!ds || ds->discard || ds->finished) {
  616. report_new_stream(d, dt.pkt_demux);
  617. av_packet_unref(dt.pkt_demux);
  618. continue;
  619. }
  620. if (dt.pkt_demux->flags & AV_PKT_FLAG_CORRUPT) {
  621. av_log(d, exit_on_error ? AV_LOG_FATAL : AV_LOG_WARNING,
  622. "corrupt input packet in stream %d\n",
  623. dt.pkt_demux->stream_index);
  624. if (exit_on_error) {
  625. av_packet_unref(dt.pkt_demux);
  626. ret = AVERROR_INVALIDDATA;
  627. break;
  628. }
  629. }
  630. ret = input_packet_process(d, dt.pkt_demux, &send_flags);
  631. if (ret < 0)
  632. break;
  633. if (d->readrate)
  634. readrate_sleep(d);
  635. ret = demux_send(d, &dt, ds, dt.pkt_demux, send_flags);
  636. if (ret < 0)
  637. break;
  638. }
  639. // EOF/EXIT is normal termination
  640. if (ret == AVERROR_EOF || ret == AVERROR_EXIT)
  641. ret = 0;
  642. finish:
  643. demux_thread_uninit(&dt);
  644. return ret;
  645. }
  646. static void demux_final_stats(Demuxer *d)
  647. {
  648. InputFile *f = &d->f;
  649. uint64_t total_packets = 0, total_size = 0;
  650. av_log(f, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
  651. f->index, f->ctx->url);
  652. for (int j = 0; j < f->nb_streams; j++) {
  653. InputStream *ist = f->streams[j];
  654. DemuxStream *ds = ds_from_ist(ist);
  655. enum AVMediaType type = ist->par->codec_type;
  656. if (ds->discard || type == AVMEDIA_TYPE_ATTACHMENT)
  657. continue;
  658. total_size += ds->data_size;
  659. total_packets += ds->nb_packets;
  660. av_log(f, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
  661. f->index, j, av_get_media_type_string(type));
  662. av_log(f, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
  663. ds->nb_packets, ds->data_size);
  664. if (ds->decoding_needed) {
  665. av_log(f, AV_LOG_VERBOSE,
  666. "%"PRIu64" frames decoded; %"PRIu64" decode errors",
  667. ist->decoder->frames_decoded, ist->decoder->decode_errors);
  668. if (type == AVMEDIA_TYPE_AUDIO)
  669. av_log(f, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->decoder->samples_decoded);
  670. av_log(f, AV_LOG_VERBOSE, "; ");
  671. }
  672. av_log(f, AV_LOG_VERBOSE, "\n");
  673. }
  674. av_log(f, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
  675. total_packets, total_size);
  676. }
  677. static void ist_free(InputStream **pist)
  678. {
  679. InputStream *ist = *pist;
  680. DemuxStream *ds;
  681. if (!ist)
  682. return;
  683. ds = ds_from_ist(ist);
  684. dec_free(&ist->decoder);
  685. av_dict_free(&ds->decoder_opts);
  686. av_freep(&ist->filters);
  687. av_freep(&ds->dec_opts.hwaccel_device);
  688. avcodec_parameters_free(&ist->par);
  689. av_frame_free(&ds->decoded_params);
  690. av_bsf_free(&ds->bsf);
  691. av_freep(pist);
  692. }
  693. void ifile_close(InputFile **pf)
  694. {
  695. InputFile *f = *pf;
  696. Demuxer *d = demuxer_from_ifile(f);
  697. if (!f)
  698. return;
  699. if (d->read_started)
  700. demux_final_stats(d);
  701. for (int i = 0; i < f->nb_streams; i++)
  702. ist_free(&f->streams[i]);
  703. av_freep(&f->streams);
  704. avformat_close_input(&f->ctx);
  705. av_packet_free(&d->pkt_heartbeat);
  706. av_freep(pf);
  707. }
  708. int ist_use(InputStream *ist, int decoding_needed,
  709. const ViewSpecifier *vs, SchedulerNode *src)
  710. {
  711. Demuxer *d = demuxer_from_ifile(ist->file);
  712. DemuxStream *ds = ds_from_ist(ist);
  713. int ret;
  714. if (ist->user_set_discard == AVDISCARD_ALL) {
  715. av_log(ist, AV_LOG_ERROR, "Cannot %s a disabled input stream\n",
  716. decoding_needed ? "decode" : "streamcopy");
  717. return AVERROR(EINVAL);
  718. }
  719. if (decoding_needed && !ist->dec) {
  720. av_log(ist, AV_LOG_ERROR,
  721. "Decoding requested, but no decoder found for: %s\n",
  722. avcodec_get_name(ist->par->codec_id));
  723. return AVERROR(EINVAL);
  724. }
  725. if (ds->sch_idx_stream < 0) {
  726. ret = sch_add_demux_stream(d->sch, d->f.index);
  727. if (ret < 0)
  728. return ret;
  729. ds->sch_idx_stream = ret;
  730. }
  731. if (ds->discard) {
  732. ds->discard = 0;
  733. d->nb_streams_used++;
  734. }
  735. ist->st->discard = ist->user_set_discard;
  736. ds->decoding_needed |= decoding_needed;
  737. ds->streamcopy_needed |= !decoding_needed;
  738. if (decoding_needed && ds->sch_idx_dec < 0) {
  739. int is_audio = ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
  740. ds->dec_opts.flags |= (!!ist->fix_sub_duration * DECODER_FLAG_FIX_SUB_DURATION) |
  741. (!!(d->f.ctx->iformat->flags & AVFMT_NOTIMESTAMPS) * DECODER_FLAG_TS_UNRELIABLE) |
  742. (!!(d->loop && is_audio) * DECODER_FLAG_SEND_END_TS)
  743. #if FFMPEG_OPT_TOP
  744. | ((ist->top_field_first >= 0) * DECODER_FLAG_TOP_FIELD_FIRST)
  745. #endif
  746. ;
  747. if (ist->framerate.num) {
  748. ds->dec_opts.flags |= DECODER_FLAG_FRAMERATE_FORCED;
  749. ds->dec_opts.framerate = ist->framerate;
  750. } else
  751. ds->dec_opts.framerate = ist->st->avg_frame_rate;
  752. if (ist->dec->id == AV_CODEC_ID_DVB_SUBTITLE &&
  753. (ds->decoding_needed & DECODING_FOR_OST)) {
  754. av_dict_set(&ds->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
  755. if (ds->decoding_needed & DECODING_FOR_FILTER)
  756. av_log(ist, AV_LOG_WARNING,
  757. "Warning using DVB subtitles for filtering and output at the "
  758. "same time is not fully supported, also see -compute_edt [0|1]\n");
  759. }
  760. snprintf(ds->dec_name, sizeof(ds->dec_name), "%d:%d", ist->file->index, ist->index);
  761. ds->dec_opts.name = ds->dec_name;
  762. ds->dec_opts.codec = ist->dec;
  763. ds->dec_opts.par = ist->par;
  764. ds->dec_opts.log_parent = ist;
  765. ds->decoded_params = av_frame_alloc();
  766. if (!ds->decoded_params)
  767. return AVERROR(ENOMEM);
  768. ret = dec_init(&ist->decoder, d->sch,
  769. &ds->decoder_opts, &ds->dec_opts, ds->decoded_params);
  770. if (ret < 0)
  771. return ret;
  772. ds->sch_idx_dec = ret;
  773. ret = sch_connect(d->sch, SCH_DSTREAM(d->f.index, ds->sch_idx_stream),
  774. SCH_DEC_IN(ds->sch_idx_dec));
  775. if (ret < 0)
  776. return ret;
  777. d->have_audio_dec |= is_audio;
  778. }
  779. if (decoding_needed && ist->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  780. ret = dec_request_view(ist->decoder, vs, src);
  781. if (ret < 0)
  782. return ret;
  783. } else {
  784. *src = decoding_needed ?
  785. SCH_DEC_OUT(ds->sch_idx_dec, 0) :
  786. SCH_DSTREAM(d->f.index, ds->sch_idx_stream);
  787. }
  788. return 0;
  789. }
  790. int ist_filter_add(InputStream *ist, InputFilter *ifilter, int is_simple,
  791. const ViewSpecifier *vs, InputFilterOptions *opts,
  792. SchedulerNode *src)
  793. {
  794. Demuxer *d = demuxer_from_ifile(ist->file);
  795. DemuxStream *ds = ds_from_ist(ist);
  796. int64_t tsoffset = 0;
  797. int ret;
  798. ret = ist_use(ist, is_simple ? DECODING_FOR_OST : DECODING_FOR_FILTER,
  799. vs, src);
  800. if (ret < 0)
  801. return ret;
  802. ret = GROW_ARRAY(ist->filters, ist->nb_filters);
  803. if (ret < 0)
  804. return ret;
  805. ist->filters[ist->nb_filters - 1] = ifilter;
  806. if (ist->par->codec_type == AVMEDIA_TYPE_VIDEO) {
  807. const AVPacketSideData *sd = av_packet_side_data_get(ist->par->coded_side_data,
  808. ist->par->nb_coded_side_data,
  809. AV_PKT_DATA_FRAME_CROPPING);
  810. if (ist->framerate.num > 0 && ist->framerate.den > 0) {
  811. opts->framerate = ist->framerate;
  812. opts->flags |= IFILTER_FLAG_CFR;
  813. } else
  814. opts->framerate = av_guess_frame_rate(d->f.ctx, ist->st, NULL);
  815. if (sd && sd->size >= sizeof(uint32_t) * 4) {
  816. opts->crop_top = AV_RL32(sd->data + 0);
  817. opts->crop_bottom = AV_RL32(sd->data + 4);
  818. opts->crop_left = AV_RL32(sd->data + 8);
  819. opts->crop_right = AV_RL32(sd->data + 12);
  820. if (ds->apply_cropping && ds->apply_cropping != CROP_CODEC &&
  821. (opts->crop_top | opts->crop_bottom | opts->crop_left | opts->crop_right))
  822. opts->flags |= IFILTER_FLAG_CROP;
  823. }
  824. } else if (ist->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  825. /* Compute the size of the canvas for the subtitles stream.
  826. If the subtitles codecpar has set a size, use it. Otherwise use the
  827. maximum dimensions of the video streams in the same file. */
  828. opts->sub2video_width = ist->par->width;
  829. opts->sub2video_height = ist->par->height;
  830. if (!(opts->sub2video_width && opts->sub2video_height)) {
  831. for (int j = 0; j < d->f.nb_streams; j++) {
  832. AVCodecParameters *par1 = d->f.streams[j]->par;
  833. if (par1->codec_type == AVMEDIA_TYPE_VIDEO) {
  834. opts->sub2video_width = FFMAX(opts->sub2video_width, par1->width);
  835. opts->sub2video_height = FFMAX(opts->sub2video_height, par1->height);
  836. }
  837. }
  838. }
  839. if (!(opts->sub2video_width && opts->sub2video_height)) {
  840. opts->sub2video_width = FFMAX(opts->sub2video_width, 720);
  841. opts->sub2video_height = FFMAX(opts->sub2video_height, 576);
  842. }
  843. if (!d->pkt_heartbeat) {
  844. d->pkt_heartbeat = av_packet_alloc();
  845. if (!d->pkt_heartbeat)
  846. return AVERROR(ENOMEM);
  847. }
  848. ds->have_sub2video = 1;
  849. }
  850. ret = av_frame_copy_props(opts->fallback, ds->decoded_params);
  851. if (ret < 0)
  852. return ret;
  853. opts->fallback->format = ds->decoded_params->format;
  854. opts->fallback->width = ds->decoded_params->width;
  855. opts->fallback->height = ds->decoded_params->height;
  856. ret = av_channel_layout_copy(&opts->fallback->ch_layout, &ds->decoded_params->ch_layout);
  857. if (ret < 0)
  858. return ret;
  859. if (copy_ts) {
  860. tsoffset = d->f.start_time == AV_NOPTS_VALUE ? 0 : d->f.start_time;
  861. if (!start_at_zero && d->f.ctx->start_time != AV_NOPTS_VALUE)
  862. tsoffset += d->f.ctx->start_time;
  863. }
  864. opts->trim_start_us = ((d->f.start_time == AV_NOPTS_VALUE) || !d->accurate_seek) ?
  865. AV_NOPTS_VALUE : tsoffset;
  866. opts->trim_end_us = d->recording_time;
  867. opts->name = av_strdup(ds->dec_name);
  868. if (!opts->name)
  869. return AVERROR(ENOMEM);
  870. opts->flags |= IFILTER_FLAG_AUTOROTATE * !!(ds->autorotate) |
  871. IFILTER_FLAG_REINIT * !!(ds->reinit_filters);
  872. return 0;
  873. }
  874. static int choose_decoder(const OptionsContext *o, void *logctx,
  875. AVFormatContext *s, AVStream *st,
  876. enum HWAccelID hwaccel_id, enum AVHWDeviceType hwaccel_device_type,
  877. const AVCodec **pcodec)
  878. {
  879. const char *codec_name = NULL;
  880. opt_match_per_stream_str(logctx, &o->codec_names, s, st, &codec_name);
  881. if (codec_name) {
  882. int ret = find_codec(NULL, codec_name, st->codecpar->codec_type, 0, pcodec);
  883. if (ret < 0)
  884. return ret;
  885. st->codecpar->codec_id = (*pcodec)->id;
  886. if (recast_media && st->codecpar->codec_type != (*pcodec)->type)
  887. st->codecpar->codec_type = (*pcodec)->type;
  888. return 0;
  889. } else {
  890. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  891. hwaccel_id == HWACCEL_GENERIC &&
  892. hwaccel_device_type != AV_HWDEVICE_TYPE_NONE) {
  893. const AVCodec *c;
  894. void *i = NULL;
  895. while ((c = av_codec_iterate(&i))) {
  896. const AVCodecHWConfig *config;
  897. if (c->id != st->codecpar->codec_id ||
  898. !av_codec_is_decoder(c))
  899. continue;
  900. for (int j = 0; config = avcodec_get_hw_config(c, j); j++) {
  901. if (config->device_type == hwaccel_device_type) {
  902. av_log(logctx, AV_LOG_VERBOSE, "Selecting decoder '%s' because of requested hwaccel method %s\n",
  903. c->name, av_hwdevice_get_type_name(hwaccel_device_type));
  904. *pcodec = c;
  905. return 0;
  906. }
  907. }
  908. }
  909. }
  910. *pcodec = avcodec_find_decoder(st->codecpar->codec_id);
  911. return 0;
  912. }
  913. }
  914. static int guess_input_channel_layout(InputStream *ist, AVCodecParameters *par,
  915. int guess_layout_max)
  916. {
  917. if (par->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC) {
  918. char layout_name[256];
  919. if (par->ch_layout.nb_channels > guess_layout_max)
  920. return 0;
  921. av_channel_layout_default(&par->ch_layout, par->ch_layout.nb_channels);
  922. if (par->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC)
  923. return 0;
  924. av_channel_layout_describe(&par->ch_layout, layout_name, sizeof(layout_name));
  925. av_log(ist, AV_LOG_WARNING, "Guessed Channel Layout: %s\n", layout_name);
  926. }
  927. return 1;
  928. }
  929. static int add_display_matrix_to_stream(const OptionsContext *o,
  930. AVFormatContext *ctx, InputStream *ist)
  931. {
  932. AVStream *st = ist->st;
  933. AVPacketSideData *sd;
  934. double rotation = DBL_MAX;
  935. int hflip = -1, vflip = -1;
  936. int hflip_set = 0, vflip_set = 0, rotation_set = 0;
  937. int32_t *buf;
  938. opt_match_per_stream_dbl(ist, &o->display_rotations, ctx, st, &rotation);
  939. opt_match_per_stream_int(ist, &o->display_hflips, ctx, st, &hflip);
  940. opt_match_per_stream_int(ist, &o->display_vflips, ctx, st, &vflip);
  941. rotation_set = rotation != DBL_MAX;
  942. hflip_set = hflip != -1;
  943. vflip_set = vflip != -1;
  944. if (!rotation_set && !hflip_set && !vflip_set)
  945. return 0;
  946. sd = av_packet_side_data_new(&st->codecpar->coded_side_data,
  947. &st->codecpar->nb_coded_side_data,
  948. AV_PKT_DATA_DISPLAYMATRIX,
  949. sizeof(int32_t) * 9, 0);
  950. if (!sd) {
  951. av_log(ist, AV_LOG_FATAL, "Failed to generate a display matrix!\n");
  952. return AVERROR(ENOMEM);
  953. }
  954. buf = (int32_t *)sd->data;
  955. av_display_rotation_set(buf,
  956. rotation_set ? -(rotation) : -0.0f);
  957. av_display_matrix_flip(buf,
  958. hflip_set ? hflip : 0,
  959. vflip_set ? vflip : 0);
  960. return 0;
  961. }
  962. static const char *input_stream_item_name(void *obj)
  963. {
  964. const DemuxStream *ds = obj;
  965. return ds->log_name;
  966. }
  967. static const AVClass input_stream_class = {
  968. .class_name = "InputStream",
  969. .version = LIBAVUTIL_VERSION_INT,
  970. .item_name = input_stream_item_name,
  971. .category = AV_CLASS_CATEGORY_DEMUXER,
  972. };
  973. static DemuxStream *demux_stream_alloc(Demuxer *d, AVStream *st)
  974. {
  975. const char *type_str = av_get_media_type_string(st->codecpar->codec_type);
  976. InputFile *f = &d->f;
  977. DemuxStream *ds;
  978. ds = allocate_array_elem(&f->streams, sizeof(*ds), &f->nb_streams);
  979. if (!ds)
  980. return NULL;
  981. ds->sch_idx_stream = -1;
  982. ds->sch_idx_dec = -1;
  983. ds->ist.st = st;
  984. ds->ist.file = f;
  985. ds->ist.index = st->index;
  986. ds->ist.class = &input_stream_class;
  987. snprintf(ds->log_name, sizeof(ds->log_name), "%cist#%d:%d/%s",
  988. type_str ? *type_str : '?', d->f.index, st->index,
  989. avcodec_get_name(st->codecpar->codec_id));
  990. return ds;
  991. }
  992. static int ist_add(const OptionsContext *o, Demuxer *d, AVStream *st, AVDictionary **opts_used)
  993. {
  994. AVFormatContext *ic = d->f.ctx;
  995. AVCodecParameters *par = st->codecpar;
  996. DemuxStream *ds;
  997. InputStream *ist;
  998. const char *framerate = NULL, *hwaccel_device = NULL;
  999. const char *hwaccel = NULL;
  1000. const char *apply_cropping = NULL;
  1001. const char *hwaccel_output_format = NULL;
  1002. const char *codec_tag = NULL;
  1003. const char *bsfs = NULL;
  1004. char *next;
  1005. const char *discard_str = NULL;
  1006. int ret;
  1007. ds = demux_stream_alloc(d, st);
  1008. if (!ds)
  1009. return AVERROR(ENOMEM);
  1010. ist = &ds->ist;
  1011. ds->discard = 1;
  1012. st->discard = AVDISCARD_ALL;
  1013. ds->first_dts = AV_NOPTS_VALUE;
  1014. ds->next_dts = AV_NOPTS_VALUE;
  1015. ds->dec_opts.time_base = st->time_base;
  1016. ds->ts_scale = 1.0;
  1017. opt_match_per_stream_dbl(ist, &o->ts_scale, ic, st, &ds->ts_scale);
  1018. ds->autorotate = 1;
  1019. opt_match_per_stream_int(ist, &o->autorotate, ic, st, &ds->autorotate);
  1020. ds->apply_cropping = CROP_ALL;
  1021. opt_match_per_stream_str(ist, &o->apply_cropping, ic, st, &apply_cropping);
  1022. if (apply_cropping) {
  1023. const AVOption opts[] = {
  1024. { "apply_cropping", NULL, 0, AV_OPT_TYPE_INT,
  1025. { .i64 = CROP_ALL }, CROP_DISABLED, CROP_CONTAINER, AV_OPT_FLAG_DECODING_PARAM, .unit = "apply_cropping" },
  1026. { "none", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CROP_DISABLED }, .unit = "apply_cropping" },
  1027. { "all", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CROP_ALL }, .unit = "apply_cropping" },
  1028. { "codec", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CROP_CODEC }, .unit = "apply_cropping" },
  1029. { "container", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CROP_CONTAINER }, .unit = "apply_cropping" },
  1030. { NULL },
  1031. };
  1032. const AVClass class = {
  1033. .class_name = "apply_cropping",
  1034. .item_name = av_default_item_name,
  1035. .option = opts,
  1036. .version = LIBAVUTIL_VERSION_INT,
  1037. };
  1038. const AVClass *pclass = &class;
  1039. ret = av_opt_eval_int(&pclass, opts, apply_cropping, &ds->apply_cropping);
  1040. if (ret < 0) {
  1041. av_log(ist, AV_LOG_ERROR, "Invalid apply_cropping value '%s'.\n", apply_cropping);
  1042. return ret;
  1043. }
  1044. }
  1045. opt_match_per_stream_str(ist, &o->codec_tags, ic, st, &codec_tag);
  1046. if (codec_tag) {
  1047. uint32_t tag = strtol(codec_tag, &next, 0);
  1048. if (*next) {
  1049. uint8_t buf[4] = { 0 };
  1050. memcpy(buf, codec_tag, FFMIN(sizeof(buf), strlen(codec_tag)));
  1051. tag = AV_RL32(buf);
  1052. }
  1053. st->codecpar->codec_tag = tag;
  1054. }
  1055. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  1056. ret = add_display_matrix_to_stream(o, ic, ist);
  1057. if (ret < 0)
  1058. return ret;
  1059. opt_match_per_stream_str(ist, &o->hwaccels, ic, st, &hwaccel);
  1060. opt_match_per_stream_str(ist, &o->hwaccel_output_formats, ic, st,
  1061. &hwaccel_output_format);
  1062. if (!hwaccel_output_format && hwaccel && !strcmp(hwaccel, "cuvid")) {
  1063. av_log(ist, AV_LOG_WARNING,
  1064. "WARNING: defaulting hwaccel_output_format to cuda for compatibility "
  1065. "with old commandlines. This behaviour is DEPRECATED and will be removed "
  1066. "in the future. Please explicitly set \"-hwaccel_output_format cuda\".\n");
  1067. ds->dec_opts.hwaccel_output_format = AV_PIX_FMT_CUDA;
  1068. } else if (!hwaccel_output_format && hwaccel && !strcmp(hwaccel, "qsv")) {
  1069. av_log(ist, AV_LOG_WARNING,
  1070. "WARNING: defaulting hwaccel_output_format to qsv for compatibility "
  1071. "with old commandlines. This behaviour is DEPRECATED and will be removed "
  1072. "in the future. Please explicitly set \"-hwaccel_output_format qsv\".\n");
  1073. ds->dec_opts.hwaccel_output_format = AV_PIX_FMT_QSV;
  1074. } else if (!hwaccel_output_format && hwaccel && !strcmp(hwaccel, "mediacodec")) {
  1075. // There is no real AVHWFrameContext implementation. Set
  1076. // hwaccel_output_format to avoid av_hwframe_transfer_data error.
  1077. ds->dec_opts.hwaccel_output_format = AV_PIX_FMT_MEDIACODEC;
  1078. } else if (hwaccel_output_format) {
  1079. ds->dec_opts.hwaccel_output_format = av_get_pix_fmt(hwaccel_output_format);
  1080. if (ds->dec_opts.hwaccel_output_format == AV_PIX_FMT_NONE) {
  1081. av_log(ist, AV_LOG_FATAL, "Unrecognised hwaccel output "
  1082. "format: %s", hwaccel_output_format);
  1083. }
  1084. } else {
  1085. ds->dec_opts.hwaccel_output_format = AV_PIX_FMT_NONE;
  1086. }
  1087. if (hwaccel) {
  1088. // The NVDEC hwaccels use a CUDA device, so remap the name here.
  1089. if (!strcmp(hwaccel, "nvdec") || !strcmp(hwaccel, "cuvid"))
  1090. hwaccel = "cuda";
  1091. if (!strcmp(hwaccel, "none"))
  1092. ds->dec_opts.hwaccel_id = HWACCEL_NONE;
  1093. else if (!strcmp(hwaccel, "auto"))
  1094. ds->dec_opts.hwaccel_id = HWACCEL_AUTO;
  1095. else {
  1096. enum AVHWDeviceType type = av_hwdevice_find_type_by_name(hwaccel);
  1097. if (type != AV_HWDEVICE_TYPE_NONE) {
  1098. ds->dec_opts.hwaccel_id = HWACCEL_GENERIC;
  1099. ds->dec_opts.hwaccel_device_type = type;
  1100. }
  1101. if (!ds->dec_opts.hwaccel_id) {
  1102. av_log(ist, AV_LOG_FATAL, "Unrecognized hwaccel: %s.\n",
  1103. hwaccel);
  1104. av_log(ist, AV_LOG_FATAL, "Supported hwaccels: ");
  1105. type = AV_HWDEVICE_TYPE_NONE;
  1106. while ((type = av_hwdevice_iterate_types(type)) !=
  1107. AV_HWDEVICE_TYPE_NONE)
  1108. av_log(ist, AV_LOG_FATAL, "%s ",
  1109. av_hwdevice_get_type_name(type));
  1110. av_log(ist, AV_LOG_FATAL, "\n");
  1111. return AVERROR(EINVAL);
  1112. }
  1113. }
  1114. }
  1115. opt_match_per_stream_str(ist, &o->hwaccel_devices, ic, st, &hwaccel_device);
  1116. if (hwaccel_device) {
  1117. ds->dec_opts.hwaccel_device = av_strdup(hwaccel_device);
  1118. if (!ds->dec_opts.hwaccel_device)
  1119. return AVERROR(ENOMEM);
  1120. }
  1121. }
  1122. ret = choose_decoder(o, ist, ic, st, ds->dec_opts.hwaccel_id,
  1123. ds->dec_opts.hwaccel_device_type, &ist->dec);
  1124. if (ret < 0)
  1125. return ret;
  1126. if (ist->dec) {
  1127. ret = filter_codec_opts(o->g->codec_opts, ist->st->codecpar->codec_id,
  1128. ic, st, ist->dec, &ds->decoder_opts, opts_used);
  1129. if (ret < 0)
  1130. return ret;
  1131. }
  1132. ds->reinit_filters = -1;
  1133. opt_match_per_stream_int(ist, &o->reinit_filters, ic, st, &ds->reinit_filters);
  1134. ist->user_set_discard = AVDISCARD_NONE;
  1135. if ((o->video_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) ||
  1136. (o->audio_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) ||
  1137. (o->subtitle_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) ||
  1138. (o->data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA))
  1139. ist->user_set_discard = AVDISCARD_ALL;
  1140. opt_match_per_stream_str(ist, &o->discard, ic, st, &discard_str);
  1141. if (discard_str) {
  1142. ret = av_opt_set(ist->st, "discard", discard_str, 0);
  1143. if (ret < 0) {
  1144. av_log(ist, AV_LOG_ERROR, "Error parsing discard %s.\n", discard_str);
  1145. return ret;
  1146. }
  1147. ist->user_set_discard = ist->st->discard;
  1148. }
  1149. ds->dec_opts.flags |= DECODER_FLAG_BITEXACT * !!o->bitexact;
  1150. av_dict_set_int(&ds->decoder_opts, "apply_cropping",
  1151. ds->apply_cropping && ds->apply_cropping != CROP_CONTAINER, 0);
  1152. /* Attached pics are sparse, therefore we would not want to delay their decoding
  1153. * till EOF. */
  1154. if (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC)
  1155. av_dict_set(&ds->decoder_opts, "thread_type", "-frame", 0);
  1156. switch (par->codec_type) {
  1157. case AVMEDIA_TYPE_VIDEO:
  1158. opt_match_per_stream_str(ist, &o->frame_rates, ic, st, &framerate);
  1159. if (framerate) {
  1160. ret = av_parse_video_rate(&ist->framerate, framerate);
  1161. if (ret < 0) {
  1162. av_log(ist, AV_LOG_ERROR, "Error parsing framerate %s.\n",
  1163. framerate);
  1164. return ret;
  1165. }
  1166. }
  1167. #if FFMPEG_OPT_TOP
  1168. ist->top_field_first = -1;
  1169. opt_match_per_stream_int(ist, &o->top_field_first, ic, st, &ist->top_field_first);
  1170. #endif
  1171. break;
  1172. case AVMEDIA_TYPE_AUDIO: {
  1173. const char *ch_layout_str = NULL;
  1174. opt_match_per_stream_str(ist, &o->audio_ch_layouts, ic, st, &ch_layout_str);
  1175. if (ch_layout_str) {
  1176. AVChannelLayout ch_layout;
  1177. ret = av_channel_layout_from_string(&ch_layout, ch_layout_str);
  1178. if (ret < 0) {
  1179. av_log(ist, AV_LOG_ERROR, "Error parsing channel layout %s.\n", ch_layout_str);
  1180. return ret;
  1181. }
  1182. if (par->ch_layout.nb_channels <= 0 || par->ch_layout.nb_channels == ch_layout.nb_channels) {
  1183. av_channel_layout_uninit(&par->ch_layout);
  1184. par->ch_layout = ch_layout;
  1185. } else {
  1186. av_log(ist, AV_LOG_ERROR,
  1187. "Specified channel layout '%s' has %d channels, but input has %d channels.\n",
  1188. ch_layout_str, ch_layout.nb_channels, par->ch_layout.nb_channels);
  1189. av_channel_layout_uninit(&ch_layout);
  1190. return AVERROR(EINVAL);
  1191. }
  1192. } else {
  1193. int guess_layout_max = INT_MAX;
  1194. opt_match_per_stream_int(ist, &o->guess_layout_max, ic, st, &guess_layout_max);
  1195. guess_input_channel_layout(ist, par, guess_layout_max);
  1196. }
  1197. break;
  1198. }
  1199. case AVMEDIA_TYPE_DATA:
  1200. case AVMEDIA_TYPE_SUBTITLE: {
  1201. const char *canvas_size = NULL;
  1202. opt_match_per_stream_int(ist, &o->fix_sub_duration, ic, st, &ist->fix_sub_duration);
  1203. opt_match_per_stream_str(ist, &o->canvas_sizes, ic, st, &canvas_size);
  1204. if (canvas_size) {
  1205. ret = av_parse_video_size(&par->width, &par->height,
  1206. canvas_size);
  1207. if (ret < 0) {
  1208. av_log(ist, AV_LOG_FATAL, "Invalid canvas size: %s.\n", canvas_size);
  1209. return ret;
  1210. }
  1211. }
  1212. break;
  1213. }
  1214. case AVMEDIA_TYPE_ATTACHMENT:
  1215. case AVMEDIA_TYPE_UNKNOWN:
  1216. break;
  1217. default: av_assert0(0);
  1218. }
  1219. ist->par = avcodec_parameters_alloc();
  1220. if (!ist->par)
  1221. return AVERROR(ENOMEM);
  1222. ret = avcodec_parameters_copy(ist->par, par);
  1223. if (ret < 0) {
  1224. av_log(ist, AV_LOG_ERROR, "Error exporting stream parameters.\n");
  1225. return ret;
  1226. }
  1227. if (ist->st->sample_aspect_ratio.num)
  1228. ist->par->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1229. opt_match_per_stream_str(ist, &o->bitstream_filters, ic, st, &bsfs);
  1230. if (bsfs) {
  1231. ret = av_bsf_list_parse_str(bsfs, &ds->bsf);
  1232. if (ret < 0) {
  1233. av_log(ist, AV_LOG_ERROR,
  1234. "Error parsing bitstream filter sequence '%s': %s\n",
  1235. bsfs, av_err2str(ret));
  1236. return ret;
  1237. }
  1238. ret = avcodec_parameters_copy(ds->bsf->par_in, ist->par);
  1239. if (ret < 0)
  1240. return ret;
  1241. ds->bsf->time_base_in = ist->st->time_base;
  1242. ret = av_bsf_init(ds->bsf);
  1243. if (ret < 0) {
  1244. av_log(ist, AV_LOG_ERROR, "Error initializing bitstream filters: %s\n",
  1245. av_err2str(ret));
  1246. return ret;
  1247. }
  1248. ret = avcodec_parameters_copy(ist->par, ds->bsf->par_out);
  1249. if (ret < 0)
  1250. return ret;
  1251. }
  1252. ds->codec_desc = avcodec_descriptor_get(ist->par->codec_id);
  1253. return 0;
  1254. }
  1255. static int dump_attachment(InputStream *ist, const char *filename)
  1256. {
  1257. AVStream *st = ist->st;
  1258. int ret;
  1259. AVIOContext *out = NULL;
  1260. const AVDictionaryEntry *e;
  1261. if (!st->codecpar->extradata_size) {
  1262. av_log(ist, AV_LOG_WARNING, "No extradata to dump.\n");
  1263. return 0;
  1264. }
  1265. if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
  1266. filename = e->value;
  1267. if (!*filename) {
  1268. av_log(ist, AV_LOG_FATAL, "No filename specified and no 'filename' tag");
  1269. return AVERROR(EINVAL);
  1270. }
  1271. ret = assert_file_overwrite(filename);
  1272. if (ret < 0)
  1273. return ret;
  1274. if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
  1275. av_log(ist, AV_LOG_FATAL, "Could not open file %s for writing.\n",
  1276. filename);
  1277. return ret;
  1278. }
  1279. avio_write(out, st->codecpar->extradata, st->codecpar->extradata_size);
  1280. ret = avio_close(out);
  1281. if (ret >= 0)
  1282. av_log(ist, AV_LOG_INFO, "Wrote attachment (%d bytes) to '%s'\n",
  1283. st->codecpar->extradata_size, filename);
  1284. return ret;
  1285. }
  1286. static const char *input_file_item_name(void *obj)
  1287. {
  1288. const Demuxer *d = obj;
  1289. return d->log_name;
  1290. }
  1291. static const AVClass input_file_class = {
  1292. .class_name = "InputFile",
  1293. .version = LIBAVUTIL_VERSION_INT,
  1294. .item_name = input_file_item_name,
  1295. .category = AV_CLASS_CATEGORY_DEMUXER,
  1296. };
  1297. static Demuxer *demux_alloc(void)
  1298. {
  1299. Demuxer *d = allocate_array_elem(&input_files, sizeof(*d), &nb_input_files);
  1300. if (!d)
  1301. return NULL;
  1302. d->f.class = &input_file_class;
  1303. d->f.index = nb_input_files - 1;
  1304. snprintf(d->log_name, sizeof(d->log_name), "in#%d", d->f.index);
  1305. return d;
  1306. }
  1307. int ifile_open(const OptionsContext *o, const char *filename, Scheduler *sch)
  1308. {
  1309. Demuxer *d;
  1310. InputFile *f;
  1311. AVFormatContext *ic;
  1312. const AVInputFormat *file_iformat = NULL;
  1313. int err, ret = 0;
  1314. int64_t timestamp;
  1315. AVDictionary *opts_used = NULL;
  1316. const char* video_codec_name = NULL;
  1317. const char* audio_codec_name = NULL;
  1318. const char* subtitle_codec_name = NULL;
  1319. const char* data_codec_name = NULL;
  1320. int scan_all_pmts_set = 0;
  1321. int64_t start_time = o->start_time;
  1322. int64_t start_time_eof = o->start_time_eof;
  1323. int64_t stop_time = o->stop_time;
  1324. int64_t recording_time = o->recording_time;
  1325. d = demux_alloc();
  1326. if (!d)
  1327. return AVERROR(ENOMEM);
  1328. f = &d->f;
  1329. ret = sch_add_demux(sch, input_thread, d);
  1330. if (ret < 0)
  1331. return ret;
  1332. d->sch = sch;
  1333. if (stop_time != INT64_MAX && recording_time != INT64_MAX) {
  1334. stop_time = INT64_MAX;
  1335. av_log(d, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
  1336. }
  1337. if (stop_time != INT64_MAX && recording_time == INT64_MAX) {
  1338. int64_t start = start_time == AV_NOPTS_VALUE ? 0 : start_time;
  1339. if (stop_time <= start) {
  1340. av_log(d, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
  1341. return AVERROR(EINVAL);
  1342. } else {
  1343. recording_time = stop_time - start;
  1344. }
  1345. }
  1346. if (o->format) {
  1347. if (!(file_iformat = av_find_input_format(o->format))) {
  1348. av_log(d, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
  1349. return AVERROR(EINVAL);
  1350. }
  1351. }
  1352. if (!strcmp(filename, "-"))
  1353. filename = "fd:";
  1354. stdin_interaction &= strncmp(filename, "pipe:", 5) &&
  1355. strcmp(filename, "fd:") &&
  1356. strcmp(filename, "/dev/stdin");
  1357. /* get default parameters from command line */
  1358. ic = avformat_alloc_context();
  1359. if (!ic)
  1360. return AVERROR(ENOMEM);
  1361. if (o->audio_sample_rate.nb_opt) {
  1362. av_dict_set_int(&o->g->format_opts, "sample_rate", o->audio_sample_rate.opt[o->audio_sample_rate.nb_opt - 1].u.i, 0);
  1363. }
  1364. if (o->audio_channels.nb_opt) {
  1365. const AVClass *priv_class;
  1366. if (file_iformat && (priv_class = file_iformat->priv_class) &&
  1367. av_opt_find(&priv_class, "ch_layout", NULL, 0,
  1368. AV_OPT_SEARCH_FAKE_OBJ)) {
  1369. char buf[32];
  1370. snprintf(buf, sizeof(buf), "%dC", o->audio_channels.opt[o->audio_channels.nb_opt - 1].u.i);
  1371. av_dict_set(&o->g->format_opts, "ch_layout", buf, 0);
  1372. }
  1373. }
  1374. if (o->audio_ch_layouts.nb_opt) {
  1375. const AVClass *priv_class;
  1376. if (file_iformat && (priv_class = file_iformat->priv_class) &&
  1377. av_opt_find(&priv_class, "ch_layout", NULL, 0,
  1378. AV_OPT_SEARCH_FAKE_OBJ)) {
  1379. av_dict_set(&o->g->format_opts, "ch_layout", o->audio_ch_layouts.opt[o->audio_ch_layouts.nb_opt - 1].u.str, 0);
  1380. }
  1381. }
  1382. if (o->frame_rates.nb_opt) {
  1383. const AVClass *priv_class;
  1384. /* set the format-level framerate option;
  1385. * this is important for video grabbers, e.g. x11 */
  1386. if (file_iformat && (priv_class = file_iformat->priv_class) &&
  1387. av_opt_find(&priv_class, "framerate", NULL, 0,
  1388. AV_OPT_SEARCH_FAKE_OBJ)) {
  1389. av_dict_set(&o->g->format_opts, "framerate",
  1390. o->frame_rates.opt[o->frame_rates.nb_opt - 1].u.str, 0);
  1391. }
  1392. }
  1393. if (o->frame_sizes.nb_opt) {
  1394. av_dict_set(&o->g->format_opts, "video_size", o->frame_sizes.opt[o->frame_sizes.nb_opt - 1].u.str, 0);
  1395. }
  1396. if (o->frame_pix_fmts.nb_opt)
  1397. av_dict_set(&o->g->format_opts, "pixel_format", o->frame_pix_fmts.opt[o->frame_pix_fmts.nb_opt - 1].u.str, 0);
  1398. video_codec_name = opt_match_per_type_str(&o->codec_names, 'v');
  1399. audio_codec_name = opt_match_per_type_str(&o->codec_names, 'a');
  1400. subtitle_codec_name = opt_match_per_type_str(&o->codec_names, 's');
  1401. data_codec_name = opt_match_per_type_str(&o->codec_names, 'd');
  1402. if (video_codec_name)
  1403. ret = err_merge(ret, find_codec(NULL, video_codec_name , AVMEDIA_TYPE_VIDEO , 0,
  1404. &ic->video_codec));
  1405. if (audio_codec_name)
  1406. ret = err_merge(ret, find_codec(NULL, audio_codec_name , AVMEDIA_TYPE_AUDIO , 0,
  1407. &ic->audio_codec));
  1408. if (subtitle_codec_name)
  1409. ret = err_merge(ret, find_codec(NULL, subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0,
  1410. &ic->subtitle_codec));
  1411. if (data_codec_name)
  1412. ret = err_merge(ret, find_codec(NULL, data_codec_name , AVMEDIA_TYPE_DATA, 0,
  1413. &ic->data_codec));
  1414. if (ret < 0) {
  1415. avformat_free_context(ic);
  1416. return ret;
  1417. }
  1418. ic->video_codec_id = video_codec_name ? ic->video_codec->id : AV_CODEC_ID_NONE;
  1419. ic->audio_codec_id = audio_codec_name ? ic->audio_codec->id : AV_CODEC_ID_NONE;
  1420. ic->subtitle_codec_id = subtitle_codec_name ? ic->subtitle_codec->id : AV_CODEC_ID_NONE;
  1421. ic->data_codec_id = data_codec_name ? ic->data_codec->id : AV_CODEC_ID_NONE;
  1422. ic->flags |= AVFMT_FLAG_NONBLOCK;
  1423. if (o->bitexact)
  1424. ic->flags |= AVFMT_FLAG_BITEXACT;
  1425. ic->interrupt_callback = int_cb;
  1426. if (!av_dict_get(o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
  1427. av_dict_set(&o->g->format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
  1428. scan_all_pmts_set = 1;
  1429. }
  1430. /* open the input file with generic avformat function */
  1431. err = avformat_open_input(&ic, filename, file_iformat, &o->g->format_opts);
  1432. if (err < 0) {
  1433. if (err != AVERROR_EXIT)
  1434. av_log(d, AV_LOG_ERROR,
  1435. "Error opening input: %s\n", av_err2str(err));
  1436. if (err == AVERROR_PROTOCOL_NOT_FOUND)
  1437. av_log(d, AV_LOG_ERROR, "Did you mean file:%s?\n", filename);
  1438. return err;
  1439. }
  1440. f->ctx = ic;
  1441. av_strlcat(d->log_name, "/", sizeof(d->log_name));
  1442. av_strlcat(d->log_name, ic->iformat->name, sizeof(d->log_name));
  1443. if (scan_all_pmts_set)
  1444. av_dict_set(&o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
  1445. remove_avoptions(&o->g->format_opts, o->g->codec_opts);
  1446. ret = check_avoptions(o->g->format_opts);
  1447. if (ret < 0)
  1448. return ret;
  1449. /* apply forced codec ids */
  1450. for (int i = 0; i < ic->nb_streams; i++) {
  1451. const AVCodec *dummy;
  1452. ret = choose_decoder(o, f, ic, ic->streams[i], HWACCEL_NONE, AV_HWDEVICE_TYPE_NONE,
  1453. &dummy);
  1454. if (ret < 0)
  1455. return ret;
  1456. }
  1457. if (o->find_stream_info) {
  1458. AVDictionary **opts;
  1459. int orig_nb_streams = ic->nb_streams;
  1460. ret = setup_find_stream_info_opts(ic, o->g->codec_opts, &opts);
  1461. if (ret < 0)
  1462. return ret;
  1463. /* If not enough info to get the stream parameters, we decode the
  1464. first frames to get it. (used in mpeg case for example) */
  1465. ret = avformat_find_stream_info(ic, opts);
  1466. for (int i = 0; i < orig_nb_streams; i++)
  1467. av_dict_free(&opts[i]);
  1468. av_freep(&opts);
  1469. if (ret < 0) {
  1470. av_log(d, AV_LOG_FATAL, "could not find codec parameters\n");
  1471. if (ic->nb_streams == 0)
  1472. return ret;
  1473. }
  1474. }
  1475. if (start_time != AV_NOPTS_VALUE && start_time_eof != AV_NOPTS_VALUE) {
  1476. av_log(d, AV_LOG_WARNING, "Cannot use -ss and -sseof both, using -ss\n");
  1477. start_time_eof = AV_NOPTS_VALUE;
  1478. }
  1479. if (start_time_eof != AV_NOPTS_VALUE) {
  1480. if (start_time_eof >= 0) {
  1481. av_log(d, AV_LOG_ERROR, "-sseof value must be negative; aborting\n");
  1482. return AVERROR(EINVAL);
  1483. }
  1484. if (ic->duration > 0) {
  1485. start_time = start_time_eof + ic->duration;
  1486. if (start_time < 0) {
  1487. av_log(d, AV_LOG_WARNING, "-sseof value seeks to before start of file; ignored\n");
  1488. start_time = AV_NOPTS_VALUE;
  1489. }
  1490. } else
  1491. av_log(d, AV_LOG_WARNING, "Cannot use -sseof, file duration not known\n");
  1492. }
  1493. timestamp = (start_time == AV_NOPTS_VALUE) ? 0 : start_time;
  1494. /* add the stream start time */
  1495. if (!o->seek_timestamp && ic->start_time != AV_NOPTS_VALUE)
  1496. timestamp += ic->start_time;
  1497. /* if seeking requested, we execute it */
  1498. if (start_time != AV_NOPTS_VALUE) {
  1499. int64_t seek_timestamp = timestamp;
  1500. if (!(ic->iformat->flags & AVFMT_SEEK_TO_PTS)) {
  1501. int dts_heuristic = 0;
  1502. for (int i = 0; i < ic->nb_streams; i++) {
  1503. const AVCodecParameters *par = ic->streams[i]->codecpar;
  1504. if (par->video_delay) {
  1505. dts_heuristic = 1;
  1506. break;
  1507. }
  1508. }
  1509. if (dts_heuristic) {
  1510. seek_timestamp -= 3*AV_TIME_BASE / 23;
  1511. }
  1512. }
  1513. ret = avformat_seek_file(ic, -1, INT64_MIN, seek_timestamp, seek_timestamp, 0);
  1514. if (ret < 0) {
  1515. av_log(d, AV_LOG_WARNING, "could not seek to position %0.3f\n",
  1516. (double)timestamp / AV_TIME_BASE);
  1517. }
  1518. }
  1519. f->start_time = start_time;
  1520. d->recording_time = recording_time;
  1521. f->input_sync_ref = o->input_sync_ref;
  1522. f->input_ts_offset = o->input_ts_offset;
  1523. f->ts_offset = o->input_ts_offset - (copy_ts ? (start_at_zero && ic->start_time != AV_NOPTS_VALUE ? ic->start_time : 0) : timestamp);
  1524. d->accurate_seek = o->accurate_seek;
  1525. d->loop = o->loop;
  1526. d->nb_streams_warn = ic->nb_streams;
  1527. d->duration = (Timestamp){ .ts = 0, .tb = (AVRational){ 1, 1 } };
  1528. d->min_pts = (Timestamp){ .ts = AV_NOPTS_VALUE, .tb = (AVRational){ 1, 1 } };
  1529. d->max_pts = (Timestamp){ .ts = AV_NOPTS_VALUE, .tb = (AVRational){ 1, 1 } };
  1530. d->readrate = o->readrate ? o->readrate : 0.0;
  1531. if (d->readrate < 0.0f) {
  1532. av_log(d, AV_LOG_ERROR, "Option -readrate is %0.3f; it must be non-negative.\n", d->readrate);
  1533. return AVERROR(EINVAL);
  1534. }
  1535. if (o->rate_emu) {
  1536. if (d->readrate) {
  1537. av_log(d, AV_LOG_WARNING, "Both -readrate and -re set. Using -readrate %0.3f.\n", d->readrate);
  1538. } else
  1539. d->readrate = 1.0f;
  1540. }
  1541. if (d->readrate) {
  1542. d->readrate_initial_burst = o->readrate_initial_burst ? o->readrate_initial_burst : 0.5;
  1543. if (d->readrate_initial_burst < 0.0) {
  1544. av_log(d, AV_LOG_ERROR,
  1545. "Option -readrate_initial_burst is %0.3f; it must be non-negative.\n",
  1546. d->readrate_initial_burst);
  1547. return AVERROR(EINVAL);
  1548. }
  1549. } else if (o->readrate_initial_burst) {
  1550. av_log(d, AV_LOG_WARNING, "Option -readrate_initial_burst ignored "
  1551. "since neither -readrate nor -re were given\n");
  1552. }
  1553. /* Add all the streams from the given input file to the demuxer */
  1554. for (int i = 0; i < ic->nb_streams; i++) {
  1555. ret = ist_add(o, d, ic->streams[i], &opts_used);
  1556. if (ret < 0) {
  1557. av_dict_free(&opts_used);
  1558. return ret;
  1559. }
  1560. }
  1561. /* dump the file content */
  1562. av_dump_format(ic, f->index, filename, 0);
  1563. /* check if all codec options have been used */
  1564. ret = check_avoptions_used(o->g->codec_opts, opts_used, d, 1);
  1565. av_dict_free(&opts_used);
  1566. if (ret < 0)
  1567. return ret;
  1568. for (int i = 0; i < o->dump_attachment.nb_opt; i++) {
  1569. for (int j = 0; j < f->nb_streams; j++) {
  1570. InputStream *ist = f->streams[j];
  1571. if (check_stream_specifier(ic, ist->st, o->dump_attachment.opt[i].specifier) == 1) {
  1572. ret = dump_attachment(ist, o->dump_attachment.opt[i].u.str);
  1573. if (ret < 0)
  1574. return ret;
  1575. }
  1576. }
  1577. }
  1578. return 0;
  1579. }