ffmpeg_demux.c 64 KB

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