FFmpeg
ffmpeg_dec.c
Go to the documentation of this file.
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 
19 #include "libavutil/avassert.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/timestamp.h"
26 
27 #include "libavcodec/avcodec.h"
28 #include "libavcodec/codec.h"
29 
30 #include "libavfilter/buffersrc.h"
31 
32 #include "ffmpeg.h"
33 #include "thread_queue.h"
34 
35 struct Decoder {
38 
40 
41  // pts/estimated duration of the last decoded frame
42  // * in decoder timebase for video,
43  // * in last_frame_tb (may change during decoding) for audio
44  int64_t last_frame_pts;
49 
50  /* previous decoded subtitles */
53 
55  /**
56  * Queue for sending coded packets from the main thread to
57  * the decoder thread.
58  *
59  * An empty packet is sent to flush the decoder without terminating
60  * decoding.
61  */
63  /**
64  * Queue for sending decoded frames from the decoder thread
65  * to the main thread.
66  *
67  * An empty frame is sent to signal that a single packet has been fully
68  * processed.
69  */
71 };
72 
73 // data that is local to the decoder thread and not visible outside of it
74 typedef struct DecThreadContext {
78 
80 {
81  void *ret;
82 
83  if (!d->queue_in)
84  return 0;
85 
86  tq_send_finish(d->queue_in, 0);
87  tq_receive_finish(d->queue_out, 0);
88 
89  pthread_join(d->thread, &ret);
90 
91  tq_free(&d->queue_in);
92  tq_free(&d->queue_out);
93 
94  return (intptr_t)ret;
95 }
96 
97 void dec_free(Decoder **pdec)
98 {
99  Decoder *dec = *pdec;
100 
101  if (!dec)
102  return;
103 
104  dec_thread_stop(dec);
105 
106  av_frame_free(&dec->frame);
107  av_packet_free(&dec->pkt);
108 
109  for (int i = 0; i < FF_ARRAY_ELEMS(dec->sub_prev); i++)
110  av_frame_free(&dec->sub_prev[i]);
112 
113  av_freep(pdec);
114 }
115 
116 static int dec_alloc(Decoder **pdec)
117 {
118  Decoder *dec;
119 
120  *pdec = NULL;
121 
122  dec = av_mallocz(sizeof(*dec));
123  if (!dec)
124  return AVERROR(ENOMEM);
125 
126  dec->frame = av_frame_alloc();
127  if (!dec->frame)
128  goto fail;
129 
130  dec->pkt = av_packet_alloc();
131  if (!dec->pkt)
132  goto fail;
133 
136  dec->last_frame_tb = (AVRational){ 1, 1 };
138 
139  *pdec = dec;
140 
141  return 0;
142 fail:
143  dec_free(&dec);
144  return AVERROR(ENOMEM);
145 }
146 
147 static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
148 {
149  int i, ret;
150 
151  av_assert1(ist->nb_filters > 0); /* ensure ret is initialized */
152  for (i = 0; i < ist->nb_filters; i++) {
153  ret = ifilter_send_frame(ist->filters[i], decoded_frame, i < ist->nb_filters - 1);
154  if (ret == AVERROR_EOF)
155  ret = 0; /* ignore */
156  if (ret < 0) {
158  "Failed to inject frame into filter network: %s\n", av_err2str(ret));
159  break;
160  }
161  }
162  return ret;
163 }
164 
166  const AVFrame *frame)
167 {
168  const int prev = d->last_frame_tb.den;
169  const int sr = frame->sample_rate;
170 
171  AVRational tb_new;
172  int64_t gcd;
173 
174  if (frame->sample_rate == d->last_frame_sample_rate)
175  goto finish;
176 
177  gcd = av_gcd(prev, sr);
178 
179  if (prev / gcd >= INT_MAX / sr) {
180  av_log(logctx, AV_LOG_WARNING,
181  "Audio timestamps cannot be represented exactly after "
182  "sample rate change: %d -> %d\n", prev, sr);
183 
184  // LCM of 192000, 44100, allows to represent all common samplerates
185  tb_new = (AVRational){ 1, 28224000 };
186  } else
187  tb_new = (AVRational){ 1, prev / gcd * sr };
188 
189  // keep the frame timebase if it is strictly better than
190  // the samplerate-defined one
191  if (frame->time_base.num == 1 && frame->time_base.den > tb_new.den &&
192  !(frame->time_base.den % tb_new.den))
193  tb_new = frame->time_base;
194 
195  if (d->last_frame_pts != AV_NOPTS_VALUE)
196  d->last_frame_pts = av_rescale_q(d->last_frame_pts,
197  d->last_frame_tb, tb_new);
198  d->last_frame_duration_est = av_rescale_q(d->last_frame_duration_est,
199  d->last_frame_tb, tb_new);
200 
201  d->last_frame_tb = tb_new;
202  d->last_frame_sample_rate = frame->sample_rate;
203 
204 finish:
205  return d->last_frame_tb;
206 }
207 
208 static void audio_ts_process(void *logctx, Decoder *d, AVFrame *frame)
209 {
210  AVRational tb_filter = (AVRational){1, frame->sample_rate};
211  AVRational tb;
212  int64_t pts_pred;
213 
214  // on samplerate change, choose a new internal timebase for timestamp
215  // generation that can represent timestamps from all the samplerates
216  // seen so far
217  tb = audio_samplerate_update(logctx, d, frame);
218  pts_pred = d->last_frame_pts == AV_NOPTS_VALUE ? 0 :
219  d->last_frame_pts + d->last_frame_duration_est;
220 
221  if (frame->pts == AV_NOPTS_VALUE) {
222  frame->pts = pts_pred;
223  frame->time_base = tb;
224  } else if (d->last_frame_pts != AV_NOPTS_VALUE &&
225  frame->pts > av_rescale_q_rnd(pts_pred, tb, frame->time_base,
226  AV_ROUND_UP)) {
227  // there was a gap in timestamps, reset conversion state
228  d->last_filter_in_rescale_delta = AV_NOPTS_VALUE;
229  }
230 
231  frame->pts = av_rescale_delta(frame->time_base, frame->pts,
232  tb, frame->nb_samples,
233  &d->last_filter_in_rescale_delta, tb);
234 
235  d->last_frame_pts = frame->pts;
236  d->last_frame_duration_est = av_rescale_q(frame->nb_samples,
237  tb_filter, tb);
238 
239  // finally convert to filtering timebase
240  frame->pts = av_rescale_q(frame->pts, tb, tb_filter);
241  frame->duration = frame->nb_samples;
242  frame->time_base = tb_filter;
243 }
244 
245 static int64_t video_duration_estimate(const InputStream *ist, const AVFrame *frame)
246 {
247  const Decoder *d = ist->decoder;
248  const InputFile *ifile = input_files[ist->file_index];
249  int64_t codec_duration = 0;
250 
251  // XXX lavf currently makes up frame durations when they are not provided by
252  // the container. As there is no way to reliably distinguish real container
253  // durations from the fake made-up ones, we use heuristics based on whether
254  // the container has timestamps. Eventually lavf should stop making up
255  // durations, then this should be simplified.
256 
257  // prefer frame duration for containers with timestamps
258  if (frame->duration > 0 && (!ifile->format_nots || ist->framerate.num))
259  return frame->duration;
260 
261  if (ist->dec_ctx->framerate.den && ist->dec_ctx->framerate.num) {
262  int fields = frame->repeat_pict + 2;
263  AVRational field_rate = av_mul_q(ist->dec_ctx->framerate,
264  (AVRational){ 2, 1 });
265  codec_duration = av_rescale_q(fields, av_inv_q(field_rate),
266  frame->time_base);
267  }
268 
269  // prefer codec-layer duration for containers without timestamps
270  if (codec_duration > 0 && ifile->format_nots)
271  return codec_duration;
272 
273  // when timestamps are available, repeat last frame's actual duration
274  // (i.e. pts difference between this and last frame)
275  if (frame->pts != AV_NOPTS_VALUE && d->last_frame_pts != AV_NOPTS_VALUE &&
276  frame->pts > d->last_frame_pts)
277  return frame->pts - d->last_frame_pts;
278 
279  // try frame/codec duration
280  if (frame->duration > 0)
281  return frame->duration;
282  if (codec_duration > 0)
283  return codec_duration;
284 
285  // try average framerate
286  if (ist->st->avg_frame_rate.num && ist->st->avg_frame_rate.den) {
287  int64_t d = av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
288  frame->time_base);
289  if (d > 0)
290  return d;
291  }
292 
293  // last resort is last frame's estimated duration, and 1
294  return FFMAX(d->last_frame_duration_est, 1);
295 }
296 
298 {
299  Decoder *d = ist->decoder;
300 
301  // The following line may be required in some cases where there is no parser
302  // or the parser does not has_b_frames correctly
303  if (ist->par->video_delay < ist->dec_ctx->has_b_frames) {
304  if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
305  ist->par->video_delay = ist->dec_ctx->has_b_frames;
306  } else
308  "video_delay is larger in decoder than demuxer %d > %d.\n"
309  "If you want to help, upload a sample "
310  "of this file to https://streams.videolan.org/upload/ "
311  "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
312  ist->dec_ctx->has_b_frames,
313  ist->par->video_delay);
314  }
315 
316  if (ist->dec_ctx->width != frame->width ||
317  ist->dec_ctx->height != frame->height ||
318  ist->dec_ctx->pix_fmt != frame->format) {
319  av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
320  frame->width,
321  frame->height,
322  frame->format,
323  ist->dec_ctx->width,
324  ist->dec_ctx->height,
325  ist->dec_ctx->pix_fmt);
326  }
327 
328 #if FFMPEG_OPT_TOP
329  if(ist->top_field_first>=0) {
330  av_log(ist, AV_LOG_WARNING, "-top is deprecated, use the setfield filter instead\n");
332  }
333 #endif
334 
335  if (frame->format == d->hwaccel_pix_fmt) {
336  int err = hwaccel_retrieve_data(ist->dec_ctx, frame);
337  if (err < 0)
338  return err;
339  }
340 
341  frame->pts = frame->best_effort_timestamp;
342 
343  // forced fixed framerate
344  if (ist->framerate.num) {
345  frame->pts = AV_NOPTS_VALUE;
346  frame->duration = 1;
347  frame->time_base = av_inv_q(ist->framerate);
348  }
349 
350  // no timestamp available - extrapolate from previous frame duration
351  if (frame->pts == AV_NOPTS_VALUE)
352  frame->pts = d->last_frame_pts == AV_NOPTS_VALUE ? 0 :
353  d->last_frame_pts + d->last_frame_duration_est;
354 
355  // update timestamp history
356  d->last_frame_duration_est = video_duration_estimate(ist, frame);
357  d->last_frame_pts = frame->pts;
358  d->last_frame_tb = frame->time_base;
359 
360  if (debug_ts) {
361  av_log(ist, AV_LOG_INFO,
362  "decoder -> pts:%s pts_time:%s "
363  "pkt_dts:%s pkt_dts_time:%s "
364  "duration:%s duration_time:%s "
365  "keyframe:%d frame_type:%d time_base:%d/%d\n",
366  av_ts2str(frame->pts),
367  av_ts2timestr(frame->pts, &frame->time_base),
368  av_ts2str(frame->pkt_dts),
369  av_ts2timestr(frame->pkt_dts, &frame->time_base),
370  av_ts2str(frame->duration),
371  av_ts2timestr(frame->duration, &frame->time_base),
372  !!(frame->flags & AV_FRAME_FLAG_KEY), frame->pict_type,
373  frame->time_base.num, frame->time_base.den);
374  }
375 
376  if (ist->st->sample_aspect_ratio.num)
377  frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
378 
379  return 0;
380 }
381 
382 static void sub2video_flush(InputStream *ist)
383 {
384  for (int i = 0; i < ist->nb_filters; i++) {
385  int ret = ifilter_sub2video(ist->filters[i], NULL);
386  if (ret != AVERROR_EOF && ret < 0)
387  av_log(NULL, AV_LOG_WARNING, "Flush the frame error.\n");
388  }
389 }
390 
392 {
393  Decoder *d = ist->decoder;
394  const AVSubtitle *subtitle = (AVSubtitle*)frame->buf[0]->data;
395  int ret = 0;
396 
397  if (ist->fix_sub_duration) {
398  AVSubtitle *sub_prev = d->sub_prev[0]->buf[0] ?
399  (AVSubtitle*)d->sub_prev[0]->buf[0]->data : NULL;
400  int end = 1;
401  if (sub_prev) {
402  end = av_rescale(subtitle->pts - sub_prev->pts,
403  1000, AV_TIME_BASE);
404  if (end < sub_prev->end_display_time) {
406  "Subtitle duration reduced from %"PRId32" to %d%s\n",
407  sub_prev->end_display_time, end,
408  end <= 0 ? ", dropping it" : "");
409  sub_prev->end_display_time = end;
410  }
411  }
412 
413  av_frame_unref(d->sub_prev[1]);
414  av_frame_move_ref(d->sub_prev[1], frame);
415 
416  frame = d->sub_prev[0];
417  subtitle = frame->buf[0] ? (AVSubtitle*)frame->buf[0]->data : NULL;
418 
419  FFSWAP(AVFrame*, d->sub_prev[0], d->sub_prev[1]);
420 
421  if (end <= 0)
422  return 0;
423  }
424 
425  if (!subtitle)
426  return 0;
427 
428  for (int i = 0; i < ist->nb_filters; i++) {
429  ret = ifilter_sub2video(ist->filters[i], frame);
430  if (ret < 0) {
431  av_log(ist, AV_LOG_ERROR, "Error sending a subtitle for filtering: %s\n",
432  av_err2str(ret));
433  return ret;
434  }
435  }
436 
437  subtitle = (AVSubtitle*)frame->buf[0]->data;
438  if (!subtitle->num_rects)
439  return 0;
440 
441  for (int oidx = 0; oidx < ist->nb_outputs; oidx++) {
442  OutputStream *ost = ist->outputs[oidx];
443  if (!ost->enc || ost->type != AVMEDIA_TYPE_SUBTITLE)
444  continue;
445 
446  ret = enc_subtitle(output_files[ost->file_index], ost, subtitle);
447  if (ret < 0)
448  return ret;
449  }
450 
451  return 0;
452 }
453 
454 int fix_sub_duration_heartbeat(InputStream *ist, int64_t signal_pts)
455 {
456  Decoder *d = ist->decoder;
457  int ret = AVERROR_BUG;
458  AVSubtitle *prev_subtitle = d->sub_prev[0]->buf[0] ?
459  (AVSubtitle*)d->sub_prev[0]->buf[0]->data : NULL;
460  AVSubtitle *subtitle;
461 
462  if (!ist->fix_sub_duration || !prev_subtitle ||
463  !prev_subtitle->num_rects || signal_pts <= prev_subtitle->pts)
464  return 0;
465 
466  av_frame_unref(d->sub_heartbeat);
467  ret = subtitle_wrap_frame(d->sub_heartbeat, prev_subtitle, 1);
468  if (ret < 0)
469  return ret;
470 
471  subtitle = (AVSubtitle*)d->sub_heartbeat->buf[0]->data;
472  subtitle->pts = signal_pts;
473 
474  return process_subtitle(ist, d->sub_heartbeat);
475 }
476 
477 static int transcode_subtitles(InputStream *ist, const AVPacket *pkt,
478  AVFrame *frame)
479 {
480  Decoder *d = ist->decoder;
481  AVPacket *flush_pkt = NULL;
482  AVSubtitle subtitle;
483  int got_output;
484  int ret;
485 
486  if (!pkt) {
487  flush_pkt = av_packet_alloc();
488  if (!flush_pkt)
489  return AVERROR(ENOMEM);
490  }
491 
492  ret = avcodec_decode_subtitle2(ist->dec_ctx, &subtitle, &got_output,
493  pkt ? pkt : flush_pkt);
494  av_packet_free(&flush_pkt);
495 
496  if (ret < 0) {
497  av_log(ist, AV_LOG_ERROR, "Error decoding subtitles: %s\n",
498  av_err2str(ret));
499  ist->decode_errors++;
500  return exit_on_error ? ret : 0;
501  }
502 
503  if (!got_output)
504  return pkt ? 0 : AVERROR_EOF;
505 
506  ist->frames_decoded++;
507 
508  // XXX the queue for transferring data back to the main thread 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 
518  frame->width = ist->dec_ctx->width;
519  frame->height = ist->dec_ctx->height;
520 
521  ret = tq_send(d->queue_out, 0, frame);
522  if (ret < 0)
524 
525  return ret;
526 }
527 
528 static int send_filter_eof(InputStream *ist)
529 {
530  Decoder *d = ist->decoder;
531  int i, ret;
532 
533  for (i = 0; i < ist->nb_filters; i++) {
534  int64_t end_pts = d->last_frame_pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE :
535  d->last_frame_pts + d->last_frame_duration_est;
536  ret = ifilter_send_eof(ist->filters[i], end_pts, d->last_frame_tb);
537  if (ret < 0)
538  return ret;
539  }
540  return 0;
541 }
542 
543 static int packet_decode(InputStream *ist, const AVPacket *pkt, AVFrame *frame)
544 {
545  Decoder *d = ist->decoder;
546  AVCodecContext *dec = ist->dec_ctx;
547  const char *type_desc = av_get_media_type_string(dec->codec_type);
548  int ret;
549 
550  if (dec->codec_type == AVMEDIA_TYPE_SUBTITLE)
551  return transcode_subtitles(ist, pkt, frame);
552 
553  // With fate-indeo3-2, we're getting 0-sized packets before EOF for some
554  // reason. This seems like a semi-critical bug. Don't trigger EOF, and
555  // skip the packet.
556  if (pkt && pkt->size == 0)
557  return 0;
558 
559  ret = avcodec_send_packet(dec, pkt);
560  if (ret < 0 && !(ret == AVERROR_EOF && !pkt)) {
561  // In particular, we don't expect AVERROR(EAGAIN), because we read all
562  // decoded frames with avcodec_receive_frame() until done.
563  if (ret == AVERROR(EAGAIN)) {
564  av_log(ist, AV_LOG_FATAL, "A decoder returned an unexpected error code. "
565  "This is a bug, please report it.\n");
566  return AVERROR_BUG;
567  }
568  av_log(ist, AV_LOG_ERROR, "Error submitting %s to decoder: %s\n",
569  pkt ? "packet" : "EOF", av_err2str(ret));
570 
571  if (ret != AVERROR_EOF) {
572  ist->decode_errors++;
573  if (!exit_on_error)
574  ret = 0;
575  }
576 
577  return ret;
578  }
579 
580  while (1) {
581  FrameData *fd;
582 
584 
587  update_benchmark("decode_%s %d.%d", type_desc,
588  ist->file_index, ist->index);
589 
590  if (ret == AVERROR(EAGAIN)) {
591  av_assert0(pkt); // should never happen during flushing
592  return 0;
593  } else if (ret == AVERROR_EOF) {
594  return ret;
595  } else if (ret < 0) {
596  av_log(ist, AV_LOG_ERROR, "Decoding error: %s\n", av_err2str(ret));
597  ist->decode_errors++;
598 
599  if (exit_on_error)
600  return ret;
601 
602  continue;
603  }
604 
605  if (frame->decode_error_flags || (frame->flags & AV_FRAME_FLAG_CORRUPT)) {
607  "corrupt decoded frame\n");
608  if (exit_on_error)
609  return AVERROR_INVALIDDATA;
610  }
611 
612 
613  av_assert0(!frame->opaque_ref);
614  fd = frame_data(frame);
615  if (!fd) {
617  return AVERROR(ENOMEM);
618  }
619  fd->dec.pts = frame->pts;
620  fd->dec.tb = dec->pkt_timebase;
621  fd->dec.frame_num = dec->frame_num - 1;
623 
624  frame->time_base = dec->pkt_timebase;
625 
626  if (dec->codec_type == AVMEDIA_TYPE_AUDIO) {
627  ist->samples_decoded += frame->nb_samples;
628  ist->nb_samples = frame->nb_samples;
629 
630  audio_ts_process(ist, ist->decoder, frame);
631  } else {
632  ret = video_frame_process(ist, frame);
633  if (ret < 0) {
634  av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
635  "data for stream #%d:%d\n", ist->file_index, ist->index);
636  return ret;
637  }
638  }
639 
640  ist->frames_decoded++;
641 
642  ret = tq_send(d->queue_out, 0, frame);
643  if (ret < 0)
644  return ret;
645  }
646 }
647 
648 static void dec_thread_set_name(const InputStream *ist)
649 {
650  char name[16];
651  snprintf(name, sizeof(name), "dec%d:%d:%s", ist->file_index, ist->index,
652  ist->dec_ctx->codec->name);
654 }
655 
657 {
658  av_packet_free(&dt->pkt);
659  av_frame_free(&dt->frame);
660 
661  memset(dt, 0, sizeof(*dt));
662 }
663 
665 {
666  memset(dt, 0, sizeof(*dt));
667 
668  dt->frame = av_frame_alloc();
669  if (!dt->frame)
670  goto fail;
671 
672  dt->pkt = av_packet_alloc();
673  if (!dt->pkt)
674  goto fail;
675 
676  return 0;
677 
678 fail:
679  dec_thread_uninit(dt);
680  return AVERROR(ENOMEM);
681 }
682 
683 static void *decoder_thread(void *arg)
684 {
685  InputStream *ist = arg;
686  InputFile *ifile = input_files[ist->file_index];
687  Decoder *d = ist->decoder;
688  DecThreadContext dt;
689  int ret = 0, input_status = 0;
690 
691  ret = dec_thread_init(&dt);
692  if (ret < 0)
693  goto finish;
694 
695  dec_thread_set_name(ist);
696 
697  while (!input_status) {
698  int dummy, flush_buffers;
699 
700  input_status = tq_receive(d->queue_in, &dummy, dt.pkt);
701  flush_buffers = input_status >= 0 && !dt.pkt->buf;
702  if (!dt.pkt->buf)
703  av_log(ist, AV_LOG_VERBOSE, "Decoder thread received %s packet\n",
704  flush_buffers ? "flush" : "EOF");
705 
706  ret = packet_decode(ist, dt.pkt->buf ? dt.pkt : NULL, dt.frame);
707 
708  av_packet_unref(dt.pkt);
709  av_frame_unref(dt.frame);
710 
711  if (ret == AVERROR_EOF) {
712  av_log(ist, AV_LOG_VERBOSE, "Decoder returned EOF, %s\n",
713  flush_buffers ? "resetting" : "finishing");
714 
715  if (!flush_buffers)
716  break;
717 
718  /* report last frame duration to the demuxer thread */
719  if (ist->dec->type == AVMEDIA_TYPE_AUDIO) {
720  LastFrameDuration dur;
721 
722  dur.stream_idx = ist->index;
723  dur.duration = av_rescale_q(ist->nb_samples,
724  (AVRational){ 1, ist->dec_ctx->sample_rate},
725  ist->st->time_base);
726 
728  }
729 
731  } else if (ret < 0) {
732  av_log(ist, AV_LOG_ERROR, "Error processing packet in decoder: %s\n",
733  av_err2str(ret));
734  break;
735  }
736 
737  // signal to the consumer thread that the entire packet was processed
738  ret = tq_send(d->queue_out, 0, dt.frame);
739  if (ret < 0) {
740  if (ret != AVERROR_EOF)
741  av_log(ist, AV_LOG_ERROR, "Error communicating with the main thread\n");
742  break;
743  }
744  }
745 
746  // EOF is normal thread termination
747  if (ret == AVERROR_EOF)
748  ret = 0;
749 
750 finish:
751  tq_receive_finish(d->queue_in, 0);
752  tq_send_finish (d->queue_out, 0);
753 
754  // make sure the demuxer does not get stuck waiting for audio durations
755  // that will never arrive
756  if (ifile->audio_duration_queue && ist->dec->type == AVMEDIA_TYPE_AUDIO)
758 
759  dec_thread_uninit(&dt);
760 
761  av_log(ist, AV_LOG_VERBOSE, "Terminating decoder thread\n");
762 
763  return (void*)(intptr_t)ret;
764 }
765 
766 int dec_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
767 {
768  Decoder *d = ist->decoder;
769  int ret = 0, thread_ret;
770 
771  // thread already joined
772  if (!d->queue_in)
773  return AVERROR_EOF;
774 
775  // send the packet/flush request/EOF to the decoder thread
776  if (pkt || no_eof) {
777  av_packet_unref(d->pkt);
778 
779  if (pkt) {
780  ret = av_packet_ref(d->pkt, pkt);
781  if (ret < 0)
782  goto finish;
783  }
784 
785  ret = tq_send(d->queue_in, 0, d->pkt);
786  if (ret < 0)
787  goto finish;
788  } else
789  tq_send_finish(d->queue_in, 0);
790 
791  // retrieve all decoded data for the packet
792  while (1) {
793  int dummy;
794 
795  ret = tq_receive(d->queue_out, &dummy, d->frame);
796  if (ret < 0)
797  goto finish;
798 
799  // packet fully processed
800  if (!d->frame->buf[0])
801  return 0;
802 
803  // process the decoded frame
804  if (ist->dec->type == AVMEDIA_TYPE_SUBTITLE) {
805  ret = process_subtitle(ist, d->frame);
806  } else {
807  ret = send_frame_to_filters(ist, d->frame);
808  }
809  av_frame_unref(d->frame);
810  if (ret < 0)
811  goto finish;
812  }
813 
814 finish:
815  thread_ret = dec_thread_stop(d);
816  if (thread_ret < 0) {
817  av_log(ist, AV_LOG_ERROR, "Decoder thread returned error: %s\n",
818  av_err2str(thread_ret));
819  ret = err_merge(ret, thread_ret);
820  }
821  // non-EOF errors here are all fatal
822  if (ret < 0 && ret != AVERROR_EOF)
823  return ret;
824 
825  // signal EOF to our downstreams
826  if (ist->dec->type == AVMEDIA_TYPE_SUBTITLE)
827  sub2video_flush(ist);
828  else {
829  ret = send_filter_eof(ist);
830  if (ret < 0) {
831  av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
832  return ret;
833  }
834  }
835 
836  return AVERROR_EOF;
837 }
838 
840 {
841  Decoder *d = ist->decoder;
842  ObjPool *op;
843  int ret = 0;
844 
846  if (!op)
847  return AVERROR(ENOMEM);
848 
849  d->queue_in = tq_alloc(1, 1, op, pkt_move);
850  if (!d->queue_in) {
851  objpool_free(&op);
852  return AVERROR(ENOMEM);
853  }
854 
856  if (!op)
857  goto fail;
858 
859  d->queue_out = tq_alloc(1, 4, op, frame_move);
860  if (!d->queue_out) {
861  objpool_free(&op);
862  goto fail;
863  }
864 
865  ret = pthread_create(&d->thread, NULL, decoder_thread, ist);
866  if (ret) {
867  ret = AVERROR(ret);
868  av_log(ist, AV_LOG_ERROR, "pthread_create() failed: %s\n",
869  av_err2str(ret));
870  goto fail;
871  }
872 
873  return 0;
874 fail:
875  if (ret >= 0)
876  ret = AVERROR(ENOMEM);
877 
878  tq_free(&d->queue_in);
879  tq_free(&d->queue_out);
880  return ret;
881 }
882 
884 {
885  InputStream *ist = s->opaque;
886  Decoder *d = ist->decoder;
887  const enum AVPixelFormat *p;
888 
889  for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
891  const AVCodecHWConfig *config = NULL;
892  int i;
893 
894  if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
895  break;
896 
897  if (ist->hwaccel_id == HWACCEL_GENERIC ||
898  ist->hwaccel_id == HWACCEL_AUTO) {
899  for (i = 0;; i++) {
900  config = avcodec_get_hw_config(s->codec, i);
901  if (!config)
902  break;
903  if (!(config->methods &
905  continue;
906  if (config->pix_fmt == *p)
907  break;
908  }
909  }
910  if (config && config->device_type == ist->hwaccel_device_type) {
911  d->hwaccel_pix_fmt = *p;
912  break;
913  }
914  }
915 
916  return *p;
917 }
918 
920 {
921  const AVCodecHWConfig *config;
922  HWDevice *dev;
923  int i;
924  for (i = 0;; i++) {
925  config = avcodec_get_hw_config(codec, i);
926  if (!config)
927  return NULL;
929  continue;
930  dev = hw_device_get_by_type(config->device_type);
931  if (dev)
932  return dev;
933  }
934 }
935 
937 {
938  const AVCodecHWConfig *config;
939  enum AVHWDeviceType type;
940  HWDevice *dev = NULL;
941  int err, auto_device = 0;
942 
943  if (ist->hwaccel_device) {
945  if (!dev) {
946  if (ist->hwaccel_id == HWACCEL_AUTO) {
947  auto_device = 1;
948  } else if (ist->hwaccel_id == HWACCEL_GENERIC) {
949  type = ist->hwaccel_device_type;
951  &dev);
952  } else {
953  // This will be dealt with by API-specific initialisation
954  // (using hwaccel_device), so nothing further needed here.
955  return 0;
956  }
957  } else {
958  if (ist->hwaccel_id == HWACCEL_AUTO) {
959  ist->hwaccel_device_type = dev->type;
960  } else if (ist->hwaccel_device_type != dev->type) {
961  av_log(NULL, AV_LOG_ERROR, "Invalid hwaccel device "
962  "specified for decoder: device %s of type %s is not "
963  "usable with hwaccel %s.\n", dev->name,
966  return AVERROR(EINVAL);
967  }
968  }
969  } else {
970  if (ist->hwaccel_id == HWACCEL_AUTO) {
971  auto_device = 1;
972  } else if (ist->hwaccel_id == HWACCEL_GENERIC) {
973  type = ist->hwaccel_device_type;
975 
976  // When "-qsv_device device" is used, an internal QSV device named
977  // as "__qsv_device" is created. Another QSV device is created too
978  // if "-init_hw_device qsv=name:device" is used. There are 2 QSV devices
979  // if both "-qsv_device device" and "-init_hw_device qsv=name:device"
980  // are used, hw_device_get_by_type(AV_HWDEVICE_TYPE_QSV) returns NULL.
981  // To keep back-compatibility with the removed ad-hoc libmfx setup code,
982  // call hw_device_get_by_name("__qsv_device") to select the internal QSV
983  // device.
984  if (!dev && type == AV_HWDEVICE_TYPE_QSV)
985  dev = hw_device_get_by_name("__qsv_device");
986 
987  if (!dev)
988  err = hw_device_init_from_type(type, NULL, &dev);
989  } else {
990  dev = hw_device_match_by_codec(ist->dec);
991  if (!dev) {
992  // No device for this codec, but not using generic hwaccel
993  // and therefore may well not need one - ignore.
994  return 0;
995  }
996  }
997  }
998 
999  if (auto_device) {
1000  int i;
1001  if (!avcodec_get_hw_config(ist->dec, 0)) {
1002  // Decoder does not support any hardware devices.
1003  return 0;
1004  }
1005  for (i = 0; !dev; i++) {
1006  config = avcodec_get_hw_config(ist->dec, i);
1007  if (!config)
1008  break;
1009  type = config->device_type;
1010  dev = hw_device_get_by_type(type);
1011  if (dev) {
1012  av_log(NULL, AV_LOG_INFO, "Using auto "
1013  "hwaccel type %s with existing device %s.\n",
1015  }
1016  }
1017  for (i = 0; !dev; i++) {
1018  config = avcodec_get_hw_config(ist->dec, i);
1019  if (!config)
1020  break;
1021  type = config->device_type;
1022  // Try to make a new device of this type.
1024  &dev);
1025  if (err < 0) {
1026  // Can't make a device of this type.
1027  continue;
1028  }
1029  if (ist->hwaccel_device) {
1030  av_log(NULL, AV_LOG_INFO, "Using auto "
1031  "hwaccel type %s with new device created "
1032  "from %s.\n", av_hwdevice_get_type_name(type),
1033  ist->hwaccel_device);
1034  } else {
1035  av_log(NULL, AV_LOG_INFO, "Using auto "
1036  "hwaccel type %s with new default device.\n",
1038  }
1039  }
1040  if (dev) {
1041  ist->hwaccel_device_type = type;
1042  } else {
1043  av_log(NULL, AV_LOG_INFO, "Auto hwaccel "
1044  "disabled: no device found.\n");
1045  ist->hwaccel_id = HWACCEL_NONE;
1046  return 0;
1047  }
1048  }
1049 
1050  if (!dev) {
1051  av_log(NULL, AV_LOG_ERROR, "No device available "
1052  "for decoder: device type %s needed for codec %s.\n",
1054  return err;
1055  }
1056 
1058  if (!ist->dec_ctx->hw_device_ctx)
1059  return AVERROR(ENOMEM);
1060 
1061  return 0;
1062 }
1063 
1065 {
1066  Decoder *d;
1067  const AVCodec *codec = ist->dec;
1068  int ret;
1069 
1070  if (!codec) {
1071  av_log(ist, AV_LOG_ERROR,
1072  "Decoding requested, but no decoder found for: %s\n",
1074  return AVERROR(EINVAL);
1075  }
1076 
1077  ret = dec_alloc(&ist->decoder);
1078  if (ret < 0)
1079  return ret;
1080  d = ist->decoder;
1081 
1082  if (codec->type == AVMEDIA_TYPE_SUBTITLE && ist->fix_sub_duration) {
1083  for (int i = 0; i < FF_ARRAY_ELEMS(d->sub_prev); i++) {
1084  d->sub_prev[i] = av_frame_alloc();
1085  if (!d->sub_prev[i])
1086  return AVERROR(ENOMEM);
1087  }
1088  d->sub_heartbeat = av_frame_alloc();
1089  if (!d->sub_heartbeat)
1090  return AVERROR(ENOMEM);
1091  }
1092 
1093  ist->dec_ctx->opaque = ist;
1094  ist->dec_ctx->get_format = get_format;
1095 
1096  if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
1097  (ist->decoding_needed & DECODING_FOR_OST)) {
1098  av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
1100  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");
1101  }
1102 
1103  /* Useful for subtitles retiming by lavf (FIXME), skipping samples in
1104  * audio, and video decoders such as cuvid or mediacodec */
1105  ist->dec_ctx->pkt_timebase = ist->st->time_base;
1106 
1107  if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
1108  av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
1109  /* Attached pics are sparse, therefore we would not want to delay their decoding till EOF. */
1111  av_dict_set(&ist->decoder_opts, "threads", "1", 0);
1112 
1114  if (ret < 0) {
1115  av_log(ist, AV_LOG_ERROR,
1116  "Hardware device setup failed for decoder: %s\n",
1117  av_err2str(ret));
1118  return ret;
1119  }
1120 
1121  if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
1122  av_log(ist, AV_LOG_ERROR, "Error while opening decoder: %s\n",
1123  av_err2str(ret));
1124  return ret;
1125  }
1126 
1128  if (ret < 0)
1129  return ret;
1130 
1131  ret = dec_thread_start(ist);
1132  if (ret < 0) {
1133  av_log(ist, AV_LOG_ERROR, "Error starting decoder thread: %s\n",
1134  av_err2str(ret));
1135  return ret;
1136  }
1137 
1138  return 0;
1139 }
AVSubtitle
Definition: avcodec.h:2263
process_subtitle
static int process_subtitle(InputStream *ist, AVFrame *frame)
Definition: ffmpeg_dec.c:391
av_packet_unref
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:423
AVCodec
AVCodec.
Definition: codec.h:187
InputFile::format_nots
int format_nots
Definition: ffmpeg.h:401
pthread_join
static av_always_inline int pthread_join(pthread_t thread, void **value_ptr)
Definition: os2threads.h:94
AVMEDIA_TYPE_SUBTITLE
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
AVPixelFormat
AVPixelFormat
Pixel format.
Definition: pixfmt.h:64
send_filter_eof
static int send_filter_eof(InputStream *ist)
Definition: ffmpeg_dec.c:528
name
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default minimum maximum flags name is the option name
Definition: writing_filters.txt:88
InputStream::hwaccel_device
char * hwaccel_device
Definition: ffmpeg.h:380
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
AVCodecContext::get_format
enum AVPixelFormat(* get_format)(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
Callback to negotiate the pixel format.
Definition: avcodec.h:708
audio_samplerate_update
static AVRational audio_samplerate_update(void *logctx, Decoder *d, const AVFrame *frame)
Definition: ffmpeg_dec.c:165
FrameData
Definition: ffmpeg.h:636
av_pix_fmt_desc_get
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:2964
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
AV_DISPOSITION_ATTACHED_PIC
#define AV_DISPOSITION_ATTACHED_PIC
The stream is stored in the file as an attached picture/"cover art" (e.g.
Definition: avformat.h:770
dec_thread_uninit
static void dec_thread_uninit(DecThreadContext *dt)
Definition: ffmpeg_dec.c:656
InputStream::outputs
struct OutputStream ** outputs
Definition: ffmpeg.h:372
audio_ts_process
static void audio_ts_process(void *logctx, Decoder *d, AVFrame *frame)
Definition: ffmpeg_dec.c:208
InputStream::dec_ctx
AVCodecContext * dec_ctx
Definition: ffmpeg.h:340
AVSubtitle::num_rects
unsigned num_rects
Definition: avcodec.h:2267
hw_device_match_by_codec
static HWDevice * hw_device_match_by_codec(const AVCodec *codec)
Definition: ffmpeg_dec.c:919
DecThreadContext::pkt
AVPacket * pkt
Definition: ffmpeg_dec.c:76
av_frame_free
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:100
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:340
pixdesc.h
LastFrameDuration::stream_idx
int stream_idx
Definition: ffmpeg.h:391
dec_thread_init
static int dec_thread_init(DecThreadContext *dt)
Definition: ffmpeg_dec.c:664
AVStream::avg_frame_rate
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:928
InputStream::nb_filters
int nb_filters
Definition: ffmpeg.h:365
objpool_free
void objpool_free(ObjPool **pop)
Definition: objpool.c:54
ffmpeg.h
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:196
video_duration_estimate
static int64_t video_duration_estimate(const InputStream *ist, const AVFrame *frame)
Definition: ffmpeg_dec.c:245
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
HWDevice
Definition: ffmpeg.h:82
av_buffer_ref
AVBufferRef * av_buffer_ref(const AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition: buffer.c:103
objpool_alloc_packets
ObjPool * objpool_alloc_packets(void)
Definition: objpool.c:124
InputStream::decoding_needed
int decoding_needed
Definition: ffmpeg.h:329
LastFrameDuration
Definition: ffmpeg.h:390
ost
static AVStream * ost
Definition: vaapi_transcode.c:42
tf_sess_config.config
config
Definition: tf_sess_config.py:33
av_packet_free
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition: avpacket.c:74
dec_free
void dec_free(Decoder **pdec)
Definition: ffmpeg_dec.c:97
InputStream::nb_outputs
int nb_outputs
Definition: ffmpeg.h:373
AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX
@ AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX
The codec supports this format via the hw_device_ctx interface.
Definition: codec.h:309
av_gcd
int64_t av_gcd(int64_t a, int64_t b)
Compute the greatest common divisor of two integer operands.
Definition: mathematics.c:37
AV_FRAME_FLAG_TOP_FIELD_FIRST
#define AV_FRAME_FLAG_TOP_FIELD_FIRST
A flag to mark frames where the top field is displayed first if the content is interlaced.
Definition: frame.h:641
FrameData::frame_num
uint64_t frame_num
Definition: ffmpeg.h:639
InputStream
Definition: ffmpeg.h:320
AVCodecContext::framerate
AVRational framerate
Definition: avcodec.h:1797
debug_ts
int debug_ts
Definition: ffmpeg_opt.c:81
hw_device_setup_for_decode
static int hw_device_setup_for_decode(InputStream *ist)
Definition: ffmpeg_dec.c:936
finish
static void finish(void)
Definition: movenc.c:342
AVCodecContext::codec
const struct AVCodec * codec
Definition: avcodec.h:446
fail
#define fail()
Definition: checkasm.h:138
AV_PIX_FMT_FLAG_HWACCEL
#define AV_PIX_FMT_FLAG_HWACCEL
Pixel format is an HW accelerated format.
Definition: pixdesc.h:128
get_format
static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
Definition: ffmpeg_dec.c:883
dummy
int dummy
Definition: motion.c:66
InputStream::decoder_opts
AVDictionary * decoder_opts
Definition: ffmpeg.h:348
update_benchmark
void update_benchmark(const char *fmt,...)
Definition: ffmpeg.c:466
type
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf type
Definition: writing_filters.txt:86
pts
static int64_t pts
Definition: transcode_aac.c:643
AV_ROUND_UP
@ AV_ROUND_UP
Round toward +infinity.
Definition: mathematics.h:134
FrameData::tb
AVRational tb
Definition: ffmpeg.h:642
codec.h
AVRational::num
int num
Numerator.
Definition: rational.h:59
InputFile
Definition: ffmpeg.h:395
avsubtitle_free
void avsubtitle_free(AVSubtitle *sub)
Free all allocated data in the given subtitle struct.
Definition: avcodec.c:411
packet_decode
static int packet_decode(InputStream *ist, const AVPacket *pkt, AVFrame *frame)
Definition: ffmpeg_dec.c:543
dec_alloc
static int dec_alloc(Decoder **pdec)
Definition: ffmpeg_dec.c:116
av_frame_alloc
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:88
AV_CODEC_ID_DVB_SUBTITLE
@ AV_CODEC_ID_DVB_SUBTITLE
Definition: codec_id.h:551
avcodec_decode_subtitle2
int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, const AVPacket *avpkt)
Decode a subtitle message.
Definition: decode.c:970
avassert.h
DecThreadContext
Definition: ffmpeg_dec.c:74
enc_subtitle
int enc_subtitle(OutputFile *of, OutputStream *ost, const AVSubtitle *sub)
Definition: ffmpeg_enc.c:519
pkt
AVPacket * pkt
Definition: movenc.c:59
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
FF_ARRAY_ELEMS
#define FF_ARRAY_ELEMS(a)
Definition: sinewin_tablegen.c:29
av_thread_message_queue_send
int av_thread_message_queue_send(AVThreadMessageQueue *mq, void *msg, unsigned flags)
Send a message on the queue.
Definition: threadmessage.c:161
AV_FRAME_FLAG_KEY
#define AV_FRAME_FLAG_KEY
A flag to mark frames that are keyframes.
Definition: frame.h:628
DecThreadContext::frame
AVFrame * frame
Definition: ffmpeg_dec.c:75
dec_packet
int dec_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
Submit a packet for decoding.
Definition: ffmpeg_dec.c:766
av_dict_get
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:62
HWACCEL_GENERIC
@ HWACCEL_GENERIC
Definition: ffmpeg.h:79
AVCodecContext::has_b_frames
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:740
Decoder::last_frame_sample_rate
int last_frame_sample_rate
Definition: ffmpeg_dec.c:48
s
#define s(width, name)
Definition: cbs_vp9.c:198
InputStream::framerate
AVRational framerate
Definition: ffmpeg.h:349
Decoder::queue_in
ThreadQueue * queue_in
Queue for sending coded packets from the main thread to the decoder thread.
Definition: ffmpeg_dec.c:62
AVMEDIA_TYPE_AUDIO
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
op
static int op(uint8_t **dst, const uint8_t *dst_end, GetByteContext *gb, int pixel, int count, int *x, int width, int linesize)
Perform decode operation.
Definition: anm.c:76
subtitle_wrap_frame
int subtitle_wrap_frame(AVFrame *frame, AVSubtitle *subtitle, int copy)
Definition: ffmpeg.c:741
hwaccel_retrieve_data
int hwaccel_retrieve_data(AVCodecContext *avctx, AVFrame *input)
Definition: ffmpeg_hw.c:300
avcodec_receive_frame
int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
Return decoded output data from a decoder or encoder (when the AV_CODEC_FLAG_RECON_FRAME flag is used...
Definition: avcodec.c:711
av_assert0
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:40
AVHWDeviceType
AVHWDeviceType
Definition: hwcontext.h:27
pix_fmts
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:297
AVCodecContext::bits_per_raw_sample
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:1513
AV_LOG_DEBUG
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:201
InputStream::filters
InputFilter ** filters
Definition: ffmpeg.h:364
dec_thread_set_name
static void dec_thread_set_name(const InputStream *ist)
Definition: ffmpeg_dec.c:648
av_rescale_q
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
AVSubtitle::pts
int64_t pts
Same as packet pts, in AV_TIME_BASE.
Definition: avcodec.h:2269
av_hwdevice_get_type_name
const char * av_hwdevice_get_type_name(enum AVHWDeviceType type)
Get the string name of an AVHWDeviceType.
Definition: hwcontext.c:93
objpool_alloc_frames
ObjPool * objpool_alloc_frames(void)
Definition: objpool.c:128
AV_CODEC_ID_H264
@ AV_CODEC_ID_H264
Definition: codec_id.h:79
av_rescale_delta
int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts, AVRational fs_tb, int duration, int64_t *last, AVRational out_tb)
Rescale a timestamp while preserving known durations.
Definition: mathematics.c:168
AVCodecContext::codec_id
enum AVCodecID codec_id
Definition: avcodec.h:447
arg
const char * arg
Definition: jacosubdec.c:67
pthread_create
static av_always_inline int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
Definition: os2threads.h:80
fields
the definition of that something depends on the semantic of the filter The callback must examine the status of the filter s links and proceed accordingly The status of output links is stored in the status_in and status_out fields and tested by the then the processing requires a frame on this link and the filter is expected to make efforts in that direction The status of input links is stored by the fifo and status_out fields
Definition: filter_design.txt:155
if
if(ret)
Definition: filter_design.txt:179
AVPacket::buf
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: packet.h:357
tq_free
void tq_free(ThreadQueue **ptq)
Definition: thread_queue.c:55
AVStream::time_base
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avformat.h:878
NULL
#define NULL
Definition: coverity.c:32
InputStream::top_field_first
int top_field_first
Definition: ffmpeg.h:351
InputStream::st
AVStream * st
Definition: ffmpeg.h:326
tq_receive_finish
void tq_receive_finish(ThreadQueue *tq, unsigned int stream_idx)
Mark the given stream finished from the receiving side.
Definition: thread_queue.c:232
AVCodec::type
enum AVMediaType type
Definition: codec.h:200
Decoder
Definition: ffmpeg_dec.c:35
hw_device_init_from_type
int hw_device_init_from_type(enum AVHWDeviceType type, const char *device, HWDevice **dev_out)
Definition: ffmpeg_hw.c:245
AVRational
Rational number (pair of numerator and denominator).
Definition: rational.h:58
InputStream::hwaccel_id
enum HWAccelID hwaccel_id
Definition: ffmpeg.h:378
InputStream::fix_sub_duration
int fix_sub_duration
Definition: ffmpeg.h:356
AV_DICT_DONT_OVERWRITE
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition: dict.h:81
avcodec_open2
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: avcodec.c:126
av_packet_ref
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
Definition: avpacket.c:431
InputStream::par
AVCodecParameters * par
Codec parameters - to be used by the decoding/streamcopy code.
Definition: ffmpeg.h:338
input_files
InputFile ** input_files
Definition: ffmpeg.c:123
error.h
InputStream::frames_decoded
uint64_t frames_decoded
Definition: ffmpeg.h:385
frame_move
static void frame_move(void *dst, void *src)
Definition: ffmpeg.h:950
tq_send
int tq_send(ThreadQueue *tq, unsigned int stream_idx, void *data)
Send an item for the given stream to the queue.
Definition: thread_queue.c:120
av_ts2timestr
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:76
InputStream::hwaccel_device_type
enum AVHWDeviceType hwaccel_device_type
Definition: ffmpeg.h:379
Decoder::last_frame_pts
int64_t last_frame_pts
Definition: ffmpeg_dec.c:44
AVPacket::size
int size
Definition: packet.h:375
InputStream::file_index
int file_index
Definition: ffmpeg.h:323
output_files
OutputFile ** output_files
Definition: ffmpeg.c:126
FrameData::dec
struct FrameData::@3 dec
av_err2str
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:121
ifilter_send_frame
int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame, int keep_reference)
Definition: ffmpeg_filter.c:1961
AVCodecContext::pkt_timebase
AVRational pkt_timebase
Timebase in which pkt_dts/pts and AVPacket.dts/pts are expressed.
Definition: avcodec.h:1811
AV_NOPTS_VALUE
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
check_avoptions
int check_avoptions(AVDictionary *m)
Definition: ffmpeg.c:455
dec_open
int dec_open(InputStream *ist)
Definition: ffmpeg_dec.c:1064
HWDevice::device_ref
AVBufferRef * device_ref
Definition: ffmpeg.h:85
hw_device_get_by_type
HWDevice * hw_device_get_by_type(enum AVHWDeviceType type)
Definition: ffmpeg_hw.c:30
DECODING_FOR_OST
#define DECODING_FOR_OST
Definition: ffmpeg.h:330
decoder_thread
static void * decoder_thread(void *arg)
Definition: ffmpeg_dec.c:683
frame_data
FrameData * frame_data(AVFrame *frame)
Get our axiliary frame data attached to the frame, allocating it if needed.
Definition: ffmpeg.c:429
AVStream::sample_aspect_ratio
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:917
AVSubtitle::end_display_time
uint32_t end_display_time
Definition: avcodec.h:2266
ObjPool
Definition: objpool.c:30
InputStream::samples_decoded
uint64_t samples_decoded
Definition: ffmpeg.h:386
FrameData::pts
int64_t pts
Definition: ffmpeg.h:641
fix_sub_duration_heartbeat
int fix_sub_duration_heartbeat(InputStream *ist, int64_t signal_pts)
Definition: ffmpeg_dec.c:454
pkt_move
static void pkt_move(void *dst, void *src)
Definition: ffmpeg.h:945
av_packet_alloc
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: avpacket.c:63
tq_alloc
ThreadQueue * tq_alloc(unsigned int nb_streams, size_t queue_size, ObjPool *obj_pool, void(*obj_move)(void *dst, void *src))
Allocate a queue for sending data between threads.
Definition: thread_queue.c:79
dec_thread_stop
static int dec_thread_stop(Decoder *d)
Definition: ffmpeg_dec.c:79
pthread_t
Definition: os2threads.h:44
AV_LOG_INFO
#define AV_LOG_INFO
Standard information.
Definition: log.h:191
sub2video_flush
static void sub2video_flush(InputStream *ist)
Definition: ffmpeg_dec.c:382
Decoder::last_frame_tb
AVRational last_frame_tb
Definition: ffmpeg_dec.c:46
Decoder::frame
AVFrame * frame
Definition: ffmpeg_dec.c:36
avcodec_get_name
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:414
HWACCEL_AUTO
@ HWACCEL_AUTO
Definition: ffmpeg.h:78
avcodec_send_packet
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
Supply raw packet data as input to a decoder.
Definition: decode.c:710
DECODING_FOR_FILTER
#define DECODING_FOR_FILTER
Definition: ffmpeg.h:331
log.h
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:244
FrameData::bits_per_raw_sample
int bits_per_raw_sample
Definition: ffmpeg.h:647
AV_FRAME_FLAG_CORRUPT
#define AV_FRAME_FLAG_CORRUPT
The frame data may be corrupted, e.g.
Definition: frame.h:624
AV_TIME_BASE
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:254
exit_on_error
int exit_on_error
Definition: ffmpeg_opt.c:82
av_assert1
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:56
av_frame_move_ref
void av_frame_move_ref(AVFrame *dst, AVFrame *src)
Move everything contained in src to dst and reset src.
Definition: frame.c:649
av_frame_unref
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition: frame.c:622
tb
#define tb
Definition: regdef.h:68
av_mallocz
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:254
Decoder::last_frame_duration_est
int64_t last_frame_duration_est
Definition: ffmpeg_dec.c:45
AVCodec::name
const char * name
Name of the codec implementation.
Definition: codec.h:194
av_inv_q
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:159
AVCodecContext::hw_device_ctx
AVBufferRef * hw_device_ctx
A reference to the AVHWDeviceContext describing the device which will be used by a hardware encoder/d...
Definition: avcodec.h:1975
av_rescale
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:129
AVCodecContext::height
int height
Definition: avcodec.h:617
tq_receive
int tq_receive(ThreadQueue *tq, int *stream_idx, void *data)
Read the next item from the queue.
Definition: thread_queue.c:191
AVCodecContext::pix_fmt
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:654
transcode_subtitles
static int transcode_subtitles(InputStream *ist, const AVPacket *pkt, AVFrame *frame)
Definition: ffmpeg_dec.c:477
avcodec.h
InputStream::decoder
Decoder * decoder
Definition: ffmpeg.h:339
AVCodecContext::frame_num
int64_t frame_num
Frame counter, set by libavcodec.
Definition: avcodec.h:2112
AVStream::disposition
int disposition
Stream disposition - a combination of AV_DISPOSITION_* flags.
Definition: avformat.h:908
ret
ret
Definition: filter_design.txt:187
AV_LOG_FATAL
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: log.h:174
pixfmt.h
FFSWAP
#define FFSWAP(type, a, b)
Definition: macros.h:52
avcodec_flush_buffers
void avcodec_flush_buffers(AVCodecContext *avctx)
Reset the internal codec state / flush internal buffers.
Definition: avcodec.c:382
frame
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
Definition: filter_design.txt:264
ThreadQueue
Definition: thread_queue.c:42
AVCodecContext::opaque
void * opaque
Private data of the user, can be used to carry app specific stuff.
Definition: avcodec.h:479
dict.h
AV_HWDEVICE_TYPE_QSV
@ AV_HWDEVICE_TYPE_QSV
Definition: hwcontext.h:33
av_get_media_type_string
const char * av_get_media_type_string(enum AVMediaType media_type)
Return a string describing the media_type enum, NULL if media_type is unknown.
Definition: utils.c:28
AVCodecContext
main external API structure.
Definition: avcodec.h:437
HWDevice::name
const char * name
Definition: ffmpeg.h:83
InputFile::audio_duration_queue
AVThreadMessageQueue * audio_duration_queue
Definition: ffmpeg.h:427
AVRational::den
int den
Denominator.
Definition: rational.h:60
AV_PIX_FMT_NONE
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:65
InputStream::nb_samples
int64_t nb_samples
Definition: ffmpeg.h:346
video_frame_process
static int video_frame_process(InputStream *ist, AVFrame *frame)
Definition: ffmpeg_dec.c:297
thread_queue.h
av_mul_q
AVRational av_mul_q(AVRational b, AVRational c)
Multiply two rationals.
Definition: rational.c:80
ifilter_send_eof
int ifilter_send_eof(InputFilter *ifilter, int64_t pts, AVRational tb)
Definition: ffmpeg_filter.c:1913
HWACCEL_NONE
@ HWACCEL_NONE
Definition: ffmpeg.h:77
avcodec_get_hw_config
const AVCodecHWConfig * avcodec_get_hw_config(const AVCodec *codec, int index)
Retrieve supported hardware configurations for a codec.
Definition: utils.c:856
InputStream::decode_errors
uint64_t decode_errors
Definition: ffmpeg.h:387
AVCodecContext::codec_type
enum AVMediaType codec_type
Definition: avcodec.h:445
desc
const char * desc
Definition: libsvtav1.c:83
AVCodecParameters::video_delay
int video_delay
Video only.
Definition: codec_par.h:157
AVPixFmtDescriptor
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition: pixdesc.h:69
InputStream::index
int index
Definition: ffmpeg.h:324
Decoder::last_filter_in_rescale_delta
int64_t last_filter_in_rescale_delta
Definition: ffmpeg_dec.c:47
Decoder::thread
pthread_t thread
Definition: ffmpeg_dec.c:54
LastFrameDuration::duration
int64_t duration
Definition: ffmpeg.h:392
AVPacket
This structure stores compressed data.
Definition: packet.h:351
ifilter_sub2video
int ifilter_sub2video(InputFilter *ifilter, const AVFrame *frame)
Definition: ffmpeg_filter.c:1880
Decoder::queue_out
ThreadQueue * queue_out
Queue for sending decoded frames from the decoder thread to the main thread.
Definition: ffmpeg_dec.c:70
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:34
av_dict_set
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:88
Decoder::sub_heartbeat
AVFrame * sub_heartbeat
Definition: ffmpeg_dec.c:52
HWDevice::type
enum AVHWDeviceType type
Definition: ffmpeg.h:84
Decoder::sub_prev
AVFrame * sub_prev[2]
Definition: ffmpeg_dec.c:51
d
d
Definition: ffmpeg_filter.c:331
AVCodecContext::width
int width
picture width / height.
Definition: avcodec.h:617
timestamp.h
OutputStream
Definition: mux.c:53
AVERROR_BUG
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition: error.h:52
av_thread_message_queue_set_err_recv
void av_thread_message_queue_set_err_recv(AVThreadMessageQueue *mq, int err)
Set the receiving error code.
Definition: threadmessage.c:204
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
AVERROR_INVALIDDATA
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:61
av_ts2str
#define av_ts2str(ts)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:54
AVCodecHWConfig
Definition: codec.h:341
err_merge
static int err_merge(int err0, int err1)
Merge two return codes - return one of the error codes if at least one of them was negative,...
Definition: ffmpeg.h:889
dec_thread_start
static int dec_thread_start(InputStream *ist)
Definition: ffmpeg_dec.c:839
hw_device_get_by_name
HWDevice * hw_device_get_by_name(const char *name)
Definition: ffmpeg_hw.c:44
InputStream::dec
const AVCodec * dec
Definition: ffmpeg.h:341
Decoder::hwaccel_pix_fmt
enum AVPixelFormat hwaccel_pix_fmt
Definition: ffmpeg_dec.c:39
snprintf
#define snprintf
Definition: snprintf.h:34
Decoder::pkt
AVPacket * pkt
Definition: ffmpeg_dec.c:37
buffersrc.h
av_rescale_q_rnd
int64_t av_rescale_q_rnd(int64_t a, AVRational bq, AVRational cq, enum AVRounding rnd)
Rescale a 64-bit integer by 2 rational numbers with specified rounding.
Definition: mathematics.c:134
send_frame_to_filters
static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
Definition: ffmpeg_dec.c:147
ff_thread_setname
static int ff_thread_setname(const char *name)
Definition: thread.h:214
tq_send_finish
void tq_send_finish(ThreadQueue *tq, unsigned int stream_idx)
Mark the given stream finished from the sending side.
Definition: thread_queue.c:217