ffmpeg_dec.c 41 KB

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