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 enc_ctx->chroma_sample_location = frame->chroma_location;
342
344 (frame->flags & AV_FRAME_FLAG_INTERLACED)) {
345 int top_field_first = !!(frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST);
346
347 if (enc->id == AV_CODEC_ID_MJPEG)
348 enc_ctx->field_order = top_field_first ? AV_FIELD_TT : AV_FIELD_BB;
349 else
350 enc_ctx->field_order = top_field_first ? AV_FIELD_TB : AV_FIELD_BT;
351 } else
353
354 break;
355 }
357 enc_ctx->time_base = AV_TIME_BASE_Q;
358
359 if (!enc_ctx->width) {
360 enc_ctx->width = ost->ist->par->width;
361 enc_ctx->height = ost->ist->par->height;
362 }
363
364 av_assert0(dec);
365 if (dec->subtitle_header) {
366 /* ASS code assumes this buffer is null terminated so add extra byte. */
368 if (!enc_ctx->subtitle_header)
369 return AVERROR(ENOMEM);
370 memcpy(enc_ctx->subtitle_header, dec->subtitle_header,
373 }
374
375 break;
376 default:
377 av_assert0(0);
378 break;
379 }
380
381 if (ost->bitexact)
382 enc_ctx->flags |= AV_CODEC_FLAG_BITEXACT;
383
386
388
389 ret = hw_device_setup_for_encode(e, enc_ctx, frame ? frame->hw_frames_ctx : NULL);
390 if (ret < 0) {
392 "Encoding hardware device setup failed: %s\n", av_err2str(ret));
393 return ret;
394 }
395
396 if ((ret = avcodec_open2(enc_ctx, enc, NULL)) < 0) {
397 if (ret != AVERROR_EXPERIMENTAL)
398 av_log(e, AV_LOG_ERROR, "Error while opening encoder - maybe "
399 "incorrect parameters such as bit_rate, rate, width or height.\n");
400 return ret;
401 }
402
403 ep->opened = 1;
404
405 if (enc_ctx->bit_rate && enc_ctx->bit_rate < 1000 &&
406 enc_ctx->codec_id != AV_CODEC_ID_CODEC2 /* don't complain about 700 bit/s modes */)
407 av_log(e, AV_LOG_WARNING, "The bitrate parameter is set too low."
408 " It takes bits/s as argument, not kbits/s\n");
409
410 return 0;
411}
412
413int enc_open(void *opaque, const AVFrame *frame)
414{
415 OutputStream *ost = opaque;
416 Encoder *e = ost->enc;
417 EncoderPriv *ep = ep_from_enc(e);
418 AVCodecContext *enc_ctx = e->enc_ctx;
419 OutputFile *of = ost->file;
420 int frame_samples = 0;
421 int ret;
422
423 if (ep->opened)
424 return 0;
425
426 ret = enc_reopen(opaque, frame, NULL);
427 if (ret < 0)
428 return ret;
429
430 if (enc_ctx->frame_size)
431 frame_samples = enc_ctx->frame_size;
432
433 ret = of_stream_init(of, ost, enc_ctx);
434 if (ret < 0)
435 return ret;
436
437 return frame_samples;
438}
439
441{
442 OutputFile *of = ost->file;
443
444 if (of->recording_time != INT64_MAX &&
445 av_compare_ts(ts, tb, of->recording_time, AV_TIME_BASE_Q) >= 0) {
446 return 0;
447 }
448 return 1;
449}
450
452 AVPacket *pkt)
453{
454 Encoder *e = ost->enc;
455 EncoderPriv *ep = ep_from_enc(e);
456 int subtitle_out_max_size = 1024 * 1024;
457 int subtitle_out_size, nb, i, ret;
458 AVCodecContext *enc;
459 int64_t pts;
460
461 if (sub->pts == AV_NOPTS_VALUE) {
462 av_log(e, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
463 return exit_on_error ? AVERROR(EINVAL) : 0;
464 }
465 if ((of->start_time != AV_NOPTS_VALUE && sub->pts < of->start_time))
466 return 0;
467
468 enc = e->enc_ctx;
469
470 /* Note: DVB subtitle need one packet to draw them and one other
471 packet to clear them */
472 /* XXX: signal it in the codec context ? */
474 nb = 2;
475 else if (enc->codec_id == AV_CODEC_ID_ASS)
476 nb = FFMAX(sub->num_rects, 1);
477 else
478 nb = 1;
479
480 /* shift timestamp to honor -ss and make check_recording_time() work with -t */
481 pts = sub->pts;
482 if (of->start_time != AV_NOPTS_VALUE)
483 pts -= of->start_time;
484 for (i = 0; i < nb; i++) {
485 AVSubtitle local_sub = *sub;
486
488 return AVERROR_EOF;
489
490 ret = av_new_packet(pkt, subtitle_out_max_size);
491 if (ret < 0)
492 return AVERROR(ENOMEM);
493
494 local_sub.pts = pts;
495 // start_display_time is required to be 0
496 local_sub.pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
497 local_sub.end_display_time -= sub->start_display_time;
498 local_sub.start_display_time = 0;
499
500 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE && i == 1)
501 local_sub.num_rects = 0;
502 else if (enc->codec_id == AV_CODEC_ID_ASS && sub->num_rects > 0) {
503 local_sub.num_rects = 1;
504 local_sub.rects += i;
505 }
506
507 e->frames_encoded++;
508
509 subtitle_out_size = avcodec_encode_subtitle(enc, pkt->data, pkt->size, &local_sub);
510 if (subtitle_out_size < 0) {
511 av_log(e, AV_LOG_FATAL, "Subtitle encoding failed\n");
512 return subtitle_out_size;
513 }
514
515 av_shrink_packet(pkt, subtitle_out_size);
516 pkt->time_base = AV_TIME_BASE_Q;
517 pkt->pts = pts;
518 pkt->duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, pkt->time_base);
520 /* XXX: the pts correction is handled here. Maybe handling
521 it in the codec would be better */
522 if (i == 0)
523 pkt->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, pkt->time_base);
524 else
525 pkt->pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, pkt->time_base);
526 }
527 pkt->dts = pkt->pts;
528
529 ret = sch_enc_send(ep->sch, ep->sch_idx, pkt);
530 if (ret < 0) {
532 return ret;
533 }
534 }
535
536 return 0;
537}
538
540 const AVFrame *frame, const AVPacket *pkt,
541 uint64_t frame_num)
542{
543 Encoder *e = ost->enc;
544 EncoderPriv *ep = ep_from_enc(e);
545 AVIOContext *io = es->io;
546 AVRational tb = frame ? frame->time_base : pkt->time_base;
547 int64_t pts = frame ? frame->pts : pkt->pts;
548
549 AVRational tbi = (AVRational){ 0, 1};
550 int64_t ptsi = INT64_MAX;
551
552 const FrameData *fd = NULL;
553
554 if (frame ? frame->opaque_ref : pkt->opaque_ref) {
555 fd = (const FrameData*)(frame ? frame->opaque_ref->data : pkt->opaque_ref->data);
556 tbi = fd->dec.tb;
557 ptsi = fd->dec.pts;
558 }
559
561
562 for (size_t i = 0; i < es->nb_components; i++) {
563 const EncStatsComponent *c = &es->components[i];
564
565 switch (c->type) {
566 case ENC_STATS_LITERAL: avio_write (io, c->str, c->str_len); continue;
567 case ENC_STATS_FILE_IDX: avio_printf(io, "%d", ost->file->index); continue;
568 case ENC_STATS_STREAM_IDX: avio_printf(io, "%d", ost->index); continue;
569 case ENC_STATS_TIMEBASE: avio_printf(io, "%d/%d", tb.num, tb.den); continue;
570 case ENC_STATS_TIMEBASE_IN: avio_printf(io, "%d/%d", tbi.num, tbi.den); continue;
571 case ENC_STATS_PTS: avio_printf(io, "%"PRId64, pts); continue;
572 case ENC_STATS_PTS_IN: avio_printf(io, "%"PRId64, ptsi); continue;
573 case ENC_STATS_PTS_TIME: avio_printf(io, "%g", pts * av_q2d(tb)); continue;
574 case ENC_STATS_PTS_TIME_IN: avio_printf(io, "%g", ptsi == INT64_MAX ?
575 INFINITY : ptsi * av_q2d(tbi)); continue;
576 case ENC_STATS_FRAME_NUM: avio_printf(io, "%"PRIu64, frame_num); continue;
577 case ENC_STATS_FRAME_NUM_IN: avio_printf(io, "%"PRIu64, fd ? fd->dec.frame_num : -1); continue;
578 }
579
580 if (frame) {
581 switch (c->type) {
582 case ENC_STATS_SAMPLE_NUM: avio_printf(io, "%"PRIu64, e->samples_encoded); continue;
583 case ENC_STATS_NB_SAMPLES: avio_printf(io, "%d", frame->nb_samples); continue;
584 default: av_assert0(0);
585 }
586 } else {
587 switch (c->type) {
588 case ENC_STATS_DTS: avio_printf(io, "%"PRId64, pkt->dts); continue;
589 case ENC_STATS_DTS_TIME: avio_printf(io, "%g", pkt->dts * av_q2d(tb)); continue;
590 case ENC_STATS_PKT_SIZE: avio_printf(io, "%d", pkt->size); continue;
591 case ENC_STATS_KEYFRAME: avio_write(io, (pkt->flags & AV_PKT_FLAG_KEY) ?
592 "K" : "N", 1); continue;
593 case ENC_STATS_BITRATE: {
594 double duration = FFMAX(pkt->duration, 1) * av_q2d(tb);
595 avio_printf(io, "%g", 8.0 * pkt->size / duration);
596 continue;
597 }
599 double duration = pkt->dts * av_q2d(tb);
600 avio_printf(io, "%g", duration > 0 ? 8.0 * ep->data_size / duration : -1.);
601 continue;
602 }
603 default: av_assert0(0);
604 }
605 }
606 }
607 avio_w8(io, '\n');
608 avio_flush(io);
609
611}
612
613static inline double psnr(double d)
614{
615 return -10.0 * log10(d);
616}
617
618static int update_video_stats(OutputStream *ost, const AVPacket *pkt, int write_vstats)
619{
620 Encoder *e = ost->enc;
621 EncoderPriv *ep = ep_from_enc(e);
623 NULL);
624 AVCodecContext *enc = e->enc_ctx;
625 enum AVPictureType pict_type;
626 int64_t frame_number;
627 double ti1, bitrate, avg_bitrate;
628 double psnr_val = -1;
629 int quality;
630
631 quality = sd ? AV_RL32(sd) : -1;
632 pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
633
634 atomic_store(&ost->quality, quality);
635
636 if ((enc->flags & AV_CODEC_FLAG_PSNR) && sd && sd[5]) {
637 // FIXME the scaling assumes 8bit
638 double error = AV_RL64(sd + 8) / (enc->width * enc->height * 255.0 * 255.0);
639 if (error >= 0 && error <= 1)
640 psnr_val = psnr(error);
641 }
642
643 if (!write_vstats)
644 return 0;
645
646 /* this is executed just the first time update_video_stats is called */
647 if (!vstats_file) {
648 vstats_file = fopen(vstats_filename, "w");
649 if (!vstats_file) {
650 perror("fopen");
651 return AVERROR(errno);
652 }
653 }
654
655 frame_number = ep->packets_encoded;
656 if (vstats_version <= 1) {
657 fprintf(vstats_file, "frame= %5"PRId64" q= %2.1f ", frame_number,
658 quality / (float)FF_QP2LAMBDA);
659 } else {
660 fprintf(vstats_file, "out= %2d st= %2d frame= %5"PRId64" q= %2.1f ",
661 ost->file->index, ost->index, frame_number,
662 quality / (float)FF_QP2LAMBDA);
663 }
664
665 if (psnr_val >= 0)
666 fprintf(vstats_file, "PSNR= %6.2f ", psnr_val);
667
668 fprintf(vstats_file,"f_size= %6d ", pkt->size);
669 /* compute pts value */
670 ti1 = pkt->dts * av_q2d(pkt->time_base);
671 if (ti1 < 0.01)
672 ti1 = 0.01;
673
674 bitrate = (pkt->size * 8) / av_q2d(enc->time_base) / 1000.0;
675 avg_bitrate = (double)(ep->data_size * 8) / ti1 / 1000.0;
676 fprintf(vstats_file, "s_size= %8.0fKiB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
677 (double)ep->data_size / 1024, ti1, bitrate, avg_bitrate);
678 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(pict_type));
679
680 return 0;
681}
682
684 AVPacket *pkt)
685{
686 Encoder *e = ost->enc;
687 EncoderPriv *ep = ep_from_enc(e);
688 AVCodecContext *enc = e->enc_ctx;
689 const char *type_desc = av_get_media_type_string(enc->codec_type);
690 const char *action = frame ? "encode" : "flush";
691 int ret;
692
693 if (frame) {
695
696 if (!fd)
697 return AVERROR(ENOMEM);
698
700
701 if (ost->enc_stats_pre.io)
702 enc_stats_write(ost, &ost->enc_stats_pre, frame, NULL,
703 e->frames_encoded);
704
705 e->frames_encoded++;
706 e->samples_encoded += frame->nb_samples;
707
708 if (debug_ts) {
709 av_log(e, AV_LOG_INFO, "encoder <- type:%s "
710 "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
711 type_desc,
712 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
713 enc->time_base.num, enc->time_base.den);
714 }
715
716 if (frame->sample_aspect_ratio.num && !ost->frame_aspect_ratio.num)
717 enc->sample_aspect_ratio = frame->sample_aspect_ratio;
718 }
719
721
722 ret = avcodec_send_frame(enc, frame);
723 if (ret < 0 && !(ret == AVERROR_EOF && !frame)) {
724 av_log(e, AV_LOG_ERROR, "Error submitting %s frame to the encoder\n",
725 type_desc);
726 return ret;
727 }
728
729 while (1) {
730 FrameData *fd;
731
733
734 ret = avcodec_receive_packet(enc, pkt);
735 update_benchmark("%s_%s %d.%d", action, type_desc,
736 of->index, ost->index);
737
738 pkt->time_base = enc->time_base;
739
740 /* if two pass, output log on success and EOF */
741 if ((ret >= 0 || ret == AVERROR_EOF) && ost->logfile && enc->stats_out)
742 fprintf(ost->logfile, "%s", enc->stats_out);
743
744 if (ret == AVERROR(EAGAIN)) {
745 av_assert0(frame); // should never happen during flushing
746 return 0;
747 } else if (ret < 0) {
748 if (ret != AVERROR_EOF)
749 av_log(e, AV_LOG_ERROR, "%s encoding failed\n", type_desc);
750 return ret;
751 }
752
753 fd = packet_data(pkt);
754 if (!fd)
755 return AVERROR(ENOMEM);
757
758 // attach extradata to first packet if the encoder was reinitialized
759 if (!ep->got_first_packet && ep->packets_encoded && enc->extradata_size) {
761 enc->extradata_size);
762 if (!extradata)
763 return AVERROR(ENOMEM);
764 memcpy(extradata, enc->extradata, enc->extradata_size);
765 ep->got_first_packet = 1;
766 }
767 // attach stream parameters to first packet if requested
769 if (!ep->packets_encoded) {
770 if (ep->attach_par) {
772 if (!fd->par_enc)
773 return AVERROR(ENOMEM);
774
776 if (ret < 0)
777 return ret;
778 }
779 ep->got_first_packet = 1;
780 }
781
782 pkt->flags |= AV_PKT_FLAG_TRUSTED;
783
784 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
786 if (ret < 0)
787 return ret;
788 }
789
790 if (ost->enc_stats_post.io)
791 enc_stats_write(ost, &ost->enc_stats_post, NULL, pkt,
792 ep->packets_encoded);
793
794 if (debug_ts) {
795 av_log(e, AV_LOG_INFO, "encoder -> type:%s "
796 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s "
797 "duration:%s duration_time:%s\n",
798 type_desc,
799 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &enc->time_base),
800 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &enc->time_base),
801 av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, &enc->time_base));
802 }
803
804 ep->data_size += pkt->size;
805
806 ep->packets_encoded++;
807
808 ret = sch_enc_send(ep->sch, ep->sch_idx, pkt);
809 if (ret < 0) {
811 return ret;
812 }
813 }
814
815 av_unreachable("encode_frame() loop should return");
816}
817
818static enum AVPictureType forced_kf_apply(void *logctx, KeyframeForceCtx *kf,
819 const AVFrame *frame)
820{
821 double pts_time;
822
823 if (kf->ref_pts == AV_NOPTS_VALUE)
824 kf->ref_pts = frame->pts;
825
826 pts_time = (frame->pts - kf->ref_pts) * av_q2d(frame->time_base);
827 if (kf->index < kf->nb_pts &&
828 av_compare_ts(frame->pts, frame->time_base, kf->pts[kf->index], AV_TIME_BASE_Q) >= 0) {
829 kf->index++;
830 goto force_keyframe;
831 } else if (kf->pexpr) {
832 double res;
833 kf->expr_const_values[FKF_T] = pts_time;
834 res = av_expr_eval(kf->pexpr,
836 av_log(logctx, AV_LOG_TRACE,
837 "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
843 res);
844
845 kf->expr_const_values[FKF_N] += 1;
846
847 if (res) {
851 goto force_keyframe;
852 }
853 } else if (kf->type == KF_FORCE_SOURCE && (frame->flags & AV_FRAME_FLAG_KEY)) {
854 goto force_keyframe;
855 } else if (kf->type == KF_FORCE_SCD_METADATA &&
856 av_dict_get(frame->metadata, "lavfi.scd.time", NULL, 0)) {
857 goto force_keyframe;
858 }
859
861
862force_keyframe:
863 av_log(logctx, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
864 return AV_PICTURE_TYPE_I;
865}
866
868{
869 Encoder *e = ost->enc;
870 OutputFile *of = ost->file;
871 enum AVMediaType type = ost->type;
872
874 const AVSubtitle *subtitle = frame && frame->buf[0] ?
875 (AVSubtitle*)frame->buf[0]->data : NULL;
876
877 // no flushing for subtitles
878 return subtitle && subtitle->num_rects ?
879 do_subtitle_out(of, ost, subtitle, pkt) : 0;
880 }
881
882 if (frame) {
883 if (!check_recording_time(ost, frame->pts, frame->time_base))
884 return AVERROR_EOF;
885
886 if (type == AVMEDIA_TYPE_VIDEO) {
887 frame->quality = e->enc_ctx->global_quality;
888 frame->pict_type = forced_kf_apply(e, &ost->kf, frame);
889 } else {
891 e->enc_ctx->ch_layout.nb_channels != frame->ch_layout.nb_channels) {
893 "Audio channel count changed and encoder does not support parameter changes\n");
894 return 0;
895 }
896 }
897 }
898
899 return encode_frame(of, ost, frame, pkt);
900}
901
903{
904 char name[16];
905 snprintf(name, sizeof(name), "enc%d:%d:%s", ost->file->index, ost->index,
906 ost->enc->enc_ctx->codec->name);
908}
909
911{
912 av_packet_free(&et->pkt);
913 av_frame_free(&et->frame);
914
915 memset(et, 0, sizeof(*et));
916}
917
919{
920 memset(et, 0, sizeof(*et));
921
922 et->frame = av_frame_alloc();
923 if (!et->frame)
924 goto fail;
925
926 et->pkt = av_packet_alloc();
927 if (!et->pkt)
928 goto fail;
929
930 return 0;
931
932fail:
934 return AVERROR(ENOMEM);
935}
936
938{
939 Encoder *e = ost->enc;
940 int ret;
941
942 ret = frame_encode(ost, NULL, et->pkt);
943 if (ret < 0 && ret != AVERROR_EOF)
944 av_log(e, AV_LOG_ERROR, "Error flushing encoder: %s\n",
945 av_err2str(ret));
946
947 return ret;
948}
949
951{
952 Encoder *e = ost->enc;
954 const FrameData *fd = frame_data_c(et->frame);
955 int force_reinit, ret = AVERROR_BUG;
956
957 ret = av_dict_copy(&copy, fd->reinit_opts, 0);
958 if (ret < 0)
959 return ret;
960
961 force_reinit = !!av_dict_get(copy, "force_reinit", NULL, 0);
962 if (force_reinit)
963 av_dict_set(&copy, "force_reinit", NULL, 0);
964 // Lets try a graceful reconfiguration first
967 if (!ret)
968 goto end;
969
971 if (ret < 0)
972 goto end;
973 av_dict_set(&copy, "force_reinit", NULL, 0);
974
975 av_log(e, AV_LOG_INFO, "Could not reconfigure the encoder."
976 " Trying to restart it instead\n");
977 }
978
979 // Go ahead and do a full restart of the encoder
980 ret = flush_encoder(ost, et);
981 if (ret < 0 && ret != AVERROR_EOF)
982 goto end;
983
984 ret = enc_realloc(e, e->enc_ctx->codec);
985 if (ret < 0)
986 goto end;
987 av_log(e, AV_LOG_DEBUG, "Restarting encoder\n");
988 ret = enc_reopen(ost, et->frame, &copy);
989 if (ret < 0)
990 goto end;
991
992 ret = 0;
993end:
995 return ret;
996}
997
999{
1000 OutputStream *ost = arg;
1001 Encoder *e = ost->enc;
1002 EncoderPriv *ep = ep_from_enc(e);
1003 EncoderThread et;
1004 const FrameData *fd;
1005 int ret = 0, input_status = 0;
1006 int name_set = 0;
1007
1008 ret = enc_thread_init(&et);
1009 if (ret < 0)
1010 goto finish;
1011
1012 /* Open the subtitle encoders immediately. AVFrame-based encoders
1013 * are opened through a callback from the scheduler once they get
1014 * their first frame
1015 *
1016 * N.B.: because the callback is called from a different thread,
1017 * enc_ctx MUST NOT be accessed before sch_enc_receive() returns
1018 * for the first time for audio/video. */
1019 if (ost->type != AVMEDIA_TYPE_VIDEO && ost->type != AVMEDIA_TYPE_AUDIO) {
1020 ret = enc_open(ost, NULL);
1021 if (ret < 0)
1022 goto finish;
1023 }
1024
1025 while (!input_status) {
1026 input_status = sch_enc_receive(ep->sch, ep->sch_idx, et.frame);
1027 if (input_status < 0) {
1028 if (input_status == AVERROR_EOF) {
1029 av_log(e, AV_LOG_VERBOSE, "Encoder thread received EOF\n");
1030 if (ep->opened)
1031 break;
1032
1033 av_log(e, AV_LOG_ERROR, "Could not open encoder before EOF\n");
1034 ret = AVERROR(EINVAL);
1035 } else {
1036 av_log(e, AV_LOG_ERROR, "Error receiving a frame for encoding: %s\n",
1037 av_err2str(ret));
1038 ret = input_status;
1039 }
1040 goto finish;
1041 }
1042
1043 if (!name_set) {
1045 name_set = 1;
1046 }
1047
1048 fd = frame_data_c(et.frame);
1049 if (fd && fd->reinit_opts) {
1050 ret = reinit_encoder(ost, &et);
1051 if (ret < 0) {
1052 av_log(e, AV_LOG_ERROR, "Error reconfiguring or restarting encoder: %s\n",
1053 av_err2str(ret));
1054 goto finish;
1055 }
1056 }
1057
1058 ret = frame_encode(ost, et.frame, et.pkt);
1059
1060 av_packet_unref(et.pkt);
1062
1063 if (ret < 0) {
1064 if (ret == AVERROR_EOF)
1065 av_log(e, AV_LOG_VERBOSE, "Encoder returned EOF, finishing\n");
1066 else
1067 av_log(e, AV_LOG_ERROR, "Error encoding a frame: %s\n",
1068 av_err2str(ret));
1069 break;
1070 }
1071 }
1072
1073 // flush the encoder
1074 if (ret == 0 || ret == AVERROR_EOF)
1075 ret = flush_encoder(ost, &et);
1076
1077 // EOF is normal thread termination
1078 if (ret == AVERROR_EOF)
1079 ret = 0;
1080
1081finish:
1082 enc_thread_uninit(&et);
1083
1084 return ret;
1085}
1086
1088{
1089 EncoderPriv *ep = ep_from_enc(enc);
1090 ep->attach_par = 1;
1091 return ep->sch_idx;
1092}
static void finish(void)
static AVDictionary * opts
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:1603
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:228
@ AV_FIELD_BB
Bottom coded first, bottom displayed first.
Definition defs.h:229
@ AV_FIELD_PROGRESSIVE
Definition defs.h:227
@ AV_FIELD_BT
Bottom coded first, top displayed first.
Definition defs.h:231
@ AV_FIELD_TB
Top coded first, bottom displayed first.
Definition defs.h:230
static AVPacket * pkt
static AVFrame * frame
Public dictionary API.
Display matrix.
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:607
@ 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:541
@ FKF_T
Definition ffmpeg.h:543
@ FKF_PREV_FORCED_T
Definition ffmpeg.h:542
@ FKF_N_FORCED
Definition ffmpeg.h:540
@ FKF_N
Definition ffmpeg.h:539
@ KF_FORCE_SCD_METADATA
Definition ffmpeg.h:592
@ KF_FORCE_SOURCE
Definition ffmpeg.h:590
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:553
@ ENC_STATS_PTS_TIME
Definition ffmpeg.h:559
@ ENC_STATS_SAMPLE_NUM
Definition ffmpeg.h:564
@ ENC_STATS_AVG_BITRATE
Definition ffmpeg.h:568
@ ENC_STATS_LITERAL
Definition ffmpeg.h:551
@ ENC_STATS_TIMEBASE
Definition ffmpeg.h:556
@ ENC_STATS_KEYFRAME
Definition ffmpeg.h:569
@ ENC_STATS_DTS_TIME
Definition ffmpeg.h:563
@ ENC_STATS_PKT_SIZE
Definition ffmpeg.h:566
@ ENC_STATS_FRAME_NUM_IN
Definition ffmpeg.h:555
@ ENC_STATS_PTS
Definition ffmpeg.h:558
@ ENC_STATS_FRAME_NUM
Definition ffmpeg.h:554
@ ENC_STATS_FILE_IDX
Definition ffmpeg.h:552
@ ENC_STATS_DTS
Definition ffmpeg.h:562
@ ENC_STATS_BITRATE
Definition ffmpeg.h:567
@ ENC_STATS_PTS_IN
Definition ffmpeg.h:560
@ ENC_STATS_TIMEBASE_IN
Definition ffmpeg.h:557
@ ENC_STATS_PTS_TIME_IN
Definition ffmpeg.h:561
@ ENC_STATS_NB_SAMPLES
Definition ffmpeg.h:565
static void enc_thread_uninit(EncoderThread *et)
Definition ffmpeg_enc.c:910
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:918
int enc_loopback(Encoder *enc)
static double psnr(double d)
Definition ffmpeg_enc.c:613
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:440
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:818
static int enc_reopen(void *opaque, const AVFrame *frame, AVDictionary **extra_encoder_opts)
Definition ffmpeg_enc.c:228
int encoder_thread(void *arg)
Definition ffmpeg_enc.c:998
int enc_open(void *opaque, const AVFrame *frame)
Definition ffmpeg_enc.c:413
static int update_video_stats(OutputStream *ost, const AVPacket *pkt, int write_vstats)
Definition ffmpeg_enc.c:618
static int encode_frame(OutputFile *of, OutputStream *ost, AVFrame *frame, AVPacket *pkt)
Definition ffmpeg_enc.c:683
static int flush_encoder(OutputStream *ost, EncoderThread *et)
Definition ffmpeg_enc.c:937
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:451
static int frame_encode(OutputStream *ost, AVFrame *frame, AVPacket *pkt)
Definition ffmpeg_enc.c:867
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:902
static int reinit_encoder(OutputStream *ost, EncoderThread *et)
Definition ffmpeg_enc.c:950
void enc_stats_write(OutputStream *ost, EncStats *es, const AVFrame *frame, const AVPacket *pkt, uint64_t frame_num)
Definition ffmpeg_enc.c:539
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:399
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:858
#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:569
@ AV_CODEC_ID_CODEC2
Definition codec_id.h:522
@ AV_CODEC_ID_ASS
Definition codec_id.h:590
@ 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:104
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:702
#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:707
#define AV_FRAME_FLAG_KEY
A flag to mark frames that are keyframes.
Definition frame.h:694
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:1100
#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:109
@ 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:2042
const char * av_hwdevice_get_type_name(enum AVHWDeviceType type)
Get the string name of an AVHWDeviceType.
Definition hwcontext.c:120
#define AV_RL64(p)
#define AV_RL32(p)
uint32_t type
Definition jpegmpfenc.c:80
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.
static const char * obj
Definition mscl.c:57
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:132
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 AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition pixdesc.c:3460
@ AV_PIX_FMT_NONE
Definition pixfmt.h:72
const char * name
Definition qsvenc.c:142
Utilities for rational number calculation.
#define atomic_store(object, desired)
Definition stdatomic.h:256
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:1748
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:1472
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:1935
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition avcodec.h:1576
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:1584
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition avcodec.h:664
uint8_t * subtitle_header
Definition avcodec.h:1749
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:1934
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:1942
AVBufferRef * hw_device_ctx
A reference to the AVHWDeviceContext describing the device which will be used by a hardware encoder/d...
Definition avcodec.h:1494
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:479
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:2104
uint32_t end_display_time
Definition avcodec.h:2105
unsigned num_rects
Definition avcodec.h:2106
AVSubtitleRect ** rects
Definition avcodec.h:2107
int64_t pts
Same as packet pts, in AV_TIME_BASE.
Definition avcodec.h:2108
uint8_t * subtitle_header
Definition ffmpeg.h:459
int subtitle_header_size
Definition ffmpeg.h:460
int nb_components
Definition ffmpeg.h:581
AVIOContext * io
Definition ffmpeg.h:583
EncStatsComponent * components
Definition ffmpeg.h:580
pthread_mutex_t lock
Definition ffmpeg.h:585
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:617
int global_quality
Definition ffmpeg.h:624
AVCodecContext * enc_ctx
Definition ffmpeg.h:614
uint64_t frames_encoded
Definition ffmpeg.h:627
uint64_t samples_encoded
Definition ffmpeg.h:628
uint32_t codec_tag
Definition ffmpeg.h:621
int flags
Definition ffmpeg.h:622
const AVClass * class
Definition ffmpeg.h:612
int flags2
Definition ffmpeg.h:623
uint64_t frame_num
Definition ffmpeg.h:714
struct FrameData::@304126211346234154321045014345346376220164157123 dec
AVRational frame_rate_filter
Definition ffmpeg.h:720
int64_t wallclock[LATENCY_PROBE_NB]
Definition ffmpeg.h:724
int64_t pts
Definition ffmpeg.h:716
int nb_side_data
Definition ffmpeg.h:729
AVCodecParameters * par_enc
Definition ffmpeg.h:726
int bits_per_raw_sample
Definition ffmpeg.h:722
AVFrameSideData ** side_data
Definition ffmpeg.h:728
AVDictionary * reinit_opts
Definition ffmpeg.h:731
AVRational tb
Definition ffmpeg.h:717
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:485
int64_t * pts
Definition ffmpeg.h:601
int64_t ref_pts
Definition ffmpeg.h:598
double expr_const_values[FKF_NB]
Definition ffmpeg.h:606
AVExpr * pexpr
Definition ffmpeg.h:605
int index
Definition ffmpeg.h:693
int64_t start_time
start time in microseconds == AV_TIME_BASE units
Definition ffmpeg.h:701
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
Definition ffmpeg.h:700
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
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]