FFmpeg
Loading...
Searching...
No Matches
ffmpeg_enc.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 <math.h>
20#include <stdint.h>
21
22#include "ffmpeg.h"
23
24#include "libavutil/avassert.h"
25#include "libavutil/avstring.h"
26#include "libavutil/avutil.h"
27#include "libavutil/dict.h"
28#include "libavutil/display.h"
29#include "libavutil/eval.h"
30#include "libavutil/frame.h"
32#include "libavutil/log.h"
33#include "libavutil/mem.h"
34#include "libavutil/opt.h"
35#include "libavutil/pixdesc.h"
36#include "libavutil/rational.h"
37#include "libavutil/time.h"
38#include "libavutil/timestamp.h"
39
40#include "libavcodec/avcodec.h"
41
42typedef struct EncoderPriv {
44
46 char log_name[32];
47
48 // combined size of all the packets received from the encoder
49 uint64_t data_size;
50
51 // number of packets received from the encoder
54
55 int opened;
57
59 unsigned sch_idx;
61
63{
64 return (EncoderPriv*)enc;
65}
66
67// data that is local to the decoder thread and not visible outside of it
72
73void enc_free(Encoder **penc)
74{
75 Encoder *enc = *penc;
76
77 if (!enc)
78 return;
79
80 if (enc->enc_ctx)
84
85 av_freep(penc);
86}
87
88static const char *enc_item_name(void *obj)
89{
90 const EncoderPriv *ep = obj;
91
92 return ep->log_name;
93}
94
95static const AVClass enc_class = {
96 .class_name = "Encoder",
97 .version = LIBAVUTIL_VERSION_INT,
98 .parent_log_context_offset = offsetof(EncoderPriv, log_parent),
99 .item_name = enc_item_name,
100};
101
102static int enc_realloc(Encoder *enc, const AVCodec *codec)
103{
104 EncoderPriv *ep = ep_from_enc(enc);
105 char *stats_in = NULL;
106
107 if (enc->enc_ctx)
108 stats_in = enc->enc_ctx->stats_in;
110
111 ep->opened = 0;
112 ep->got_first_packet = 0;
113
114 enc->enc_ctx = avcodec_alloc_context3(codec);
115 if (!enc->enc_ctx) {
116 av_freep(&stats_in);
117 return AVERROR(ENOMEM);
118 }
119
120 enc->enc_ctx->stats_in = stats_in;
121
122 return 0;
123}
124
125int enc_alloc(Encoder **penc, const AVCodec *codec,
126 Scheduler *sch, unsigned sch_idx, void *log_parent)
127{
128 EncoderPriv *ep;
129 int ret = 0;
130
131 *penc = NULL;
132
133 ep = av_mallocz(sizeof(*ep));
134 if (!ep)
135 return AVERROR(ENOMEM);
136
137 ep->e.class = &enc_class;
138 ep->log_parent = log_parent;
139
140 ep->sch = sch;
141 ep->sch_idx = sch_idx;
142
143 snprintf(ep->log_name, sizeof(ep->log_name), "enc:%s", codec->name);
144
145 ep->e.enc_ctx = avcodec_alloc_context3(codec);
146 if (!ep->e.enc_ctx) {
147 ret = AVERROR(ENOMEM);
148 goto fail;
149 }
150
151 *penc = &ep->e;
152
153 return 0;
154fail:
155 enc_free((Encoder**)&ep);
156 return ret;
157}
158
160 AVBufferRef *frames_ref)
161{
162 const AVCodecHWConfig *config;
163 HWDevice *dev = NULL;
164
165 if (frames_ref &&
166 ((AVHWFramesContext*)frames_ref->data)->format ==
167 enc_ctx->pix_fmt) {
168 // Matching format, will try to use hw_frames_ctx.
169 } else {
170 frames_ref = NULL;
171 }
172
173 for (int i = 0;; i++) {
174 config = avcodec_get_hw_config(enc_ctx->codec, i);
175 if (!config)
176 break;
177
178 if (frames_ref &&
179 config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX &&
180 (config->pix_fmt == AV_PIX_FMT_NONE ||
181 config->pix_fmt == enc_ctx->pix_fmt)) {
182 av_log(e, AV_LOG_VERBOSE, "Using input "
183 "frames context (format %s) with %s encoder.\n",
185 enc_ctx->codec->name);
186 enc_ctx->hw_frames_ctx = av_buffer_ref(frames_ref);
187 if (!enc_ctx->hw_frames_ctx)
188 return AVERROR(ENOMEM);
189 return 0;
190 }
191
192 if (!dev &&
194 dev = hw_device_get_by_type(config->device_type);
195 }
196
197 if (dev) {
198 av_log(e, AV_LOG_VERBOSE, "Using device %s "
199 "(type %s) with %s encoder.\n", dev->name,
200 av_hwdevice_get_type_name(dev->type), enc_ctx->codec->name);
201 enc_ctx->hw_device_ctx = av_buffer_ref(dev->device_ref);
202 if (!enc_ctx->hw_device_ctx)
203 return AVERROR(ENOMEM);
204 } else {
205 // No device required, or no device available.
206 }
207 return 0;
208}
209
211{
212 AVCodecContext *enc_ctx = e->enc_ctx;
213
214 int ret = av_opt_set_dict2(enc_ctx, opts, AV_OPT_SEARCH_CHILDREN);
215 if (ret < 0) {
216 av_log(e, AV_LOG_ERROR, "Error applying encoder options: %s\n",
217 av_err2str(ret));
218 return ret;
219 }
220
221 ret = check_avoptions(*opts);
222 if (ret < 0)
223 return ret;
224
225 return 0;
226}
227
228static int enc_reopen(void *opaque, const AVFrame *frame,
229 AVDictionary **extra_encoder_opts)
230{
231 OutputStream *ost = opaque;
232 InputStream *ist = ost->ist;
233 Encoder *e = ost->enc;
234 EncoderPriv *ep = ep_from_enc(e);
235 AVCodecContext *enc_ctx = e->enc_ctx;
236 Decoder *dec = NULL;
237 const AVCodec *enc = enc_ctx->codec;
238 AVDictionary *encoder_opts = NULL;
239 FrameData *fd;
240 int threads_manual;
241 int ret;
242
243 ret = av_dict_copy(&encoder_opts, ost->enc->encoder_opts, 0);
244 if (ret < 0)
245 return ret;
246
247 threads_manual = !!av_dict_get(encoder_opts, "threads", NULL, 0);
248 ret = apply_enc_options(e, &encoder_opts);
249 av_dict_free(&encoder_opts);
250 if (ret < 0)
251 return ret;
252
253 if (extra_encoder_opts) {
254 threads_manual |= !!av_dict_get(*extra_encoder_opts, "threads", NULL, 0);
255 ret = apply_enc_options(e, extra_encoder_opts);
256 if (ret < 0)
257 return ret;
258 }
259
260 // default to automatic thread count
261 if (!threads_manual)
262 enc_ctx->thread_count = 0;
263
264 // frame is always non-NULL for audio and video
266
267 if (frame) {
268 av_assert0(frame->opaque_ref);
269 fd = (FrameData*)frame->opaque_ref->data;
270
271 ret = clone_side_data(&enc_ctx->decoded_side_data, &enc_ctx->nb_decoded_side_data,
273 if (ret < 0)
274 return ret;
275 }
276
277 if (ist)
278 dec = ist->decoder;
279
280 if (ost->enc->codec_tag)
281 enc_ctx->codec_tag = e->codec_tag;
282 enc_ctx->flags |= e->flags;
283 enc_ctx->flags2 |= e->flags2;
284 enc_ctx->global_quality = e->global_quality;
285
286 // the timebase is chosen by filtering code
287 if (ost->type == AVMEDIA_TYPE_AUDIO || ost->type == AVMEDIA_TYPE_VIDEO) {
288 enc_ctx->time_base = frame->time_base;
289 enc_ctx->framerate = fd->frame_rate_filter;
290 }
291
292 switch (enc_ctx->codec_type) {
295 frame->sample_rate > 0 &&
296 frame->ch_layout.nb_channels > 0);
297 enc_ctx->sample_fmt = frame->format;
298 enc_ctx->sample_rate = frame->sample_rate;
299 if (!enc_ctx->frame_size && (!(enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE) ||
301 enc_ctx->frame_size = frame->nb_samples;
302 ret = av_channel_layout_copy(&enc_ctx->ch_layout, &frame->ch_layout);
303 if (ret < 0)
304 return ret;
305
306 if (ost->bits_per_raw_sample)
307 enc_ctx->bits_per_raw_sample = ost->bits_per_raw_sample;
308 else
310 av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
311 break;
312
313 case AVMEDIA_TYPE_VIDEO: {
314 av_assert0(frame->format != AV_PIX_FMT_NONE &&
315 frame->width > 0 &&
316 frame->height > 0);
317 enc_ctx->width = frame->width;
318 enc_ctx->height = frame->height;
319 enc_ctx->sample_aspect_ratio =
320 ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
321 av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
322 frame->sample_aspect_ratio;
323
324 enc_ctx->pix_fmt = frame->format;
325
326 if (ost->bits_per_raw_sample)
327 enc_ctx->bits_per_raw_sample = ost->bits_per_raw_sample;
328 else
330 av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
331
332 /**
333 * The video color properties should always be in sync with the user-
334 * requested values, since we forward them to the filter graph.
335 */
336 enc_ctx->color_range = frame->color_range;
337 enc_ctx->color_primaries = frame->color_primaries;
338 enc_ctx->color_trc = frame->color_trc;
339 enc_ctx->colorspace = frame->colorspace;
340 enc_ctx->alpha_mode = frame->alpha_mode;
341
342 /* Video properties which are not part of filter graph negotiation */
344 enc_ctx->chroma_sample_location = frame->chroma_location;
345 } else if (enc_ctx->chroma_sample_location != frame->chroma_location &&
346 frame->chroma_location != AVCHROMA_LOC_UNSPECIFIED) {
348 "Requested chroma sample location '%s' does not match the "
349 "frame tagged sample location '%s'; result may be incorrect.\n",
351 av_chroma_location_name(frame->chroma_location));
352 }
353
355 (frame->flags & AV_FRAME_FLAG_INTERLACED)) {
356 int top_field_first = !!(frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST);
357
358 if (enc->id == AV_CODEC_ID_MJPEG)
359 enc_ctx->field_order = top_field_first ? AV_FIELD_TT : AV_FIELD_BB;
360 else
361 enc_ctx->field_order = top_field_first ? AV_FIELD_TB : AV_FIELD_BT;
362 } else
364
365 break;
366 }
368 enc_ctx->time_base = AV_TIME_BASE_Q;
369
370 if (!enc_ctx->width) {
371 enc_ctx->width = ost->ist->par->width;
372 enc_ctx->height = ost->ist->par->height;
373 }
374
375 av_assert0(dec);
376 if (dec->subtitle_header) {
377 /* ASS code assumes this buffer is null terminated so add extra byte. */
379 if (!enc_ctx->subtitle_header)
380 return AVERROR(ENOMEM);
381 memcpy(enc_ctx->subtitle_header, dec->subtitle_header,
384 }
385
386 break;
387 default:
388 av_assert0(0);
389 break;
390 }
391
392 if (ost->bitexact)
393 enc_ctx->flags |= AV_CODEC_FLAG_BITEXACT;
394
397
399
400 ret = hw_device_setup_for_encode(e, enc_ctx, frame ? frame->hw_frames_ctx : NULL);
401 if (ret < 0) {
403 "Encoding hardware device setup failed: %s\n", av_err2str(ret));
404 return ret;
405 }
406
407 if ((ret = avcodec_open2(enc_ctx, enc, NULL)) < 0) {
408 if (ret != AVERROR_EXPERIMENTAL)
409 av_log(e, AV_LOG_ERROR, "Error while opening encoder - maybe "
410 "incorrect parameters such as bit_rate, rate, width or height.\n");
411 return ret;
412 }
413
414 ep->opened = 1;
415
416 if (enc_ctx->bit_rate && enc_ctx->bit_rate < 1000 &&
417 enc_ctx->codec_id != AV_CODEC_ID_CODEC2 /* don't complain about 700 bit/s modes */)
418 av_log(e, AV_LOG_WARNING, "The bitrate parameter is set too low."
419 " It takes bits/s as argument, not kbits/s\n");
420
421 return 0;
422}
423
424int enc_open(void *opaque, const AVFrame *frame)
425{
426 OutputStream *ost = opaque;
427 Encoder *e = ost->enc;
428 EncoderPriv *ep = ep_from_enc(e);
429 AVCodecContext *enc_ctx = e->enc_ctx;
430 OutputFile *of = ost->file;
431 int frame_samples = 0;
432 int ret;
433
434 if (ep->opened)
435 return 0;
436
437 ret = enc_reopen(opaque, frame, NULL);
438 if (ret < 0)
439 return ret;
440
441 if (enc_ctx->frame_size)
442 frame_samples = enc_ctx->frame_size;
443
444 ret = of_stream_init(of, ost, enc_ctx);
445 if (ret < 0)
446 return ret;
447
448 return frame_samples;
449}
450
452{
453 OutputFile *of = ost->file;
454
455 if (of->recording_time != INT64_MAX &&
456 av_compare_ts(ts, tb, of->recording_time, AV_TIME_BASE_Q) >= 0) {
457 return 0;
458 }
459 return 1;
460}
461
463 AVPacket *pkt)
464{
465 Encoder *e = ost->enc;
466 EncoderPriv *ep = ep_from_enc(e);
467 int subtitle_out_max_size = 1024 * 1024;
468 int subtitle_out_size, nb, i, ret;
469 AVCodecContext *enc;
470 int64_t pts;
471
472 if (sub->pts == AV_NOPTS_VALUE) {
473 av_log(e, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
474 return exit_on_error ? AVERROR(EINVAL) : 0;
475 }
476 if ((of->start_time != AV_NOPTS_VALUE && sub->pts < of->start_time))
477 return 0;
478
479 enc = e->enc_ctx;
480
481 /* Note: DVB subtitle need one packet to draw them and one other
482 packet to clear them */
483 /* XXX: signal it in the codec context ? */
485 nb = 2;
486 else if (enc->codec_id == AV_CODEC_ID_ASS)
487 nb = FFMAX(sub->num_rects, 1);
488 else
489 nb = 1;
490
491 /* shift timestamp to honor -ss and make check_recording_time() work with -t */
492 pts = sub->pts;
493 if (of->start_time != AV_NOPTS_VALUE)
494 pts -= of->start_time;
495 for (i = 0; i < nb; i++) {
496 AVSubtitle local_sub = *sub;
497
499 return AVERROR_EOF;
500
501 ret = av_new_packet(pkt, subtitle_out_max_size);
502 if (ret < 0)
503 return AVERROR(ENOMEM);
504
505 local_sub.pts = pts;
506 // start_display_time is required to be 0
507 local_sub.pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
508 local_sub.end_display_time -= sub->start_display_time;
509 local_sub.start_display_time = 0;
510
511 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE && i == 1)
512 local_sub.num_rects = 0;
513 else if (enc->codec_id == AV_CODEC_ID_ASS && sub->num_rects > 0) {
514 local_sub.num_rects = 1;
515 local_sub.rects += i;
516 }
517
518 e->frames_encoded++;
519
520 subtitle_out_size = avcodec_encode_subtitle(enc, pkt->data, pkt->size, &local_sub);
521 if (subtitle_out_size < 0) {
522 av_log(e, AV_LOG_FATAL, "Subtitle encoding failed\n");
523 return subtitle_out_size;
524 }
525
526 av_shrink_packet(pkt, subtitle_out_size);
527 pkt->time_base = AV_TIME_BASE_Q;
528 pkt->pts = sub->pts;
529 pkt->duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, pkt->time_base);
531 /* XXX: the pts correction is handled here. Maybe handling
532 it in the codec would be better */
533 if (i == 0)
534 pkt->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, pkt->time_base);
535 else
536 pkt->pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, pkt->time_base);
537 }
538 pkt->dts = pkt->pts;
539
540 ret = sch_enc_send(ep->sch, ep->sch_idx, pkt);
541 if (ret < 0) {
543 return ret;
544 }
545 }
546
547 return 0;
548}
549
551 const AVFrame *frame, const AVPacket *pkt,
552 uint64_t frame_num)
553{
554 Encoder *e = ost->enc;
555 EncoderPriv *ep = ep_from_enc(e);
556 AVIOContext *io = es->io;
557 AVRational tb = frame ? frame->time_base : pkt->time_base;
558 int64_t pts = frame ? frame->pts : pkt->pts;
559
560 AVRational tbi = (AVRational){ 0, 1};
561 int64_t ptsi = INT64_MAX;
562
563 const FrameData *fd = NULL;
564
565 if (frame ? frame->opaque_ref : pkt->opaque_ref) {
566 fd = (const FrameData*)(frame ? frame->opaque_ref->data : pkt->opaque_ref->data);
567 tbi = fd->dec.tb;
568 ptsi = fd->dec.pts;
569 }
570
572
573 for (size_t i = 0; i < es->nb_components; i++) {
574 const EncStatsComponent *c = &es->components[i];
575
576 switch (c->type) {
577 case ENC_STATS_LITERAL: avio_write (io, c->str, c->str_len); continue;
578 case ENC_STATS_FILE_IDX: avio_printf(io, "%d", ost->file->index); continue;
579 case ENC_STATS_STREAM_IDX: avio_printf(io, "%d", ost->index); continue;
580 case ENC_STATS_TIMEBASE: avio_printf(io, "%d/%d", tb.num, tb.den); continue;
581 case ENC_STATS_TIMEBASE_IN: avio_printf(io, "%d/%d", tbi.num, tbi.den); continue;
582 case ENC_STATS_PTS: avio_printf(io, "%"PRId64, pts); continue;
583 case ENC_STATS_PTS_IN: avio_printf(io, "%"PRId64, ptsi); continue;
584 case ENC_STATS_PTS_TIME: avio_printf(io, "%g", pts * av_q2d(tb)); continue;
585 case ENC_STATS_PTS_TIME_IN: avio_printf(io, "%g", ptsi == INT64_MAX ?
586 INFINITY : ptsi * av_q2d(tbi)); continue;
587 case ENC_STATS_FRAME_NUM: avio_printf(io, "%"PRIu64, frame_num); continue;
588 case ENC_STATS_FRAME_NUM_IN: avio_printf(io, "%"PRIu64, fd ? fd->dec.frame_num : -1); continue;
589 }
590
591 if (frame) {
592 switch (c->type) {
593 case ENC_STATS_SAMPLE_NUM: avio_printf(io, "%"PRIu64, e->samples_encoded); continue;
594 case ENC_STATS_NB_SAMPLES: avio_printf(io, "%d", frame->nb_samples); continue;
595 default: av_assert0(0);
596 }
597 } else {
598 switch (c->type) {
599 case ENC_STATS_DTS: avio_printf(io, "%"PRId64, pkt->dts); continue;
600 case ENC_STATS_DTS_TIME: avio_printf(io, "%g", pkt->dts * av_q2d(tb)); continue;
601 case ENC_STATS_PKT_SIZE: avio_printf(io, "%d", pkt->size); continue;
602 case ENC_STATS_KEYFRAME: avio_write(io, (pkt->flags & AV_PKT_FLAG_KEY) ?
603 "K" : "N", 1); continue;
604 case ENC_STATS_BITRATE: {
605 double duration = FFMAX(pkt->duration, 1) * av_q2d(tb);
606 avio_printf(io, "%g", 8.0 * pkt->size / duration);
607 continue;
608 }
610 double duration = pkt->dts * av_q2d(tb);
611 avio_printf(io, "%g", duration > 0 ? 8.0 * ep->data_size / duration : -1.);
612 continue;
613 }
614 default: av_assert0(0);
615 }
616 }
617 }
618 avio_w8(io, '\n');
619 avio_flush(io);
620
622}
623
624static inline double psnr(double d)
625{
626 return -10.0 * log10(d);
627}
628
629static int update_video_stats(OutputStream *ost, const AVPacket *pkt, int write_vstats)
630{
631 Encoder *e = ost->enc;
632 EncoderPriv *ep = ep_from_enc(e);
634 NULL);
635 AVCodecContext *enc = e->enc_ctx;
636 enum AVPictureType pict_type;
637 int64_t frame_number;
638 double ti1, bitrate, avg_bitrate;
639 double psnr_val = -1;
640 int quality;
641
642 quality = sd ? AV_RL32(sd) : -1;
643 pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
644
645 atomic_store(&ost->quality, quality);
646
647 if ((enc->flags & AV_CODEC_FLAG_PSNR) && sd && sd[5]) {
648 // FIXME the scaling assumes 8bit
649 double error = AV_RL64(sd + 8) / (enc->width * enc->height * 255.0 * 255.0);
650 if (error >= 0 && error <= 1)
651 psnr_val = psnr(error);
652 }
653
654 if (!write_vstats)
655 return 0;
656
657 /* this is executed just the first time update_video_stats is called */
658 if (!vstats_file) {
659 vstats_file = fopen(vstats_filename, "w");
660 if (!vstats_file) {
661 perror("fopen");
662 return AVERROR(errno);
663 }
664 }
665
666 frame_number = ep->packets_encoded;
667 if (vstats_version <= 1) {
668 fprintf(vstats_file, "frame= %5"PRId64" q= %2.1f ", frame_number,
669 quality / (float)FF_QP2LAMBDA);
670 } else {
671 fprintf(vstats_file, "out= %2d st= %2d frame= %5"PRId64" q= %2.1f ",
672 ost->file->index, ost->index, frame_number,
673 quality / (float)FF_QP2LAMBDA);
674 }
675
676 if (psnr_val >= 0)
677 fprintf(vstats_file, "PSNR= %6.2f ", psnr_val);
678
679 fprintf(vstats_file,"f_size= %6d ", pkt->size);
680 /* compute pts value */
681 ti1 = pkt->dts * av_q2d(pkt->time_base);
682 if (ti1 < 0.01)
683 ti1 = 0.01;
684
685 bitrate = (pkt->size * 8) / av_q2d(enc->time_base) / 1000.0;
686 avg_bitrate = (double)(ep->data_size * 8) / ti1 / 1000.0;
687 fprintf(vstats_file, "s_size= %8.0fKiB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
688 (double)ep->data_size / 1024, ti1, bitrate, avg_bitrate);
689 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(pict_type));
690
691 return 0;
692}
693
695 AVPacket *pkt)
696{
697 Encoder *e = ost->enc;
698 EncoderPriv *ep = ep_from_enc(e);
699 AVCodecContext *enc = e->enc_ctx;
700 const char *type_desc = av_get_media_type_string(enc->codec_type);
701 const char *action = frame ? "encode" : "flush";
702 int ret;
703
704 if (frame) {
706
707 if (!fd)
708 return AVERROR(ENOMEM);
709
711
712 if (ost->enc_stats_pre.io)
713 enc_stats_write(ost, &ost->enc_stats_pre, frame, NULL,
714 e->frames_encoded);
715
716 e->frames_encoded++;
717 e->samples_encoded += frame->nb_samples;
718
719 if (debug_ts) {
720 av_log(e, AV_LOG_INFO, "encoder <- type:%s "
721 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
722 type_desc,
723 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
724 enc->time_base.num, enc->time_base.den);
725 }
726
727 if (frame->sample_aspect_ratio.num && !ost->frame_aspect_ratio.num)
728 enc->sample_aspect_ratio = frame->sample_aspect_ratio;
729 }
730
732
733 ret = avcodec_send_frame(enc, frame);
734 if (ret < 0 && !(ret == AVERROR_EOF && !frame)) {
735 av_log(e, AV_LOG_ERROR, "Error submitting %s frame to the encoder\n",
736 type_desc);
737 return ret;
738 }
739
740 while (1) {
741 FrameData *fd;
742
744
745 ret = avcodec_receive_packet(enc, pkt);
746 update_benchmark("%s_%s %d.%d", action, type_desc,
747 of->index, ost->index);
748
749 pkt->time_base = enc->time_base;
750
751 /* if two pass, output log on success and EOF */
752 if ((ret >= 0 || ret == AVERROR_EOF) && ost->logfile && enc->stats_out)
753 fprintf(ost->logfile, "%s", enc->stats_out);
754
755 if (ret == AVERROR(EAGAIN)) {
756 av_assert0(frame); // should never happen during flushing
757 return 0;
758 } else if (ret < 0) {
759 if (ret != AVERROR_EOF)
760 av_log(e, AV_LOG_ERROR, "%s encoding failed\n", type_desc);
761 return ret;
762 }
763
764 fd = packet_data(pkt);
765 if (!fd)
766 return AVERROR(ENOMEM);
768
769 // attach extradata to first packet if the encoder was reinitialized
770 if (!ep->got_first_packet && ep->packets_encoded && enc->extradata_size) {
772 enc->extradata_size);
773 if (!extradata)
774 return AVERROR(ENOMEM);
775 memcpy(extradata, enc->extradata, enc->extradata_size);
776 ep->got_first_packet = 1;
777 }
778 // attach stream parameters to first packet if requested
780 if (!ep->packets_encoded) {
781 if (ep->attach_par) {
783 if (!fd->par_enc)
784 return AVERROR(ENOMEM);
785
787 if (ret < 0)
788 return ret;
789 }
790 ep->got_first_packet = 1;
791 }
792
793 pkt->flags |= AV_PKT_FLAG_TRUSTED;
794
795 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
797 if (ret < 0)
798 return ret;
799 }
800
801 if (ost->enc_stats_post.io)
802 enc_stats_write(ost, &ost->enc_stats_post, NULL, pkt,
803 ep->packets_encoded);
804
805 if (debug_ts) {
806 av_log(e, AV_LOG_INFO, "encoder -> type:%s "
807 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s "
808 "duration:%s duration_time:%s\n",
809 type_desc,
810 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &enc->time_base),
811 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &enc->time_base),
812 av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, &enc->time_base));
813 }
814
815 ep->data_size += pkt->size;
816
817 ep->packets_encoded++;
818
819 ret = sch_enc_send(ep->sch, ep->sch_idx, pkt);
820 if (ret < 0) {
822 return ret;
823 }
824 }
825
826 av_unreachable("encode_frame() loop should return");
827}
828
829static enum AVPictureType forced_kf_apply(void *logctx, KeyframeForceCtx *kf,
830 const AVFrame *frame)
831{
832 double pts_time;
833
834 if (kf->ref_pts == AV_NOPTS_VALUE)
835 kf->ref_pts = frame->pts;
836
837 pts_time = (frame->pts - kf->ref_pts) * av_q2d(frame->time_base);
838 if (kf->index < kf->nb_pts &&
839 av_compare_ts(frame->pts, frame->time_base, kf->pts[kf->index], AV_TIME_BASE_Q) >= 0) {
840 kf->index++;
841 goto force_keyframe;
842 } else if (kf->pexpr) {
843 double res;
844 kf->expr_const_values[FKF_T] = pts_time;
845 res = av_expr_eval(kf->pexpr,
847 av_log(logctx, AV_LOG_TRACE,
848 "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
854 res);
855
856 kf->expr_const_values[FKF_N] += 1;
857
858 if (res) {
862 goto force_keyframe;
863 }
864 } else if (kf->type == KF_FORCE_SOURCE && (frame->flags & AV_FRAME_FLAG_KEY)) {
865 goto force_keyframe;
866 } else if (kf->type == KF_FORCE_SCD_METADATA &&
867 av_dict_get(frame->metadata, "lavfi.scd.time", NULL, 0)) {
868 goto force_keyframe;
869 }
870
872
873force_keyframe:
874 av_log(logctx, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
875 return AV_PICTURE_TYPE_I;
876}
877
879{
880 Encoder *e = ost->enc;
881 OutputFile *of = ost->file;
882 enum AVMediaType type = ost->type;
883
885 const AVSubtitle *subtitle = frame && frame->buf[0] ?
886 (AVSubtitle*)frame->buf[0]->data : NULL;
887
888 // no flushing for subtitles
889 return subtitle && subtitle->num_rects ?
890 do_subtitle_out(of, ost, subtitle, pkt) : 0;
891 }
892
893 if (frame) {
894 if (!check_recording_time(ost, frame->pts, frame->time_base))
895 return AVERROR_EOF;
896
897 if (type == AVMEDIA_TYPE_VIDEO) {
898 frame->quality = e->enc_ctx->global_quality;
899 frame->pict_type = forced_kf_apply(e, &ost->kf, frame);
900 } else {
902 e->enc_ctx->ch_layout.nb_channels != frame->ch_layout.nb_channels) {
904 "Audio channel count changed and encoder does not support parameter changes\n");
905 return 0;
906 }
907 }
908 }
909
910 return encode_frame(of, ost, frame, pkt);
911}
912
914{
915 char name[16];
916 snprintf(name, sizeof(name), "enc%d:%d:%s", ost->file->index, ost->index,
917 ost->enc->enc_ctx->codec->name);
919}
920
922{
923 av_packet_free(&et->pkt);
924 av_frame_free(&et->frame);
925
926 memset(et, 0, sizeof(*et));
927}
928
930{
931 memset(et, 0, sizeof(*et));
932
933 et->frame = av_frame_alloc();
934 if (!et->frame)
935 goto fail;
936
937 et->pkt = av_packet_alloc();
938 if (!et->pkt)
939 goto fail;
940
941 return 0;
942
943fail:
945 return AVERROR(ENOMEM);
946}
947
949{
950 Encoder *e = ost->enc;
951 int ret;
952
953 ret = frame_encode(ost, NULL, et->pkt);
954 if (ret < 0 && ret != AVERROR_EOF)
955 av_log(e, AV_LOG_ERROR, "Error flushing encoder: %s\n",
956 av_err2str(ret));
957
958 return ret;
959}
960
962{
963 Encoder *e = ost->enc;
965 const FrameData *fd = frame_data_c(et->frame);
966 int force_reinit, ret = AVERROR_BUG;
967
968 ret = av_dict_copy(&copy, fd->reinit_opts, 0);
969 if (ret < 0)
970 return ret;
971
972 force_reinit = !!av_dict_get(copy, "force_reinit", NULL, 0);
973 if (force_reinit)
974 av_dict_set(&copy, "force_reinit", NULL, 0);
975 // Lets try a graceful reconfiguration first
978 if (!ret)
979 goto end;
980
982 if (ret < 0)
983 goto end;
984 av_dict_set(&copy, "force_reinit", NULL, 0);
985
986 av_log(e, AV_LOG_INFO, "Could not reconfigure the encoder."
987 " Trying to restart it instead\n");
988 }
989
990 // Go ahead and do a full restart of the encoder
991 ret = flush_encoder(ost, et);
992 if (ret < 0 && ret != AVERROR_EOF)
993 goto end;
994
995 ret = enc_realloc(e, e->enc_ctx->codec);
996 if (ret < 0)
997 goto end;
998 av_log(e, AV_LOG_DEBUG, "Restarting encoder\n");
999 ret = enc_reopen(ost, et->frame, &copy);
1000 if (ret < 0)
1001 goto end;
1002
1003 ret = 0;
1004end:
1006 return ret;
1007}
1008
1010{
1011 OutputStream *ost = arg;
1012 Encoder *e = ost->enc;
1013 EncoderPriv *ep = ep_from_enc(e);
1014 EncoderThread et;
1015 const FrameData *fd;
1016 int ret = 0, input_status = 0;
1017 int name_set = 0;
1018
1019 ret = enc_thread_init(&et);
1020 if (ret < 0)
1021 goto finish;
1022
1023 /* Open the subtitle encoders immediately. AVFrame-based encoders
1024 * are opened through a callback from the scheduler once they get
1025 * their first frame
1026 *
1027 * N.B.: because the callback is called from a different thread,
1028 * enc_ctx MUST NOT be accessed before sch_enc_receive() returns
1029 * for the first time for audio/video. */
1030 if (ost->type != AVMEDIA_TYPE_VIDEO && ost->type != AVMEDIA_TYPE_AUDIO) {
1031 ret = enc_open(ost, NULL);
1032 if (ret < 0)
1033 goto finish;
1034 }
1035
1036 while (!input_status) {
1037 input_status = sch_enc_receive(ep->sch, ep->sch_idx, et.frame);
1038 if (input_status < 0) {
1039 if (input_status == AVERROR_EOF) {
1040 av_log(e, AV_LOG_VERBOSE, "Encoder thread received EOF\n");
1041 if (ep->opened)
1042 break;
1043
1044 av_log(e, AV_LOG_ERROR, "Could not open encoder before EOF\n");
1045 ret = AVERROR(EINVAL);
1046 } else {
1047 av_log(e, AV_LOG_ERROR, "Error receiving a frame for encoding: %s\n",
1048 av_err2str(ret));
1049 ret = input_status;
1050 }
1051 goto finish;
1052 }
1053
1054 if (!name_set) {
1056 name_set = 1;
1057 }
1058
1059 fd = frame_data_c(et.frame);
1060 if (fd && fd->reinit_opts) {
1061 ret = reinit_encoder(ost, &et);
1062 if (ret < 0) {
1063 av_log(e, AV_LOG_ERROR, "Error reconfiguring or restarting encoder: %s\n",
1064 av_err2str(ret));
1065 goto finish;
1066 }
1067 }
1068
1069 ret = frame_encode(ost, et.frame, et.pkt);
1070
1071 av_packet_unref(et.pkt);
1073
1074 if (ret < 0) {
1075 if (ret == AVERROR_EOF)
1076 av_log(e, AV_LOG_VERBOSE, "Encoder returned EOF, finishing\n");
1077 else
1078 av_log(e, AV_LOG_ERROR, "Error encoding a frame: %s\n",
1079 av_err2str(ret));
1080 break;
1081 }
1082 }
1083
1084 // flush the encoder
1085 if (ret == 0 || ret == AVERROR_EOF)
1086 ret = flush_encoder(ost, &et);
1087
1088 // EOF is normal thread termination
1089 if (ret == AVERROR_EOF)
1090 ret = 0;
1091
1092finish:
1093 enc_thread_uninit(&et);
1094
1095 return ret;
1096}
1097
1099{
1100 EncoderPriv *ep = ep_from_enc(enc);
1101 ep->attach_par = 1;
1102 return ep->sch_idx;
1103}
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_unreachable(msg)
Asserts that are used as compiler optimization hints depending upon ASSERT_LEVEL and NBDEBUG.
Definition avassert.h:109
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
Libavcodec external API header.
void avio_w8(AVIOContext *s, int b)
Definition aviobuf.c:184
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2
Writes a formatted string to the context.
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition aviobuf.c:206
void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition aviobuf.c:228
Convenience header that includes libavutil's core.
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
int check_avoptions(AVDictionary *m)
Definition cmdutils.c:1605
int avcodec_parameters_from_context(AVCodecParameters *par, const AVCodecContext *codec)
Definition codec_par.c:138
AVCodecParameters * avcodec_parameters_alloc(void)
Definition codec_par.c:57
void avcodec_parameters_free(AVCodecParameters **ppar)
Definition codec_par.c:67
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
@ AV_FIELD_TT
Top coded_first, top displayed first.
Definition defs.h:214
@ AV_FIELD_BB
Bottom coded first, bottom displayed first.
Definition defs.h:215
@ AV_FIELD_PROGRESSIVE
Definition defs.h:213
@ AV_FIELD_BT
Bottom coded first, top displayed first.
Definition defs.h:217
@ AV_FIELD_TB
Top coded first, bottom displayed first.
Definition defs.h:216
static AVPacket * pkt
static AVFrame * frame
Public dictionary API.
Display matrix.
#define atomic_store(object, desired)
Definition stdatomic.h:85
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
Definition eval.c:824
simple arithmetic expression evaluator
const FrameData * frame_data_c(AVFrame *frame)
Definition ffmpeg.c:497
FrameData * frame_data(AVFrame *frame)
Get our axiliary frame data attached to the frame, allocating it if needed.
Definition ffmpeg.c:491
FrameData * packet_data(AVPacket *pkt)
Definition ffmpeg.c:503
FILE * vstats_file
Definition ffmpeg.c:92
void update_benchmark(const char *fmt,...)
Definition ffmpeg.c:565
int debug_ts
Definition ffmpeg_opt.c:67
int of_stream_init(OutputFile *of, OutputStream *ost, const AVCodecContext *enc_ctx)
Definition ffmpeg_mux.c:606
@ LATENCY_PROBE_ENC_PRE
Definition ffmpeg.h:92
@ LATENCY_PROBE_ENC_POST
Definition ffmpeg.h:93
int vstats_version
Definition ffmpeg_opt.c:76
char * vstats_filename
Definition ffmpeg_opt.c:54
@ FKF_PREV_FORCED_N
Definition ffmpeg.h:538
@ FKF_T
Definition ffmpeg.h:540
@ FKF_PREV_FORCED_T
Definition ffmpeg.h:539
@ FKF_N_FORCED
Definition ffmpeg.h:537
@ FKF_N
Definition ffmpeg.h:536
@ KF_FORCE_SCD_METADATA
Definition ffmpeg.h:589
@ KF_FORCE_SOURCE
Definition ffmpeg.h:587
HWDevice * hw_device_get_by_type(enum AVHWDeviceType type)
Definition ffmpeg_hw.c:28
int exit_on_error
Definition ffmpeg_opt.c:68
@ ENC_STATS_STREAM_IDX
Definition ffmpeg.h:550
@ ENC_STATS_PTS_TIME
Definition ffmpeg.h:556
@ ENC_STATS_SAMPLE_NUM
Definition ffmpeg.h:561
@ ENC_STATS_AVG_BITRATE
Definition ffmpeg.h:565
@ ENC_STATS_LITERAL
Definition ffmpeg.h:548
@ ENC_STATS_TIMEBASE
Definition ffmpeg.h:553
@ ENC_STATS_KEYFRAME
Definition ffmpeg.h:566
@ ENC_STATS_DTS_TIME
Definition ffmpeg.h:560
@ ENC_STATS_PKT_SIZE
Definition ffmpeg.h:563
@ ENC_STATS_FRAME_NUM_IN
Definition ffmpeg.h:552
@ ENC_STATS_PTS
Definition ffmpeg.h:555
@ ENC_STATS_FRAME_NUM
Definition ffmpeg.h:551
@ ENC_STATS_FILE_IDX
Definition ffmpeg.h:549
@ ENC_STATS_DTS
Definition ffmpeg.h:559
@ ENC_STATS_BITRATE
Definition ffmpeg.h:564
@ ENC_STATS_PTS_IN
Definition ffmpeg.h:557
@ ENC_STATS_TIMEBASE_IN
Definition ffmpeg.h:554
@ ENC_STATS_PTS_TIME_IN
Definition ffmpeg.h:558
@ ENC_STATS_NB_SAMPLES
Definition ffmpeg.h:562
static void enc_thread_uninit(EncoderThread *et)
Definition ffmpeg_enc.c:921
static int hw_device_setup_for_encode(Encoder *e, AVCodecContext *enc_ctx, AVBufferRef *frames_ref)
Definition ffmpeg_enc.c:159
static int enc_realloc(Encoder *enc, const AVCodec *codec)
Definition ffmpeg_enc.c:102
static int enc_thread_init(EncoderThread *et)
Definition ffmpeg_enc.c:929
int enc_loopback(Encoder *enc)
static double psnr(double d)
Definition ffmpeg_enc.c:624
static const AVClass enc_class
Definition ffmpeg_enc.c:95
static int check_recording_time(OutputStream *ost, int64_t ts, AVRational tb)
Definition ffmpeg_enc.c:451
int enc_alloc(Encoder **penc, const AVCodec *codec, Scheduler *sch, unsigned sch_idx, void *log_parent)
Definition ffmpeg_enc.c:125
static enum AVPictureType forced_kf_apply(void *logctx, KeyframeForceCtx *kf, const AVFrame *frame)
Definition ffmpeg_enc.c:829
static int enc_reopen(void *opaque, const AVFrame *frame, AVDictionary **extra_encoder_opts)
Definition ffmpeg_enc.c:228
int encoder_thread(void *arg)
int enc_open(void *opaque, const AVFrame *frame)
Definition ffmpeg_enc.c:424
static int update_video_stats(OutputStream *ost, const AVPacket *pkt, int write_vstats)
Definition ffmpeg_enc.c:629
static int encode_frame(OutputFile *of, OutputStream *ost, AVFrame *frame, AVPacket *pkt)
Definition ffmpeg_enc.c:694
static int flush_encoder(OutputStream *ost, EncoderThread *et)
Definition ffmpeg_enc.c:948
static int apply_enc_options(Encoder *e, AVDictionary **opts)
Definition ffmpeg_enc.c:210
static const char * enc_item_name(void *obj)
Definition ffmpeg_enc.c:88
static int do_subtitle_out(OutputFile *of, OutputStream *ost, const AVSubtitle *sub, AVPacket *pkt)
Definition ffmpeg_enc.c:462
static int frame_encode(OutputStream *ost, AVFrame *frame, AVPacket *pkt)
Definition ffmpeg_enc.c:878
void enc_free(Encoder **penc)
Definition ffmpeg_enc.c:73
static EncoderPriv * ep_from_enc(Encoder *enc)
Definition ffmpeg_enc.c:62
static void enc_thread_set_name(const OutputStream *ost)
Definition ffmpeg_enc.c:913
static int reinit_encoder(OutputStream *ost, EncoderThread *et)
Definition ffmpeg_enc.c:961
void enc_stats_write(OutputStream *ost, EncStats *es, const AVFrame *frame, const AVPacket *pkt, uint64_t frame_num)
Definition ffmpeg_enc.c:550
int sch_enc_receive(Scheduler *sch, unsigned enc_idx, AVFrame *frame)
Called by encoder tasks to obtain frames for encoding.
int sch_enc_send(Scheduler *sch, unsigned enc_idx, AVPacket *pkt)
Called by encoder tasks to send encoded packets downstream.
static int clone_side_data(AVFrameSideData ***dst, int *nb_dst, AVFrameSideData *const *src, int nb_src, unsigned int flags)
Wrapper calling av_frame_side_data_clone() in a loop for all source entries.
static int64_t duration
Definition ffplay.c:330
reference-counted frame API
#define fail
Definition test.h:479
int avcodec_encode_reconfigure(AVCodecContext *avctx, AVDictionary **options)
Try to reconfigure the encoder with the provided dictionary.
Definition encode.c:673
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition avcodec.c:144
#define AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE
This encoder can reorder user opaque values from input AVFrames and return them with corresponding ou...
Definition codec.h:147
#define AV_CODEC_FLAG_BITEXACT
Use only bitexact stuff (except (I)DCT).
Definition avcodec.h:322
#define AV_CODEC_CAP_ENCODER_RECONF
Encoder can be reconfigured by passing new initialization parameters.
Definition codec.h:54
#define AV_CODEC_CAP_VARIABLE_FRAME_SIZE
Audio encoder supports receiving a different number of samples in each call.
Definition codec.h:116
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition options.c:149
#define AV_CODEC_FLAG_INTERLACED_DCT
Use interlaced DCT.
Definition avcodec.h:310
#define AV_CODEC_FLAG_FRAME_DURATION
Signal to the encoder that the values of AVFrame.duration are valid and should be used (typically for...
Definition avcodec.h:286
#define AV_CODEC_FLAG2_FIXED_FRAME_SIZE
Force audio encoders to use a fixed frame size.
Definition avcodec.h:359
#define AV_CODEC_FLAG_INTERLACED_ME
interlaced motion estimation
Definition avcodec.h:331
const AVCodecHWConfig * avcodec_get_hw_config(const AVCodec *codec, int index)
Retrieve supported hardware configurations for a codec.
Definition utils.c:857
#define AV_CODEC_FLAG_PSNR
error[?
Definition avcodec.h:306
#define AV_CODEC_CAP_PARAM_CHANGE
Codec supports changed parameters at any point.
Definition codec.h:106
#define AV_CODEC_FLAG_COPY_OPAQUE
Definition avcodec.h:279
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
Definition options.c:164
@ AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX
The codec supports this format via the hw_frames_ctx interface.
Definition codec.h:295
@ AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX
The codec supports this format via the hw_device_ctx interface.
Definition codec.h:282
@ AV_CODEC_ID_DVB_SUBTITLE
Definition codec_id.h:567
@ AV_CODEC_ID_CODEC2
Definition codec_id.h:520
@ AV_CODEC_ID_ASS
Definition codec_id.h:588
@ AV_CODEC_ID_MJPEG
Definition codec_id.h:57
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
Read encoded data from the encoder.
Definition encode.c:578
int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Supply a raw video or audio frame to the encoder.
Definition encode.c:545
int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size, const AVSubtitle *sub)
Definition encode.c:204
@ AV_PKT_DATA_QUALITY_STATS
This side data contains quality related information from the encoder.
Definition packet.h:129
@ AV_PKT_DATA_NEW_EXTRADATA
The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was...
Definition packet.h:56
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition packet.c:74
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:434
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, size_t size)
Allocate new information of a packet.
Definition packet.c:231
#define AV_PKT_FLAG_TRUSTED
The packet comes from a trusted source.
Definition packet.h:664
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:650
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, size_t *size)
Get side information from packet.
Definition packet.c:252
void av_shrink_packet(AVPacket *pkt, int size)
Reduce packet size, correctly zeroing padding.
Definition packet.c:113
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition packet.c:63
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition packet.c:98
int av_channel_layout_copy(AVChannelLayout *dst, const AVChannelLayout *src)
Make a copy of a channel layout.
AVBufferRef * av_buffer_ref(const AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition buffer.c:103
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:233
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:60
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition dict.c:247
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:86
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition dict.h:81
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition avutil.h:226
#define AVERROR_EXPERIMENTAL
Requested feature is flagged experimental. Set strict_std_compliance if you really want to use it.
Definition error.h:74
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition error.h:52
#define AVERROR_EOF
End of file.
Definition error.h:57
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
#define AVERROR(e)
Definition error.h:45
#define AV_FRAME_FLAG_INTERLACED
A flag to mark frames whose content is interlaced.
Definition frame.h:695
#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:700
#define AV_FRAME_FLAG_KEY
A flag to mark frames that are keyframes.
Definition frame.h:687
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition frame.c:496
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition frame.c:64
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition frame.c:52
#define AV_FRAME_SIDE_DATA_FLAG_UNIQUE
Remove existing entries before adding new ones.
Definition frame.h:1093
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition log.h:236
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition log.h:204
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
AVRational av_mul_q(AVRational b, AVRational c)
Multiply two rationals.
Definition rational.c:80
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition rational.h:104
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare two timestamps each in its own time base.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
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
AVMediaType
Definition avutil.h:198
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_SUBTITLE
Definition avutil.h:203
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
char av_get_picture_type_char(enum AVPictureType pict_type)
Return a single letter to describe the given picture type pict_type.
Definition utils.c:40
AVPictureType
Definition avutil.h:276
@ AV_PICTURE_TYPE_I
Intra.
Definition avutil.h:278
@ AV_PICTURE_TYPE_NONE
Undefined.
Definition avutil.h:277
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition samplefmt.c:108
@ AV_SAMPLE_FMT_NONE
Definition samplefmt.h:56
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition avutil.h:263
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
#define AV_OPT_SEARCH_CHILDREN
Search in possible children of the given object first.
Definition opt.h:604
int av_opt_set_dict2(void *obj, AVDictionary **options, int search_flags)
Set all the options from a given dictionary on an object.
Definition opt.c:2038
const char * av_hwdevice_get_type_name(enum AVHWDeviceType type)
Get the string name of an AVHWDeviceType.
Definition hwcontext.c:120
cl_device_type type
#define AV_RL64(p)
#define AV_RL32(p)
const char * arg
Definition jacosubdec.c:65
static int ff_thread_setname(const char *name)
Definition thread.h:216
#define FFMIN(a, b)
Definition macros.h:49
#define FFMAX(a, b)
Definition macros.h:47
#define INFINITY
Memory handling functions.
AVOptions.
static av_always_inline int pthread_mutex_lock(pthread_mutex_t *mutex)
Definition os2threads.h:119
static av_always_inline int pthread_mutex_unlock(pthread_mutex_t *mutex)
Definition os2threads.h:126
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition pixdesc.c:3380
const char * av_chroma_location_name(enum AVChromaLocation location)
Definition pixdesc.c:3881
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition pixdesc.c:3460
@ AVCHROMA_LOC_UNSPECIFIED
Definition pixfmt.h:803
@ AV_PIX_FMT_NONE
Definition pixfmt.h:72
const char * name
Definition qsvenc.c:142
Utilities for rational number calculation.
#define snprintf
Definition snprintf.h:34
A reference to a data buffer.
Definition buffer.h:82
uint8_t * data
The data buffer.
Definition buffer.h:90
int nb_channels
Number of channels in this layout.
Describe the class of an AVClass context structure.
Definition log.h:76
main external API structure.
Definition avcodec.h:443
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition avcodec.h:643
int subtitle_header_size
Header containing style information for text subtitles.
Definition avcodec.h:1743
int width
picture width / height.
Definition avcodec.h:604
char * stats_out
pass1 encoding statistics output buffer
Definition avcodec.h:1330
AVChannelLayout ch_layout
Audio channel layout.
Definition avcodec.h:1055
int flags2
AV_CODEC_FLAG2_*.
Definition avcodec.h:507
enum AVSampleFormat sample_fmt
audio sample format
Definition avcodec.h:1047
int global_quality
Global quality for codecs which cannot change it per frame.
Definition avcodec.h:1235
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition avcodec.h:681
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition avcodec.h:468
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition avcodec.h:657
AVBufferRef * hw_frames_ctx
A reference to the AVHWFramesContext describing the input (for encoding) or output (decoding) frames.
Definition avcodec.h:1471
enum AVMediaType codec_type
Definition avcodec.h:451
AVRational framerate
Definition avcodec.h:563
char * stats_in
pass2 encoding statistics input buffer Concatenated stuff from stats_out of pass1 should be placed he...
Definition avcodec.h:1338
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition avcodec.h:628
enum AVFieldOrder field_order
Field order.
Definition avcodec.h:694
int64_t bit_rate
the average bitrate
Definition avcodec.h:493
const struct AVCodec * codec
Definition avcodec.h:452
int nb_decoded_side_data
Definition avcodec.h:1930
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition avcodec.h:1571
enum AVColorSpace colorspace
YUV colorspace type.
Definition avcodec.h:671
int sample_rate
samples per second
Definition avcodec.h:1040
int thread_count
thread count is used to decide how many independent tasks should be passed to execute()
Definition avcodec.h:1579
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition avcodec.h:664
uint8_t * subtitle_header
Definition avcodec.h:1744
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avcodec.h:547
int flags
AV_CODEC_FLAG_*.
Definition avcodec.h:500
AVFrameSideData ** decoded_side_data
Array containing static side data, such as HDR10 CLL / MDCV structures.
Definition avcodec.h:1929
uint8_t * extradata
Out-of-band global headers that may be used by some codecs.
Definition avcodec.h:526
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
Definition avcodec.h:688
enum AVAlphaMode alpha_mode
Indicates how the alpha channel of the video is represented.
Definition avcodec.h:1937
AVBufferRef * hw_device_ctx
A reference to the AVHWDeviceContext describing the device which will be used by a hardware encoder/d...
Definition avcodec.h:1493
enum AVCodecID codec_id
Definition avcodec.h:453
int extradata_size
Definition avcodec.h:527
int frame_size
Number of samples per channel in an audio frame.
Definition avcodec.h:1068
AVCodec.
Definition codec.h:175
enum AVCodecID id
Definition codec.h:189
enum AVMediaType type
Definition codec.h:188
const char * name
Name of the codec implementation.
Definition codec.h:182
int capabilities
Codec capabilities.
Definition codec.h:194
This structure describes decoded (raw) audio or video data.
Definition frame.h:472
This struct describes a set or pool of "hardware" frames (i.e.
Definition hwcontext.h:118
Bytestream IO Context.
Definition avio.h:160
This structure stores compressed data.
Definition packet.h:580
Rational number (pair of numerator and denominator).
Definition rational.h:58
int num
Numerator.
Definition rational.h:59
int den
Denominator.
Definition rational.h:60
uint32_t start_display_time
Definition avcodec.h:2089
uint32_t end_display_time
Definition avcodec.h:2090
unsigned num_rects
Definition avcodec.h:2091
AVSubtitleRect ** rects
Definition avcodec.h:2092
int64_t pts
Same as packet pts, in AV_TIME_BASE.
Definition avcodec.h:2093
uint8_t * subtitle_header
Definition ffmpeg.h:456
int subtitle_header_size
Definition ffmpeg.h:457
int nb_components
Definition ffmpeg.h:578
AVIOContext * io
Definition ffmpeg.h:580
EncStatsComponent * components
Definition ffmpeg.h:577
pthread_mutex_t lock
Definition ffmpeg.h:582
char log_name[32]
Definition ffmpeg_enc.c:46
unsigned sch_idx
Definition ffmpeg_enc.c:59
int got_first_packet
Definition ffmpeg_enc.c:53
uint64_t packets_encoded
Definition ffmpeg_enc.c:52
Scheduler * sch
Definition ffmpeg_enc.c:58
void * log_parent
Definition ffmpeg_enc.c:45
Encoder e
Definition ffmpeg_enc.c:43
uint64_t data_size
Definition ffmpeg_enc.c:49
AVFrame * frame
Definition ffmpeg_enc.c:69
AVPacket * pkt
Definition ffmpeg_enc.c:70
AVDictionary * encoder_opts
Definition ffmpeg.h:614
int global_quality
Definition ffmpeg.h:621
AVCodecContext * enc_ctx
Definition ffmpeg.h:611
uint64_t frames_encoded
Definition ffmpeg.h:624
uint64_t samples_encoded
Definition ffmpeg.h:625
uint32_t codec_tag
Definition ffmpeg.h:618
int flags
Definition ffmpeg.h:619
const AVClass * class
Definition ffmpeg.h:609
int flags2
Definition ffmpeg.h:620
uint64_t frame_num
Definition ffmpeg.h:711
struct FrameData::@304126211346234154321045014345346376220164157123 dec
AVRational frame_rate_filter
Definition ffmpeg.h:717
int64_t wallclock[LATENCY_PROBE_NB]
Definition ffmpeg.h:721
int64_t pts
Definition ffmpeg.h:713
int nb_side_data
Definition ffmpeg.h:726
AVCodecParameters * par_enc
Definition ffmpeg.h:723
int bits_per_raw_sample
Definition ffmpeg.h:719
AVFrameSideData ** side_data
Definition ffmpeg.h:725
AVDictionary * reinit_opts
Definition ffmpeg.h:728
AVRational tb
Definition ffmpeg.h:714
AVBufferRef * device_ref
Definition ffmpeg.h:100
enum AVHWDeviceType type
Definition ffmpeg.h:99
const char * name
Definition ffmpeg.h:98
Decoder * decoder
Definition ffmpeg.h:482
int64_t * pts
Definition ffmpeg.h:598
int64_t ref_pts
Definition ffmpeg.h:595
double expr_const_values[FKF_NB]
Definition ffmpeg.h:603
AVExpr * pexpr
Definition ffmpeg.h:602
int index
Definition ffmpeg.h:690
int64_t start_time
start time in microseconds == AV_TIME_BASE units
Definition ffmpeg.h:698
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
Definition ffmpeg.h:697
static int frame_samples(const SyncQueue *sq, SyncQueueFrame frame)
Definition sync_queue.c:131
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
static void error(const char *err)
int64_t bitrate
Definition av1_levels.c:47
static void finish(void)
Definition movenc.c:374
static AVDictionary * opts
Definition movenc.c:51
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition time.c:57
timestamp utils, mostly useful for debugging/logging purposes
#define av_ts2str(ts)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition timestamp.h:54
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition timestamp.h:83
static int64_t pts
static AVStream * ost
static void copy(const float *p1, float *p2, const int length)
static const uint8_t quality[]
Definition vmixdec.c:58
static double c[64]