ffmpeg_dec.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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/dict.h"
  20. #include "libavutil/error.h"
  21. #include "libavutil/log.h"
  22. #include "libavutil/pixdesc.h"
  23. #include "libavutil/pixfmt.h"
  24. #include "libavutil/timestamp.h"
  25. #include "libavcodec/avcodec.h"
  26. #include "libavcodec/codec.h"
  27. #include "libavfilter/buffersrc.h"
  28. #include "ffmpeg.h"
  29. #include "thread_queue.h"
  30. struct Decoder {
  31. AVFrame *frame;
  32. AVPacket *pkt;
  33. enum AVPixelFormat hwaccel_pix_fmt;
  34. // pts/estimated duration of the last decoded frame
  35. // * in decoder timebase for video,
  36. // * in last_frame_tb (may change during decoding) for audio
  37. int64_t last_frame_pts;
  38. int64_t last_frame_duration_est;
  39. AVRational last_frame_tb;
  40. int64_t last_filter_in_rescale_delta;
  41. int last_frame_sample_rate;
  42. /* previous decoded subtitles */
  43. AVFrame *sub_prev[2];
  44. AVFrame *sub_heartbeat;
  45. pthread_t thread;
  46. /**
  47. * Queue for sending coded packets from the main thread to
  48. * the decoder thread.
  49. *
  50. * An empty packet is sent to flush the decoder without terminating
  51. * decoding.
  52. */
  53. ThreadQueue *queue_in;
  54. /**
  55. * Queue for sending decoded frames from the decoder thread
  56. * to the main thread.
  57. *
  58. * An empty frame is sent to signal that a single packet has been fully
  59. * processed.
  60. */
  61. ThreadQueue *queue_out;
  62. };
  63. // data that is local to the decoder thread and not visible outside of it
  64. typedef struct DecThreadContext {
  65. AVFrame *frame;
  66. AVPacket *pkt;
  67. } DecThreadContext;
  68. static int dec_thread_stop(Decoder *d)
  69. {
  70. void *ret;
  71. if (!d->queue_in)
  72. return 0;
  73. tq_send_finish(d->queue_in, 0);
  74. tq_receive_finish(d->queue_out, 0);
  75. pthread_join(d->thread, &ret);
  76. tq_free(&d->queue_in);
  77. tq_free(&d->queue_out);
  78. return (intptr_t)ret;
  79. }
  80. void dec_free(Decoder **pdec)
  81. {
  82. Decoder *dec = *pdec;
  83. if (!dec)
  84. return;
  85. dec_thread_stop(dec);
  86. av_frame_free(&dec->frame);
  87. av_packet_free(&dec->pkt);
  88. for (int i = 0; i < FF_ARRAY_ELEMS(dec->sub_prev); i++)
  89. av_frame_free(&dec->sub_prev[i]);
  90. av_frame_free(&dec->sub_heartbeat);
  91. av_freep(pdec);
  92. }
  93. static int dec_alloc(Decoder **pdec)
  94. {
  95. Decoder *dec;
  96. *pdec = NULL;
  97. dec = av_mallocz(sizeof(*dec));
  98. if (!dec)
  99. return AVERROR(ENOMEM);
  100. dec->frame = av_frame_alloc();
  101. if (!dec->frame)
  102. goto fail;
  103. dec->pkt = av_packet_alloc();
  104. if (!dec->pkt)
  105. goto fail;
  106. dec->last_filter_in_rescale_delta = AV_NOPTS_VALUE;
  107. dec->last_frame_pts = AV_NOPTS_VALUE;
  108. dec->last_frame_tb = (AVRational){ 1, 1 };
  109. dec->hwaccel_pix_fmt = AV_PIX_FMT_NONE;
  110. *pdec = dec;
  111. return 0;
  112. fail:
  113. dec_free(&dec);
  114. return AVERROR(ENOMEM);
  115. }
  116. static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
  117. {
  118. int i, ret;
  119. av_assert1(ist->nb_filters > 0); /* ensure ret is initialized */
  120. for (i = 0; i < ist->nb_filters; i++) {
  121. ret = ifilter_send_frame(ist->filters[i], decoded_frame, i < ist->nb_filters - 1);
  122. if (ret == AVERROR_EOF)
  123. ret = 0; /* ignore */
  124. if (ret < 0) {
  125. av_log(NULL, AV_LOG_ERROR,
  126. "Failed to inject frame into filter network: %s\n", av_err2str(ret));
  127. break;
  128. }
  129. }
  130. return ret;
  131. }
  132. static AVRational audio_samplerate_update(void *logctx, Decoder *d,
  133. const AVFrame *frame)
  134. {
  135. const int prev = d->last_frame_tb.den;
  136. const int sr = frame->sample_rate;
  137. AVRational tb_new;
  138. int64_t gcd;
  139. if (frame->sample_rate == d->last_frame_sample_rate)
  140. goto finish;
  141. gcd = av_gcd(prev, sr);
  142. if (prev / gcd >= INT_MAX / sr) {
  143. av_log(logctx, AV_LOG_WARNING,
  144. "Audio timestamps cannot be represented exactly after "
  145. "sample rate change: %d -> %d\n", prev, sr);
  146. // LCM of 192000, 44100, allows to represent all common samplerates
  147. tb_new = (AVRational){ 1, 28224000 };
  148. } else
  149. tb_new = (AVRational){ 1, prev / gcd * sr };
  150. // keep the frame timebase if it is strictly better than
  151. // the samplerate-defined one
  152. if (frame->time_base.num == 1 && frame->time_base.den > tb_new.den &&
  153. !(frame->time_base.den % tb_new.den))
  154. tb_new = frame->time_base;
  155. if (d->last_frame_pts != AV_NOPTS_VALUE)
  156. d->last_frame_pts = av_rescale_q(d->last_frame_pts,
  157. d->last_frame_tb, tb_new);
  158. d->last_frame_duration_est = av_rescale_q(d->last_frame_duration_est,
  159. d->last_frame_tb, tb_new);
  160. d->last_frame_tb = tb_new;
  161. d->last_frame_sample_rate = frame->sample_rate;
  162. finish:
  163. return d->last_frame_tb;
  164. }
  165. static void audio_ts_process(void *logctx, Decoder *d, AVFrame *frame)
  166. {
  167. AVRational tb_filter = (AVRational){1, frame->sample_rate};
  168. AVRational tb;
  169. int64_t pts_pred;
  170. // on samplerate change, choose a new internal timebase for timestamp
  171. // generation that can represent timestamps from all the samplerates
  172. // seen so far
  173. tb = audio_samplerate_update(logctx, d, frame);
  174. pts_pred = d->last_frame_pts == AV_NOPTS_VALUE ? 0 :
  175. d->last_frame_pts + d->last_frame_duration_est;
  176. if (frame->pts == AV_NOPTS_VALUE) {
  177. frame->pts = pts_pred;
  178. frame->time_base = tb;
  179. } else if (d->last_frame_pts != AV_NOPTS_VALUE &&
  180. frame->pts > av_rescale_q_rnd(pts_pred, tb, frame->time_base,
  181. AV_ROUND_UP)) {
  182. // there was a gap in timestamps, reset conversion state
  183. d->last_filter_in_rescale_delta = AV_NOPTS_VALUE;
  184. }
  185. frame->pts = av_rescale_delta(frame->time_base, frame->pts,
  186. tb, frame->nb_samples,
  187. &d->last_filter_in_rescale_delta, tb);
  188. d->last_frame_pts = frame->pts;
  189. d->last_frame_duration_est = av_rescale_q(frame->nb_samples,
  190. tb_filter, tb);
  191. // finally convert to filtering timebase
  192. frame->pts = av_rescale_q(frame->pts, tb, tb_filter);
  193. frame->duration = frame->nb_samples;
  194. frame->time_base = tb_filter;
  195. }
  196. static int64_t video_duration_estimate(const InputStream *ist, const AVFrame *frame)
  197. {
  198. const Decoder *d = ist->decoder;
  199. const InputFile *ifile = input_files[ist->file_index];
  200. int64_t codec_duration = 0;
  201. // XXX lavf currently makes up frame durations when they are not provided by
  202. // the container. As there is no way to reliably distinguish real container
  203. // durations from the fake made-up ones, we use heuristics based on whether
  204. // the container has timestamps. Eventually lavf should stop making up
  205. // durations, then this should be simplified.
  206. // prefer frame duration for containers with timestamps
  207. if (frame->duration > 0 && (!ifile->format_nots || ist->framerate.num))
  208. return frame->duration;
  209. if (ist->dec_ctx->framerate.den && ist->dec_ctx->framerate.num) {
  210. int fields = frame->repeat_pict + 2;
  211. AVRational field_rate = av_mul_q(ist->dec_ctx->framerate,
  212. (AVRational){ 2, 1 });
  213. codec_duration = av_rescale_q(fields, av_inv_q(field_rate),
  214. frame->time_base);
  215. }
  216. // prefer codec-layer duration for containers without timestamps
  217. if (codec_duration > 0 && ifile->format_nots)
  218. return codec_duration;
  219. // when timestamps are available, repeat last frame's actual duration
  220. // (i.e. pts difference between this and last frame)
  221. if (frame->pts != AV_NOPTS_VALUE && d->last_frame_pts != AV_NOPTS_VALUE &&
  222. frame->pts > d->last_frame_pts)
  223. return frame->pts - d->last_frame_pts;
  224. // try frame/codec duration
  225. if (frame->duration > 0)
  226. return frame->duration;
  227. if (codec_duration > 0)
  228. return codec_duration;
  229. // try average framerate
  230. if (ist->st->avg_frame_rate.num && ist->st->avg_frame_rate.den) {
  231. int64_t d = av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
  232. frame->time_base);
  233. if (d > 0)
  234. return d;
  235. }
  236. // last resort is last frame's estimated duration, and 1
  237. return FFMAX(d->last_frame_duration_est, 1);
  238. }
  239. static int video_frame_process(InputStream *ist, AVFrame *frame)
  240. {
  241. Decoder *d = ist->decoder;
  242. // The following line may be required in some cases where there is no parser
  243. // or the parser does not has_b_frames correctly
  244. if (ist->par->video_delay < ist->dec_ctx->has_b_frames) {
  245. if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
  246. ist->par->video_delay = ist->dec_ctx->has_b_frames;
  247. } else
  248. av_log(ist->dec_ctx, AV_LOG_WARNING,
  249. "video_delay is larger in decoder than demuxer %d > %d.\n"
  250. "If you want to help, upload a sample "
  251. "of this file to https://streams.videolan.org/upload/ "
  252. "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
  253. ist->dec_ctx->has_b_frames,
  254. ist->par->video_delay);
  255. }
  256. if (ist->dec_ctx->width != frame->width ||
  257. ist->dec_ctx->height != frame->height ||
  258. ist->dec_ctx->pix_fmt != frame->format) {
  259. av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
  260. frame->width,
  261. frame->height,
  262. frame->format,
  263. ist->dec_ctx->width,
  264. ist->dec_ctx->height,
  265. ist->dec_ctx->pix_fmt);
  266. }
  267. #if FFMPEG_OPT_TOP
  268. if(ist->top_field_first>=0) {
  269. av_log(ist, AV_LOG_WARNING, "-top is deprecated, use the setfield filter instead\n");
  270. frame->flags |= AV_FRAME_FLAG_TOP_FIELD_FIRST;
  271. }
  272. #endif
  273. if (frame->format == d->hwaccel_pix_fmt) {
  274. int err = hwaccel_retrieve_data(ist->dec_ctx, frame);
  275. if (err < 0)
  276. return err;
  277. }
  278. frame->pts = frame->best_effort_timestamp;
  279. // forced fixed framerate
  280. if (ist->framerate.num) {
  281. frame->pts = AV_NOPTS_VALUE;
  282. frame->duration = 1;
  283. frame->time_base = av_inv_q(ist->framerate);
  284. }
  285. // no timestamp available - extrapolate from previous frame duration
  286. if (frame->pts == AV_NOPTS_VALUE)
  287. frame->pts = d->last_frame_pts == AV_NOPTS_VALUE ? 0 :
  288. d->last_frame_pts + d->last_frame_duration_est;
  289. // update timestamp history
  290. d->last_frame_duration_est = video_duration_estimate(ist, frame);
  291. d->last_frame_pts = frame->pts;
  292. d->last_frame_tb = frame->time_base;
  293. if (debug_ts) {
  294. av_log(ist, AV_LOG_INFO,
  295. "decoder -> pts:%s pts_time:%s "
  296. "pkt_dts:%s pkt_dts_time:%s "
  297. "duration:%s duration_time:%s "
  298. "keyframe:%d frame_type:%d time_base:%d/%d\n",
  299. av_ts2str(frame->pts),
  300. av_ts2timestr(frame->pts, &frame->time_base),
  301. av_ts2str(frame->pkt_dts),
  302. av_ts2timestr(frame->pkt_dts, &frame->time_base),
  303. av_ts2str(frame->duration),
  304. av_ts2timestr(frame->duration, &frame->time_base),
  305. !!(frame->flags & AV_FRAME_FLAG_KEY), frame->pict_type,
  306. frame->time_base.num, frame->time_base.den);
  307. }
  308. if (ist->st->sample_aspect_ratio.num)
  309. frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  310. return 0;
  311. }
  312. static void sub2video_flush(InputStream *ist)
  313. {
  314. for (int i = 0; i < ist->nb_filters; i++) {
  315. int ret = ifilter_sub2video(ist->filters[i], NULL);
  316. if (ret != AVERROR_EOF && ret < 0)
  317. av_log(NULL, AV_LOG_WARNING, "Flush the frame error.\n");
  318. }
  319. }
  320. static int process_subtitle(InputStream *ist, AVFrame *frame)
  321. {
  322. Decoder *d = ist->decoder;
  323. const AVSubtitle *subtitle = (AVSubtitle*)frame->buf[0]->data;
  324. int ret = 0;
  325. if (ist->fix_sub_duration) {
  326. AVSubtitle *sub_prev = d->sub_prev[0]->buf[0] ?
  327. (AVSubtitle*)d->sub_prev[0]->buf[0]->data : NULL;
  328. int end = 1;
  329. if (sub_prev) {
  330. end = av_rescale(subtitle->pts - sub_prev->pts,
  331. 1000, AV_TIME_BASE);
  332. if (end < sub_prev->end_display_time) {
  333. av_log(NULL, AV_LOG_DEBUG,
  334. "Subtitle duration reduced from %"PRId32" to %d%s\n",
  335. sub_prev->end_display_time, end,
  336. end <= 0 ? ", dropping it" : "");
  337. sub_prev->end_display_time = end;
  338. }
  339. }
  340. av_frame_unref(d->sub_prev[1]);
  341. av_frame_move_ref(d->sub_prev[1], frame);
  342. frame = d->sub_prev[0];
  343. subtitle = frame->buf[0] ? (AVSubtitle*)frame->buf[0]->data : NULL;
  344. FFSWAP(AVFrame*, d->sub_prev[0], d->sub_prev[1]);
  345. if (end <= 0)
  346. return 0;
  347. }
  348. if (!subtitle)
  349. return 0;
  350. for (int i = 0; i < ist->nb_filters; i++) {
  351. ret = ifilter_sub2video(ist->filters[i], frame);
  352. if (ret < 0) {
  353. av_log(ist, AV_LOG_ERROR, "Error sending a subtitle for filtering: %s\n",
  354. av_err2str(ret));
  355. return ret;
  356. }
  357. }
  358. subtitle = (AVSubtitle*)frame->buf[0]->data;
  359. if (!subtitle->num_rects)
  360. return 0;
  361. for (int oidx = 0; oidx < ist->nb_outputs; oidx++) {
  362. OutputStream *ost = ist->outputs[oidx];
  363. if (!ost->enc || ost->type != AVMEDIA_TYPE_SUBTITLE)
  364. continue;
  365. ret = enc_subtitle(output_files[ost->file_index], ost, subtitle);
  366. if (ret < 0)
  367. return ret;
  368. }
  369. return 0;
  370. }
  371. int fix_sub_duration_heartbeat(InputStream *ist, int64_t signal_pts)
  372. {
  373. Decoder *d = ist->decoder;
  374. int ret = AVERROR_BUG;
  375. AVSubtitle *prev_subtitle = d->sub_prev[0]->buf[0] ?
  376. (AVSubtitle*)d->sub_prev[0]->buf[0]->data : NULL;
  377. AVSubtitle *subtitle;
  378. if (!ist->fix_sub_duration || !prev_subtitle ||
  379. !prev_subtitle->num_rects || signal_pts <= prev_subtitle->pts)
  380. return 0;
  381. av_frame_unref(d->sub_heartbeat);
  382. ret = subtitle_wrap_frame(d->sub_heartbeat, prev_subtitle, 1);
  383. if (ret < 0)
  384. return ret;
  385. subtitle = (AVSubtitle*)d->sub_heartbeat->buf[0]->data;
  386. subtitle->pts = signal_pts;
  387. return process_subtitle(ist, d->sub_heartbeat);
  388. }
  389. static int transcode_subtitles(InputStream *ist, const AVPacket *pkt,
  390. AVFrame *frame)
  391. {
  392. Decoder *d = ist->decoder;
  393. AVPacket *flush_pkt = NULL;
  394. AVSubtitle subtitle;
  395. int got_output;
  396. int ret;
  397. if (!pkt) {
  398. flush_pkt = av_packet_alloc();
  399. if (!flush_pkt)
  400. return AVERROR(ENOMEM);
  401. }
  402. ret = avcodec_decode_subtitle2(ist->dec_ctx, &subtitle, &got_output,
  403. pkt ? pkt : flush_pkt);
  404. av_packet_free(&flush_pkt);
  405. if (ret < 0) {
  406. av_log(ist, AV_LOG_ERROR, "Error decoding subtitles: %s\n",
  407. av_err2str(ret));
  408. ist->decode_errors++;
  409. return exit_on_error ? ret : 0;
  410. }
  411. if (!got_output)
  412. return pkt ? 0 : AVERROR_EOF;
  413. ist->frames_decoded++;
  414. // XXX the queue for transferring data back to the main thread runs
  415. // on AVFrames, so we wrap AVSubtitle in an AVBufferRef and put that
  416. // inside the frame
  417. // eventually, subtitles should be switched to use AVFrames natively
  418. ret = subtitle_wrap_frame(frame, &subtitle, 0);
  419. if (ret < 0) {
  420. avsubtitle_free(&subtitle);
  421. return ret;
  422. }
  423. frame->width = ist->dec_ctx->width;
  424. frame->height = ist->dec_ctx->height;
  425. ret = tq_send(d->queue_out, 0, frame);
  426. if (ret < 0)
  427. av_frame_unref(frame);
  428. return ret;
  429. }
  430. static int send_filter_eof(InputStream *ist)
  431. {
  432. Decoder *d = ist->decoder;
  433. int i, ret;
  434. for (i = 0; i < ist->nb_filters; i++) {
  435. int64_t end_pts = d->last_frame_pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE :
  436. d->last_frame_pts + d->last_frame_duration_est;
  437. ret = ifilter_send_eof(ist->filters[i], end_pts, d->last_frame_tb);
  438. if (ret < 0)
  439. return ret;
  440. }
  441. return 0;
  442. }
  443. static int packet_decode(InputStream *ist, AVPacket *pkt, AVFrame *frame)
  444. {
  445. const InputFile *ifile = input_files[ist->file_index];
  446. Decoder *d = ist->decoder;
  447. AVCodecContext *dec = ist->dec_ctx;
  448. const char *type_desc = av_get_media_type_string(dec->codec_type);
  449. int ret;
  450. if (dec->codec_type == AVMEDIA_TYPE_SUBTITLE)
  451. return transcode_subtitles(ist, pkt, frame);
  452. // With fate-indeo3-2, we're getting 0-sized packets before EOF for some
  453. // reason. This seems like a semi-critical bug. Don't trigger EOF, and
  454. // skip the packet.
  455. if (pkt && pkt->size == 0)
  456. return 0;
  457. if (pkt && ifile->format_nots) {
  458. pkt->pts = AV_NOPTS_VALUE;
  459. pkt->dts = AV_NOPTS_VALUE;
  460. }
  461. ret = avcodec_send_packet(dec, pkt);
  462. if (ret < 0 && !(ret == AVERROR_EOF && !pkt)) {
  463. // In particular, we don't expect AVERROR(EAGAIN), because we read all
  464. // decoded frames with avcodec_receive_frame() until done.
  465. if (ret == AVERROR(EAGAIN)) {
  466. av_log(ist, AV_LOG_FATAL, "A decoder returned an unexpected error code. "
  467. "This is a bug, please report it.\n");
  468. return AVERROR_BUG;
  469. }
  470. av_log(ist, AV_LOG_ERROR, "Error submitting %s to decoder: %s\n",
  471. pkt ? "packet" : "EOF", av_err2str(ret));
  472. if (ret != AVERROR_EOF) {
  473. ist->decode_errors++;
  474. if (!exit_on_error)
  475. ret = 0;
  476. }
  477. return ret;
  478. }
  479. while (1) {
  480. FrameData *fd;
  481. av_frame_unref(frame);
  482. update_benchmark(NULL);
  483. ret = avcodec_receive_frame(dec, frame);
  484. update_benchmark("decode_%s %d.%d", type_desc,
  485. ist->file_index, ist->index);
  486. if (ret == AVERROR(EAGAIN)) {
  487. av_assert0(pkt); // should never happen during flushing
  488. return 0;
  489. } else if (ret == AVERROR_EOF) {
  490. return ret;
  491. } else if (ret < 0) {
  492. av_log(ist, AV_LOG_ERROR, "Decoding error: %s\n", av_err2str(ret));
  493. ist->decode_errors++;
  494. if (exit_on_error)
  495. return ret;
  496. continue;
  497. }
  498. if (frame->decode_error_flags || (frame->flags & AV_FRAME_FLAG_CORRUPT)) {
  499. av_log(ist, exit_on_error ? AV_LOG_FATAL : AV_LOG_WARNING,
  500. "corrupt decoded frame\n");
  501. if (exit_on_error)
  502. return AVERROR_INVALIDDATA;
  503. }
  504. av_assert0(!frame->opaque_ref);
  505. fd = frame_data(frame);
  506. if (!fd) {
  507. av_frame_unref(frame);
  508. return AVERROR(ENOMEM);
  509. }
  510. fd->dec.pts = frame->pts;
  511. fd->dec.tb = dec->pkt_timebase;
  512. fd->dec.frame_num = dec->frame_num - 1;
  513. fd->bits_per_raw_sample = dec->bits_per_raw_sample;
  514. frame->time_base = dec->pkt_timebase;
  515. if (dec->codec_type == AVMEDIA_TYPE_AUDIO) {
  516. ist->samples_decoded += frame->nb_samples;
  517. ist->nb_samples = frame->nb_samples;
  518. audio_ts_process(ist, ist->decoder, frame);
  519. } else {
  520. ret = video_frame_process(ist, frame);
  521. if (ret < 0) {
  522. av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
  523. "data for stream #%d:%d\n", ist->file_index, ist->index);
  524. return ret;
  525. }
  526. }
  527. ist->frames_decoded++;
  528. ret = tq_send(d->queue_out, 0, frame);
  529. if (ret < 0)
  530. return ret;
  531. }
  532. }
  533. static void dec_thread_set_name(const InputStream *ist)
  534. {
  535. char name[16];
  536. snprintf(name, sizeof(name), "dec%d:%d:%s", ist->file_index, ist->index,
  537. ist->dec_ctx->codec->name);
  538. ff_thread_setname(name);
  539. }
  540. static void dec_thread_uninit(DecThreadContext *dt)
  541. {
  542. av_packet_free(&dt->pkt);
  543. av_frame_free(&dt->frame);
  544. memset(dt, 0, sizeof(*dt));
  545. }
  546. static int dec_thread_init(DecThreadContext *dt)
  547. {
  548. memset(dt, 0, sizeof(*dt));
  549. dt->frame = av_frame_alloc();
  550. if (!dt->frame)
  551. goto fail;
  552. dt->pkt = av_packet_alloc();
  553. if (!dt->pkt)
  554. goto fail;
  555. return 0;
  556. fail:
  557. dec_thread_uninit(dt);
  558. return AVERROR(ENOMEM);
  559. }
  560. static void *decoder_thread(void *arg)
  561. {
  562. InputStream *ist = arg;
  563. InputFile *ifile = input_files[ist->file_index];
  564. Decoder *d = ist->decoder;
  565. DecThreadContext dt;
  566. int ret = 0, input_status = 0;
  567. ret = dec_thread_init(&dt);
  568. if (ret < 0)
  569. goto finish;
  570. dec_thread_set_name(ist);
  571. while (!input_status) {
  572. int dummy, flush_buffers;
  573. input_status = tq_receive(d->queue_in, &dummy, dt.pkt);
  574. flush_buffers = input_status >= 0 && !dt.pkt->buf;
  575. if (!dt.pkt->buf)
  576. av_log(ist, AV_LOG_VERBOSE, "Decoder thread received %s packet\n",
  577. flush_buffers ? "flush" : "EOF");
  578. ret = packet_decode(ist, dt.pkt->buf ? dt.pkt : NULL, dt.frame);
  579. av_packet_unref(dt.pkt);
  580. av_frame_unref(dt.frame);
  581. if (ret == AVERROR_EOF) {
  582. av_log(ist, AV_LOG_VERBOSE, "Decoder returned EOF, %s\n",
  583. flush_buffers ? "resetting" : "finishing");
  584. if (!flush_buffers)
  585. break;
  586. /* report last frame duration to the demuxer thread */
  587. if (ist->dec->type == AVMEDIA_TYPE_AUDIO) {
  588. LastFrameDuration dur;
  589. dur.stream_idx = ist->index;
  590. dur.duration = av_rescale_q(ist->nb_samples,
  591. (AVRational){ 1, ist->dec_ctx->sample_rate},
  592. ist->st->time_base);
  593. av_thread_message_queue_send(ifile->audio_duration_queue, &dur, 0);
  594. }
  595. avcodec_flush_buffers(ist->dec_ctx);
  596. } else if (ret < 0) {
  597. av_log(ist, AV_LOG_ERROR, "Error processing packet in decoder: %s\n",
  598. av_err2str(ret));
  599. break;
  600. }
  601. // signal to the consumer thread that the entire packet was processed
  602. ret = tq_send(d->queue_out, 0, dt.frame);
  603. if (ret < 0) {
  604. if (ret != AVERROR_EOF)
  605. av_log(ist, AV_LOG_ERROR, "Error communicating with the main thread\n");
  606. break;
  607. }
  608. }
  609. // EOF is normal thread termination
  610. if (ret == AVERROR_EOF)
  611. ret = 0;
  612. finish:
  613. tq_receive_finish(d->queue_in, 0);
  614. tq_send_finish (d->queue_out, 0);
  615. // make sure the demuxer does not get stuck waiting for audio durations
  616. // that will never arrive
  617. if (ifile->audio_duration_queue && ist->dec->type == AVMEDIA_TYPE_AUDIO)
  618. av_thread_message_queue_set_err_recv(ifile->audio_duration_queue, AVERROR_EOF);
  619. dec_thread_uninit(&dt);
  620. av_log(ist, AV_LOG_VERBOSE, "Terminating decoder thread\n");
  621. return (void*)(intptr_t)ret;
  622. }
  623. int dec_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
  624. {
  625. Decoder *d = ist->decoder;
  626. int ret = 0, thread_ret;
  627. // thread already joined
  628. if (!d->queue_in)
  629. return AVERROR_EOF;
  630. // send the packet/flush request/EOF to the decoder thread
  631. if (pkt || no_eof) {
  632. av_packet_unref(d->pkt);
  633. if (pkt) {
  634. ret = av_packet_ref(d->pkt, pkt);
  635. if (ret < 0)
  636. goto finish;
  637. }
  638. ret = tq_send(d->queue_in, 0, d->pkt);
  639. if (ret < 0)
  640. goto finish;
  641. } else
  642. tq_send_finish(d->queue_in, 0);
  643. // retrieve all decoded data for the packet
  644. while (1) {
  645. int dummy;
  646. ret = tq_receive(d->queue_out, &dummy, d->frame);
  647. if (ret < 0)
  648. goto finish;
  649. // packet fully processed
  650. if (!d->frame->buf[0])
  651. return 0;
  652. // process the decoded frame
  653. if (ist->dec->type == AVMEDIA_TYPE_SUBTITLE) {
  654. ret = process_subtitle(ist, d->frame);
  655. } else {
  656. ret = send_frame_to_filters(ist, d->frame);
  657. }
  658. av_frame_unref(d->frame);
  659. if (ret < 0)
  660. goto finish;
  661. }
  662. finish:
  663. thread_ret = dec_thread_stop(d);
  664. if (thread_ret < 0) {
  665. av_log(ist, AV_LOG_ERROR, "Decoder thread returned error: %s\n",
  666. av_err2str(thread_ret));
  667. ret = err_merge(ret, thread_ret);
  668. }
  669. // non-EOF errors here are all fatal
  670. if (ret < 0 && ret != AVERROR_EOF)
  671. return ret;
  672. // signal EOF to our downstreams
  673. if (ist->dec->type == AVMEDIA_TYPE_SUBTITLE)
  674. sub2video_flush(ist);
  675. else {
  676. ret = send_filter_eof(ist);
  677. if (ret < 0) {
  678. av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
  679. return ret;
  680. }
  681. }
  682. return AVERROR_EOF;
  683. }
  684. static int dec_thread_start(InputStream *ist)
  685. {
  686. Decoder *d = ist->decoder;
  687. ObjPool *op;
  688. int ret = 0;
  689. op = objpool_alloc_packets();
  690. if (!op)
  691. return AVERROR(ENOMEM);
  692. d->queue_in = tq_alloc(1, 1, op, pkt_move);
  693. if (!d->queue_in) {
  694. objpool_free(&op);
  695. return AVERROR(ENOMEM);
  696. }
  697. op = objpool_alloc_frames();
  698. if (!op)
  699. goto fail;
  700. d->queue_out = tq_alloc(1, 4, op, frame_move);
  701. if (!d->queue_out) {
  702. objpool_free(&op);
  703. goto fail;
  704. }
  705. ret = pthread_create(&d->thread, NULL, decoder_thread, ist);
  706. if (ret) {
  707. ret = AVERROR(ret);
  708. av_log(ist, AV_LOG_ERROR, "pthread_create() failed: %s\n",
  709. av_err2str(ret));
  710. goto fail;
  711. }
  712. return 0;
  713. fail:
  714. if (ret >= 0)
  715. ret = AVERROR(ENOMEM);
  716. tq_free(&d->queue_in);
  717. tq_free(&d->queue_out);
  718. return ret;
  719. }
  720. static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
  721. {
  722. InputStream *ist = s->opaque;
  723. Decoder *d = ist->decoder;
  724. const enum AVPixelFormat *p;
  725. for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
  726. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
  727. const AVCodecHWConfig *config = NULL;
  728. int i;
  729. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  730. break;
  731. if (ist->hwaccel_id == HWACCEL_GENERIC ||
  732. ist->hwaccel_id == HWACCEL_AUTO) {
  733. for (i = 0;; i++) {
  734. config = avcodec_get_hw_config(s->codec, i);
  735. if (!config)
  736. break;
  737. if (!(config->methods &
  738. AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
  739. continue;
  740. if (config->pix_fmt == *p)
  741. break;
  742. }
  743. }
  744. if (config && config->device_type == ist->hwaccel_device_type) {
  745. d->hwaccel_pix_fmt = *p;
  746. break;
  747. }
  748. }
  749. return *p;
  750. }
  751. static HWDevice *hw_device_match_by_codec(const AVCodec *codec)
  752. {
  753. const AVCodecHWConfig *config;
  754. HWDevice *dev;
  755. int i;
  756. for (i = 0;; i++) {
  757. config = avcodec_get_hw_config(codec, i);
  758. if (!config)
  759. return NULL;
  760. if (!(config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
  761. continue;
  762. dev = hw_device_get_by_type(config->device_type);
  763. if (dev)
  764. return dev;
  765. }
  766. }
  767. static int hw_device_setup_for_decode(InputStream *ist)
  768. {
  769. const AVCodecHWConfig *config;
  770. enum AVHWDeviceType type;
  771. HWDevice *dev = NULL;
  772. int err, auto_device = 0;
  773. if (ist->hwaccel_device) {
  774. dev = hw_device_get_by_name(ist->hwaccel_device);
  775. if (!dev) {
  776. if (ist->hwaccel_id == HWACCEL_AUTO) {
  777. auto_device = 1;
  778. } else if (ist->hwaccel_id == HWACCEL_GENERIC) {
  779. type = ist->hwaccel_device_type;
  780. err = hw_device_init_from_type(type, ist->hwaccel_device,
  781. &dev);
  782. } else {
  783. // This will be dealt with by API-specific initialisation
  784. // (using hwaccel_device), so nothing further needed here.
  785. return 0;
  786. }
  787. } else {
  788. if (ist->hwaccel_id == HWACCEL_AUTO) {
  789. ist->hwaccel_device_type = dev->type;
  790. } else if (ist->hwaccel_device_type != dev->type) {
  791. av_log(NULL, AV_LOG_ERROR, "Invalid hwaccel device "
  792. "specified for decoder: device %s of type %s is not "
  793. "usable with hwaccel %s.\n", dev->name,
  794. av_hwdevice_get_type_name(dev->type),
  795. av_hwdevice_get_type_name(ist->hwaccel_device_type));
  796. return AVERROR(EINVAL);
  797. }
  798. }
  799. } else {
  800. if (ist->hwaccel_id == HWACCEL_AUTO) {
  801. auto_device = 1;
  802. } else if (ist->hwaccel_id == HWACCEL_GENERIC) {
  803. type = ist->hwaccel_device_type;
  804. dev = hw_device_get_by_type(type);
  805. // When "-qsv_device device" is used, an internal QSV device named
  806. // as "__qsv_device" is created. Another QSV device is created too
  807. // if "-init_hw_device qsv=name:device" is used. There are 2 QSV devices
  808. // if both "-qsv_device device" and "-init_hw_device qsv=name:device"
  809. // are used, hw_device_get_by_type(AV_HWDEVICE_TYPE_QSV) returns NULL.
  810. // To keep back-compatibility with the removed ad-hoc libmfx setup code,
  811. // call hw_device_get_by_name("__qsv_device") to select the internal QSV
  812. // device.
  813. if (!dev && type == AV_HWDEVICE_TYPE_QSV)
  814. dev = hw_device_get_by_name("__qsv_device");
  815. if (!dev)
  816. err = hw_device_init_from_type(type, NULL, &dev);
  817. } else {
  818. dev = hw_device_match_by_codec(ist->dec);
  819. if (!dev) {
  820. // No device for this codec, but not using generic hwaccel
  821. // and therefore may well not need one - ignore.
  822. return 0;
  823. }
  824. }
  825. }
  826. if (auto_device) {
  827. int i;
  828. if (!avcodec_get_hw_config(ist->dec, 0)) {
  829. // Decoder does not support any hardware devices.
  830. return 0;
  831. }
  832. for (i = 0; !dev; i++) {
  833. config = avcodec_get_hw_config(ist->dec, i);
  834. if (!config)
  835. break;
  836. type = config->device_type;
  837. dev = hw_device_get_by_type(type);
  838. if (dev) {
  839. av_log(NULL, AV_LOG_INFO, "Using auto "
  840. "hwaccel type %s with existing device %s.\n",
  841. av_hwdevice_get_type_name(type), dev->name);
  842. }
  843. }
  844. for (i = 0; !dev; i++) {
  845. config = avcodec_get_hw_config(ist->dec, i);
  846. if (!config)
  847. break;
  848. type = config->device_type;
  849. // Try to make a new device of this type.
  850. err = hw_device_init_from_type(type, ist->hwaccel_device,
  851. &dev);
  852. if (err < 0) {
  853. // Can't make a device of this type.
  854. continue;
  855. }
  856. if (ist->hwaccel_device) {
  857. av_log(NULL, AV_LOG_INFO, "Using auto "
  858. "hwaccel type %s with new device created "
  859. "from %s.\n", av_hwdevice_get_type_name(type),
  860. ist->hwaccel_device);
  861. } else {
  862. av_log(NULL, AV_LOG_INFO, "Using auto "
  863. "hwaccel type %s with new default device.\n",
  864. av_hwdevice_get_type_name(type));
  865. }
  866. }
  867. if (dev) {
  868. ist->hwaccel_device_type = type;
  869. } else {
  870. av_log(NULL, AV_LOG_INFO, "Auto hwaccel "
  871. "disabled: no device found.\n");
  872. ist->hwaccel_id = HWACCEL_NONE;
  873. return 0;
  874. }
  875. }
  876. if (!dev) {
  877. av_log(NULL, AV_LOG_ERROR, "No device available "
  878. "for decoder: device type %s needed for codec %s.\n",
  879. av_hwdevice_get_type_name(type), ist->dec->name);
  880. return err;
  881. }
  882. ist->dec_ctx->hw_device_ctx = av_buffer_ref(dev->device_ref);
  883. if (!ist->dec_ctx->hw_device_ctx)
  884. return AVERROR(ENOMEM);
  885. return 0;
  886. }
  887. int dec_open(InputStream *ist)
  888. {
  889. Decoder *d;
  890. const AVCodec *codec = ist->dec;
  891. int ret;
  892. if (!codec) {
  893. av_log(ist, AV_LOG_ERROR,
  894. "Decoding requested, but no decoder found for: %s\n",
  895. avcodec_get_name(ist->dec_ctx->codec_id));
  896. return AVERROR(EINVAL);
  897. }
  898. ret = dec_alloc(&ist->decoder);
  899. if (ret < 0)
  900. return ret;
  901. d = ist->decoder;
  902. if (codec->type == AVMEDIA_TYPE_SUBTITLE && ist->fix_sub_duration) {
  903. for (int i = 0; i < FF_ARRAY_ELEMS(d->sub_prev); i++) {
  904. d->sub_prev[i] = av_frame_alloc();
  905. if (!d->sub_prev[i])
  906. return AVERROR(ENOMEM);
  907. }
  908. d->sub_heartbeat = av_frame_alloc();
  909. if (!d->sub_heartbeat)
  910. return AVERROR(ENOMEM);
  911. }
  912. ist->dec_ctx->opaque = ist;
  913. ist->dec_ctx->get_format = get_format;
  914. if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
  915. (ist->decoding_needed & DECODING_FOR_OST)) {
  916. av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
  917. if (ist->decoding_needed & DECODING_FOR_FILTER)
  918. av_log(NULL, AV_LOG_WARNING, "Warning using DVB subtitles for filtering and output at the same time is not fully supported, also see -compute_edt [0|1]\n");
  919. }
  920. /* Useful for subtitles retiming by lavf (FIXME), skipping samples in
  921. * audio, and video decoders such as cuvid or mediacodec */
  922. ist->dec_ctx->pkt_timebase = ist->st->time_base;
  923. if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
  924. av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
  925. /* Attached pics are sparse, therefore we would not want to delay their decoding till EOF. */
  926. if (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC)
  927. av_dict_set(&ist->decoder_opts, "threads", "1", 0);
  928. ret = hw_device_setup_for_decode(ist);
  929. if (ret < 0) {
  930. av_log(ist, AV_LOG_ERROR,
  931. "Hardware device setup failed for decoder: %s\n",
  932. av_err2str(ret));
  933. return ret;
  934. }
  935. if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
  936. av_log(ist, AV_LOG_ERROR, "Error while opening decoder: %s\n",
  937. av_err2str(ret));
  938. return ret;
  939. }
  940. ret = check_avoptions(ist->decoder_opts);
  941. if (ret < 0)
  942. return ret;
  943. ret = dec_thread_start(ist);
  944. if (ret < 0) {
  945. av_log(ist, AV_LOG_ERROR, "Error starting decoder thread: %s\n",
  946. av_err2str(ret));
  947. return ret;
  948. }
  949. return 0;
  950. }