Coverage Report

Created: 2026-10-28 08:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/magicyuvenc.c
Line
Count
Source
1
/*
2
 * MagicYUV encoder
3
 * Copyright (c) 2017 Paul B Mahol
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21
22
#include <stdlib.h>
23
#include <string.h>
24
25
#include "libavutil/cpu.h"
26
#include "libavutil/mem.h"
27
#include "libavutil/opt.h"
28
#include "libavutil/pixdesc.h"
29
#include "libavutil/qsort.h"
30
31
#include "avcodec.h"
32
#include "bytestream.h"
33
#include "codec_internal.h"
34
#include "encode.h"
35
#include "put_bits.h"
36
#include "lossless_videoencdsp.h"
37
38
744
#define MAGICYUV_EXTRADATA_SIZE 32
39
40
typedef enum Prediction {
41
    LEFT = 1,
42
    GRADIENT,
43
    MEDIAN,
44
} Prediction;
45
46
typedef struct HuffEntry {
47
    uint8_t  len;
48
    uint32_t code;
49
} HuffEntry;
50
51
typedef struct PTable {
52
    int     value;  ///< input value
53
    int64_t prob;   ///< number of occurrences of this value in input
54
} PTable;
55
56
typedef struct Slice {
57
    int width;
58
    int height;
59
    int encode_raw;
60
    unsigned pos;
61
    unsigned size;
62
    uint8_t *slice;
63
    uint8_t *dst;
64
    int64_t counts[256];
65
} Slice;
66
67
typedef struct MagicYUVContext {
68
    const AVClass       *class;
69
    int                  frame_pred;
70
    int                  planes;
71
    uint8_t              format;
72
    int                  slice_height;
73
    int                  nb_slices;
74
    int                  correlate;
75
    int                  hshift[4];
76
    int                  vshift[4];
77
    uint8_t             *decorrelate_buf[2];
78
    Slice               *slices;
79
    HuffEntry            he[4][256];
80
    LLVidEncDSPContext   llvidencdsp;
81
    void (*predict)(struct MagicYUVContext *s, const uint8_t *src, uint8_t *dst,
82
                    ptrdiff_t stride, int width, int height);
83
} MagicYUVContext;
84
85
static void left_predict(MagicYUVContext *s,
86
                         const uint8_t *src, uint8_t *dst, ptrdiff_t stride,
87
                         int width, int height)
88
13.6k
{
89
13.6k
    uint8_t prev = 0;
90
13.6k
    int i, j;
91
92
6.12M
    for (i = 0; i < width; i++) {
93
6.11M
        dst[i] = src[i] - prev;
94
6.11M
        prev   = src[i];
95
6.11M
    }
96
13.6k
    dst += width;
97
13.6k
    src += stride;
98
4.90M
    for (j = 1; j < height; j++) {
99
4.88M
        prev = src[-stride];
100
64.7M
        for (i = 0; i < width; i++) {
101
59.9M
            dst[i] = src[i] - prev;
102
59.9M
            prev   = src[i];
103
59.9M
        }
104
4.88M
        dst += width;
105
4.88M
        src += stride;
106
4.88M
    }
107
13.6k
}
108
109
static void gradient_predict(MagicYUVContext *s,
110
                             const uint8_t *src, uint8_t *dst, ptrdiff_t stride,
111
                             int width, int height)
112
0
{
113
0
    int left = 0, top, lefttop;
114
0
    int i, j;
115
116
0
    for (i = 0; i < width; i++) {
117
0
        dst[i] = src[i] - left;
118
0
        left   = src[i];
119
0
    }
120
0
    dst += width;
121
0
    src += stride;
122
0
    for (j = 1; j < height; j++) {
123
0
        top = src[-stride];
124
0
        left = src[0] - top;
125
0
        dst[0] = left;
126
0
        for (i = 1; i < width; i++) {
127
0
            top = src[i - stride];
128
0
            lefttop = src[i - (stride + 1)];
129
0
            left = src[i-1];
130
0
            dst[i] = (src[i] - top) - left + lefttop;
131
0
        }
132
0
        dst += width;
133
0
        src += stride;
134
0
    }
135
0
}
136
137
static void median_predict(MagicYUVContext *s,
138
                           const uint8_t *src, uint8_t *dst, ptrdiff_t stride,
139
                           int width, int height)
140
0
{
141
0
    int left = 0, lefttop;
142
0
    int i, j;
143
144
0
    for (i = 0; i < width; i++) {
145
0
        dst[i] = src[i] - left;
146
0
        left   = src[i];
147
0
    }
148
0
    dst += width;
149
0
    src += stride;
150
0
    for (j = 1; j < height; j++) {
151
0
        left = lefttop = src[-stride];
152
0
        s->llvidencdsp.sub_median_pred(dst, src - stride, src, width, &left, &lefttop);
153
0
        dst += width;
154
0
        src += stride;
155
0
    }
156
0
}
157
158
static av_cold int magy_encode_init(AVCodecContext *avctx)
159
372
{
160
372
    MagicYUVContext *s = avctx->priv_data;
161
372
    PutByteContext pb;
162
163
372
    switch (avctx->pix_fmt) {
164
120
    case AV_PIX_FMT_GBRP:
165
120
        avctx->codec_tag = MKTAG('M', '8', 'R', 'G');
166
120
        s->correlate = 1;
167
120
        s->format = 0x65;
168
120
        break;
169
48
    case AV_PIX_FMT_GBRAP:
170
48
        avctx->codec_tag = MKTAG('M', '8', 'R', 'A');
171
48
        s->correlate = 1;
172
48
        s->format = 0x66;
173
48
        break;
174
47
    case AV_PIX_FMT_YUV420P:
175
47
        avctx->codec_tag = MKTAG('M', '8', 'Y', '0');
176
47
        s->hshift[1] =
177
47
        s->vshift[1] =
178
47
        s->hshift[2] =
179
47
        s->vshift[2] = 1;
180
47
        s->format = 0x69;
181
47
        break;
182
55
    case AV_PIX_FMT_YUV422P:
183
55
        avctx->codec_tag = MKTAG('M', '8', 'Y', '2');
184
55
        s->hshift[1] =
185
55
        s->hshift[2] = 1;
186
55
        s->format = 0x68;
187
55
        break;
188
7
    case AV_PIX_FMT_YUV444P:
189
7
        avctx->codec_tag = MKTAG('M', '8', 'Y', '4');
190
7
        s->format = 0x67;
191
7
        break;
192
8
    case AV_PIX_FMT_YUVA444P:
193
8
        avctx->codec_tag = MKTAG('M', '8', 'Y', 'A');
194
8
        s->format = 0x6a;
195
8
        break;
196
87
    case AV_PIX_FMT_GRAY8:
197
87
        avctx->codec_tag = MKTAG('M', '8', 'G', '0');
198
87
        s->format = 0x6b;
199
87
        break;
200
372
    }
201
202
372
    ff_llvidencdsp_init(&s->llvidencdsp);
203
204
372
    s->planes = av_pix_fmt_count_planes(avctx->pix_fmt);
205
206
372
    s->nb_slices = avctx->slices > 0 ? avctx->slices : avctx->thread_count;
207
372
    s->nb_slices = FFMIN(s->nb_slices, avctx->height >> s->vshift[1]);
208
372
    s->nb_slices = FFMAX(1, s->nb_slices);
209
372
    s->slice_height = FFALIGN((avctx->height + s->nb_slices - 1) / s->nb_slices, 1 << s->vshift[1]);
210
372
    s->nb_slices = (avctx->height + s->slice_height - 1) / s->slice_height;
211
372
    s->nb_slices = FFMIN(256U / s->planes, s->nb_slices);
212
372
    s->slices = av_calloc(s->nb_slices * s->planes, sizeof(*s->slices));
213
372
    if (!s->slices)
214
0
        return AVERROR(ENOMEM);
215
216
372
    if (s->correlate) {
217
168
        size_t max_align = av_cpu_max_align();
218
168
        size_t aligned_width = FFALIGN(avctx->width, max_align);
219
168
        s->decorrelate_buf[0] = av_calloc(2U * (s->nb_slices * s->slice_height),
220
168
                                          aligned_width);
221
168
        if (!s->decorrelate_buf[0])
222
0
            return AVERROR(ENOMEM);
223
168
        s->decorrelate_buf[1] = s->decorrelate_buf[0] + (s->nb_slices * s->slice_height) * aligned_width;
224
168
    }
225
226
744
    for (int n = 0; n < s->nb_slices; n++) {
227
1.37k
        for (int i = 0; i < s->planes; i++) {
228
998
            Slice *sl = &s->slices[n * s->planes + i];
229
230
998
            sl->height = n == s->nb_slices - 1 ? avctx->height - n * s->slice_height : s->slice_height;
231
998
            sl->height = AV_CEIL_RSHIFT(sl->height, s->vshift[i]);
232
998
            sl->width  = AV_CEIL_RSHIFT(avctx->width, s->hshift[i]);
233
234
998
            sl->slice = av_malloc(avctx->width * (s->slice_height + 2) +
235
998
                                                     AV_INPUT_BUFFER_PADDING_SIZE);
236
998
            if (!sl->slice)
237
0
                return AVERROR(ENOMEM);
238
998
        }
239
372
    }
240
241
372
    switch (s->frame_pred) {
242
372
    case LEFT:     s->predict = left_predict;     break;
243
0
    case GRADIENT: s->predict = gradient_predict; break;
244
0
    case MEDIAN:   s->predict = median_predict;   break;
245
372
    }
246
247
372
    avctx->extradata_size = MAGICYUV_EXTRADATA_SIZE;
248
249
372
    avctx->extradata = av_mallocz(avctx->extradata_size +
250
372
                                  AV_INPUT_BUFFER_PADDING_SIZE);
251
372
    if (!avctx->extradata)
252
0
        return AVERROR(ENOMEM);
253
254
372
    bytestream2_init_writer(&pb, avctx->extradata, MAGICYUV_EXTRADATA_SIZE);
255
372
    bytestream2_put_le32u(&pb, MKTAG('M', 'A', 'G', 'Y'));
256
372
    bytestream2_put_le32u(&pb, 32);
257
372
    bytestream2_put_byteu(&pb, 7);
258
372
    bytestream2_put_byteu(&pb, s->format);
259
372
    bytestream2_put_byteu(&pb, 12);
260
372
    bytestream2_put_byteu(&pb, 0);
261
262
372
    bytestream2_put_byteu(&pb, 0);
263
372
    bytestream2_put_byteu(&pb, 0);
264
372
    bytestream2_put_byteu(&pb, 32);
265
372
    bytestream2_put_byteu(&pb, 0);
266
267
372
    bytestream2_put_le32u(&pb, avctx->width);
268
372
    bytestream2_put_le32u(&pb, avctx->height);
269
372
    bytestream2_put_le32u(&pb, avctx->width);
270
372
    bytestream2_put_le32u(&pb, avctx->height);
271
272
372
    return 0;
273
372
}
274
275
static void calculate_codes(HuffEntry *he, uint16_t codes_count[33])
276
13.6k
{
277
451k
    for (unsigned i = 32, nb_codes = 0; i > 0; i--) {
278
437k
        uint16_t curr = codes_count[i];   // # of leafs of length i
279
437k
        codes_count[i] = nb_codes / 2;    // # of non-leaf nodes on level i
280
437k
        nb_codes = codes_count[i] + curr; // # of nodes on level i
281
437k
    }
282
283
3.51M
    for (unsigned i = 0; i < 256; i++) {
284
3.49M
        he[i].code = codes_count[he[i].len];
285
3.49M
        codes_count[he[i].len]++;
286
3.49M
    }
287
13.6k
}
288
289
static void count_usage(const uint8_t *src, int width,
290
                        int height, int64_t *counts)
291
13.6k
{
292
4.91M
    for (int j = 0; j < height; j++) {
293
70.9M
        for (int i = 0; i < width; i++)
294
66.0M
            counts[src[i]]++;
295
4.90M
        src += width;
296
4.90M
    }
297
13.6k
}
298
299
typedef struct PackageMergerList {
300
    int nitems;             ///< number of items in the list and probability      ex. 4
301
    int item_idx[515];      ///< index range for each item in items                   0, 2, 5, 9, 13
302
    int probability[514];   ///< probability of each item                             3, 8, 18, 46
303
    int items[257 * 16];    ///< chain of all individual values that make up items    A, B, A, B, C, A, B, C, D, C, D, D, E
304
} PackageMergerList;
305
306
static int compare_by_prob(const void *a, const void *b)
307
15.6M
{
308
15.6M
    const PTable *a2 = a;
309
15.6M
    const PTable *b2 = b;
310
15.6M
    return a2->prob - b2->prob;
311
15.6M
}
312
313
static void magy_huffman_compute_bits(PTable *prob_table, HuffEntry *distincts,
314
                                      uint16_t codes_counts[33],
315
                                      int size, int max_length)
316
13.6k
{
317
13.6k
    PackageMergerList list_a, list_b, *to = &list_a, *from = &list_b, *temp;
318
13.6k
    int times, i, j, k;
319
13.6k
    int nbits[257] = {0};
320
13.6k
    int min;
321
322
13.6k
    av_assert0(max_length > 0);
323
324
13.6k
    to->nitems = 0;
325
13.6k
    from->nitems = 0;
326
13.6k
    to->item_idx[0] = 0;
327
13.6k
    from->item_idx[0] = 0;
328
13.6k
    AV_QSORT(prob_table, size, PTable, compare_by_prob);
329
330
191k
    for (times = 0; times <= max_length; times++) {
331
177k
        to->nitems = 0;
332
177k
        to->item_idx[0] = 0;
333
334
177k
        j = 0;
335
177k
        k = 0;
336
337
177k
        if (times < max_length) {
338
164k
            i = 0;
339
164k
        }
340
80.6M
        while (i < size || j + 1 < from->nitems) {
341
80.4M
            to->nitems++;
342
80.4M
            to->item_idx[to->nitems] = to->item_idx[to->nitems - 1];
343
80.4M
            if (i < size &&
344
65.0M
                (j + 1 >= from->nitems ||
345
61.5M
                 prob_table[i].prob <
346
61.5M
                     from->probability[j] + from->probability[j + 1])) {
347
41.9M
                to->items[to->item_idx[to->nitems]++] = prob_table[i].value;
348
41.9M
                to->probability[to->nitems - 1] = prob_table[i].prob;
349
41.9M
                i++;
350
41.9M
            } else {
351
278M
                for (k = from->item_idx[j]; k < from->item_idx[j + 2]; k++) {
352
240M
                    to->items[to->item_idx[to->nitems]++] = from->items[k];
353
240M
                }
354
38.4M
                to->probability[to->nitems - 1] =
355
38.4M
                    from->probability[j] + from->probability[j + 1];
356
38.4M
                j += 2;
357
38.4M
            }
358
80.4M
        }
359
177k
        temp = to;
360
177k
        to = from;
361
177k
        from = temp;
362
177k
    }
363
364
13.6k
    min = (size - 1 < from->nitems) ? size - 1 : from->nitems;
365
28.6M
    for (i = 0; i < from->item_idx[min]; i++) {
366
28.6M
        nbits[from->items[i]]++;
367
28.6M
    }
368
369
3.51M
    for (i = 0; i < size; i++) {
370
3.49M
        distincts[i].len = nbits[i];
371
3.49M
        codes_counts[nbits[i]]++;
372
3.49M
    }
373
13.6k
}
374
375
static int count_plane_slice(AVCodecContext *avctx, int n, int plane)
376
13.6k
{
377
13.6k
    MagicYUVContext *s = avctx->priv_data;
378
13.6k
    Slice *sl = &s->slices[n * s->planes + plane];
379
13.6k
    const uint8_t *dst = sl->slice;
380
13.6k
    int64_t *counts = sl->counts;
381
382
13.6k
    memset(counts, 0, sizeof(sl->counts));
383
384
13.6k
    count_usage(dst, sl->width, sl->height, counts);
385
386
13.6k
    return 0;
387
13.6k
}
388
389
static void generate_codes(AVCodecContext *avctx,
390
                           HuffEntry *he, int plane)
391
13.6k
{
392
13.6k
    MagicYUVContext *s = avctx->priv_data;
393
13.6k
    PTable counts[256];
394
13.6k
    uint16_t codes_counts[33] = { 0 };
395
396
3.51M
    for (size_t i = 0; i < FF_ARRAY_ELEMS(counts); i++) {
397
3.49M
        counts[i].prob  = 1;
398
3.49M
        counts[i].value = i;
399
3.49M
    }
400
401
27.3k
    for (int n = 0; n < s->nb_slices; n++) {
402
13.6k
        Slice *sl = &s->slices[n * s->planes + plane];
403
13.6k
        int64_t *slice_counts = sl->counts;
404
405
3.51M
        for (int i = 0; i < 256; i++)
406
3.49M
            counts[i].prob += slice_counts[i];
407
13.6k
    }
408
409
13.6k
    magy_huffman_compute_bits(counts, he, codes_counts, 256, 12);
410
411
13.6k
    calculate_codes(he, codes_counts);
412
13.6k
}
413
414
static void output_codes(PutByteContext *pb, const HuffEntry he[256])
415
13.6k
{
416
3.51M
    for (int i = 0; i < 256; i++) {
417
        // The seven low bits are len; the top bit means the run of
418
        // codes of this length has length one.
419
3.49M
        bytestream2_put_byteu(pb, he[i].len);
420
3.49M
    }
421
13.6k
}
422
423
static void encode_plane_slice_raw(const uint8_t *src, uint8_t *dst,
424
                                   int width, int height, int prediction)
425
6.87k
{
426
6.87k
    unsigned count = width * height;
427
428
6.87k
    dst[0] = 1;
429
6.87k
    dst[1] = prediction;
430
431
6.87k
    memcpy(dst + 2, src, count);
432
6.87k
}
433
434
static void encode_plane_slice(const uint8_t *src, uint8_t *dst, unsigned dst_size,
435
                               int width, int height, HuffEntry *he, int prediction)
436
6.79k
{
437
6.79k
    PutBitContext pb;
438
439
6.79k
    init_put_bits(&pb, dst, dst_size);
440
441
6.79k
    put_bits(&pb, 8, 0);
442
6.79k
    put_bits(&pb, 8, prediction);
443
444
4.88M
    for (int j = 0; j < height; j++) {
445
70.8M
        for (int i = 0; i < width; i++) {
446
65.9M
            const int idx = src[i];
447
65.9M
            const int len = he[idx].len;
448
65.9M
            put_bits(&pb, len, he[idx].code);
449
65.9M
        }
450
451
4.87M
        src += width;
452
4.87M
    }
453
454
6.79k
    flush_put_bits(&pb);
455
6.79k
    av_assert1(put_bytes_left(&pb, 0) <= 3);
456
6.79k
}
457
458
static int encode_slice(AVCodecContext *avctx, void *tdata,
459
                        int n, int threadnr)
460
8.78k
{
461
8.78k
    MagicYUVContext *s = avctx->priv_data;
462
463
22.4k
    for (int i = 0; i < s->planes; i++) {
464
13.6k
        Slice *sl = &s->slices[n * s->planes + i];
465
466
        // Zero the padding now
467
13.6k
        AV_WN32(sl->dst + sl->size - 4, 0);
468
469
13.6k
        if (sl->encode_raw)
470
6.87k
            encode_plane_slice_raw(sl->slice, sl->dst,
471
6.87k
                                   sl->width, sl->height, s->frame_pred);
472
6.79k
        else
473
6.79k
            encode_plane_slice(sl->slice,
474
6.79k
                               sl->dst,
475
6.79k
                               sl->size,
476
6.79k
                               sl->width, sl->height,
477
6.79k
                               s->he[i], s->frame_pred);
478
13.6k
    }
479
480
8.78k
    return 0;
481
8.78k
}
482
483
static int predict_slice(AVCodecContext *avctx, void *tdata,
484
                         int n, int threadnr)
485
8.78k
{
486
8.78k
    size_t max_align = av_cpu_max_align();
487
8.78k
    const int aligned_width = FFALIGN(avctx->width, max_align);
488
8.78k
    MagicYUVContext *s = avctx->priv_data;
489
8.78k
    const int slice_height = s->slice_height;
490
8.78k
    const int last_height = FFMIN(slice_height, avctx->height - n * slice_height);
491
8.78k
    const int height = (n < (s->nb_slices - 1)) ? slice_height : last_height;
492
8.78k
    const int width = avctx->width;
493
8.78k
    AVFrame *frame = tdata;
494
495
8.78k
    if (s->correlate) {
496
1.02k
        uint8_t *decorrelated[2] = { s->decorrelate_buf[0] + n * slice_height * aligned_width,
497
1.02k
                                     s->decorrelate_buf[1] + n * slice_height * aligned_width };
498
1.02k
        const int decorrelate_linesize = aligned_width;
499
1.02k
        const uint8_t *const data[4] = { decorrelated[0], frame->data[0] + n * slice_height * frame->linesize[0],
500
1.02k
                                         decorrelated[1], s->planes == 4 ? frame->data[3] + n * slice_height * frame->linesize[3] : NULL };
501
1.02k
        const uint8_t *r, *g, *b;
502
1.02k
        const int linesize[4]  = { decorrelate_linesize, frame->linesize[0],
503
1.02k
                                   decorrelate_linesize, frame->linesize[3] };
504
505
1.02k
        g = frame->data[0] + n * slice_height * frame->linesize[0];
506
1.02k
        b = frame->data[1] + n * slice_height * frame->linesize[1];
507
1.02k
        r = frame->data[2] + n * slice_height * frame->linesize[2];
508
509
892k
        for (int i = 0; i < height; i++) {
510
891k
            s->llvidencdsp.diff_bytes(decorrelated[0], b, g, width);
511
891k
            s->llvidencdsp.diff_bytes(decorrelated[1], r, g, width);
512
891k
            g += frame->linesize[0];
513
891k
            b += frame->linesize[1];
514
891k
            r += frame->linesize[2];
515
891k
            decorrelated[0] += decorrelate_linesize;
516
891k
            decorrelated[1] += decorrelate_linesize;
517
891k
        }
518
519
4.73k
        for (int i = 0; i < s->planes; i++) {
520
3.70k
            Slice *sl = &s->slices[n * s->planes + i];
521
522
3.70k
            s->predict(s, data[i], sl->slice, linesize[i],
523
3.70k
                       frame->width, height);
524
3.70k
        }
525
7.75k
    } else {
526
17.7k
        for (int i = 0; i < s->planes; i++) {
527
9.96k
            Slice *sl = &s->slices[n * s->planes + i];
528
529
9.96k
            s->predict(s, frame->data[i] + n * (slice_height >> s->vshift[i]) * frame->linesize[i],
530
9.96k
                       sl->slice,
531
9.96k
                       frame->linesize[i],
532
9.96k
                       sl->width, sl->height);
533
9.96k
        }
534
7.75k
    }
535
536
22.4k
    for (int p = 0; p < s->planes; p++)
537
13.6k
        count_plane_slice(avctx, n, p);
538
539
8.78k
    return 0;
540
8.78k
}
541
542
static int magy_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
543
                             const AVFrame *frame, int *got_packet)
544
8.78k
{
545
8.78k
    MagicYUVContext *s = avctx->priv_data;
546
8.78k
    PutByteContext pb;
547
8.78k
    int header_size = 32 + (4 + 1) * (s->planes * s->nb_slices + 1)
548
8.78k
                         + 256 * s->planes /* Hufftables */;
549
8.78k
    int64_t pkt_size = header_size;
550
8.78k
    int ret;
551
552
8.78k
    avctx->execute2(avctx, predict_slice, (void *)frame, NULL, s->nb_slices);
553
554
22.4k
    for (int i = 0; i < s->planes; i++)
555
13.6k
        generate_codes(avctx, s->he[i], i);
556
557
17.5k
    for (int i = 0; i < s->nb_slices; ++i) {
558
22.4k
        for (int j = 0; j < s->planes; ++j) {
559
13.6k
            Slice *const sl = &s->slices[i * s->planes + j];
560
13.6k
            int64_t size = 0;
561
562
3.51M
            for (size_t k = 0; k < FF_ARRAY_ELEMS(sl->counts); ++k)
563
3.49M
                size += sl->counts[k] * s->he[j][k].len;
564
13.6k
            size = AV_CEIL_RSHIFT(size, 3);
565
13.6k
            sl->encode_raw = size >= sl->width * sl->height;
566
13.6k
            if (sl->encode_raw)
567
6.87k
                size = sl->width * sl->height;
568
13.6k
            sl->size = FFALIGN(size + 2, 4);
569
13.6k
            sl->pos  = pkt_size;
570
13.6k
            pkt_size += sl->size;
571
13.6k
        }
572
8.78k
    }
573
574
8.78k
    ret = ff_get_encode_buffer(avctx, pkt, pkt_size, 0);
575
8.78k
    if (ret < 0)
576
0
        return ret;
577
578
8.78k
    bytestream2_init_writer(&pb, pkt->data, pkt->size);
579
8.78k
    bytestream2_put_le32u(&pb, MKTAG('M', 'A', 'G', 'Y'));
580
8.78k
    bytestream2_put_le32u(&pb, 32); // header size
581
8.78k
    bytestream2_put_byteu(&pb, 7);  // version
582
8.78k
    bytestream2_put_byteu(&pb, s->format);
583
8.78k
    bytestream2_put_byteu(&pb, 12); // max huffman length
584
8.78k
    bytestream2_put_byteu(&pb, 0);
585
586
8.78k
    bytestream2_put_byteu(&pb, 0);
587
8.78k
    bytestream2_put_byteu(&pb, 0);
588
8.78k
    bytestream2_put_byteu(&pb, 32); // coder type
589
8.78k
    bytestream2_put_byteu(&pb, 0);
590
591
8.78k
    bytestream2_put_le32u(&pb, avctx->width);
592
8.78k
    bytestream2_put_le32u(&pb, avctx->height);
593
8.78k
    bytestream2_put_le32u(&pb, avctx->width);
594
8.78k
    bytestream2_put_le32u(&pb, s->slice_height);
595
596
    // Slice position is relative to the current position (i.e. 32)
597
8.78k
    bytestream2_put_le32u(&pb, header_size - 32);
598
599
22.4k
    for (int i = 0; i < s->planes; ++i) {
600
27.3k
        for (int j = 0; j < s->nb_slices; ++j) {
601
13.6k
            Slice *const sl = &s->slices[j * s->planes + i];
602
13.6k
            bytestream2_put_le32u(&pb, sl->pos - 32);
603
13.6k
            sl->dst    = pkt->data + sl->pos;
604
13.6k
        }
605
13.6k
    }
606
607
8.78k
    bytestream2_put_byteu(&pb, s->planes);
608
609
22.4k
    for (int i = 0; i < s->planes; i++) {
610
27.3k
        for (int n = 0; n < s->nb_slices; n++)
611
13.6k
            bytestream2_put_byteu(&pb, n * s->planes + i);
612
13.6k
    }
613
614
22.4k
    for (int i = 0; i < s->planes; ++i)
615
13.6k
        output_codes(&pb, s->he[i]);
616
617
8.78k
    avctx->execute2(avctx, encode_slice, NULL, NULL, s->nb_slices);
618
619
8.78k
    *got_packet = 1;
620
621
8.78k
    return 0;
622
8.78k
}
623
624
static av_cold int magy_encode_close(AVCodecContext *avctx)
625
372
{
626
372
    MagicYUVContext *s = avctx->priv_data;
627
628
372
    if (s->slices) {
629
1.37k
        for (int i = 0; i < s->planes * s->nb_slices; i++) {
630
998
            Slice *sl = &s->slices[i];
631
632
998
            av_freep(&sl->slice);
633
998
        }
634
372
        av_freep(&s->slices);
635
372
    }
636
372
    av_freep(&s->decorrelate_buf);
637
638
372
    return 0;
639
372
}
640
641
#define OFFSET(x) offsetof(MagicYUVContext, x)
642
#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
643
static const AVOption options[] = {
644
    { "pred", "Prediction method", OFFSET(frame_pred), AV_OPT_TYPE_INT, {.i64=LEFT}, LEFT, MEDIAN, VE, .unit = "pred" },
645
    { "left",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = LEFT },     0, 0, VE, .unit = "pred" },
646
    { "gradient", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = GRADIENT }, 0, 0, VE, .unit = "pred" },
647
    { "median",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = MEDIAN },   0, 0, VE, .unit = "pred" },
648
    { NULL},
649
};
650
651
static const AVClass magicyuv_class = {
652
    .class_name = "magicyuv",
653
    .item_name  = av_default_item_name,
654
    .option     = options,
655
    .version    = LIBAVUTIL_VERSION_INT,
656
};
657
658
const FFCodec ff_magicyuv_encoder = {
659
    .p.name           = "magicyuv",
660
    CODEC_LONG_NAME("MagicYUV video"),
661
    .p.type           = AVMEDIA_TYPE_VIDEO,
662
    .p.id             = AV_CODEC_ID_MAGICYUV,
663
    .p.capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
664
                        AV_CODEC_CAP_SLICE_THREADS |
665
                        AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE,
666
    .priv_data_size   = sizeof(MagicYUVContext),
667
    .p.priv_class     = &magicyuv_class,
668
    .init             = magy_encode_init,
669
    .close            = magy_encode_close,
670
    FF_CODEC_ENCODE_CB(magy_encode_frame),
671
    CODEC_PIXFMTS(AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP, AV_PIX_FMT_YUV422P,
672
                  AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVA444P,
673
                  AV_PIX_FMT_GRAY8),
674
    .color_ranges     = AVCOL_RANGE_MPEG, /* FIXME: implement tagging */
675
    .caps_internal    = FF_CODEC_CAP_INIT_CLEANUP,
676
};