ffmpeg_dec.c 42 KB

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