Coverage Report

Created: 2026-01-25 07:18

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
    int ret;
159
160
0
    frame->format         = src->format;
161
0
    frame->nb_samples     = out_samples;
162
0
    ret = av_channel_layout_copy(&frame->ch_layout, &s->ch_layout);
163
0
    if (ret < 0)
164
0
        goto fail;
165
0
    ret = av_frame_get_buffer(frame, 0);
166
0
    if (ret < 0)
167
0
        goto fail;
168
169
0
    ret = av_frame_copy_props(frame, src);
170
0
    if (ret < 0)
171
0
        goto fail;
172
173
0
    if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
174
0
                               src->nb_samples, s->ch_layout.nb_channels,
175
0
                               s->sample_fmt)) < 0)
176
0
        goto fail;
177
0
    if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
178
0
                                      frame->nb_samples - src->nb_samples,
179
0
                                      s->ch_layout.nb_channels, s->sample_fmt)) < 0)
180
0
        goto fail;
181
182
0
    return 0;
183
184
0
fail:
185
0
    av_frame_unref(frame);
186
0
    encode_ctx(s->internal)->last_audio_frame = 0;
187
0
    return ret;
188
0
}
189
190
int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
191
                            const AVSubtitle *sub)
192
0
{
193
0
    int ret;
194
0
    if (sub->start_display_time) {
195
0
        av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
196
0
        return -1;
197
0
    }
198
199
0
    ret = ffcodec(avctx->codec)->cb.encode_sub(avctx, buf, buf_size, sub);
200
0
    avctx->frame_num++;
201
0
    return ret;
202
0
}
203
204
int ff_encode_get_frame(AVCodecContext *avctx, AVFrame *frame)
205
0
{
206
0
    AVCodecInternal *avci = avctx->internal;
207
208
0
    if (avci->draining)
209
0
        return AVERROR_EOF;
210
211
0
    if (!avci->buffer_frame->buf[0])
212
0
        return AVERROR(EAGAIN);
213
214
0
    av_frame_move_ref(frame, avci->buffer_frame);
215
216
0
    return 0;
217
0
}
218
219
int ff_encode_reordered_opaque(AVCodecContext *avctx,
220
                               AVPacket *pkt, const AVFrame *frame)
221
0
{
222
0
    if (avctx->flags & AV_CODEC_FLAG_COPY_OPAQUE) {
223
0
        int ret = av_buffer_replace(&pkt->opaque_ref, frame->opaque_ref);
224
0
        if (ret < 0)
225
0
            return ret;
226
0
        pkt->opaque = frame->opaque;
227
0
    }
228
229
0
    return 0;
230
0
}
231
232
int ff_encode_encode_cb(AVCodecContext *avctx, AVPacket *avpkt,
233
                        AVFrame *frame, int *got_packet)
234
0
{
235
0
    const FFCodec *const codec = ffcodec(avctx->codec);
236
0
    int ret;
237
238
0
    ret = codec->cb.encode(avctx, avpkt, frame, got_packet);
239
0
    emms_c();
240
0
    av_assert0(ret <= 0);
241
242
0
    if (!ret && *got_packet) {
243
0
        if (avpkt->data) {
244
0
            ret = encode_make_refcounted(avctx, avpkt);
245
0
            if (ret < 0)
246
0
                goto unref;
247
            // Date returned by encoders must always be ref-counted
248
0
            av_assert0(avpkt->buf);
249
0
        }
250
251
        // set the timestamps for the simple no-delay case
252
        // encoders with delay have to set the timestamps themselves
253
0
        if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) ||
254
0
            (frame && (codec->caps_internal & FF_CODEC_CAP_EOF_FLUSH))) {
255
0
            if (avpkt->pts == AV_NOPTS_VALUE)
256
0
                avpkt->pts = frame->pts;
257
258
0
            if (!avpkt->duration) {
259
0
                if (frame->duration)
260
0
                    avpkt->duration = frame->duration;
261
0
                else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
262
0
                    avpkt->duration = ff_samples_to_time_base(avctx,
263
0
                                                              frame->nb_samples);
264
0
                }
265
0
            }
266
267
0
            ret = ff_encode_reordered_opaque(avctx, avpkt, frame);
268
0
            if (ret < 0)
269
0
                goto unref;
270
0
        }
271
272
        // dts equals pts unless there is reordering
273
        // there can be no reordering if there is no encoder delay
274
0
        if (!(avctx->codec_descriptor->props & AV_CODEC_PROP_REORDER) ||
275
0
            !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)        ||
276
0
            (codec->caps_internal & FF_CODEC_CAP_EOF_FLUSH))
277
0
            avpkt->dts = avpkt->pts;
278
0
    } else {
279
0
unref:
280
0
        av_packet_unref(avpkt);
281
0
    }
282
283
0
    if (frame)
284
0
        av_frame_unref(frame);
285
286
0
    return ret;
287
0
}
288
289
static int encode_simple_internal(AVCodecContext *avctx, AVPacket *avpkt)
290
0
{
291
0
    AVCodecInternal   *avci = avctx->internal;
292
0
    AVFrame          *frame = avci->in_frame;
293
0
    const FFCodec *const codec = ffcodec(avctx->codec);
294
0
    int got_packet;
295
0
    int ret;
296
297
0
    if (avci->draining_done)
298
0
        return AVERROR_EOF;
299
300
0
    if (!frame->buf[0] && !avci->draining) {
301
0
        av_frame_unref(frame);
302
0
        ret = ff_encode_get_frame(avctx, frame);
303
0
        if (ret < 0 && ret != AVERROR_EOF)
304
0
            return ret;
305
0
    }
306
307
0
    if (!frame->buf[0]) {
308
0
        if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
309
0
              avci->frame_thread_encoder))
310
0
            return AVERROR_EOF;
311
312
        // Flushing is signaled with a NULL frame
313
0
        frame = NULL;
314
0
    }
315
316
0
    got_packet = 0;
317
318
0
    av_assert0(codec->cb_type == FF_CODEC_CB_TYPE_ENCODE);
319
320
#if CONFIG_FRAME_THREAD_ENCODER
321
    if (avci->frame_thread_encoder)
322
        /* This will unref frame. */
323
        ret = ff_thread_video_encode_frame(avctx, avpkt, frame, &got_packet);
324
    else
325
#endif
326
0
        ret = ff_encode_encode_cb(avctx, avpkt, frame, &got_packet);
327
328
0
    if (avci->draining && !got_packet)
329
0
        avci->draining_done = 1;
330
331
0
    return ret;
332
0
}
333
334
static int encode_simple_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
335
0
{
336
0
    int ret;
337
338
0
    while (!avpkt->data && !avpkt->side_data) {
339
0
        ret = encode_simple_internal(avctx, avpkt);
340
0
        if (ret < 0)
341
0
            return ret;
342
0
    }
343
344
0
    return 0;
345
0
}
346
347
static int encode_receive_packet_internal(AVCodecContext *avctx, AVPacket *avpkt)
348
0
{
349
0
    AVCodecInternal *avci = avctx->internal;
350
0
    int ret;
351
352
0
    if (avci->draining_done)
353
0
        return AVERROR_EOF;
354
355
0
    av_assert0(!avpkt->data && !avpkt->side_data);
356
357
0
    if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
358
0
        if ((avctx->flags & AV_CODEC_FLAG_PASS1) && avctx->stats_out)
359
0
            avctx->stats_out[0] = '\0';
360
0
    }
361
362
0
    if (ffcodec(avctx->codec)->cb_type == FF_CODEC_CB_TYPE_RECEIVE_PACKET) {
363
0
        ret = ffcodec(avctx->codec)->cb.receive_packet(avctx, avpkt);
364
0
        if (ret < 0)
365
0
            av_packet_unref(avpkt);
366
0
        else
367
            // Encoders must always return ref-counted buffers.
368
            // Side-data only packets have no data and can be not ref-counted.
369
0
            av_assert0(!avpkt->data || avpkt->buf);
370
0
    } else
371
0
        ret = encode_simple_receive_packet(avctx, avpkt);
372
0
    if (ret >= 0)
373
0
        avpkt->flags |= encode_ctx(avci)->intra_only_flag;
374
375
0
    if (ret == AVERROR_EOF)
376
0
        avci->draining_done = 1;
377
378
0
    return ret;
379
0
}
380
381
#if CONFIG_LCMS2
382
static int encode_generate_icc_profile(AVCodecContext *avctx, AVFrame *frame)
383
{
384
    enum AVColorTransferCharacteristic trc = frame->color_trc;
385
    enum AVColorPrimaries prim = frame->color_primaries;
386
    const FFCodec *const codec = ffcodec(avctx->codec);
387
    AVCodecInternal *avci = avctx->internal;
388
    cmsHPROFILE profile;
389
    int ret;
390
391
    /* don't generate ICC profiles if disabled or unsupported */
392
    if (!(avctx->flags2 & AV_CODEC_FLAG2_ICC_PROFILES))
393
        return 0;
394
    if (!(codec->caps_internal & FF_CODEC_CAP_ICC_PROFILES))
395
        return 0;
396
397
    if (trc == AVCOL_TRC_UNSPECIFIED)
398
        trc = avctx->color_trc;
399
    if (prim == AVCOL_PRI_UNSPECIFIED)
400
        prim = avctx->color_primaries;
401
    if (trc == AVCOL_TRC_UNSPECIFIED || prim == AVCOL_PRI_UNSPECIFIED)
402
        return 0; /* can't generate ICC profile with missing csp tags */
403
404
    if (av_frame_get_side_data(frame, AV_FRAME_DATA_ICC_PROFILE))
405
        return 0; /* don't overwrite existing ICC profile */
406
407
    if (!avci->icc.avctx) {
408
        ret = ff_icc_context_init(&avci->icc, avctx);
409
        if (ret < 0)
410
            return ret;
411
    }
412
413
    ret = ff_icc_profile_generate(&avci->icc, prim, trc, &profile);
414
    if (ret < 0)
415
        return ret;
416
417
    ret = ff_icc_profile_attach(&avci->icc, profile, frame);
418
    cmsCloseProfile(profile);
419
    return ret;
420
}
421
#else /* !CONFIG_LCMS2 */
422
static int encode_generate_icc_profile(av_unused AVCodecContext *c, av_unused AVFrame *f)
423
0
{
424
0
    return 0;
425
0
}
426
#endif
427
428
static int encode_send_frame_internal(AVCodecContext *avctx, const AVFrame *src)
429
0
{
430
0
    AVCodecInternal *avci = avctx->internal;
431
0
    EncodeContext     *ec = encode_ctx(avci);
432
0
    AVFrame *dst = avci->buffer_frame;
433
0
    int ret;
434
435
0
    if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
436
        /* extract audio service type metadata */
437
0
        AVFrameSideData *sd = av_frame_get_side_data(src, AV_FRAME_DATA_AUDIO_SERVICE_TYPE);
438
0
        if (sd && sd->size >= sizeof(enum AVAudioServiceType))
439
0
            avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data;
440
441
        /* check for valid frame size */
442
0
        if (!(avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)) {
443
            /* if we already got an undersized frame, that must have been the last */
444
0
            if (ec->last_audio_frame) {
445
0
                av_log(avctx, AV_LOG_ERROR, "frame_size (%d) was not respected for a non-last frame\n", avctx->frame_size);
446
0
                return AVERROR(EINVAL);
447
0
            }
448
0
            if (src->nb_samples > avctx->frame_size) {
449
0
                av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) > frame_size (%d)\n", src->nb_samples, avctx->frame_size);
450
0
                return AVERROR(EINVAL);
451
0
            }
452
0
            if (src->nb_samples < avctx->frame_size) {
453
0
                ec->last_audio_frame = 1;
454
0
                if (!(avctx->codec->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME)) {
455
0
                    int pad_samples = avci->pad_samples ? avci->pad_samples : avctx->frame_size;
456
0
                    int out_samples = (src->nb_samples + pad_samples - 1) / pad_samples * pad_samples;
457
458
0
                    if (out_samples != src->nb_samples) {
459
0
                        ret = pad_last_frame(avctx, dst, src, out_samples);
460
0
                        if (ret < 0)
461
0
                            return ret;
462
0
                        goto finish;
463
0
                    }
464
0
                }
465
0
            }
466
0
        }
467
0
    }
468
469
0
    ret = av_frame_ref(dst, src);
470
0
    if (ret < 0)
471
0
        return ret;
472
473
0
finish:
474
475
0
    if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
476
0
        ret = encode_generate_icc_profile(avctx, dst);
477
0
        if (ret < 0)
478
0
            return ret;
479
0
    }
480
481
    // unset frame duration unless AV_CODEC_FLAG_FRAME_DURATION is set,
482
    // since otherwise we cannot be sure that whatever value it has is in the
483
    // right timebase, so we would produce an incorrect value, which is worse
484
    // than none at all
485
0
    if (!(avctx->flags & AV_CODEC_FLAG_FRAME_DURATION))
486
0
        dst->duration = 0;
487
488
0
    return 0;
489
0
}
490
491
int attribute_align_arg avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
492
0
{
493
0
    AVCodecInternal *avci = avctx->internal;
494
0
    int ret;
495
496
0
    if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec))
497
0
        return AVERROR(EINVAL);
498
499
0
    if (avci->draining)
500
0
        return AVERROR_EOF;
501
502
0
    if (avci->buffer_frame->buf[0])
503
0
        return AVERROR(EAGAIN);
504
505
0
    if (!frame) {
506
0
        avci->draining = 1;
507
0
    } else {
508
0
        ret = encode_send_frame_internal(avctx, frame);
509
0
        if (ret < 0)
510
0
            return ret;
511
0
    }
512
513
0
    if (!avci->buffer_pkt->data && !avci->buffer_pkt->side_data) {
514
0
        ret = encode_receive_packet_internal(avctx, avci->buffer_pkt);
515
0
        if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
516
0
            return ret;
517
0
    }
518
519
0
    avctx->frame_num++;
520
521
0
    return 0;
522
0
}
523
524
int attribute_align_arg avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
525
0
{
526
0
    AVCodecInternal *avci = avctx->internal;
527
0
    int ret;
528
529
0
    av_packet_unref(avpkt);
530
531
0
    if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec))
532
0
        return AVERROR(EINVAL);
533
534
0
    if (avci->buffer_pkt->data || avci->buffer_pkt->side_data) {
535
0
        av_packet_move_ref(avpkt, avci->buffer_pkt);
536
0
    } else {
537
0
        ret = encode_receive_packet_internal(avctx, avpkt);
538
0
        if (ret < 0)
539
0
            return ret;
540
0
    }
541
542
0
    return 0;
543
0
}
544
545
static int encode_preinit_video(AVCodecContext *avctx)
546
0
{
547
0
    const AVCodec *c = avctx->codec;
548
0
    const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt);
549
0
    const enum AVPixelFormat *pix_fmts;
550
0
    int ret, i, num_pix_fmts;
551
552
0
    if (!pixdesc) {
553
0
        av_log(avctx, AV_LOG_ERROR, "Invalid video pixel format: %d\n",
554
0
               avctx->pix_fmt);
555
0
        return AVERROR(EINVAL);
556
0
    }
557
558
0
    ret = avcodec_get_supported_config(avctx, NULL, AV_CODEC_CONFIG_PIX_FORMAT,
559
0
                                       0, (const void **) &pix_fmts, &num_pix_fmts);
560
0
    if (ret < 0)
561
0
        return ret;
562
563
0
    if (pix_fmts) {
564
0
        for (i = 0; i < num_pix_fmts; i++)
565
0
            if (avctx->pix_fmt == pix_fmts[i])
566
0
                break;
567
0
        if (i == num_pix_fmts) {
568
0
            av_log(avctx, AV_LOG_ERROR,
569
0
                   "Specified pixel format %s is not supported by the %s encoder.\n",
570
0
                   av_get_pix_fmt_name(avctx->pix_fmt), c->name);
571
572
0
            av_log(avctx, AV_LOG_ERROR, "Supported pixel formats:\n");
573
0
            for (int p = 0; pix_fmts[p] != AV_PIX_FMT_NONE; p++) {
574
0
                av_log(avctx, AV_LOG_ERROR, "  %s\n",
575
0
                       av_get_pix_fmt_name(pix_fmts[p]));
576
0
            }
577
578
0
            return AVERROR(EINVAL);
579
0
        }
580
0
        if (pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
581
0
            pix_fmts[i] == AV_PIX_FMT_YUVJ411P ||
582
0
            pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
583
0
            pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
584
0
            pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
585
0
            avctx->color_range = AVCOL_RANGE_JPEG;
586
0
    }
587
588
0
    if (pixdesc->flags & AV_PIX_FMT_FLAG_ALPHA) {
589
0
        const enum AVAlphaMode *alpha_modes;
590
0
        int num_alpha_modes;
591
0
        ret = avcodec_get_supported_config(avctx, NULL, AV_CODEC_CONFIG_ALPHA_MODE,
592
0
                                           0, (const void **) &alpha_modes, &num_alpha_modes);
593
0
        if (ret < 0)
594
0
            return ret;
595
596
0
        if (avctx->alpha_mode != AVALPHA_MODE_UNSPECIFIED && alpha_modes) {
597
0
            for (i = 0; i < num_alpha_modes; i++) {
598
0
                if (avctx->alpha_mode == alpha_modes[i])
599
0
                    break;
600
0
            }
601
0
            if (i == num_alpha_modes) {
602
0
                av_log(avctx, AV_LOG_ERROR,
603
0
                       "Specified alpha mode '%s' is not supported by the %s encoder.\n",
604
0
                       av_alpha_mode_name(avctx->alpha_mode), c->name);
605
0
                av_log(avctx, AV_LOG_ERROR, "Supported alpha modes:\n");
606
0
                for (int p = 0; alpha_modes[p] != AVALPHA_MODE_UNSPECIFIED; p++) {
607
0
                    av_log(avctx, AV_LOG_ERROR, "  %s\n",
608
0
                           av_alpha_mode_name(alpha_modes[p]));
609
0
                }
610
0
                return AVERROR(EINVAL);
611
0
            }
612
0
        }
613
0
    }
614
615
0
    if (    avctx->bits_per_raw_sample < 0
616
0
        || (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) {
617
0
        av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n",
618
0
            avctx->bits_per_raw_sample, pixdesc->comp[0].depth);
619
0
        avctx->bits_per_raw_sample = pixdesc->comp[0].depth;
620
0
    }
621
0
    if (avctx->width <= 0 || avctx->height <= 0) {
622
0
        av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
623
0
        return AVERROR(EINVAL);
624
0
    }
625
626
0
    if (avctx->hw_frames_ctx) {
627
0
        AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
628
0
        if (frames_ctx->format != avctx->pix_fmt) {
629
0
            av_log(avctx, AV_LOG_ERROR,
630
0
                   "Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n");
631
0
            return AVERROR(EINVAL);
632
0
        }
633
0
        if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE &&
634
0
            avctx->sw_pix_fmt != frames_ctx->sw_format) {
635
0
            av_log(avctx, AV_LOG_ERROR,
636
0
                   "Mismatching AVCodecContext.sw_pix_fmt (%s) "
637
0
                   "and AVHWFramesContext.sw_format (%s)\n",
638
0
                   av_get_pix_fmt_name(avctx->sw_pix_fmt),
639
0
                   av_get_pix_fmt_name(frames_ctx->sw_format));
640
0
            return AVERROR(EINVAL);
641
0
        }
642
0
        avctx->sw_pix_fmt = frames_ctx->sw_format;
643
0
    }
644
645
0
    return 0;
646
0
}
647
648
static int encode_preinit_audio(AVCodecContext *avctx)
649
0
{
650
0
    const AVCodec *c = avctx->codec;
651
0
    const enum AVSampleFormat *sample_fmts;
652
0
    const int *supported_samplerates;
653
0
    const AVChannelLayout *ch_layouts;
654
0
    int ret, i, num_sample_fmts, num_samplerates, num_ch_layouts;
655
656
0
    if (!av_get_sample_fmt_name(avctx->sample_fmt)) {
657
0
        av_log(avctx, AV_LOG_ERROR, "Invalid audio sample format: %d\n",
658
0
               avctx->sample_fmt);
659
0
        return AVERROR(EINVAL);
660
0
    }
661
662
0
    ret = avcodec_get_supported_config(avctx, NULL, AV_CODEC_CONFIG_SAMPLE_FORMAT,
663
0
                                       0, (const void **) &sample_fmts,
664
0
                                       &num_sample_fmts);
665
0
    if (ret < 0)
666
0
        return ret;
667
0
    if (sample_fmts) {
668
0
        for (i = 0; i < num_sample_fmts; i++) {
669
0
            if (avctx->sample_fmt == sample_fmts[i])
670
0
                break;
671
0
            if (avctx->ch_layout.nb_channels == 1 &&
672
0
                av_get_planar_sample_fmt(avctx->sample_fmt) ==
673
0
                av_get_planar_sample_fmt(sample_fmts[i])) {
674
0
                avctx->sample_fmt = sample_fmts[i];
675
0
                break;
676
0
            }
677
0
        }
678
0
        if (i == num_sample_fmts) {
679
0
            av_log(avctx, AV_LOG_ERROR,
680
0
                   "Specified sample format %s is not supported by the %s encoder\n",
681
0
                   av_get_sample_fmt_name(avctx->sample_fmt), c->name);
682
683
0
            av_log(avctx, AV_LOG_ERROR, "Supported sample formats:\n");
684
0
            for (int p = 0; sample_fmts[p] != AV_SAMPLE_FMT_NONE; p++) {
685
0
                av_log(avctx, AV_LOG_ERROR, "  %s\n",
686
0
                       av_get_sample_fmt_name(sample_fmts[p]));
687
0
            }
688
689
0
            return AVERROR(EINVAL);
690
0
        }
691
0
    }
692
693
0
    ret = avcodec_get_supported_config(avctx, NULL, AV_CODEC_CONFIG_SAMPLE_RATE,
694
0
                                       0, (const void **) &supported_samplerates,
695
0
                                       &num_samplerates);
696
0
    if (ret < 0)
697
0
        return ret;
698
0
    if (supported_samplerates) {
699
0
        for (i = 0; i < num_samplerates; i++)
700
0
            if (avctx->sample_rate == supported_samplerates[i])
701
0
                break;
702
0
        if (i == num_samplerates) {
703
0
            av_log(avctx, AV_LOG_ERROR,
704
0
                   "Specified sample rate %d is not supported by the %s encoder\n",
705
0
                   avctx->sample_rate, c->name);
706
707
0
            av_log(avctx, AV_LOG_ERROR, "Supported sample rates:\n");
708
0
            for (int p = 0; supported_samplerates[p]; p++)
709
0
                av_log(avctx, AV_LOG_ERROR, "  %d\n", supported_samplerates[p]);
710
711
0
            return AVERROR(EINVAL);
712
0
        }
713
0
    }
714
0
    ret = avcodec_get_supported_config(avctx, NULL, AV_CODEC_CONFIG_CHANNEL_LAYOUT,
715
0
                                       0, (const void **) &ch_layouts, &num_ch_layouts);
716
0
    if (ret < 0)
717
0
        return ret;
718
0
    if (ch_layouts) {
719
0
        for (i = 0; i < num_ch_layouts; i++) {
720
0
            if (!av_channel_layout_compare(&avctx->ch_layout, &ch_layouts[i]))
721
0
                break;
722
0
        }
723
0
        if (i == num_ch_layouts) {
724
0
            char buf[512];
725
0
            int ret = av_channel_layout_describe(&avctx->ch_layout, buf, sizeof(buf));
726
0
            av_log(avctx, AV_LOG_ERROR,
727
0
                   "Specified channel layout '%s' is not supported by the %s encoder\n",
728
0
                   ret > 0 ? buf : "?", c->name);
729
730
0
            av_log(avctx, AV_LOG_ERROR, "Supported channel layouts:\n");
731
0
            for (int p = 0; ch_layouts[p].nb_channels; p++) {
732
0
                ret = av_channel_layout_describe(&ch_layouts[p], buf, sizeof(buf));
733
0
                av_log(avctx, AV_LOG_ERROR, "  %s\n", ret > 0 ? buf : "?");
734
0
            }
735
0
            return AVERROR(EINVAL);
736
0
        }
737
0
    }
738
739
0
    if (!avctx->bits_per_raw_sample)
740
0
        avctx->bits_per_raw_sample = av_get_exact_bits_per_sample(avctx->codec_id);
741
0
    if (!avctx->bits_per_raw_sample)
742
0
        avctx->bits_per_raw_sample = 8 * av_get_bytes_per_sample(avctx->sample_fmt);
743
744
0
    return 0;
745
0
}
746
747
int ff_encode_preinit(AVCodecContext *avctx)
748
0
{
749
0
    AVCodecInternal *avci = avctx->internal;
750
0
    EncodeContext     *ec = encode_ctx(avci);
751
0
    int ret = 0;
752
753
0
    if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) {
754
0
        av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n");
755
0
        return AVERROR(EINVAL);
756
0
    }
757
758
0
    if (avctx->bit_rate < 0) {
759
0
        av_log(avctx, AV_LOG_ERROR, "The encoder bitrate is negative.\n");
760
0
        return AVERROR(EINVAL);
761
0
    }
762
763
0
    if (avctx->flags & AV_CODEC_FLAG_COPY_OPAQUE &&
764
0
        !(avctx->codec->capabilities & AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE)) {
765
0
        av_log(avctx, AV_LOG_ERROR, "The copy_opaque flag is set, but the "
766
0
               "encoder does not support it.\n");
767
0
        return AVERROR(EINVAL);
768
0
    }
769
770
0
    switch (avctx->codec_type) {
771
0
    case AVMEDIA_TYPE_VIDEO: ret = encode_preinit_video(avctx); break;
772
0
    case AVMEDIA_TYPE_AUDIO: ret = encode_preinit_audio(avctx); break;
773
0
    }
774
0
    if (ret < 0)
775
0
        return ret;
776
777
0
    if (   (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
778
0
        && avctx->bit_rate>0 && avctx->bit_rate<1000) {
779
0
        av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", avctx->bit_rate, avctx->bit_rate);
780
0
    }
781
782
0
    if (!avctx->rc_initial_buffer_occupancy)
783
0
        avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4;
784
785
0
    if (avctx->codec_descriptor->props & AV_CODEC_PROP_INTRA_ONLY)
786
0
        ec->intra_only_flag = AV_PKT_FLAG_KEY;
787
788
0
    if (ffcodec(avctx->codec)->cb_type == FF_CODEC_CB_TYPE_ENCODE) {
789
0
        avci->in_frame = av_frame_alloc();
790
0
        if (!avci->in_frame)
791
0
            return AVERROR(ENOMEM);
792
0
    }
793
794
0
    if ((avctx->flags & AV_CODEC_FLAG_RECON_FRAME)) {
795
0
        if (!(avctx->codec->capabilities & AV_CODEC_CAP_ENCODER_RECON_FRAME)) {
796
0
            av_log(avctx, AV_LOG_ERROR, "Reconstructed frame output requested "
797
0
                   "from an encoder not supporting it\n");
798
0
            return AVERROR(ENOSYS);
799
0
        }
800
801
0
        avci->recon_frame = av_frame_alloc();
802
0
        if (!avci->recon_frame)
803
0
            return AVERROR(ENOMEM);
804
0
    }
805
806
0
    for (int i = 0; ff_sd_global_map[i].packet < AV_PKT_DATA_NB; i++) {
807
0
        const enum AVPacketSideDataType type_packet = ff_sd_global_map[i].packet;
808
0
        const enum AVFrameSideDataType  type_frame  = ff_sd_global_map[i].frame;
809
0
        const AVFrameSideData *sd_frame;
810
0
        AVPacketSideData      *sd_packet;
811
812
0
        sd_frame = av_frame_side_data_get(avctx->decoded_side_data,
813
0
                                          avctx->nb_decoded_side_data,
814
0
                                          type_frame);
815
0
        if (!sd_frame ||
816
0
            av_packet_side_data_get(avctx->coded_side_data, avctx->nb_coded_side_data,
817
0
                                    type_packet))
818
819
0
            continue;
820
821
0
        sd_packet = av_packet_side_data_new(&avctx->coded_side_data, &avctx->nb_coded_side_data,
822
0
                                            type_packet, sd_frame->size, 0);
823
0
        if (!sd_packet)
824
0
            return AVERROR(ENOMEM);
825
826
0
        memcpy(sd_packet->data, sd_frame->data, sd_frame->size);
827
0
    }
828
829
#if CONFIG_FRAME_THREAD_ENCODER
830
    ret = ff_frame_thread_encoder_init(avctx);
831
    if (ret < 0)
832
        return ret;
833
#endif
834
835
0
    return 0;
836
0
}
837
838
int ff_encode_alloc_frame(AVCodecContext *avctx, AVFrame *frame)
839
0
{
840
0
    int ret;
841
842
0
    av_assert1(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
843
844
0
    frame->format = avctx->pix_fmt;
845
0
    if (frame->width <= 0 || frame->height <= 0) {
846
0
        frame->width  = avctx->width;
847
0
        frame->height = avctx->height;
848
0
    }
849
850
0
    ret = avcodec_default_get_buffer2(avctx, frame, 0);
851
0
    if (ret < 0) {
852
0
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
853
0
        av_frame_unref(frame);
854
0
        return ret;
855
0
    }
856
857
0
    return 0;
858
0
}
859
860
int ff_encode_receive_frame(AVCodecContext *avctx, AVFrame *frame)
861
0
{
862
0
    AVCodecInternal *avci = avctx->internal;
863
864
0
    if (!avci->recon_frame)
865
0
        return AVERROR(EINVAL);
866
0
    if (!avci->recon_frame->buf[0])
867
0
        return avci->draining_done ? AVERROR_EOF : AVERROR(EAGAIN);
868
869
0
    av_frame_move_ref(frame, avci->recon_frame);
870
0
    return 0;
871
0
}
872
873
void ff_encode_flush_buffers(AVCodecContext *avctx)
874
0
{
875
0
    AVCodecInternal *avci = avctx->internal;
876
877
0
    if (avci->in_frame)
878
0
        av_frame_unref(avci->in_frame);
879
0
    if (avci->recon_frame)
880
0
        av_frame_unref(avci->recon_frame);
881
0
}
882
883
AVCodecInternal *ff_encode_internal_alloc(void)
884
0
{
885
0
    return av_mallocz(sizeof(EncodeContext));
886
0
}
887
888
AVCPBProperties *ff_encode_add_cpb_side_data(AVCodecContext *avctx)
889
0
{
890
0
    AVPacketSideData *tmp;
891
0
    AVCPBProperties  *props;
892
0
    size_t size;
893
0
    int i;
894
895
0
    for (i = 0; i < avctx->nb_coded_side_data; i++)
896
0
        if (avctx->coded_side_data[i].type == AV_PKT_DATA_CPB_PROPERTIES)
897
0
            return (AVCPBProperties *)avctx->coded_side_data[i].data;
898
899
0
    props = av_cpb_properties_alloc(&size);
900
0
    if (!props)
901
0
        return NULL;
902
903
0
    tmp = av_realloc_array(avctx->coded_side_data, avctx->nb_coded_side_data + 1, sizeof(*tmp));
904
0
    if (!tmp) {
905
0
        av_freep(&props);
906
0
        return NULL;
907
0
    }
908
909
0
    avctx->coded_side_data = tmp;
910
0
    avctx->nb_coded_side_data++;
911
912
0
    avctx->coded_side_data[avctx->nb_coded_side_data - 1].type = AV_PKT_DATA_CPB_PROPERTIES;
913
0
    avctx->coded_side_data[avctx->nb_coded_side_data - 1].data = (uint8_t*)props;
914
0
    avctx->coded_side_data[avctx->nb_coded_side_data - 1].size = size;
915
916
0
    return props;
917
0
}
918
919
int ff_encode_add_stats_side_data(AVPacket *pkt, int quality, const int64_t error[],
920
                                  int error_count, enum AVPictureType pict_type)
921
0
{
922
0
    uint8_t *side_data;
923
0
    size_t side_data_size;
924
925
0
    side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS, &side_data_size);
926
0
    if (!side_data) {
927
0
        side_data_size = 4+4+8*error_count;
928
0
        side_data = av_packet_new_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
929
0
                                            side_data_size);
930
0
    }
931
932
0
    if (!side_data || side_data_size < 4+4+8*error_count)
933
0
        return AVERROR(ENOMEM);
934
935
0
    AV_WL32(side_data, quality);
936
0
    side_data[4] = pict_type;
937
0
    side_data[5] = error_count;
938
0
    for (int i = 0; i < error_count; ++i)
939
0
        AV_WL64(side_data+8 + 8*i , error[i]);
940
941
0
    return 0;
942
0
}
943
944
int ff_check_codec_matrices(AVCodecContext *avctx, unsigned types, uint16_t min, uint16_t max)
945
0
{
946
0
    uint16_t  *matrices[] = {avctx->intra_matrix, avctx->inter_matrix, avctx->chroma_intra_matrix};
947
0
    const char   *names[] = {"Intra", "Inter", "Chroma Intra"};
948
0
    static_assert(FF_ARRAY_ELEMS(matrices) == FF_ARRAY_ELEMS(names), "matrix count mismatch");
949
0
    for (int m = 0; m < FF_ARRAY_ELEMS(matrices); m++) {
950
0
        uint16_t *matrix = matrices[m];
951
0
        if (matrix && (types & (1U << m))) {
952
0
            for (int i = 0; i < 64; i++) {
953
0
                if (matrix[i] < min || matrix[i] > max) {
954
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);
955
0
                    return AVERROR(EINVAL);
956
0
                }
957
0
            }
958
0
        }
959
0
    }
960
0
    return 0;
961
0
}