Coverage Report

Created: 2026-05-31 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/encode.c
Line
Count
Source
1
/*
2
 * generic encoding-related code
3
 *
4
 * This file is part of FFmpeg.
5
 *
6
 * FFmpeg is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * FFmpeg is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with FFmpeg; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
 */
20
21
#include "libavutil/avassert.h"
22
#include "libavutil/channel_layout.h"
23
#include "libavutil/emms.h"
24
#include "libavutil/frame.h"
25
#include "libavutil/internal.h"
26
#include "libavutil/intreadwrite.h"
27
#include "libavutil/mem.h"
28
#include "libavutil/pixdesc.h"
29
#include "libavutil/samplefmt.h"
30
31
#include "avcodec.h"
32
#include "avcodec_internal.h"
33
#include "codec_desc.h"
34
#include "codec_internal.h"
35
#include "encode.h"
36
#include "frame_thread_encoder.h"
37
#include "internal.h"
38
39
typedef struct EncodeContext {
40
    AVCodecInternal avci;
41
42
    /**
43
     * This is set to AV_PKT_FLAG_KEY for encoders that encode intra-only
44
     * formats (i.e. whose codec descriptor has AV_CODEC_PROP_INTRA_ONLY set).
45
     * This is used to set said flag generically for said encoders.
46
     */
47
    int intra_only_flag;
48
49
    /**
50
     * An audio frame with less than required samples has been submitted (and
51
     * potentially padded with silence). Reject all subsequent frames.
52
     */
53
    int last_audio_frame;
54
} EncodeContext;
55
56
static EncodeContext *encode_ctx(AVCodecInternal *avci)
57
0
{
58
0
    return (EncodeContext*)avci;
59
0
}
60
61
int ff_alloc_packet(AVCodecContext *avctx, AVPacket *avpkt, int64_t size)
62
0
{
63
0
    if (size < 0 || size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
64
0
        av_log(avctx, AV_LOG_ERROR, "Invalid minimum required packet size %"PRId64" (max allowed is %d)\n",
65
0
               size, INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE);
66
0
        return AVERROR(EINVAL);
67
0
    }
68
69
0
    av_assert0(!avpkt->data);
70
71
0
    av_fast_padded_malloc(&avctx->internal->byte_buffer,
72
0
                          &avctx->internal->byte_buffer_size, size);
73
0
    avpkt->data = avctx->internal->byte_buffer;
74
0
    if (!avpkt->data) {
75
0
        av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %"PRId64"\n", size);
76
0
        return AVERROR(ENOMEM);
77
0
    }
78
0
    avpkt->size = size;
79
80
0
    return 0;
81
0
}
82
83
int avcodec_default_get_encode_buffer(AVCodecContext *avctx, AVPacket *avpkt, int flags)
84
0
{
85
0
    int ret;
86
87
0
    if (avpkt->size < 0 || avpkt->size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
88
0
        return AVERROR(EINVAL);
89
90
0
    if (avpkt->data || avpkt->buf) {
91
0
        av_log(avctx, AV_LOG_ERROR, "avpkt->{data,buf} != NULL in avcodec_default_get_encode_buffer()\n");
92
0
        return AVERROR(EINVAL);
93
0
    }
94
95
0
    ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE);
96
0
    if (ret < 0) {
97
0
        av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %d\n", avpkt->size);
98
0
        return ret;
99
0
    }
100
0
    avpkt->data = avpkt->buf->data;
101
102
0
    return 0;
103
0
}
104
105
int ff_get_encode_buffer(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int flags)
106
0
{
107
0
    int ret;
108
109
0
    if (size < 0 || size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
110
0
        return AVERROR(EINVAL);
111
112
0
    av_assert0(!avpkt->data && !avpkt->buf);
113
114
0
    avpkt->size = size;
115
0
    ret = avctx->get_encode_buffer(avctx, avpkt, flags);
116
0
    if (ret < 0)
117
0
        goto fail;
118
119
0
    if (!avpkt->data || !avpkt->buf) {
120
0
        av_log(avctx, AV_LOG_ERROR, "No buffer returned by get_encode_buffer()\n");
121
0
        ret = AVERROR(EINVAL);
122
0
        goto fail;
123
0
    }
124
0
    memset(avpkt->data + avpkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
125
126
0
    ret = 0;
127
0
fail:
128
0
    if (ret < 0) {
129
0
        av_log(avctx, AV_LOG_ERROR, "get_encode_buffer() failed\n");
130
0
        av_packet_unref(avpkt);
131
0
    }
132
133
0
    return ret;
134
0
}
135
136
static int encode_make_refcounted(AVCodecContext *avctx, AVPacket *avpkt)
137
0
{
138
0
    uint8_t *data = avpkt->data;
139
0
    int ret;
140
141
0
    if (avpkt->buf)
142
0
        return 0;
143
144
0
    avpkt->data = NULL;
145
0
    ret = ff_get_encode_buffer(avctx, avpkt, avpkt->size, 0);
146
0
    if (ret < 0)
147
0
        return ret;
148
0
    memcpy(avpkt->data, data, avpkt->size);
149
150
0
    return 0;
151
0
}
152
153
/**
154
 * Pad last frame with silence.
155
 */
156
static int pad_last_frame(AVCodecContext *s, AVFrame *frame, const AVFrame *src, int out_samples)
157
0
{
158
0
    AVFrameSideData *sd;
159
0
    int discard_padding;
160
0
    int ret;
161
162
0
    frame->format         = src->format;
163
0
    frame->nb_samples     = out_samples;
164
0
    ret = av_channel_layout_copy(&frame->ch_layout, &s->ch_layout);
165
0
    if (ret < 0)
166
0
        goto fail;
167
0
    ret = av_frame_get_buffer(frame, 0);
168
0
    if (ret < 0)
169
0
        goto fail;
170
171
0
    ret = av_frame_copy_props(frame, src);
172
0
    if (ret < 0)
173
0
        goto fail;
174
175
0
    if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
176
0
                               src->nb_samples, s->ch_layout.nb_channels,
177
0
                               s->sample_fmt)) < 0)
178
0
        goto fail;
179
0
    if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
180
0
                                      frame->nb_samples - src->nb_samples,
181
0
                                      s->ch_layout.nb_channels, s->sample_fmt)) < 0)
182
0
        goto fail;
183
184
0
    discard_padding = frame->nb_samples - src->nb_samples;
185
0
    av_assert1(discard_padding > 0);
186
0
    sd = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
187
0
    if (!sd) {
188
0
        ret = AVERROR(ENOMEM);
189
0
        goto fail;
190
0
    }
191
0
    AV_WL32A(sd->data, 0);
192
0
    AV_WL32A(sd->data + 4, discard_padding);
193
0
    AV_WL16A(sd->data + 8, 0);
194
195
0
    return 0;
196
197
0
fail:
198
0
    av_frame_unref(frame);
199
0
    encode_ctx(s->internal)->last_audio_frame = 0;
200
0
    return ret;
201
0
}
202
203
int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
204
                            const AVSubtitle *sub)
205
0
{
206
0
    int ret;
207
0
    if (sub->start_display_time) {
208
0
        av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
209
0
        return -1;
210
0
    }
211
212
0
    ret = ffcodec(avctx->codec)->cb.encode_sub(avctx, buf, buf_size, sub);
213
0
    avctx->frame_num++;
214
0
    return ret;
215
0
}
216
217
int ff_encode_get_frame(AVCodecContext *avctx, AVFrame *frame)
218
0
{
219
0
    AVCodecInternal *avci = avctx->internal;
220
221
0
    if (avci->draining)
222
0
        return AVERROR_EOF;
223
224
0
    if (!avci->buffer_frame->buf[0])
225
0
        return AVERROR(EAGAIN);
226
227
0
    av_frame_move_ref(frame, avci->buffer_frame);
228
229
0
    return 0;
230
0
}
231
232
int ff_encode_reordered_opaque(AVCodecContext *avctx,
233
                               AVPacket *pkt, const AVFrame *frame)
234
0
{
235
0
    if (avctx->flags & AV_CODEC_FLAG_COPY_OPAQUE) {
236
0
        int ret = av_buffer_replace(&pkt->opaque_ref, frame->opaque_ref);
237
0
        if (ret < 0)
238
0
            return ret;
239
0
        pkt->opaque = frame->opaque;
240
0
    }
241
242
0
    return 0;
243
0
}
244
245
int ff_encode_encode_cb(AVCodecContext *avctx, AVPacket *avpkt,
246
                        AVFrame *frame, int *got_packet)
247
0
{
248
0
    const FFCodec *const codec = ffcodec(avctx->codec);
249
0
    int ret;
250
251
0
    ret = codec->cb.encode(avctx, avpkt, frame, got_packet);
252
0
    ff_assert1_fpu();
253
0
    av_assert0(ret <= 0);
254
255
0
    if (!ret && *got_packet) {
256
0
        if (avpkt->data) {
257
0
            ret = encode_make_refcounted(avctx, avpkt);
258
0
            if (ret < 0)
259
0
                goto unref;
260
            // Date returned by encoders must always be ref-counted
261
0
            av_assert0(avpkt->buf);
262
0
        }
263
264
        // set the timestamps for the simple no-delay case
265
        // encoders with delay have to set the timestamps themselves
266
0
        if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) ||
267
0
            (frame && (codec->caps_internal & FF_CODEC_CAP_EOF_FLUSH))) {
268
0
            if (avpkt->pts == AV_NOPTS_VALUE)
269
0
                avpkt->pts = frame->pts;
270
271
0
            if (!avpkt->duration) {
272
0
                if (frame->duration)
273
0
                    avpkt->duration = frame->duration;
274
0
                else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
275
0
                    avpkt->duration = ff_samples_to_time_base(avctx,
276
0
                                                              frame->nb_samples);
277
0
                }
278
0
                if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
279
0
                    AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES);
280
0
                    if (sd && sd->size >= 10) {
281
0
                        uint8_t *skip_samples = av_packet_new_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
282
0
                        if (!skip_samples) {
283
0
                            ret = AVERROR(ENOMEM);
284
0
                            goto unref;
285
0
                        }
286
0
                        AV_WL32A(skip_samples + 0, AV_RL32(sd->data + 0));
287
0
                        AV_WL32A(skip_samples + 4, AV_RL32(sd->data + 4));
288
0
                        AV_WB8  (skip_samples + 8, AV_RB8 (sd->data + 8));
289
0
                        AV_WB8  (skip_samples + 9, AV_RB8 (sd->data + 9));
290
0
                    }
291
0
                }
292
0
            }
293
294
0
            ret = ff_encode_reordered_opaque(avctx, avpkt, frame);
295
0
            if (ret < 0)
296
0
                goto unref;
297
0
        }
298
299
        // dts equals pts unless there is reordering
300
        // there can be no reordering if there is no encoder delay
301
0
        if (!(avctx->codec_descriptor->props & AV_CODEC_PROP_REORDER) ||
302
0
            !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)        ||
303
0
            (codec->caps_internal & FF_CODEC_CAP_EOF_FLUSH))
304
0
            avpkt->dts = avpkt->pts;
305
0
    } else {
306
0
unref:
307
0
        av_packet_unref(avpkt);
308
0
    }
309
310
0
    if (frame)
311
0
        av_frame_unref(frame);
312
313
0
    return ret;
314
0
}
315
316
static int encode_simple_internal(AVCodecContext *avctx, AVPacket *avpkt)
317
0
{
318
0
    AVCodecInternal   *avci = avctx->internal;
319
0
    AVFrame          *frame = avci->in_frame;
320
0
    const FFCodec *const codec = ffcodec(avctx->codec);
321
0
    int got_packet;
322
0
    int ret;
323
324
0
    if (avci->draining_done)
325
0
        return AVERROR_EOF;
326
327
0
    if (!frame->buf[0] && !avci->draining) {
328
0
        av_frame_unref(frame);
329
0
        ret = ff_encode_get_frame(avctx, frame);
330
0
        if (ret < 0 && ret != AVERROR_EOF)
331
0
            return ret;
332
0
    }
333
334
0
    if (!frame->buf[0]) {
335
0
        if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
336
0
              avci->frame_thread_encoder))
337
0
            return AVERROR_EOF;
338
339
        // Flushing is signaled with a NULL frame
340
0
        frame = NULL;
341
0
    }
342
343
0
    got_packet = 0;
344
345
0
    av_assert0(codec->cb_type == FF_CODEC_CB_TYPE_ENCODE);
346
347
#if CONFIG_FRAME_THREAD_ENCODER
348
    if (avci->frame_thread_encoder)
349
        /* This will unref frame. */
350
        ret = ff_thread_video_encode_frame(avctx, avpkt, frame, &got_packet);
351
    else
352
#endif
353
0
        ret = ff_encode_encode_cb(avctx, avpkt, frame, &got_packet);
354
355
0
    if (avci->draining && !got_packet)
356
0
        avci->draining_done = 1;
357
358
0
    return ret;
359
0
}
360
361
static int encode_simple_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
362
0
{
363
0
    int ret;
364
365
0
    while (!avpkt->data && !avpkt->side_data) {
366
0
        ret = encode_simple_internal(avctx, avpkt);
367
0
        if (ret < 0)
368
0
            return ret;
369
0
    }
370
371
0
    return 0;
372
0
}
373
374
static int encode_receive_packet_internal(AVCodecContext *avctx, AVPacket *avpkt)
375
0
{
376
0
    AVCodecInternal *avci = avctx->internal;
377
0
    int ret;
378
379
0
    if (avci->draining_done)
380
0
        return AVERROR_EOF;
381
382
0
    av_assert0(!avpkt->data && !avpkt->side_data);
383
384
0
    if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
385
0
        if ((avctx->flags & AV_CODEC_FLAG_PASS1) && avctx->stats_out)
386
0
            avctx->stats_out[0] = '\0';
387
0
    }
388
389
0
    if (ffcodec(avctx->codec)->cb_type == FF_CODEC_CB_TYPE_RECEIVE_PACKET) {
390
0
        ret = ffcodec(avctx->codec)->cb.receive_packet(avctx, avpkt);
391
0
        if (ret < 0)
392
0
            av_packet_unref(avpkt);
393
0
        else
394
            // Encoders must always return ref-counted buffers.
395
            // Side-data only packets have no data and can be not ref-counted.
396
0
            av_assert0(!avpkt->data || avpkt->buf);
397
0
    } else
398
0
        ret = encode_simple_receive_packet(avctx, avpkt);
399
0
    if (ret >= 0)
400
0
        avpkt->flags |= encode_ctx(avci)->intra_only_flag;
401
402
0
    if (ret == AVERROR_EOF)
403
0
        avci->draining_done = 1;
404
405
0
    return ret;
406
0
}
407
408
#if CONFIG_LCMS2
409
static int encode_generate_icc_profile(AVCodecContext *avctx, AVFrame *frame)
410
{
411
    enum AVColorTransferCharacteristic trc = frame->color_trc;
412
    enum AVColorPrimaries prim = frame->color_primaries;
413
    const FFCodec *const codec = ffcodec(avctx->codec);
414
    AVCodecInternal *avci = avctx->internal;
415
    cmsHPROFILE profile;
416
    int ret;
417
418
    /* don't generate ICC profiles if disabled or unsupported */
419
    if (!(avctx->flags2 & AV_CODEC_FLAG2_ICC_PROFILES))
420
        return 0;
421
    if (!(codec->caps_internal & FF_CODEC_CAP_ICC_PROFILES))
422
        return 0;
423
424
    if (trc == AVCOL_TRC_UNSPECIFIED)
425
        trc = avctx->color_trc;
426
    if (prim == AVCOL_PRI_UNSPECIFIED)
427
        prim = avctx->color_primaries;
428
    if (trc == AVCOL_TRC_UNSPECIFIED || prim == AVCOL_PRI_UNSPECIFIED)
429
        return 0; /* can't generate ICC profile with missing csp tags */
430
431
    if (av_frame_get_side_data(frame, AV_FRAME_DATA_ICC_PROFILE))
432
        return 0; /* don't overwrite existing ICC profile */
433
434
    if (!avci->icc.avctx) {
435
        ret = ff_icc_context_init(&avci->icc, avctx);
436
        if (ret < 0)
437
            return ret;
438
    }
439
440
    ret = ff_icc_profile_generate(&avci->icc, prim, trc, &profile);
441
    if (ret < 0)
442
        return ret;
443
444
    ret = ff_icc_profile_attach(&avci->icc, profile, frame);
445
    cmsCloseProfile(profile);
446
    return ret;
447
}
448
#else /* !CONFIG_LCMS2 */
449
static int encode_generate_icc_profile(av_unused AVCodecContext *c, av_unused AVFrame *f)
450
0
{
451
0
    return 0;
452
0
}
453
#endif
454
455
static int encode_send_frame_internal(AVCodecContext *avctx, const AVFrame *src)
456
0
{
457
0
    AVCodecInternal *avci = avctx->internal;
458
0
    EncodeContext     *ec = encode_ctx(avci);
459
0
    AVFrame *dst = avci->buffer_frame;
460
0
    int ret;
461
462
0
    if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
463
        /* extract audio service type metadata */
464
0
        AVFrameSideData *sd = av_frame_get_side_data(src, AV_FRAME_DATA_AUDIO_SERVICE_TYPE);
465
0
        if (sd && sd->size >= sizeof(enum AVAudioServiceType))
466
0
            avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data;
467
468
        /* check for valid frame size */
469
0
        if (avctx->frame_size) {
470
            /* if we already got an undersized frame, that must have been the last */
471
0
            if (ec->last_audio_frame) {
472
0
                av_log(avctx, AV_LOG_ERROR, "frame_size (%d) was not respected for a non-last frame\n", avctx->frame_size);
473
0
                return AVERROR(EINVAL);
474
0
            }
475
0
            if (src->nb_samples > avctx->frame_size) {
476
0
                av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) > frame_size (%d)\n", src->nb_samples, avctx->frame_size);
477
0
                return AVERROR(EINVAL);
478
0
            }
479
0
            if (src->nb_samples < avctx->frame_size) {
480
0
                ec->last_audio_frame = 1;
481
0
                if (!(avctx->codec->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME) ||
482
0
                    (avctx->flags2 & AV_CODEC_FLAG2_FIXED_FRAME_SIZE)) {
483
0
                    int pad_samples = avci->pad_samples ? avci->pad_samples : avctx->frame_size;
484
0
                    int out_samples = (src->nb_samples + pad_samples - 1) / pad_samples * pad_samples;
485
486
0
                    if (out_samples != src->nb_samples) {
487
0
                        ret = pad_last_frame(avctx, dst, src, out_samples);
488
0
                        if (ret < 0)
489
0
                            return ret;
490
0
                        goto finish;
491
0
                    }
492
0
                }
493
0
            }
494
0
        }
495
0
    }
496
497
0
    ret = av_frame_ref(dst, src);
498
0
    if (ret < 0)
499
0
        return ret;
500
501
0
finish:
502
503
0
    if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
504
0
        ret = encode_generate_icc_profile(avctx, dst);
505
0
        if (ret < 0)
506
0
            return ret;
507
0
    }
508
509
    // unset frame duration unless AV_CODEC_FLAG_FRAME_DURATION is set,
510
    // since otherwise we cannot be sure that whatever value it has is in the
511
    // right timebase, so we would produce an incorrect value, which is worse
512
    // than none at all
513
0
    if (!(avctx->flags & AV_CODEC_FLAG_FRAME_DURATION))
514
0
        dst->duration = 0;
515
516
0
    return 0;
517
0
}
518
519
int attribute_align_arg avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
520
0
{
521
0
    AVCodecInternal *avci = avctx->internal;
522
0
    int ret;
523
524
0
    if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec))
525
0
        return AVERROR(EINVAL);
526
527
0
    if (avci->draining)
528
0
        return AVERROR_EOF;
529
530
0
    if (avci->buffer_frame->buf[0])
531
0
        return AVERROR(EAGAIN);
532
533
0
    if (!frame) {
534
0
        avci->draining = 1;
535
0
    } else {
536
0
        ret = encode_send_frame_internal(avctx, frame);
537
0
        if (ret < 0)
538
0
            return ret;
539
0
    }
540
541
0
    if (!avci->buffer_pkt->data && !avci->buffer_pkt->side_data) {
542
0
        ret = encode_receive_packet_internal(avctx, avci->buffer_pkt);
543
0
        if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
544
0
            return ret;
545
0
    }
546
547
0
    avctx->frame_num++;
548
549
0
    return 0;
550
0
}
551
552
int attribute_align_arg avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
553
0
{
554
0
    AVCodecInternal *avci = avctx->internal;
555
0
    int ret;
556
557
0
    av_packet_unref(avpkt);
558
559
0
    if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec))
560
0
        return AVERROR(EINVAL);
561
562
0
    if (avci->buffer_pkt->data || avci->buffer_pkt->side_data) {
563
0
        av_packet_move_ref(avpkt, avci->buffer_pkt);
564
0
    } else {
565
0
        ret = encode_receive_packet_internal(avctx, avpkt);
566
0
        if (ret < 0)
567
0
            return ret;
568
0
    }
569
570
0
    return 0;
571
0
}
572
573
static int encode_preinit_video(AVCodecContext *avctx)
574
0
{
575
0
    const AVCodec *c = avctx->codec;
576
0
    const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt);
577
0
    const enum AVPixelFormat *pix_fmts;
578
0
    int ret, i, num_pix_fmts;
579
580
0
    if (!pixdesc) {
581
0
        av_log(avctx, AV_LOG_ERROR, "Invalid video pixel format: %d\n",
582
0
               avctx->pix_fmt);
583
0
        return AVERROR(EINVAL);
584
0
    }
585
586
0
    ret = avcodec_get_supported_config(avctx, NULL, AV_CODEC_CONFIG_PIX_FORMAT,
587
0
                                       0, (const void **) &pix_fmts, &num_pix_fmts);
588
0
    if (ret < 0)
589
0
        return ret;
590
591
0
    if (pix_fmts) {
592
0
        for (i = 0; i < num_pix_fmts; i++)
593
0
            if (avctx->pix_fmt == pix_fmts[i])
594
0
                break;
595
0
        if (i == num_pix_fmts) {
596
0
            av_log(avctx, AV_LOG_ERROR,
597
0
                   "Specified pixel format %s is not supported by the %s encoder.\n",
598
0
                   av_get_pix_fmt_name(avctx->pix_fmt), c->name);
599
600
0
            av_log(avctx, AV_LOG_ERROR, "Supported pixel formats:\n");
601
0
            for (int p = 0; pix_fmts[p] != AV_PIX_FMT_NONE; p++) {
602
0
                av_log(avctx, AV_LOG_ERROR, "  %s\n",
603
0
                       av_get_pix_fmt_name(pix_fmts[p]));
604
0
            }
605
606
0
            return AVERROR(EINVAL);
607
0
        }
608
0
        if (pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
609
0
            pix_fmts[i] == AV_PIX_FMT_YUVJ411P ||
610
0
            pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
611
0
            pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
612
0
            pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
613
0
            avctx->color_range = AVCOL_RANGE_JPEG;
614
0
    }
615
616
0
    if (pixdesc->flags & AV_PIX_FMT_FLAG_ALPHA) {
617
0
        const enum AVAlphaMode *alpha_modes;
618
0
        int num_alpha_modes;
619
0
        ret = avcodec_get_supported_config(avctx, NULL, AV_CODEC_CONFIG_ALPHA_MODE,
620
0
                                           0, (const void **) &alpha_modes, &num_alpha_modes);
621
0
        if (ret < 0)
622
0
            return ret;
623
624
0
        if (avctx->alpha_mode != AVALPHA_MODE_UNSPECIFIED && alpha_modes) {
625
0
            for (i = 0; i < num_alpha_modes; i++) {
626
0
                if (avctx->alpha_mode == alpha_modes[i])
627
0
                    break;
628
0
            }
629
0
            if (i == num_alpha_modes) {
630
0
                av_log(avctx, AV_LOG_ERROR,
631
0
                       "Specified alpha mode '%s' is not supported by the %s encoder.\n",
632
0
                       av_alpha_mode_name(avctx->alpha_mode), c->name);
633
0
                av_log(avctx, AV_LOG_ERROR, "Supported alpha modes:\n");
634
0
                for (int p = 0; alpha_modes[p] != AVALPHA_MODE_UNSPECIFIED; p++) {
635
0
                    av_log(avctx, AV_LOG_ERROR, "  %s\n",
636
0
                           av_alpha_mode_name(alpha_modes[p]));
637
0
                }
638
0
                return AVERROR(EINVAL);
639
0
            }
640
0
        }
641
0
    }
642
643
0
    if (    avctx->bits_per_raw_sample < 0
644
0
        || (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) {
645
0
        av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n",
646
0
            avctx->bits_per_raw_sample, pixdesc->comp[0].depth);
647
0
        avctx->bits_per_raw_sample = pixdesc->comp[0].depth;
648
0
    }
649
0
    if (avctx->width <= 0 || avctx->height <= 0) {
650
0
        av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
651
0
        return AVERROR(EINVAL);
652
0
    }
653
654
0
    if (avctx->hw_frames_ctx) {
655
0
        AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
656
0
        if (frames_ctx->format != avctx->pix_fmt) {
657
0
            av_log(avctx, AV_LOG_ERROR,
658
0
                   "Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n");
659
0
            return AVERROR(EINVAL);
660
0
        }
661
0
        if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE &&
662
0
            avctx->sw_pix_fmt != frames_ctx->sw_format) {
663
0
            av_log(avctx, AV_LOG_ERROR,
664
0
                   "Mismatching AVCodecContext.sw_pix_fmt (%s) "
665
0
                   "and AVHWFramesContext.sw_format (%s)\n",
666
0
                   av_get_pix_fmt_name(avctx->sw_pix_fmt),
667
0
                   av_get_pix_fmt_name(frames_ctx->sw_format));
668
0
            return AVERROR(EINVAL);
669
0
        }
670
0
        avctx->sw_pix_fmt = frames_ctx->sw_format;
671
0
    }
672
673
0
    return 0;
674
0
}
675
676
static int encode_preinit_audio(AVCodecContext *avctx)
677
0
{
678
0
    const AVCodec *c = avctx->codec;
679
0
    const enum AVSampleFormat *sample_fmts;
680
0
    const int *supported_samplerates;
681
0
    const AVChannelLayout *ch_layouts;
682
0
    int ret, i, num_sample_fmts, num_samplerates, num_ch_layouts;
683
684
0
    if (!av_get_sample_fmt_name(avctx->sample_fmt)) {
685
0
        av_log(avctx, AV_LOG_ERROR, "Invalid audio sample format: %d\n",
686
0
               avctx->sample_fmt);
687
0
        return AVERROR(EINVAL);
688
0
    }
689
690
0
    ret = avcodec_get_supported_config(avctx, NULL, AV_CODEC_CONFIG_SAMPLE_FORMAT,
691
0
                                       0, (const void **) &sample_fmts,
692
0
                                       &num_sample_fmts);
693
0
    if (ret < 0)
694
0
        return ret;
695
0
    if (sample_fmts) {
696
0
        for (i = 0; i < num_sample_fmts; i++) {
697
0
            if (avctx->sample_fmt == sample_fmts[i])
698
0
                break;
699
0
            if (avctx->ch_layout.nb_channels == 1 &&
700
0
                av_get_planar_sample_fmt(avctx->sample_fmt) ==
701
0
                av_get_planar_sample_fmt(sample_fmts[i])) {
702
0
                avctx->sample_fmt = sample_fmts[i];
703
0
                break;
704
0
            }
705
0
        }
706
0
        if (i == num_sample_fmts) {
707
0
            av_log(avctx, AV_LOG_ERROR,
708
0
                   "Specified sample format %s is not supported by the %s encoder\n",
709
0
                   av_get_sample_fmt_name(avctx->sample_fmt), c->name);
710
711
0
            av_log(avctx, AV_LOG_ERROR, "Supported sample formats:\n");
712
0
            for (int p = 0; sample_fmts[p] != AV_SAMPLE_FMT_NONE; p++) {
713
0
                av_log(avctx, AV_LOG_ERROR, "  %s\n",
714
0
                       av_get_sample_fmt_name(sample_fmts[p]));
715
0
            }
716
717
0
            return AVERROR(EINVAL);
718
0
        }
719
0
    }
720
721
0
    ret = avcodec_get_supported_config(avctx, NULL, AV_CODEC_CONFIG_SAMPLE_RATE,
722
0
                                       0, (const void **) &supported_samplerates,
723
0
                                       &num_samplerates);
724
0
    if (ret < 0)
725
0
        return ret;
726
0
    if (supported_samplerates) {
727
0
        for (i = 0; i < num_samplerates; i++)
728
0
            if (avctx->sample_rate == supported_samplerates[i])
729
0
                break;
730
0
        if (i == num_samplerates) {
731
0
            av_log(avctx, AV_LOG_ERROR,
732
0
                   "Specified sample rate %d is not supported by the %s encoder\n",
733
0
                   avctx->sample_rate, c->name);
734
735
0
            av_log(avctx, AV_LOG_ERROR, "Supported sample rates:\n");
736
0
            for (int p = 0; supported_samplerates[p]; p++)
737
0
                av_log(avctx, AV_LOG_ERROR, "  %d\n", supported_samplerates[p]);
738
739
0
            return AVERROR(EINVAL);
740
0
        }
741
0
    }
742
0
    ret = avcodec_get_supported_config(avctx, NULL, AV_CODEC_CONFIG_CHANNEL_LAYOUT,
743
0
                                       0, (const void **) &ch_layouts, &num_ch_layouts);
744
0
    if (ret < 0)
745
0
        return ret;
746
0
    if (ch_layouts) {
747
0
        for (i = 0; i < num_ch_layouts; i++) {
748
0
            if (!av_channel_layout_compare(&avctx->ch_layout, &ch_layouts[i]))
749
0
                break;
750
0
        }
751
0
        if (i == num_ch_layouts) {
752
0
            char buf[512];
753
0
            int ret = av_channel_layout_describe(&avctx->ch_layout, buf, sizeof(buf));
754
0
            av_log(avctx, AV_LOG_ERROR,
755
0
                   "Specified channel layout '%s' is not supported by the %s encoder\n",
756
0
                   ret > 0 ? buf : "?", c->name);
757
758
0
            av_log(avctx, AV_LOG_ERROR, "Supported channel layouts:\n");
759
0
            for (int p = 0; ch_layouts[p].nb_channels; p++) {
760
0
                ret = av_channel_layout_describe(&ch_layouts[p], buf, sizeof(buf));
761
0
                av_log(avctx, AV_LOG_ERROR, "  %s\n", ret > 0 ? buf : "?");
762
0
            }
763
0
            return AVERROR(EINVAL);
764
0
        }
765
0
    }
766
767
0
    if (!avctx->bits_per_raw_sample)
768
0
        avctx->bits_per_raw_sample = av_get_exact_bits_per_sample(avctx->codec_id);
769
0
    if (!avctx->bits_per_raw_sample)
770
0
        avctx->bits_per_raw_sample = 8 * av_get_bytes_per_sample(avctx->sample_fmt);
771
772
0
    return 0;
773
0
}
774
775
int ff_encode_preinit(AVCodecContext *avctx)
776
0
{
777
0
    AVCodecInternal *avci = avctx->internal;
778
0
    EncodeContext     *ec = encode_ctx(avci);
779
0
    int ret = 0;
780
781
0
    if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) {
782
0
        av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n");
783
0
        return AVERROR(EINVAL);
784
0
    }
785
786
0
    if (avctx->bit_rate < 0) {
787
0
        av_log(avctx, AV_LOG_ERROR, "The encoder bitrate is negative.\n");
788
0
        return AVERROR(EINVAL);
789
0
    }
790
791
0
    if (avctx->flags & AV_CODEC_FLAG_COPY_OPAQUE &&
792
0
        !(avctx->codec->capabilities & AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE)) {
793
0
        av_log(avctx, AV_LOG_ERROR, "The copy_opaque flag is set, but the "
794
0
               "encoder does not support it.\n");
795
0
        return AVERROR(EINVAL);
796
0
    }
797
798
0
    switch (avctx->codec_type) {
799
0
    case AVMEDIA_TYPE_VIDEO: ret = encode_preinit_video(avctx); break;
800
0
    case AVMEDIA_TYPE_AUDIO: ret = encode_preinit_audio(avctx); break;
801
0
    }
802
0
    if (ret < 0)
803
0
        return ret;
804
805
0
    if (   (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
806
0
        && avctx->bit_rate>0 && avctx->bit_rate<1000) {
807
0
        av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", avctx->bit_rate, avctx->bit_rate);
808
0
    }
809
810
0
    if (!avctx->rc_initial_buffer_occupancy)
811
0
        avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4;
812
813
0
    if (avctx->codec_descriptor->props & AV_CODEC_PROP_INTRA_ONLY)
814
0
        ec->intra_only_flag = AV_PKT_FLAG_KEY;
815
816
0
    if (ffcodec(avctx->codec)->cb_type == FF_CODEC_CB_TYPE_ENCODE) {
817
0
        avci->in_frame = av_frame_alloc();
818
0
        if (!avci->in_frame)
819
0
            return AVERROR(ENOMEM);
820
0
    }
821
822
0
    if ((avctx->flags & AV_CODEC_FLAG_RECON_FRAME)) {
823
0
        if (!(avctx->codec->capabilities & AV_CODEC_CAP_ENCODER_RECON_FRAME)) {
824
0
            av_log(avctx, AV_LOG_ERROR, "Reconstructed frame output requested "
825
0
                   "from an encoder not supporting it\n");
826
0
            return AVERROR(ENOSYS);
827
0
        }
828
829
0
        avci->recon_frame = av_frame_alloc();
830
0
        if (!avci->recon_frame)
831
0
            return AVERROR(ENOMEM);
832
0
    }
833
834
0
    for (int i = 0; ff_sd_global_map[i].packet < AV_PKT_DATA_NB; i++) {
835
0
        const enum AVPacketSideDataType type_packet = ff_sd_global_map[i].packet;
836
0
        const enum AVFrameSideDataType  type_frame  = ff_sd_global_map[i].frame;
837
0
        const AVFrameSideData *sd_frame;
838
0
        AVPacketSideData      *sd_packet;
839
840
0
        sd_frame = av_frame_side_data_get(avctx->decoded_side_data,
841
0
                                          avctx->nb_decoded_side_data,
842
0
                                          type_frame);
843
0
        if (!sd_frame ||
844
0
            av_packet_side_data_get(avctx->coded_side_data, avctx->nb_coded_side_data,
845
0
                                    type_packet))
846
847
0
            continue;
848
849
0
        sd_packet = av_packet_side_data_new(&avctx->coded_side_data, &avctx->nb_coded_side_data,
850
0
                                            type_packet, sd_frame->size, 0);
851
0
        if (!sd_packet)
852
0
            return AVERROR(ENOMEM);
853
854
0
        memcpy(sd_packet->data, sd_frame->data, sd_frame->size);
855
0
    }
856
857
#if CONFIG_FRAME_THREAD_ENCODER
858
    ret = ff_frame_thread_encoder_init(avctx);
859
    if (ret < 0)
860
        return ret;
861
#endif
862
863
0
    return 0;
864
0
}
865
866
int ff_encode_alloc_frame(AVCodecContext *avctx, AVFrame *frame)
867
0
{
868
0
    int ret;
869
870
0
    av_assert1(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
871
872
0
    frame->format = avctx->pix_fmt;
873
0
    if (frame->width <= 0 || frame->height <= 0) {
874
0
        frame->width  = avctx->width;
875
0
        frame->height = avctx->height;
876
0
    }
877
878
0
    ret = avcodec_default_get_buffer2(avctx, frame, 0);
879
0
    if (ret < 0) {
880
0
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
881
0
        av_frame_unref(frame);
882
0
        return ret;
883
0
    }
884
885
0
    return 0;
886
0
}
887
888
int ff_encode_receive_frame(AVCodecContext *avctx, AVFrame *frame)
889
0
{
890
0
    AVCodecInternal *avci = avctx->internal;
891
892
0
    if (!avci->recon_frame)
893
0
        return AVERROR(EINVAL);
894
0
    if (!avci->recon_frame->buf[0])
895
0
        return avci->draining_done ? AVERROR_EOF : AVERROR(EAGAIN);
896
897
0
    av_frame_move_ref(frame, avci->recon_frame);
898
0
    return 0;
899
0
}
900
901
void ff_encode_flush_buffers(AVCodecContext *avctx)
902
0
{
903
0
    AVCodecInternal *avci = avctx->internal;
904
905
0
    if (avci->in_frame)
906
0
        av_frame_unref(avci->in_frame);
907
0
    if (avci->recon_frame)
908
0
        av_frame_unref(avci->recon_frame);
909
0
}
910
911
AVCodecInternal *ff_encode_internal_alloc(void)
912
0
{
913
0
    return av_mallocz(sizeof(EncodeContext));
914
0
}
915
916
AVCPBProperties *ff_encode_add_cpb_side_data(AVCodecContext *avctx)
917
0
{
918
0
    AVPacketSideData *tmp;
919
0
    AVCPBProperties  *props;
920
0
    size_t size;
921
0
    int i;
922
923
0
    for (i = 0; i < avctx->nb_coded_side_data; i++)
924
0
        if (avctx->coded_side_data[i].type == AV_PKT_DATA_CPB_PROPERTIES)
925
0
            return (AVCPBProperties *)avctx->coded_side_data[i].data;
926
927
0
    props = av_cpb_properties_alloc(&size);
928
0
    if (!props)
929
0
        return NULL;
930
931
0
    tmp = av_realloc_array(avctx->coded_side_data, avctx->nb_coded_side_data + 1, sizeof(*tmp));
932
0
    if (!tmp) {
933
0
        av_freep(&props);
934
0
        return NULL;
935
0
    }
936
937
0
    avctx->coded_side_data = tmp;
938
0
    avctx->nb_coded_side_data++;
939
940
0
    avctx->coded_side_data[avctx->nb_coded_side_data - 1].type = AV_PKT_DATA_CPB_PROPERTIES;
941
0
    avctx->coded_side_data[avctx->nb_coded_side_data - 1].data = (uint8_t*)props;
942
0
    avctx->coded_side_data[avctx->nb_coded_side_data - 1].size = size;
943
944
0
    return props;
945
0
}
946
947
int ff_encode_add_stats_side_data(AVPacket *pkt, int quality, const int64_t error[],
948
                                  int error_count, enum AVPictureType pict_type)
949
0
{
950
0
    uint8_t *side_data;
951
0
    size_t side_data_size;
952
953
0
    side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS, &side_data_size);
954
0
    if (!side_data) {
955
0
        side_data_size = 4+4+8*error_count;
956
0
        side_data = av_packet_new_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
957
0
                                            side_data_size);
958
0
    }
959
960
0
    if (!side_data || side_data_size < 4+4+8*error_count)
961
0
        return AVERROR(ENOMEM);
962
963
0
    AV_WL32(side_data, quality);
964
0
    side_data[4] = pict_type;
965
0
    side_data[5] = error_count;
966
0
    for (int i = 0; i < error_count; ++i)
967
0
        AV_WL64(side_data+8 + 8*i , error[i]);
968
969
0
    return 0;
970
0
}
971
972
int ff_check_codec_matrices(AVCodecContext *avctx, unsigned types, uint16_t min, uint16_t max)
973
0
{
974
0
    uint16_t  *matrices[] = {avctx->intra_matrix, avctx->inter_matrix, avctx->chroma_intra_matrix};
975
0
    const char   *names[] = {"Intra", "Inter", "Chroma Intra"};
976
0
    static_assert(FF_ARRAY_ELEMS(matrices) == FF_ARRAY_ELEMS(names), "matrix count mismatch");
977
0
    for (int m = 0; m < FF_ARRAY_ELEMS(matrices); m++) {
978
0
        uint16_t *matrix = matrices[m];
979
0
        if (matrix && (types & (1U << m))) {
980
0
            for (int i = 0; i < 64; i++) {
981
0
                if (matrix[i] < min || matrix[i] > max) {
982
0
                    av_log(avctx, AV_LOG_ERROR, "%s matrix[%d] is %d which is out of the allowed range [%"PRIu16"-%"PRIu16"].\n", names[m], i, matrix[i], min, max);
983
0
                    return AVERROR(EINVAL);
984
0
                }
985
0
            }
986
0
        }
987
0
    }
988
0
    return 0;
989
0
}