Coverage Report

Created: 2026-02-14 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/qtrleenc.c
Line
Count
Source
1
/*
2
 * Quicktime Animation (RLE) Video Encoder
3
 * Copyright (C) 2007 Clemens Fruhwirth
4
 * Copyright (C) 2007 Alexis Ballier
5
 *
6
 * This file is based on flashsvenc.c.
7
 *
8
 * This file is part of FFmpeg.
9
 *
10
 * FFmpeg is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public
12
 * License as published by the Free Software Foundation; either
13
 * version 2.1 of the License, or (at your option) any later version.
14
 *
15
 * FFmpeg is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with FFmpeg; if not, write to the Free Software
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23
 */
24
25
#include "libavutil/imgutils.h"
26
#include "libavutil/mem.h"
27
#include "avcodec.h"
28
#include "bytestream.h"
29
#include "codec_internal.h"
30
#include "encode.h"
31
32
/** Maximum RLE code for bulk copy */
33
491
#define MAX_RLE_BULK   127
34
/** Maximum RLE code for repeat */
35
#define MAX_RLE_REPEAT 128
36
/** Maximum RLE code for skip */
37
#define MAX_RLE_SKIP   254
38
39
typedef struct QtrleEncContext {
40
    AVCodecContext *avctx;
41
    int pixel_size;
42
    AVFrame *previous_frame;
43
    unsigned int max_buf_size;
44
    int logical_width;
45
    /**
46
     * This array will contain at ith position the value of the best RLE code
47
     * if the line started at pixel i
48
     * There can be 3 values :
49
     * skip (0)     : skip as much as possible pixels because they are equal to the
50
     *                previous frame ones
51
     * repeat (<-1) : repeat that pixel -rle_code times, still as much as
52
     *                possible
53
     * copy (>0)    : copy the raw next rle_code pixels */
54
    signed char *rlecode_table;
55
    /**
56
     * This array will contain the length of the best rle encoding of the line
57
     * starting at ith pixel */
58
    int *length_table;
59
    /**
60
     * Will contain at ith position the number of consecutive pixels equal to the previous
61
     * frame starting from pixel i */
62
    uint8_t* skip_table;
63
64
    /** Encoded frame is a key frame */
65
    int key_frame;
66
} QtrleEncContext;
67
68
static av_cold int qtrle_encode_end(AVCodecContext *avctx)
69
493
{
70
493
    QtrleEncContext *s = avctx->priv_data;
71
72
493
    av_frame_free(&s->previous_frame);
73
493
    av_free(s->rlecode_table);
74
493
    av_free(s->length_table);
75
493
    av_free(s->skip_table);
76
493
    return 0;
77
493
}
78
79
static av_cold int qtrle_encode_init(AVCodecContext *avctx)
80
493
{
81
493
    QtrleEncContext *s = avctx->priv_data;
82
83
493
    if (av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0) {
84
0
        return AVERROR(EINVAL);
85
0
    }
86
493
    s->avctx=avctx;
87
493
    s->logical_width=avctx->width;
88
89
493
    switch (avctx->pix_fmt) {
90
49
    case AV_PIX_FMT_GRAY8:
91
49
        if (avctx->width % 4) {
92
2
            av_log(avctx, AV_LOG_ERROR, "Width not being a multiple of 4 is not supported\n");
93
2
            return AVERROR(EINVAL);
94
2
        }
95
47
        s->logical_width = avctx->width / 4;
96
47
        s->pixel_size = 4;
97
47
        break;
98
170
    case AV_PIX_FMT_RGB555BE:
99
170
        s->pixel_size = 2;
100
170
        break;
101
77
    case AV_PIX_FMT_RGB24:
102
77
        s->pixel_size = 3;
103
77
        break;
104
197
    case AV_PIX_FMT_ARGB:
105
197
        s->pixel_size = 4;
106
197
        break;
107
0
    default:
108
0
        av_log(avctx, AV_LOG_ERROR, "Unsupported colorspace.\n");
109
0
        break;
110
493
    }
111
491
    avctx->bits_per_coded_sample = avctx->pix_fmt == AV_PIX_FMT_GRAY8 ? 40 : s->pixel_size*8;
112
113
491
    s->rlecode_table = av_mallocz(s->logical_width);
114
491
    s->skip_table    = av_mallocz(s->logical_width);
115
491
    s->length_table  = av_calloc(s->logical_width + 1, sizeof(*s->length_table));
116
491
    if (!s->skip_table || !s->length_table || !s->rlecode_table) {
117
0
        av_log(avctx, AV_LOG_ERROR, "Error allocating memory.\n");
118
0
        return AVERROR(ENOMEM);
119
0
    }
120
491
    s->previous_frame = av_frame_alloc();
121
491
    if (!s->previous_frame) {
122
0
        av_log(avctx, AV_LOG_ERROR, "Error allocating picture\n");
123
0
        return AVERROR(ENOMEM);
124
0
    }
125
126
491
    s->max_buf_size = s->logical_width*s->avctx->height*s->pixel_size*2 /* image base material */
127
491
                      + 15                                            /* header + footer */
128
491
                      + s->avctx->height*2                            /* skip code+rle end */
129
491
                      + s->logical_width/MAX_RLE_BULK + 1             /* rle codes */;
130
131
491
    return 0;
132
491
}
133
134
/**
135
 * Compute the best RLE sequence for a line
136
 */
137
static void qtrle_encode_line(QtrleEncContext *s, const AVFrame *p, int line, uint8_t **buf)
138
1.61M
{
139
1.61M
    int width=s->logical_width;
140
1.61M
    int i;
141
1.61M
    signed char rlecode;
142
143
    /* This will be the number of pixels equal to the previous frame one's
144
     * starting from the ith pixel */
145
1.61M
    unsigned int skipcount;
146
    /* This will be the number of consecutive equal pixels in the current
147
     * frame, starting from the ith one also */
148
1.61M
    unsigned int av_uninit(repeatcount);
149
150
    /* The cost of the three different possibilities */
151
1.61M
    int total_skip_cost;
152
1.61M
    int total_repeat_cost;
153
154
1.61M
    int base_bulk_cost;
155
1.61M
    int lowest_bulk_cost;
156
1.61M
    int lowest_bulk_cost_index;
157
1.61M
    int sec_lowest_bulk_cost;
158
1.61M
    int sec_lowest_bulk_cost_index;
159
160
1.61M
    const uint8_t *this_line = p->data[0] + line * p->linesize[0] + width * s->pixel_size;
161
    /* There might be no earlier frame if the current frame is a keyframe.
162
     * So just use a pointer to the current frame to avoid a check
163
     * to avoid NULL - s->pixel_size (which is undefined behaviour). */
164
1.61M
    const uint8_t *prev_line = s->key_frame ? this_line
165
1.61M
                                            : s->previous_frame->data[0]
166
156k
                                              + line * s->previous_frame->linesize[0]
167
156k
                                              + width * s->pixel_size;
168
169
1.61M
    s->length_table[width] = 0;
170
1.61M
    skipcount = 0;
171
172
    /* Initial values */
173
1.61M
    lowest_bulk_cost = INT_MAX / 2;
174
1.61M
    lowest_bulk_cost_index = width;
175
1.61M
    sec_lowest_bulk_cost = INT_MAX / 2;
176
1.61M
    sec_lowest_bulk_cost_index = width;
177
178
1.61M
    base_bulk_cost = 1 + s->pixel_size;
179
180
12.7M
    for (i = width - 1; i >= 0; i--) {
181
182
11.1M
        int prev_bulk_cost;
183
184
11.1M
        this_line -= s->pixel_size;
185
11.1M
        prev_line -= s->pixel_size;
186
187
        /* If our lowest bulk cost index is too far away, replace it
188
         * with the next lowest bulk cost */
189
11.1M
        if (FFMIN(width, i + MAX_RLE_BULK) < lowest_bulk_cost_index) {
190
421
            lowest_bulk_cost = sec_lowest_bulk_cost;
191
421
            lowest_bulk_cost_index = sec_lowest_bulk_cost_index;
192
193
421
            sec_lowest_bulk_cost = INT_MAX / 2;
194
421
            sec_lowest_bulk_cost_index = width;
195
421
        }
196
197
        /* Deal with the first pixel's bulk cost */
198
11.1M
        if (!i) {
199
1.61M
            base_bulk_cost++;
200
1.61M
            lowest_bulk_cost++;
201
1.61M
            sec_lowest_bulk_cost++;
202
1.61M
        }
203
204
        /* Look at the bulk cost of the previous loop and see if it is
205
         * a new lower bulk cost */
206
11.1M
        prev_bulk_cost = s->length_table[i + 1] + base_bulk_cost;
207
11.1M
        if (prev_bulk_cost <= sec_lowest_bulk_cost) {
208
            /* If it's lower than the 2nd lowest, then it may be lower
209
             * than the lowest */
210
11.1M
            if (prev_bulk_cost <= lowest_bulk_cost) {
211
212
                /* If we have found a new lowest bulk cost,
213
                 * then the 2nd lowest bulk cost is now farther than the
214
                 * lowest bulk cost, and will never be used */
215
9.93M
                sec_lowest_bulk_cost = INT_MAX / 2;
216
217
9.93M
                lowest_bulk_cost = prev_bulk_cost;
218
9.93M
                lowest_bulk_cost_index = i + 1;
219
9.93M
            } else {
220
                /* Then it must be the 2nd lowest bulk cost */
221
1.19M
                sec_lowest_bulk_cost = prev_bulk_cost;
222
1.19M
                sec_lowest_bulk_cost_index = i + 1;
223
1.19M
            }
224
11.1M
        }
225
226
11.1M
        if (!s->key_frame && !memcmp(this_line, prev_line, s->pixel_size))
227
269k
            skipcount = FFMIN(skipcount + 1, MAX_RLE_SKIP);
228
10.8M
        else
229
10.8M
            skipcount = 0;
230
231
11.1M
        total_skip_cost  = s->length_table[i + skipcount] + 2;
232
11.1M
        s->skip_table[i] = skipcount;
233
234
235
11.1M
        if (i < width - 1 && !memcmp(this_line, this_line + s->pixel_size, s->pixel_size))
236
9.01M
            repeatcount = FFMIN(repeatcount + 1, MAX_RLE_REPEAT);
237
2.11M
        else
238
2.11M
            repeatcount = 1;
239
240
11.1M
        total_repeat_cost = s->length_table[i + repeatcount] + 1 + s->pixel_size;
241
242
        /* skip code is free for the first pixel, it costs one byte for repeat and bulk copy
243
         * so let's make it aware */
244
11.1M
        if (i == 0) {
245
1.61M
            total_skip_cost--;
246
1.61M
            total_repeat_cost++;
247
1.61M
        }
248
249
11.1M
        if (repeatcount > 1 && (skipcount == 0 || total_repeat_cost < total_skip_cost)) {
250
            /* repeat is the best */
251
8.83M
            s->length_table[i]  = total_repeat_cost;
252
8.83M
            s->rlecode_table[i] = -repeatcount;
253
8.83M
        }
254
2.29M
        else if (skipcount > 0) {
255
            /* skip is the best choice here */
256
233k
            s->length_table[i]  = total_skip_cost;
257
233k
            s->rlecode_table[i] = 0;
258
233k
        }
259
2.06M
        else {
260
            /* We cannot do neither skip nor repeat
261
             * thus we use the best bulk copy  */
262
263
2.06M
            s->length_table[i]  = lowest_bulk_cost;
264
2.06M
            s->rlecode_table[i] = lowest_bulk_cost_index - i;
265
266
2.06M
        }
267
268
        /* These bulk costs increase every iteration */
269
11.1M
        lowest_bulk_cost += s->pixel_size;
270
11.1M
        sec_lowest_bulk_cost += s->pixel_size;
271
11.1M
    }
272
273
    /* Good! Now we have the best sequence for this line, let's output it. */
274
275
    /* We do a special case for the first pixel so that we avoid testing it in
276
     * the whole loop */
277
278
1.61M
    i=0;
279
1.61M
    this_line = p->               data[0] + line*p->linesize[0];
280
281
1.61M
    if (s->rlecode_table[0] == 0) {
282
43.0k
        bytestream_put_byte(buf, s->skip_table[0] + 1);
283
43.0k
        i += s->skip_table[0];
284
43.0k
    }
285
1.57M
    else bytestream_put_byte(buf, 1);
286
287
288
3.34M
    while (i < width) {
289
1.72M
        rlecode = s->rlecode_table[i];
290
1.72M
        bytestream_put_byte(buf, rlecode);
291
1.72M
        if (rlecode == 0) {
292
            /* Write a skip sequence */
293
7.17k
            bytestream_put_byte(buf, s->skip_table[i] + 1);
294
7.17k
            i += s->skip_table[i];
295
7.17k
        }
296
1.71M
        else if (rlecode > 0) {
297
            /* bulk copy */
298
975k
            if (s->avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
299
73.9k
                int j;
300
                // QT grayscale colorspace has 0=white and 255=black, we will
301
                // ignore the palette that is included in the AVFrame because
302
                // AV_PIX_FMT_GRAY8 has defined color mapping
303
453k
                for (j = 0; j < rlecode*s->pixel_size; ++j)
304
379k
                    bytestream_put_byte(buf, *(this_line + i*s->pixel_size + j) ^ 0xff);
305
901k
            } else {
306
901k
                bytestream_put_buffer(buf, this_line + i*s->pixel_size, rlecode*s->pixel_size);
307
901k
            }
308
975k
            i += rlecode;
309
975k
        }
310
743k
        else {
311
            /* repeat the bits */
312
743k
            if (s->avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
313
57.7k
                int j;
314
                // QT grayscale colorspace has 0=white and 255=black, ...
315
288k
                for (j = 0; j < s->pixel_size; ++j)
316
231k
                    bytestream_put_byte(buf, *(this_line + i*s->pixel_size + j) ^ 0xff);
317
685k
            } else {
318
685k
                bytestream_put_buffer(buf, this_line + i*s->pixel_size, s->pixel_size);
319
685k
            }
320
743k
            i -= rlecode;
321
743k
        }
322
1.72M
    }
323
1.61M
    bytestream_put_byte(buf, -1); // end RLE line
324
1.61M
}
325
326
/** Encode frame including header */
327
static int encode_frame(QtrleEncContext *s, const AVFrame *p, uint8_t *buf)
328
10.7k
{
329
10.7k
    int i;
330
10.7k
    int start_line = 0;
331
10.7k
    int end_line = s->avctx->height;
332
10.7k
    uint8_t *orig_buf = buf;
333
334
10.7k
    if (!s->key_frame) {
335
8.21k
        unsigned line_size = s->logical_width * s->pixel_size;
336
40.8k
        for (start_line = 0; start_line < s->avctx->height; start_line++)
337
38.8k
            if (memcmp(p->data[0] + start_line*p->linesize[0],
338
38.8k
                       s->previous_frame->data[0] + start_line * s->previous_frame->linesize[0],
339
38.8k
                       line_size))
340
6.21k
                break;
341
342
22.6k
        for (end_line=s->avctx->height; end_line > start_line; end_line--)
343
20.6k
            if (memcmp(p->data[0] + (end_line - 1)*p->linesize[0],
344
20.6k
                       s->previous_frame->data[0] + (end_line - 1) * s->previous_frame->linesize[0],
345
20.6k
                       line_size))
346
6.21k
                break;
347
8.21k
    }
348
349
10.7k
    bytestream_put_be32(&buf, 0);                         // CHUNK SIZE, patched later
350
351
10.7k
    if ((start_line == 0 && end_line == s->avctx->height) || start_line == s->avctx->height)
352
7.23k
        bytestream_put_be16(&buf, 0);                     // header
353
3.52k
    else {
354
3.52k
        bytestream_put_be16(&buf, 8);                     // header
355
3.52k
        bytestream_put_be16(&buf, start_line);            // starting line
356
3.52k
        bytestream_put_be16(&buf, 0);                     // unknown
357
3.52k
        bytestream_put_be16(&buf, end_line - start_line); // lines to update
358
3.52k
        bytestream_put_be16(&buf, 0);                     // unknown
359
3.52k
    }
360
1.62M
    for (i = start_line; i < end_line; i++)
361
1.61M
        qtrle_encode_line(s, p, i, &buf);
362
363
10.7k
    bytestream_put_byte(&buf, 0);                         // zero skip code = frame finished
364
10.7k
    AV_WB32(orig_buf, buf - orig_buf);                    // patch the chunk size
365
10.7k
    return buf - orig_buf;
366
10.7k
}
367
368
static int qtrle_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
369
                              const AVFrame *pict, int *got_packet)
370
10.7k
{
371
10.7k
    QtrleEncContext * const s = avctx->priv_data;
372
10.7k
    int ret;
373
374
10.7k
    if ((ret = ff_alloc_packet(avctx, pkt, s->max_buf_size)) < 0)
375
0
        return ret;
376
377
10.7k
    if (avctx->gop_size == 0 || !s->previous_frame->data[0] ||
378
8.61k
        (s->avctx->frame_num % avctx->gop_size) == 0) {
379
        /* I-Frame */
380
2.55k
        s->key_frame = 1;
381
8.21k
    } else {
382
        /* P-Frame */
383
8.21k
        s->key_frame = 0;
384
8.21k
    }
385
386
10.7k
    pkt->size = encode_frame(s, pict, pkt->data);
387
388
    /* save the current frame */
389
10.7k
    ret = av_frame_replace(s->previous_frame, pict);
390
10.7k
    if (ret < 0) {
391
0
        av_log(avctx, AV_LOG_ERROR, "cannot add reference\n");
392
0
        return ret;
393
0
    }
394
395
10.7k
    if (s->key_frame)
396
2.55k
        pkt->flags |= AV_PKT_FLAG_KEY;
397
10.7k
    *got_packet = 1;
398
399
10.7k
    return 0;
400
10.7k
}
401
402
const FFCodec ff_qtrle_encoder = {
403
    .p.name         = "qtrle",
404
    CODEC_LONG_NAME("QuickTime Animation (RLE) video"),
405
    .p.type         = AVMEDIA_TYPE_VIDEO,
406
    .p.id           = AV_CODEC_ID_QTRLE,
407
    .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE,
408
    .priv_data_size = sizeof(QtrleEncContext),
409
    .init           = qtrle_encode_init,
410
    FF_CODEC_ENCODE_CB(qtrle_encode_frame),
411
    .close          = qtrle_encode_end,
412
    CODEC_PIXFMTS(AV_PIX_FMT_RGB24, AV_PIX_FMT_RGB555BE, AV_PIX_FMT_ARGB,
413
                  AV_PIX_FMT_GRAY8),
414
    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
415
};