ffmpeg_demux.c 68 KB

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