ffmpeg_demux.c 65 KB

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