ffmpeg_dec.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  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 "libavutil/avassert.h"
  19. #include "libavutil/avstring.h"
  20. #include "libavutil/dict.h"
  21. #include "libavutil/error.h"
  22. #include "libavutil/log.h"
  23. #include "libavutil/mem.h"
  24. #include "libavutil/opt.h"
  25. #include "libavutil/pixdesc.h"
  26. #include "libavutil/pixfmt.h"
  27. #include "libavutil/time.h"
  28. #include "libavutil/timestamp.h"
  29. #include "libavcodec/avcodec.h"
  30. #include "libavcodec/codec.h"
  31. #include "ffmpeg.h"
  32. typedef struct DecoderPriv {
  33. Decoder dec;
  34. AVCodecContext *dec_ctx;
  35. AVFrame *frame;
  36. AVPacket *pkt;
  37. // override output video sample aspect ratio with this value
  38. AVRational sar_override;
  39. AVRational framerate_in;
  40. // a combination of DECODER_FLAG_*, provided to dec_open()
  41. int flags;
  42. int apply_cropping;
  43. enum AVPixelFormat hwaccel_pix_fmt;
  44. enum HWAccelID hwaccel_id;
  45. enum AVHWDeviceType hwaccel_device_type;
  46. enum AVPixelFormat hwaccel_output_format;
  47. // pts/estimated duration of the last decoded frame
  48. // * in decoder timebase for video,
  49. // * in last_frame_tb (may change during decoding) for audio
  50. int64_t last_frame_pts;
  51. int64_t last_frame_duration_est;
  52. AVRational last_frame_tb;
  53. int64_t last_filter_in_rescale_delta;
  54. int last_frame_sample_rate;
  55. /* previous decoded subtitles */
  56. AVFrame *sub_prev[2];
  57. AVFrame *sub_heartbeat;
  58. Scheduler *sch;
  59. unsigned sch_idx;
  60. // this decoder's index in decoders or -1
  61. int index;
  62. void *log_parent;
  63. char log_name[32];
  64. char *parent_name;
  65. struct {
  66. AVDictionary *opts;
  67. const AVCodec *codec;
  68. } standalone_init;
  69. } DecoderPriv;
  70. static DecoderPriv *dp_from_dec(Decoder *d)
  71. {
  72. return (DecoderPriv*)d;
  73. }
  74. // data that is local to the decoder thread and not visible outside of it
  75. typedef struct DecThreadContext {
  76. AVFrame *frame;
  77. AVPacket *pkt;
  78. } DecThreadContext;
  79. void dec_free(Decoder **pdec)
  80. {
  81. Decoder *dec = *pdec;
  82. DecoderPriv *dp;
  83. if (!dec)
  84. return;
  85. dp = dp_from_dec(dec);
  86. avcodec_free_context(&dp->dec_ctx);
  87. av_frame_free(&dp->frame);
  88. av_packet_free(&dp->pkt);
  89. av_dict_free(&dp->standalone_init.opts);
  90. for (int i = 0; i < FF_ARRAY_ELEMS(dp->sub_prev); i++)
  91. av_frame_free(&dp->sub_prev[i]);
  92. av_frame_free(&dp->sub_heartbeat);
  93. av_freep(&dp->parent_name);
  94. av_freep(pdec);
  95. }
  96. static const char *dec_item_name(void *obj)
  97. {
  98. const DecoderPriv *dp = obj;
  99. return dp->log_name;
  100. }
  101. static const AVClass dec_class = {
  102. .class_name = "Decoder",
  103. .version = LIBAVUTIL_VERSION_INT,
  104. .parent_log_context_offset = offsetof(DecoderPriv, log_parent),
  105. .item_name = dec_item_name,
  106. };
  107. static int decoder_thread(void *arg);
  108. static int dec_alloc(DecoderPriv **pdec, Scheduler *sch, int send_end_ts)
  109. {
  110. DecoderPriv *dp;
  111. int ret = 0;
  112. *pdec = NULL;
  113. dp = av_mallocz(sizeof(*dp));
  114. if (!dp)
  115. return AVERROR(ENOMEM);
  116. dp->frame = av_frame_alloc();
  117. if (!dp->frame)
  118. goto fail;
  119. dp->pkt = av_packet_alloc();
  120. if (!dp->pkt)
  121. goto fail;
  122. dp->index = -1;
  123. dp->dec.class = &dec_class;
  124. dp->last_filter_in_rescale_delta = AV_NOPTS_VALUE;
  125. dp->last_frame_pts = AV_NOPTS_VALUE;
  126. dp->last_frame_tb = (AVRational){ 1, 1 };
  127. dp->hwaccel_pix_fmt = AV_PIX_FMT_NONE;
  128. ret = sch_add_dec(sch, decoder_thread, dp, send_end_ts);
  129. if (ret < 0)
  130. goto fail;
  131. dp->sch = sch;
  132. dp->sch_idx = ret;
  133. *pdec = dp;
  134. return 0;
  135. fail:
  136. dec_free((Decoder**)&dp);
  137. return ret >= 0 ? AVERROR(ENOMEM) : ret;
  138. }
  139. static AVRational audio_samplerate_update(DecoderPriv *dp,
  140. const AVFrame *frame)
  141. {
  142. const int prev = dp->last_frame_tb.den;
  143. const int sr = frame->sample_rate;
  144. AVRational tb_new;
  145. int64_t gcd;
  146. if (frame->sample_rate == dp->last_frame_sample_rate)
  147. goto finish;
  148. gcd = av_gcd(prev, sr);
  149. if (prev / gcd >= INT_MAX / sr) {
  150. av_log(dp, AV_LOG_WARNING,
  151. "Audio timestamps cannot be represented exactly after "
  152. "sample rate change: %d -> %d\n", prev, sr);
  153. // LCM of 192000, 44100, allows to represent all common samplerates
  154. tb_new = (AVRational){ 1, 28224000 };
  155. } else
  156. tb_new = (AVRational){ 1, prev / gcd * sr };
  157. // keep the frame timebase if it is strictly better than
  158. // the samplerate-defined one
  159. if (frame->time_base.num == 1 && frame->time_base.den > tb_new.den &&
  160. !(frame->time_base.den % tb_new.den))
  161. tb_new = frame->time_base;
  162. if (dp->last_frame_pts != AV_NOPTS_VALUE)
  163. dp->last_frame_pts = av_rescale_q(dp->last_frame_pts,
  164. dp->last_frame_tb, tb_new);
  165. dp->last_frame_duration_est = av_rescale_q(dp->last_frame_duration_est,
  166. dp->last_frame_tb, tb_new);
  167. dp->last_frame_tb = tb_new;
  168. dp->last_frame_sample_rate = frame->sample_rate;
  169. finish:
  170. return dp->last_frame_tb;
  171. }
  172. static void audio_ts_process(DecoderPriv *dp, AVFrame *frame)
  173. {
  174. AVRational tb_filter = (AVRational){1, frame->sample_rate};
  175. AVRational tb;
  176. int64_t pts_pred;
  177. // on samplerate change, choose a new internal timebase for timestamp
  178. // generation that can represent timestamps from all the samplerates
  179. // seen so far
  180. tb = audio_samplerate_update(dp, frame);
  181. pts_pred = dp->last_frame_pts == AV_NOPTS_VALUE ? 0 :
  182. dp->last_frame_pts + dp->last_frame_duration_est;
  183. if (frame->pts == AV_NOPTS_VALUE) {
  184. frame->pts = pts_pred;
  185. frame->time_base = tb;
  186. } else if (dp->last_frame_pts != AV_NOPTS_VALUE &&
  187. frame->pts > av_rescale_q_rnd(pts_pred, tb, frame->time_base,
  188. AV_ROUND_UP)) {
  189. // there was a gap in timestamps, reset conversion state
  190. dp->last_filter_in_rescale_delta = AV_NOPTS_VALUE;
  191. }
  192. frame->pts = av_rescale_delta(frame->time_base, frame->pts,
  193. tb, frame->nb_samples,
  194. &dp->last_filter_in_rescale_delta, tb);
  195. dp->last_frame_pts = frame->pts;
  196. dp->last_frame_duration_est = av_rescale_q(frame->nb_samples,
  197. tb_filter, tb);
  198. // finally convert to filtering timebase
  199. frame->pts = av_rescale_q(frame->pts, tb, tb_filter);
  200. frame->duration = frame->nb_samples;
  201. frame->time_base = tb_filter;
  202. }
  203. static int64_t video_duration_estimate(const DecoderPriv *dp, const AVFrame *frame)
  204. {
  205. const int ts_unreliable = dp->flags & DECODER_FLAG_TS_UNRELIABLE;
  206. const int fr_forced = dp->flags & DECODER_FLAG_FRAMERATE_FORCED;
  207. int64_t codec_duration = 0;
  208. // difference between this and last frame's timestamps
  209. const int64_t ts_diff =
  210. (frame->pts != AV_NOPTS_VALUE && dp->last_frame_pts != AV_NOPTS_VALUE) ?
  211. frame->pts - dp->last_frame_pts : -1;
  212. // XXX lavf currently makes up frame durations when they are not provided by
  213. // the container. As there is no way to reliably distinguish real container
  214. // durations from the fake made-up ones, we use heuristics based on whether
  215. // the container has timestamps. Eventually lavf should stop making up
  216. // durations, then this should be simplified.
  217. // frame duration is unreliable (typically guessed by lavf) when it is equal
  218. // to 1 and the actual duration of the last frame is more than 2x larger
  219. const int duration_unreliable = frame->duration == 1 && ts_diff > 2 * frame->duration;
  220. // prefer frame duration for containers with timestamps
  221. if (fr_forced ||
  222. (frame->duration > 0 && !ts_unreliable && !duration_unreliable))
  223. return frame->duration;
  224. if (dp->dec_ctx->framerate.den && dp->dec_ctx->framerate.num) {
  225. int fields = frame->repeat_pict + 2;
  226. AVRational field_rate = av_mul_q(dp->dec_ctx->framerate,
  227. (AVRational){ 2, 1 });
  228. codec_duration = av_rescale_q(fields, av_inv_q(field_rate),
  229. frame->time_base);
  230. }
  231. // prefer codec-layer duration for containers without timestamps
  232. if (codec_duration > 0 && ts_unreliable)
  233. return codec_duration;
  234. // when timestamps are available, repeat last frame's actual duration
  235. // (i.e. pts difference between this and last frame)
  236. if (ts_diff > 0)
  237. return ts_diff;
  238. // try frame/codec duration
  239. if (frame->duration > 0)
  240. return frame->duration;
  241. if (codec_duration > 0)
  242. return codec_duration;
  243. // try average framerate
  244. if (dp->framerate_in.num && dp->framerate_in.den) {
  245. int64_t d = av_rescale_q(1, av_inv_q(dp->framerate_in),
  246. frame->time_base);
  247. if (d > 0)
  248. return d;
  249. }
  250. // last resort is last frame's estimated duration, and 1
  251. return FFMAX(dp->last_frame_duration_est, 1);
  252. }
  253. static int hwaccel_retrieve_data(AVCodecContext *avctx, AVFrame *input)
  254. {
  255. DecoderPriv *dp = avctx->opaque;
  256. AVFrame *output = NULL;
  257. enum AVPixelFormat output_format = dp->hwaccel_output_format;
  258. int err;
  259. if (input->format == output_format) {
  260. // Nothing to do.
  261. return 0;
  262. }
  263. output = av_frame_alloc();
  264. if (!output)
  265. return AVERROR(ENOMEM);
  266. output->format = output_format;
  267. err = av_hwframe_transfer_data(output, input, 0);
  268. if (err < 0) {
  269. av_log(avctx, AV_LOG_ERROR, "Failed to transfer data to "
  270. "output frame: %d.\n", err);
  271. goto fail;
  272. }
  273. err = av_frame_copy_props(output, input);
  274. if (err < 0) {
  275. av_frame_unref(output);
  276. goto fail;
  277. }
  278. av_frame_unref(input);
  279. av_frame_move_ref(input, output);
  280. av_frame_free(&output);
  281. return 0;
  282. fail:
  283. av_frame_free(&output);
  284. return err;
  285. }
  286. static int video_frame_process(DecoderPriv *dp, AVFrame *frame)
  287. {
  288. #if FFMPEG_OPT_TOP
  289. if (dp->flags & DECODER_FLAG_TOP_FIELD_FIRST) {
  290. av_log(dp, AV_LOG_WARNING, "-top is deprecated, use the setfield filter instead\n");
  291. frame->flags |= AV_FRAME_FLAG_TOP_FIELD_FIRST;
  292. }
  293. #endif
  294. if (frame->format == dp->hwaccel_pix_fmt) {
  295. int err = hwaccel_retrieve_data(dp->dec_ctx, frame);
  296. if (err < 0)
  297. return err;
  298. }
  299. frame->pts = frame->best_effort_timestamp;
  300. // forced fixed framerate
  301. if (dp->flags & DECODER_FLAG_FRAMERATE_FORCED) {
  302. frame->pts = AV_NOPTS_VALUE;
  303. frame->duration = 1;
  304. frame->time_base = av_inv_q(dp->framerate_in);
  305. }
  306. // no timestamp available - extrapolate from previous frame duration
  307. if (frame->pts == AV_NOPTS_VALUE)
  308. frame->pts = dp->last_frame_pts == AV_NOPTS_VALUE ? 0 :
  309. dp->last_frame_pts + dp->last_frame_duration_est;
  310. // update timestamp history
  311. dp->last_frame_duration_est = video_duration_estimate(dp, frame);
  312. dp->last_frame_pts = frame->pts;
  313. dp->last_frame_tb = frame->time_base;
  314. if (debug_ts) {
  315. av_log(dp, AV_LOG_INFO,
  316. "decoder -> pts:%s pts_time:%s "
  317. "pkt_dts:%s pkt_dts_time:%s "
  318. "duration:%s duration_time:%s "
  319. "keyframe:%d frame_type:%d time_base:%d/%d\n",
  320. av_ts2str(frame->pts),
  321. av_ts2timestr(frame->pts, &frame->time_base),
  322. av_ts2str(frame->pkt_dts),
  323. av_ts2timestr(frame->pkt_dts, &frame->time_base),
  324. av_ts2str(frame->duration),
  325. av_ts2timestr(frame->duration, &frame->time_base),
  326. !!(frame->flags & AV_FRAME_FLAG_KEY), frame->pict_type,
  327. frame->time_base.num, frame->time_base.den);
  328. }
  329. if (dp->sar_override.num)
  330. frame->sample_aspect_ratio = dp->sar_override;
  331. if (dp->apply_cropping) {
  332. // lavfi does not require aligned frame data
  333. int ret = av_frame_apply_cropping(frame, AV_FRAME_CROP_UNALIGNED);
  334. if (ret < 0) {
  335. av_log(dp, AV_LOG_ERROR, "Error applying decoder cropping\n");
  336. return ret;
  337. }
  338. }
  339. return 0;
  340. }
  341. static int copy_av_subtitle(AVSubtitle *dst, const AVSubtitle *src)
  342. {
  343. int ret = AVERROR_BUG;
  344. AVSubtitle tmp = {
  345. .format = src->format,
  346. .start_display_time = src->start_display_time,
  347. .end_display_time = src->end_display_time,
  348. .num_rects = 0,
  349. .rects = NULL,
  350. .pts = src->pts
  351. };
  352. if (!src->num_rects)
  353. goto success;
  354. if (!(tmp.rects = av_calloc(src->num_rects, sizeof(*tmp.rects))))
  355. return AVERROR(ENOMEM);
  356. for (int i = 0; i < src->num_rects; i++) {
  357. AVSubtitleRect *src_rect = src->rects[i];
  358. AVSubtitleRect *dst_rect;
  359. if (!(dst_rect = tmp.rects[i] = av_mallocz(sizeof(*tmp.rects[0])))) {
  360. ret = AVERROR(ENOMEM);
  361. goto cleanup;
  362. }
  363. tmp.num_rects++;
  364. dst_rect->type = src_rect->type;
  365. dst_rect->flags = src_rect->flags;
  366. dst_rect->x = src_rect->x;
  367. dst_rect->y = src_rect->y;
  368. dst_rect->w = src_rect->w;
  369. dst_rect->h = src_rect->h;
  370. dst_rect->nb_colors = src_rect->nb_colors;
  371. if (src_rect->text)
  372. if (!(dst_rect->text = av_strdup(src_rect->text))) {
  373. ret = AVERROR(ENOMEM);
  374. goto cleanup;
  375. }
  376. if (src_rect->ass)
  377. if (!(dst_rect->ass = av_strdup(src_rect->ass))) {
  378. ret = AVERROR(ENOMEM);
  379. goto cleanup;
  380. }
  381. for (int j = 0; j < 4; j++) {
  382. // SUBTITLE_BITMAP images are special in the sense that they
  383. // are like PAL8 images. first pointer to data, second to
  384. // palette. This makes the size calculation match this.
  385. size_t buf_size = src_rect->type == SUBTITLE_BITMAP && j == 1 ?
  386. AVPALETTE_SIZE :
  387. src_rect->h * src_rect->linesize[j];
  388. if (!src_rect->data[j])
  389. continue;
  390. if (!(dst_rect->data[j] = av_memdup(src_rect->data[j], buf_size))) {
  391. ret = AVERROR(ENOMEM);
  392. goto cleanup;
  393. }
  394. dst_rect->linesize[j] = src_rect->linesize[j];
  395. }
  396. }
  397. success:
  398. *dst = tmp;
  399. return 0;
  400. cleanup:
  401. avsubtitle_free(&tmp);
  402. return ret;
  403. }
  404. static void subtitle_free(void *opaque, uint8_t *data)
  405. {
  406. AVSubtitle *sub = (AVSubtitle*)data;
  407. avsubtitle_free(sub);
  408. av_free(sub);
  409. }
  410. static int subtitle_wrap_frame(AVFrame *frame, AVSubtitle *subtitle, int copy)
  411. {
  412. AVBufferRef *buf;
  413. AVSubtitle *sub;
  414. int ret;
  415. if (copy) {
  416. sub = av_mallocz(sizeof(*sub));
  417. ret = sub ? copy_av_subtitle(sub, subtitle) : AVERROR(ENOMEM);
  418. if (ret < 0) {
  419. av_freep(&sub);
  420. return ret;
  421. }
  422. } else {
  423. sub = av_memdup(subtitle, sizeof(*subtitle));
  424. if (!sub)
  425. return AVERROR(ENOMEM);
  426. memset(subtitle, 0, sizeof(*subtitle));
  427. }
  428. buf = av_buffer_create((uint8_t*)sub, sizeof(*sub),
  429. subtitle_free, NULL, 0);
  430. if (!buf) {
  431. avsubtitle_free(sub);
  432. av_freep(&sub);
  433. return AVERROR(ENOMEM);
  434. }
  435. frame->buf[0] = buf;
  436. return 0;
  437. }
  438. static int process_subtitle(DecoderPriv *dp, AVFrame *frame)
  439. {
  440. const AVSubtitle *subtitle = (AVSubtitle*)frame->buf[0]->data;
  441. int ret = 0;
  442. if (dp->flags & DECODER_FLAG_FIX_SUB_DURATION) {
  443. AVSubtitle *sub_prev = dp->sub_prev[0]->buf[0] ?
  444. (AVSubtitle*)dp->sub_prev[0]->buf[0]->data : NULL;
  445. int end = 1;
  446. if (sub_prev) {
  447. end = av_rescale(subtitle->pts - sub_prev->pts,
  448. 1000, AV_TIME_BASE);
  449. if (end < sub_prev->end_display_time) {
  450. av_log(dp, AV_LOG_DEBUG,
  451. "Subtitle duration reduced from %"PRId32" to %d%s\n",
  452. sub_prev->end_display_time, end,
  453. end <= 0 ? ", dropping it" : "");
  454. sub_prev->end_display_time = end;
  455. }
  456. }
  457. av_frame_unref(dp->sub_prev[1]);
  458. av_frame_move_ref(dp->sub_prev[1], frame);
  459. frame = dp->sub_prev[0];
  460. subtitle = frame->buf[0] ? (AVSubtitle*)frame->buf[0]->data : NULL;
  461. FFSWAP(AVFrame*, dp->sub_prev[0], dp->sub_prev[1]);
  462. if (end <= 0)
  463. return 0;
  464. }
  465. if (!subtitle)
  466. return 0;
  467. ret = sch_dec_send(dp->sch, dp->sch_idx, frame);
  468. if (ret < 0)
  469. av_frame_unref(frame);
  470. return ret == AVERROR_EOF ? AVERROR_EXIT : ret;
  471. }
  472. static int fix_sub_duration_heartbeat(DecoderPriv *dp, int64_t signal_pts)
  473. {
  474. int ret = AVERROR_BUG;
  475. AVSubtitle *prev_subtitle = dp->sub_prev[0]->buf[0] ?
  476. (AVSubtitle*)dp->sub_prev[0]->buf[0]->data : NULL;
  477. AVSubtitle *subtitle;
  478. if (!(dp->flags & DECODER_FLAG_FIX_SUB_DURATION) || !prev_subtitle ||
  479. !prev_subtitle->num_rects || signal_pts <= prev_subtitle->pts)
  480. return 0;
  481. av_frame_unref(dp->sub_heartbeat);
  482. ret = subtitle_wrap_frame(dp->sub_heartbeat, prev_subtitle, 1);
  483. if (ret < 0)
  484. return ret;
  485. subtitle = (AVSubtitle*)dp->sub_heartbeat->buf[0]->data;
  486. subtitle->pts = signal_pts;
  487. return process_subtitle(dp, dp->sub_heartbeat);
  488. }
  489. static int transcode_subtitles(DecoderPriv *dp, const AVPacket *pkt,
  490. AVFrame *frame)
  491. {
  492. AVPacket *flush_pkt = NULL;
  493. AVSubtitle subtitle;
  494. int got_output;
  495. int ret;
  496. if (pkt && (intptr_t)pkt->opaque == PKT_OPAQUE_SUB_HEARTBEAT) {
  497. frame->pts = pkt->pts;
  498. frame->time_base = pkt->time_base;
  499. frame->opaque = (void*)(intptr_t)FRAME_OPAQUE_SUB_HEARTBEAT;
  500. ret = sch_dec_send(dp->sch, dp->sch_idx, frame);
  501. return ret == AVERROR_EOF ? AVERROR_EXIT : ret;
  502. } else if (pkt && (intptr_t)pkt->opaque == PKT_OPAQUE_FIX_SUB_DURATION) {
  503. return fix_sub_duration_heartbeat(dp, av_rescale_q(pkt->pts, pkt->time_base,
  504. AV_TIME_BASE_Q));
  505. }
  506. if (!pkt) {
  507. flush_pkt = av_packet_alloc();
  508. if (!flush_pkt)
  509. return AVERROR(ENOMEM);
  510. }
  511. ret = avcodec_decode_subtitle2(dp->dec_ctx, &subtitle, &got_output,
  512. pkt ? pkt : flush_pkt);
  513. av_packet_free(&flush_pkt);
  514. if (ret < 0) {
  515. av_log(dp, AV_LOG_ERROR, "Error decoding subtitles: %s\n",
  516. av_err2str(ret));
  517. dp->dec.decode_errors++;
  518. return exit_on_error ? ret : 0;
  519. }
  520. if (!got_output)
  521. return pkt ? 0 : AVERROR_EOF;
  522. dp->dec.frames_decoded++;
  523. // XXX the queue for transferring data to consumers runs
  524. // on AVFrames, so we wrap AVSubtitle in an AVBufferRef and put that
  525. // inside the frame
  526. // eventually, subtitles should be switched to use AVFrames natively
  527. ret = subtitle_wrap_frame(frame, &subtitle, 0);
  528. if (ret < 0) {
  529. avsubtitle_free(&subtitle);
  530. return ret;
  531. }
  532. frame->width = dp->dec_ctx->width;
  533. frame->height = dp->dec_ctx->height;
  534. return process_subtitle(dp, frame);
  535. }
  536. static int packet_decode(DecoderPriv *dp, AVPacket *pkt, AVFrame *frame)
  537. {
  538. AVCodecContext *dec = dp->dec_ctx;
  539. const char *type_desc = av_get_media_type_string(dec->codec_type);
  540. int ret;
  541. if (dec->codec_type == AVMEDIA_TYPE_SUBTITLE)
  542. return transcode_subtitles(dp, pkt, frame);
  543. // With fate-indeo3-2, we're getting 0-sized packets before EOF for some
  544. // reason. This seems like a semi-critical bug. Don't trigger EOF, and
  545. // skip the packet.
  546. if (pkt && pkt->size == 0)
  547. return 0;
  548. if (pkt && (dp->flags & DECODER_FLAG_TS_UNRELIABLE)) {
  549. pkt->pts = AV_NOPTS_VALUE;
  550. pkt->dts = AV_NOPTS_VALUE;
  551. }
  552. if (pkt) {
  553. FrameData *fd = packet_data(pkt);
  554. if (!fd)
  555. return AVERROR(ENOMEM);
  556. fd->wallclock[LATENCY_PROBE_DEC_PRE] = av_gettime_relative();
  557. }
  558. ret = avcodec_send_packet(dec, pkt);
  559. if (ret < 0 && !(ret == AVERROR_EOF && !pkt)) {
  560. // In particular, we don't expect AVERROR(EAGAIN), because we read all
  561. // decoded frames with avcodec_receive_frame() until done.
  562. if (ret == AVERROR(EAGAIN)) {
  563. av_log(dp, AV_LOG_FATAL, "A decoder returned an unexpected error code. "
  564. "This is a bug, please report it.\n");
  565. return AVERROR_BUG;
  566. }
  567. av_log(dp, AV_LOG_ERROR, "Error submitting %s to decoder: %s\n",
  568. pkt ? "packet" : "EOF", av_err2str(ret));
  569. if (ret != AVERROR_EOF) {
  570. dp->dec.decode_errors++;
  571. if (!exit_on_error)
  572. ret = 0;
  573. }
  574. return ret;
  575. }
  576. while (1) {
  577. FrameData *fd;
  578. av_frame_unref(frame);
  579. update_benchmark(NULL);
  580. ret = avcodec_receive_frame(dec, frame);
  581. update_benchmark("decode_%s %s", type_desc, dp->parent_name);
  582. if (ret == AVERROR(EAGAIN)) {
  583. av_assert0(pkt); // should never happen during flushing
  584. return 0;
  585. } else if (ret == AVERROR_EOF) {
  586. return ret;
  587. } else if (ret < 0) {
  588. av_log(dp, AV_LOG_ERROR, "Decoding error: %s\n", av_err2str(ret));
  589. dp->dec.decode_errors++;
  590. if (exit_on_error)
  591. return ret;
  592. continue;
  593. }
  594. if (frame->decode_error_flags || (frame->flags & AV_FRAME_FLAG_CORRUPT)) {
  595. av_log(dp, exit_on_error ? AV_LOG_FATAL : AV_LOG_WARNING,
  596. "corrupt decoded frame\n");
  597. if (exit_on_error)
  598. return AVERROR_INVALIDDATA;
  599. }
  600. fd = frame_data(frame);
  601. if (!fd) {
  602. av_frame_unref(frame);
  603. return AVERROR(ENOMEM);
  604. }
  605. fd->dec.pts = frame->pts;
  606. fd->dec.tb = dec->pkt_timebase;
  607. fd->dec.frame_num = dec->frame_num - 1;
  608. fd->bits_per_raw_sample = dec->bits_per_raw_sample;
  609. fd->wallclock[LATENCY_PROBE_DEC_POST] = av_gettime_relative();
  610. frame->time_base = dec->pkt_timebase;
  611. if (dec->codec_type == AVMEDIA_TYPE_AUDIO) {
  612. dp->dec.samples_decoded += frame->nb_samples;
  613. audio_ts_process(dp, frame);
  614. } else {
  615. ret = video_frame_process(dp, frame);
  616. if (ret < 0) {
  617. av_log(dp, AV_LOG_FATAL,
  618. "Error while processing the decoded data\n");
  619. return ret;
  620. }
  621. }
  622. dp->dec.frames_decoded++;
  623. ret = sch_dec_send(dp->sch, dp->sch_idx, frame);
  624. if (ret < 0) {
  625. av_frame_unref(frame);
  626. return ret == AVERROR_EOF ? AVERROR_EXIT : ret;
  627. }
  628. }
  629. }
  630. static int dec_open(DecoderPriv *dp, AVDictionary **dec_opts,
  631. const DecoderOpts *o, AVFrame *param_out);
  632. static int dec_standalone_open(DecoderPriv *dp, const AVPacket *pkt)
  633. {
  634. DecoderOpts o;
  635. const FrameData *fd;
  636. char name[16];
  637. if (!pkt->opaque_ref)
  638. return AVERROR_BUG;
  639. fd = (FrameData *)pkt->opaque_ref->data;
  640. if (!fd->par_enc)
  641. return AVERROR_BUG;
  642. memset(&o, 0, sizeof(o));
  643. o.par = fd->par_enc;
  644. o.time_base = pkt->time_base;
  645. o.codec = dp->standalone_init.codec;
  646. if (!o.codec)
  647. o.codec = avcodec_find_decoder(o.par->codec_id);
  648. if (!o.codec) {
  649. const AVCodecDescriptor *desc = avcodec_descriptor_get(o.par->codec_id);
  650. av_log(dp, AV_LOG_ERROR, "Cannot find a decoder for codec ID '%s'\n",
  651. desc ? desc->name : "?");
  652. return AVERROR_DECODER_NOT_FOUND;
  653. }
  654. snprintf(name, sizeof(name), "dec%d", dp->index);
  655. o.name = name;
  656. return dec_open(dp, &dp->standalone_init.opts, &o, NULL);
  657. }
  658. static void dec_thread_set_name(const DecoderPriv *dp)
  659. {
  660. char name[16] = "dec";
  661. if (dp->index >= 0)
  662. av_strlcatf(name, sizeof(name), "%d", dp->index);
  663. else if (dp->parent_name)
  664. av_strlcat(name, dp->parent_name, sizeof(name));
  665. if (dp->dec_ctx)
  666. av_strlcatf(name, sizeof(name), ":%s", dp->dec_ctx->codec->name);
  667. ff_thread_setname(name);
  668. }
  669. static void dec_thread_uninit(DecThreadContext *dt)
  670. {
  671. av_packet_free(&dt->pkt);
  672. av_frame_free(&dt->frame);
  673. memset(dt, 0, sizeof(*dt));
  674. }
  675. static int dec_thread_init(DecThreadContext *dt)
  676. {
  677. memset(dt, 0, sizeof(*dt));
  678. dt->frame = av_frame_alloc();
  679. if (!dt->frame)
  680. goto fail;
  681. dt->pkt = av_packet_alloc();
  682. if (!dt->pkt)
  683. goto fail;
  684. return 0;
  685. fail:
  686. dec_thread_uninit(dt);
  687. return AVERROR(ENOMEM);
  688. }
  689. static int decoder_thread(void *arg)
  690. {
  691. DecoderPriv *dp = arg;
  692. DecThreadContext dt;
  693. int ret = 0, input_status = 0;
  694. ret = dec_thread_init(&dt);
  695. if (ret < 0)
  696. goto finish;
  697. dec_thread_set_name(dp);
  698. while (!input_status) {
  699. int flush_buffers, have_data;
  700. input_status = sch_dec_receive(dp->sch, dp->sch_idx, dt.pkt);
  701. have_data = input_status >= 0 &&
  702. (dt.pkt->buf || dt.pkt->side_data_elems ||
  703. (intptr_t)dt.pkt->opaque == PKT_OPAQUE_SUB_HEARTBEAT ||
  704. (intptr_t)dt.pkt->opaque == PKT_OPAQUE_FIX_SUB_DURATION);
  705. flush_buffers = input_status >= 0 && !have_data;
  706. if (!have_data)
  707. av_log(dp, AV_LOG_VERBOSE, "Decoder thread received %s packet\n",
  708. flush_buffers ? "flush" : "EOF");
  709. // this is a standalone decoder that has not been initialized yet
  710. if (!dp->dec_ctx) {
  711. if (flush_buffers)
  712. continue;
  713. if (input_status < 0) {
  714. av_log(dp, AV_LOG_ERROR,
  715. "Cannot initialize a standalone decoder\n");
  716. ret = input_status;
  717. goto finish;
  718. }
  719. ret = dec_standalone_open(dp, dt.pkt);
  720. if (ret < 0)
  721. goto finish;
  722. }
  723. ret = packet_decode(dp, have_data ? dt.pkt : NULL, dt.frame);
  724. av_packet_unref(dt.pkt);
  725. av_frame_unref(dt.frame);
  726. // AVERROR_EOF - EOF from the decoder
  727. // AVERROR_EXIT - EOF from the scheduler
  728. // we treat them differently when flushing
  729. if (ret == AVERROR_EXIT) {
  730. ret = AVERROR_EOF;
  731. flush_buffers = 0;
  732. }
  733. if (ret == AVERROR_EOF) {
  734. av_log(dp, AV_LOG_VERBOSE, "Decoder returned EOF, %s\n",
  735. flush_buffers ? "resetting" : "finishing");
  736. if (!flush_buffers)
  737. break;
  738. /* report last frame duration to the scheduler */
  739. if (dp->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  740. dt.pkt->pts = dp->last_frame_pts + dp->last_frame_duration_est;
  741. dt.pkt->time_base = dp->last_frame_tb;
  742. }
  743. avcodec_flush_buffers(dp->dec_ctx);
  744. } else if (ret < 0) {
  745. av_log(dp, AV_LOG_ERROR, "Error processing packet in decoder: %s\n",
  746. av_err2str(ret));
  747. break;
  748. }
  749. }
  750. // EOF is normal thread termination
  751. if (ret == AVERROR_EOF)
  752. ret = 0;
  753. // on success send EOF timestamp to our downstreams
  754. if (ret >= 0) {
  755. float err_rate;
  756. av_frame_unref(dt.frame);
  757. dt.frame->opaque = (void*)(intptr_t)FRAME_OPAQUE_EOF;
  758. dt.frame->pts = dp->last_frame_pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE :
  759. dp->last_frame_pts + dp->last_frame_duration_est;
  760. dt.frame->time_base = dp->last_frame_tb;
  761. ret = sch_dec_send(dp->sch, dp->sch_idx, dt.frame);
  762. if (ret < 0 && ret != AVERROR_EOF) {
  763. av_log(dp, AV_LOG_FATAL,
  764. "Error signalling EOF timestamp: %s\n", av_err2str(ret));
  765. goto finish;
  766. }
  767. ret = 0;
  768. err_rate = (dp->dec.frames_decoded || dp->dec.decode_errors) ?
  769. dp->dec.decode_errors / (dp->dec.frames_decoded + dp->dec.decode_errors) : 0.f;
  770. if (err_rate > max_error_rate) {
  771. av_log(dp, AV_LOG_FATAL, "Decode error rate %g exceeds maximum %g\n",
  772. err_rate, max_error_rate);
  773. ret = FFMPEG_ERROR_RATE_EXCEEDED;
  774. } else if (err_rate)
  775. av_log(dp, AV_LOG_VERBOSE, "Decode error rate %g\n", err_rate);
  776. }
  777. finish:
  778. dec_thread_uninit(&dt);
  779. return ret;
  780. }
  781. static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
  782. {
  783. DecoderPriv *dp = s->opaque;
  784. const enum AVPixelFormat *p;
  785. for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
  786. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
  787. const AVCodecHWConfig *config = NULL;
  788. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  789. break;
  790. if (dp->hwaccel_id == HWACCEL_GENERIC ||
  791. dp->hwaccel_id == HWACCEL_AUTO) {
  792. for (int i = 0;; i++) {
  793. config = avcodec_get_hw_config(s->codec, i);
  794. if (!config)
  795. break;
  796. if (!(config->methods &
  797. AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
  798. continue;
  799. if (config->pix_fmt == *p)
  800. break;
  801. }
  802. }
  803. if (config && config->device_type == dp->hwaccel_device_type) {
  804. dp->hwaccel_pix_fmt = *p;
  805. break;
  806. }
  807. }
  808. return *p;
  809. }
  810. static HWDevice *hw_device_match_by_codec(const AVCodec *codec)
  811. {
  812. const AVCodecHWConfig *config;
  813. HWDevice *dev;
  814. for (int i = 0;; i++) {
  815. config = avcodec_get_hw_config(codec, i);
  816. if (!config)
  817. return NULL;
  818. if (!(config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
  819. continue;
  820. dev = hw_device_get_by_type(config->device_type);
  821. if (dev)
  822. return dev;
  823. }
  824. }
  825. static int hw_device_setup_for_decode(DecoderPriv *dp,
  826. const AVCodec *codec,
  827. const char *hwaccel_device)
  828. {
  829. const AVCodecHWConfig *config;
  830. enum AVHWDeviceType type;
  831. HWDevice *dev = NULL;
  832. int err, auto_device = 0;
  833. if (hwaccel_device) {
  834. dev = hw_device_get_by_name(hwaccel_device);
  835. if (!dev) {
  836. if (dp->hwaccel_id == HWACCEL_AUTO) {
  837. auto_device = 1;
  838. } else if (dp->hwaccel_id == HWACCEL_GENERIC) {
  839. type = dp->hwaccel_device_type;
  840. err = hw_device_init_from_type(type, hwaccel_device,
  841. &dev);
  842. } else {
  843. // This will be dealt with by API-specific initialisation
  844. // (using hwaccel_device), so nothing further needed here.
  845. return 0;
  846. }
  847. } else {
  848. if (dp->hwaccel_id == HWACCEL_AUTO) {
  849. dp->hwaccel_device_type = dev->type;
  850. } else if (dp->hwaccel_device_type != dev->type) {
  851. av_log(dp, AV_LOG_ERROR, "Invalid hwaccel device "
  852. "specified for decoder: device %s of type %s is not "
  853. "usable with hwaccel %s.\n", dev->name,
  854. av_hwdevice_get_type_name(dev->type),
  855. av_hwdevice_get_type_name(dp->hwaccel_device_type));
  856. return AVERROR(EINVAL);
  857. }
  858. }
  859. } else {
  860. if (dp->hwaccel_id == HWACCEL_AUTO) {
  861. auto_device = 1;
  862. } else if (dp->hwaccel_id == HWACCEL_GENERIC) {
  863. type = dp->hwaccel_device_type;
  864. dev = hw_device_get_by_type(type);
  865. // When "-qsv_device device" is used, an internal QSV device named
  866. // as "__qsv_device" is created. Another QSV device is created too
  867. // if "-init_hw_device qsv=name:device" is used. There are 2 QSV devices
  868. // if both "-qsv_device device" and "-init_hw_device qsv=name:device"
  869. // are used, hw_device_get_by_type(AV_HWDEVICE_TYPE_QSV) returns NULL.
  870. // To keep back-compatibility with the removed ad-hoc libmfx setup code,
  871. // call hw_device_get_by_name("__qsv_device") to select the internal QSV
  872. // device.
  873. if (!dev && type == AV_HWDEVICE_TYPE_QSV)
  874. dev = hw_device_get_by_name("__qsv_device");
  875. if (!dev)
  876. err = hw_device_init_from_type(type, NULL, &dev);
  877. } else {
  878. dev = hw_device_match_by_codec(codec);
  879. if (!dev) {
  880. // No device for this codec, but not using generic hwaccel
  881. // and therefore may well not need one - ignore.
  882. return 0;
  883. }
  884. }
  885. }
  886. if (auto_device) {
  887. if (!avcodec_get_hw_config(codec, 0)) {
  888. // Decoder does not support any hardware devices.
  889. return 0;
  890. }
  891. for (int i = 0; !dev; i++) {
  892. config = avcodec_get_hw_config(codec, i);
  893. if (!config)
  894. break;
  895. type = config->device_type;
  896. dev = hw_device_get_by_type(type);
  897. if (dev) {
  898. av_log(dp, AV_LOG_INFO, "Using auto "
  899. "hwaccel type %s with existing device %s.\n",
  900. av_hwdevice_get_type_name(type), dev->name);
  901. }
  902. }
  903. for (int i = 0; !dev; i++) {
  904. config = avcodec_get_hw_config(codec, i);
  905. if (!config)
  906. break;
  907. type = config->device_type;
  908. // Try to make a new device of this type.
  909. err = hw_device_init_from_type(type, hwaccel_device,
  910. &dev);
  911. if (err < 0) {
  912. // Can't make a device of this type.
  913. continue;
  914. }
  915. if (hwaccel_device) {
  916. av_log(dp, AV_LOG_INFO, "Using auto "
  917. "hwaccel type %s with new device created "
  918. "from %s.\n", av_hwdevice_get_type_name(type),
  919. hwaccel_device);
  920. } else {
  921. av_log(dp, AV_LOG_INFO, "Using auto "
  922. "hwaccel type %s with new default device.\n",
  923. av_hwdevice_get_type_name(type));
  924. }
  925. }
  926. if (dev) {
  927. dp->hwaccel_device_type = type;
  928. } else {
  929. av_log(dp, AV_LOG_INFO, "Auto hwaccel "
  930. "disabled: no device found.\n");
  931. dp->hwaccel_id = HWACCEL_NONE;
  932. return 0;
  933. }
  934. }
  935. if (!dev) {
  936. av_log(dp, AV_LOG_ERROR, "No device available "
  937. "for decoder: device type %s needed for codec %s.\n",
  938. av_hwdevice_get_type_name(type), codec->name);
  939. return err;
  940. }
  941. dp->dec_ctx->hw_device_ctx = av_buffer_ref(dev->device_ref);
  942. if (!dp->dec_ctx->hw_device_ctx)
  943. return AVERROR(ENOMEM);
  944. return 0;
  945. }
  946. static int dec_open(DecoderPriv *dp, AVDictionary **dec_opts,
  947. const DecoderOpts *o, AVFrame *param_out)
  948. {
  949. const AVCodec *codec = o->codec;
  950. int ret;
  951. dp->flags = o->flags;
  952. dp->log_parent = o->log_parent;
  953. dp->dec.type = codec->type;
  954. dp->framerate_in = o->framerate;
  955. dp->hwaccel_id = o->hwaccel_id;
  956. dp->hwaccel_device_type = o->hwaccel_device_type;
  957. dp->hwaccel_output_format = o->hwaccel_output_format;
  958. snprintf(dp->log_name, sizeof(dp->log_name), "dec:%s", codec->name);
  959. dp->parent_name = av_strdup(o->name ? o->name : "");
  960. if (!dp->parent_name)
  961. return AVERROR(ENOMEM);
  962. if (codec->type == AVMEDIA_TYPE_SUBTITLE &&
  963. (dp->flags & DECODER_FLAG_FIX_SUB_DURATION)) {
  964. for (int i = 0; i < FF_ARRAY_ELEMS(dp->sub_prev); i++) {
  965. dp->sub_prev[i] = av_frame_alloc();
  966. if (!dp->sub_prev[i])
  967. return AVERROR(ENOMEM);
  968. }
  969. dp->sub_heartbeat = av_frame_alloc();
  970. if (!dp->sub_heartbeat)
  971. return AVERROR(ENOMEM);
  972. }
  973. dp->sar_override = o->par->sample_aspect_ratio;
  974. dp->dec_ctx = avcodec_alloc_context3(codec);
  975. if (!dp->dec_ctx)
  976. return AVERROR(ENOMEM);
  977. ret = avcodec_parameters_to_context(dp->dec_ctx, o->par);
  978. if (ret < 0) {
  979. av_log(dp, AV_LOG_ERROR, "Error initializing the decoder context.\n");
  980. return ret;
  981. }
  982. dp->dec_ctx->opaque = dp;
  983. dp->dec_ctx->get_format = get_format;
  984. dp->dec_ctx->pkt_timebase = o->time_base;
  985. if (!av_dict_get(*dec_opts, "threads", NULL, 0))
  986. av_dict_set(dec_opts, "threads", "auto", 0);
  987. ret = hw_device_setup_for_decode(dp, codec, o->hwaccel_device);
  988. if (ret < 0) {
  989. av_log(dp, AV_LOG_ERROR,
  990. "Hardware device setup failed for decoder: %s\n",
  991. av_err2str(ret));
  992. return ret;
  993. }
  994. ret = av_opt_set_dict2(dp->dec_ctx, dec_opts, AV_OPT_SEARCH_CHILDREN);
  995. if (ret < 0) {
  996. av_log(dp, AV_LOG_ERROR, "Error applying decoder options: %s\n",
  997. av_err2str(ret));
  998. return ret;
  999. }
  1000. ret = check_avoptions(*dec_opts);
  1001. if (ret < 0)
  1002. return ret;
  1003. dp->dec_ctx->flags |= AV_CODEC_FLAG_COPY_OPAQUE;
  1004. if (o->flags & DECODER_FLAG_BITEXACT)
  1005. dp->dec_ctx->flags |= AV_CODEC_FLAG_BITEXACT;
  1006. // we apply cropping outselves
  1007. dp->apply_cropping = dp->dec_ctx->apply_cropping;
  1008. dp->dec_ctx->apply_cropping = 0;
  1009. if ((ret = avcodec_open2(dp->dec_ctx, codec, NULL)) < 0) {
  1010. av_log(dp, AV_LOG_ERROR, "Error while opening decoder: %s\n",
  1011. av_err2str(ret));
  1012. return ret;
  1013. }
  1014. if (dp->dec_ctx->hw_device_ctx) {
  1015. // Update decoder extra_hw_frames option to account for the
  1016. // frames held in queues inside the ffmpeg utility. This is
  1017. // called after avcodec_open2() because the user-set value of
  1018. // extra_hw_frames becomes valid in there, and we need to add
  1019. // this on top of it.
  1020. int extra_frames = DEFAULT_FRAME_THREAD_QUEUE_SIZE;
  1021. if (dp->dec_ctx->extra_hw_frames >= 0)
  1022. dp->dec_ctx->extra_hw_frames += extra_frames;
  1023. else
  1024. dp->dec_ctx->extra_hw_frames = extra_frames;
  1025. }
  1026. dp->dec.subtitle_header = dp->dec_ctx->subtitle_header;
  1027. dp->dec.subtitle_header_size = dp->dec_ctx->subtitle_header_size;
  1028. if (param_out) {
  1029. if (dp->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  1030. param_out->format = dp->dec_ctx->sample_fmt;
  1031. param_out->sample_rate = dp->dec_ctx->sample_rate;
  1032. ret = av_channel_layout_copy(&param_out->ch_layout, &dp->dec_ctx->ch_layout);
  1033. if (ret < 0)
  1034. return ret;
  1035. } else if (dp->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  1036. param_out->format = dp->dec_ctx->pix_fmt;
  1037. param_out->width = dp->dec_ctx->width;
  1038. param_out->height = dp->dec_ctx->height;
  1039. param_out->sample_aspect_ratio = dp->dec_ctx->sample_aspect_ratio;
  1040. param_out->colorspace = dp->dec_ctx->colorspace;
  1041. param_out->color_range = dp->dec_ctx->color_range;
  1042. }
  1043. param_out->time_base = dp->dec_ctx->pkt_timebase;
  1044. }
  1045. return 0;
  1046. }
  1047. int dec_init(Decoder **pdec, Scheduler *sch,
  1048. AVDictionary **dec_opts, const DecoderOpts *o,
  1049. AVFrame *param_out)
  1050. {
  1051. DecoderPriv *dp;
  1052. int ret;
  1053. *pdec = NULL;
  1054. ret = dec_alloc(&dp, sch, !!(o->flags & DECODER_FLAG_SEND_END_TS));
  1055. if (ret < 0)
  1056. return ret;
  1057. ret = dec_open(dp, dec_opts, o, param_out);
  1058. if (ret < 0)
  1059. goto fail;
  1060. *pdec = &dp->dec;
  1061. return dp->sch_idx;
  1062. fail:
  1063. dec_free((Decoder**)&dp);
  1064. return ret;
  1065. }
  1066. int dec_create(const OptionsContext *o, const char *arg, Scheduler *sch)
  1067. {
  1068. DecoderPriv *dp;
  1069. OutputFile *of;
  1070. OutputStream *ost;
  1071. int of_index, ost_index;
  1072. char *p;
  1073. unsigned enc_idx;
  1074. int ret;
  1075. ret = dec_alloc(&dp, sch, 0);
  1076. if (ret < 0)
  1077. return ret;
  1078. dp->index = nb_decoders;
  1079. ret = GROW_ARRAY(decoders, nb_decoders);
  1080. if (ret < 0) {
  1081. dec_free((Decoder **)&dp);
  1082. return ret;
  1083. }
  1084. decoders[nb_decoders - 1] = (Decoder *)dp;
  1085. of_index = strtol(arg, &p, 0);
  1086. if (of_index < 0 || of_index >= nb_output_files) {
  1087. av_log(dp, AV_LOG_ERROR, "Invalid output file index '%d' in %s\n", of_index, arg);
  1088. return AVERROR(EINVAL);
  1089. }
  1090. of = output_files[of_index];
  1091. ost_index = strtol(p + 1, NULL, 0);
  1092. if (ost_index < 0 || ost_index >= of->nb_streams) {
  1093. av_log(dp, AV_LOG_ERROR, "Invalid output stream index '%d' in %s\n", ost_index, arg);
  1094. return AVERROR(EINVAL);
  1095. }
  1096. ost = of->streams[ost_index];
  1097. if (!ost->enc) {
  1098. av_log(dp, AV_LOG_ERROR, "Output stream %s has no encoder\n", arg);
  1099. return AVERROR(EINVAL);
  1100. }
  1101. dp->dec.type = ost->type;
  1102. ret = enc_loopback(ost->enc);
  1103. if (ret < 0)
  1104. return ret;
  1105. enc_idx = ret;
  1106. ret = sch_connect(sch, SCH_ENC(enc_idx), SCH_DEC(dp->sch_idx));
  1107. if (ret < 0)
  1108. return ret;
  1109. ret = av_dict_copy(&dp->standalone_init.opts, o->g->codec_opts, 0);
  1110. if (ret < 0)
  1111. return ret;
  1112. if (o->codec_names.nb_opt) {
  1113. const char *name = o->codec_names.opt[o->codec_names.nb_opt - 1].u.str;
  1114. dp->standalone_init.codec = avcodec_find_decoder_by_name(name);
  1115. if (!dp->standalone_init.codec) {
  1116. av_log(dp, AV_LOG_ERROR, "No such decoder: %s\n", name);
  1117. return AVERROR_DECODER_NOT_FOUND;
  1118. }
  1119. }
  1120. return 0;
  1121. }
  1122. int dec_filter_add(Decoder *d, InputFilter *ifilter, InputFilterOptions *opts)
  1123. {
  1124. DecoderPriv *dp = dp_from_dec(d);
  1125. char name[16];
  1126. snprintf(name, sizeof(name), "dec%d", dp->index);
  1127. opts->name = av_strdup(name);
  1128. if (!opts->name)
  1129. return AVERROR(ENOMEM);
  1130. return dp->sch_idx;
  1131. }