ffmpeg_demux.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  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, AVDictionary **opts_used)
  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, opts_used);
  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 *opts_used = NULL;
  1276. const char* video_codec_name = NULL;
  1277. const char* audio_codec_name = NULL;
  1278. const char* subtitle_codec_name = NULL;
  1279. const char* data_codec_name = NULL;
  1280. int scan_all_pmts_set = 0;
  1281. int64_t start_time = o->start_time;
  1282. int64_t start_time_eof = o->start_time_eof;
  1283. int64_t stop_time = o->stop_time;
  1284. int64_t recording_time = o->recording_time;
  1285. d = demux_alloc();
  1286. if (!d)
  1287. return AVERROR(ENOMEM);
  1288. f = &d->f;
  1289. ret = sch_add_demux(sch, input_thread, d);
  1290. if (ret < 0)
  1291. return ret;
  1292. d->sch = sch;
  1293. if (stop_time != INT64_MAX && recording_time != INT64_MAX) {
  1294. stop_time = INT64_MAX;
  1295. av_log(d, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
  1296. }
  1297. if (stop_time != INT64_MAX && recording_time == INT64_MAX) {
  1298. int64_t start = start_time == AV_NOPTS_VALUE ? 0 : start_time;
  1299. if (stop_time <= start) {
  1300. av_log(d, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
  1301. return AVERROR(EINVAL);
  1302. } else {
  1303. recording_time = stop_time - start;
  1304. }
  1305. }
  1306. if (o->format) {
  1307. if (!(file_iformat = av_find_input_format(o->format))) {
  1308. av_log(d, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
  1309. return AVERROR(EINVAL);
  1310. }
  1311. }
  1312. if (!strcmp(filename, "-"))
  1313. filename = "fd:";
  1314. stdin_interaction &= strncmp(filename, "pipe:", 5) &&
  1315. strcmp(filename, "fd:") &&
  1316. strcmp(filename, "/dev/stdin");
  1317. /* get default parameters from command line */
  1318. ic = avformat_alloc_context();
  1319. if (!ic)
  1320. return AVERROR(ENOMEM);
  1321. if (o->audio_sample_rate.nb_opt) {
  1322. 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);
  1323. }
  1324. if (o->audio_channels.nb_opt) {
  1325. const AVClass *priv_class;
  1326. if (file_iformat && (priv_class = file_iformat->priv_class) &&
  1327. av_opt_find(&priv_class, "ch_layout", NULL, 0,
  1328. AV_OPT_SEARCH_FAKE_OBJ)) {
  1329. char buf[32];
  1330. snprintf(buf, sizeof(buf), "%dC", o->audio_channels.opt[o->audio_channels.nb_opt - 1].u.i);
  1331. av_dict_set(&o->g->format_opts, "ch_layout", buf, 0);
  1332. }
  1333. }
  1334. if (o->audio_ch_layouts.nb_opt) {
  1335. const AVClass *priv_class;
  1336. if (file_iformat && (priv_class = file_iformat->priv_class) &&
  1337. av_opt_find(&priv_class, "ch_layout", NULL, 0,
  1338. AV_OPT_SEARCH_FAKE_OBJ)) {
  1339. av_dict_set(&o->g->format_opts, "ch_layout", o->audio_ch_layouts.opt[o->audio_ch_layouts.nb_opt - 1].u.str, 0);
  1340. }
  1341. }
  1342. if (o->frame_rates.nb_opt) {
  1343. const AVClass *priv_class;
  1344. /* set the format-level framerate option;
  1345. * this is important for video grabbers, e.g. x11 */
  1346. if (file_iformat && (priv_class = file_iformat->priv_class) &&
  1347. av_opt_find(&priv_class, "framerate", NULL, 0,
  1348. AV_OPT_SEARCH_FAKE_OBJ)) {
  1349. av_dict_set(&o->g->format_opts, "framerate",
  1350. o->frame_rates.opt[o->frame_rates.nb_opt - 1].u.str, 0);
  1351. }
  1352. }
  1353. if (o->frame_sizes.nb_opt) {
  1354. av_dict_set(&o->g->format_opts, "video_size", o->frame_sizes.opt[o->frame_sizes.nb_opt - 1].u.str, 0);
  1355. }
  1356. if (o->frame_pix_fmts.nb_opt)
  1357. av_dict_set(&o->g->format_opts, "pixel_format", o->frame_pix_fmts.opt[o->frame_pix_fmts.nb_opt - 1].u.str, 0);
  1358. video_codec_name = opt_match_per_type_str(&o->codec_names, 'v');
  1359. audio_codec_name = opt_match_per_type_str(&o->codec_names, 'a');
  1360. subtitle_codec_name = opt_match_per_type_str(&o->codec_names, 's');
  1361. data_codec_name = opt_match_per_type_str(&o->codec_names, 'd');
  1362. if (video_codec_name)
  1363. ret = err_merge(ret, find_codec(NULL, video_codec_name , AVMEDIA_TYPE_VIDEO , 0,
  1364. &ic->video_codec));
  1365. if (audio_codec_name)
  1366. ret = err_merge(ret, find_codec(NULL, audio_codec_name , AVMEDIA_TYPE_AUDIO , 0,
  1367. &ic->audio_codec));
  1368. if (subtitle_codec_name)
  1369. ret = err_merge(ret, find_codec(NULL, subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0,
  1370. &ic->subtitle_codec));
  1371. if (data_codec_name)
  1372. ret = err_merge(ret, find_codec(NULL, data_codec_name , AVMEDIA_TYPE_DATA, 0,
  1373. &ic->data_codec));
  1374. if (ret < 0) {
  1375. avformat_free_context(ic);
  1376. return ret;
  1377. }
  1378. ic->video_codec_id = video_codec_name ? ic->video_codec->id : AV_CODEC_ID_NONE;
  1379. ic->audio_codec_id = audio_codec_name ? ic->audio_codec->id : AV_CODEC_ID_NONE;
  1380. ic->subtitle_codec_id = subtitle_codec_name ? ic->subtitle_codec->id : AV_CODEC_ID_NONE;
  1381. ic->data_codec_id = data_codec_name ? ic->data_codec->id : AV_CODEC_ID_NONE;
  1382. ic->flags |= AVFMT_FLAG_NONBLOCK;
  1383. if (o->bitexact)
  1384. ic->flags |= AVFMT_FLAG_BITEXACT;
  1385. ic->interrupt_callback = int_cb;
  1386. if (!av_dict_get(o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
  1387. av_dict_set(&o->g->format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
  1388. scan_all_pmts_set = 1;
  1389. }
  1390. /* open the input file with generic avformat function */
  1391. err = avformat_open_input(&ic, filename, file_iformat, &o->g->format_opts);
  1392. if (err < 0) {
  1393. av_log(d, AV_LOG_ERROR,
  1394. "Error opening input: %s\n", av_err2str(err));
  1395. if (err == AVERROR_PROTOCOL_NOT_FOUND)
  1396. av_log(d, AV_LOG_ERROR, "Did you mean file:%s?\n", filename);
  1397. return err;
  1398. }
  1399. f->ctx = ic;
  1400. av_strlcat(d->log_name, "/", sizeof(d->log_name));
  1401. av_strlcat(d->log_name, ic->iformat->name, sizeof(d->log_name));
  1402. if (scan_all_pmts_set)
  1403. av_dict_set(&o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
  1404. remove_avoptions(&o->g->format_opts, o->g->codec_opts);
  1405. ret = check_avoptions(o->g->format_opts);
  1406. if (ret < 0)
  1407. return ret;
  1408. /* apply forced codec ids */
  1409. for (i = 0; i < ic->nb_streams; i++) {
  1410. const AVCodec *dummy;
  1411. ret = choose_decoder(o, ic, ic->streams[i], HWACCEL_NONE, AV_HWDEVICE_TYPE_NONE,
  1412. &dummy);
  1413. if (ret < 0)
  1414. return ret;
  1415. }
  1416. if (o->find_stream_info) {
  1417. AVDictionary **opts;
  1418. int orig_nb_streams = ic->nb_streams;
  1419. ret = setup_find_stream_info_opts(ic, o->g->codec_opts, &opts);
  1420. if (ret < 0)
  1421. return ret;
  1422. /* If not enough info to get the stream parameters, we decode the
  1423. first frames to get it. (used in mpeg case for example) */
  1424. ret = avformat_find_stream_info(ic, opts);
  1425. for (i = 0; i < orig_nb_streams; i++)
  1426. av_dict_free(&opts[i]);
  1427. av_freep(&opts);
  1428. if (ret < 0) {
  1429. av_log(d, AV_LOG_FATAL, "could not find codec parameters\n");
  1430. if (ic->nb_streams == 0)
  1431. return ret;
  1432. }
  1433. }
  1434. if (start_time != AV_NOPTS_VALUE && start_time_eof != AV_NOPTS_VALUE) {
  1435. av_log(d, AV_LOG_WARNING, "Cannot use -ss and -sseof both, using -ss\n");
  1436. start_time_eof = AV_NOPTS_VALUE;
  1437. }
  1438. if (start_time_eof != AV_NOPTS_VALUE) {
  1439. if (start_time_eof >= 0) {
  1440. av_log(d, AV_LOG_ERROR, "-sseof value must be negative; aborting\n");
  1441. return AVERROR(EINVAL);
  1442. }
  1443. if (ic->duration > 0) {
  1444. start_time = start_time_eof + ic->duration;
  1445. if (start_time < 0) {
  1446. av_log(d, AV_LOG_WARNING, "-sseof value seeks to before start of file; ignored\n");
  1447. start_time = AV_NOPTS_VALUE;
  1448. }
  1449. } else
  1450. av_log(d, AV_LOG_WARNING, "Cannot use -sseof, file duration not known\n");
  1451. }
  1452. timestamp = (start_time == AV_NOPTS_VALUE) ? 0 : start_time;
  1453. /* add the stream start time */
  1454. if (!o->seek_timestamp && ic->start_time != AV_NOPTS_VALUE)
  1455. timestamp += ic->start_time;
  1456. /* if seeking requested, we execute it */
  1457. if (start_time != AV_NOPTS_VALUE) {
  1458. int64_t seek_timestamp = timestamp;
  1459. if (!(ic->iformat->flags & AVFMT_SEEK_TO_PTS)) {
  1460. int dts_heuristic = 0;
  1461. for (i=0; i<ic->nb_streams; i++) {
  1462. const AVCodecParameters *par = ic->streams[i]->codecpar;
  1463. if (par->video_delay) {
  1464. dts_heuristic = 1;
  1465. break;
  1466. }
  1467. }
  1468. if (dts_heuristic) {
  1469. seek_timestamp -= 3*AV_TIME_BASE / 23;
  1470. }
  1471. }
  1472. ret = avformat_seek_file(ic, -1, INT64_MIN, seek_timestamp, seek_timestamp, 0);
  1473. if (ret < 0) {
  1474. av_log(d, AV_LOG_WARNING, "could not seek to position %0.3f\n",
  1475. (double)timestamp / AV_TIME_BASE);
  1476. }
  1477. }
  1478. f->start_time = start_time;
  1479. d->recording_time = recording_time;
  1480. f->input_sync_ref = o->input_sync_ref;
  1481. f->input_ts_offset = o->input_ts_offset;
  1482. f->ts_offset = o->input_ts_offset - (copy_ts ? (start_at_zero && ic->start_time != AV_NOPTS_VALUE ? ic->start_time : 0) : timestamp);
  1483. d->accurate_seek = o->accurate_seek;
  1484. d->loop = o->loop;
  1485. d->nb_streams_warn = ic->nb_streams;
  1486. d->duration = (Timestamp){ .ts = 0, .tb = (AVRational){ 1, 1 } };
  1487. d->min_pts = (Timestamp){ .ts = AV_NOPTS_VALUE, .tb = (AVRational){ 1, 1 } };
  1488. d->max_pts = (Timestamp){ .ts = AV_NOPTS_VALUE, .tb = (AVRational){ 1, 1 } };
  1489. d->readrate = o->readrate ? o->readrate : 0.0;
  1490. if (d->readrate < 0.0f) {
  1491. av_log(d, AV_LOG_ERROR, "Option -readrate is %0.3f; it must be non-negative.\n", d->readrate);
  1492. return AVERROR(EINVAL);
  1493. }
  1494. if (o->rate_emu) {
  1495. if (d->readrate) {
  1496. av_log(d, AV_LOG_WARNING, "Both -readrate and -re set. Using -readrate %0.3f.\n", d->readrate);
  1497. } else
  1498. d->readrate = 1.0f;
  1499. }
  1500. if (d->readrate) {
  1501. d->readrate_initial_burst = o->readrate_initial_burst ? o->readrate_initial_burst : 0.5;
  1502. if (d->readrate_initial_burst < 0.0) {
  1503. av_log(d, AV_LOG_ERROR,
  1504. "Option -readrate_initial_burst is %0.3f; it must be non-negative.\n",
  1505. d->readrate_initial_burst);
  1506. return AVERROR(EINVAL);
  1507. }
  1508. } else if (o->readrate_initial_burst) {
  1509. av_log(d, AV_LOG_WARNING, "Option -readrate_initial_burst ignored "
  1510. "since neither -readrate nor -re were given\n");
  1511. }
  1512. /* Add all the streams from the given input file to the demuxer */
  1513. for (int i = 0; i < ic->nb_streams; i++) {
  1514. ret = ist_add(o, d, ic->streams[i], &opts_used);
  1515. if (ret < 0) {
  1516. av_dict_free(&opts_used);
  1517. return ret;
  1518. }
  1519. }
  1520. /* dump the file content */
  1521. av_dump_format(ic, f->index, filename, 0);
  1522. /* check if all codec options have been used */
  1523. ret = check_avoptions_used(o->g->codec_opts, opts_used, d, 1);
  1524. av_dict_free(&opts_used);
  1525. if (ret < 0)
  1526. return ret;
  1527. for (i = 0; i < o->dump_attachment.nb_opt; i++) {
  1528. int j;
  1529. for (j = 0; j < f->nb_streams; j++) {
  1530. InputStream *ist = f->streams[j];
  1531. if (check_stream_specifier(ic, ist->st, o->dump_attachment.opt[i].specifier) == 1) {
  1532. ret = dump_attachment(ist, o->dump_attachment.opt[i].u.str);
  1533. if (ret < 0)
  1534. return ret;
  1535. }
  1536. }
  1537. }
  1538. return 0;
  1539. }