]> git.sesse.net Git - ffmpeg/blob - libavcodec/qtrleenc.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / qtrleenc.c
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 "avcodec.h"
27 #include "bytestream.h"
28 #include "internal.h"
29
30 /** Maximum RLE code for bulk copy */
31 #define MAX_RLE_BULK   127
32 /** Maximum RLE code for repeat */
33 #define MAX_RLE_REPEAT 128
34 /** Maximum RLE code for skip */
35 #define MAX_RLE_SKIP   254
36
37 typedef struct QtrleEncContext {
38     AVCodecContext *avctx;
39     AVFrame frame;
40     int pixel_size;
41     AVPicture previous_frame;
42     unsigned int max_buf_size;
43     int logical_width;
44     /**
45      * This array will contain at ith position the value of the best RLE code
46      * if the line started at pixel i
47      * There can be 3 values :
48      * skip (0)     : skip as much as possible pixels because they are equal to the
49      *                previous frame ones
50      * repeat (<-1) : repeat that pixel -rle_code times, still as much as
51      *                possible
52      * copy (>0)    : copy the raw next rle_code pixels */
53     signed char *rlecode_table;
54     /**
55      * This array will contain the length of the best rle encoding of the line
56      * starting at ith pixel */
57     int *length_table;
58     /**
59      * Will contain at ith position the number of consecutive pixels equal to the previous
60      * frame starting from pixel i */
61     uint8_t* skip_table;
62 } QtrleEncContext;
63
64 static av_cold int qtrle_encode_init(AVCodecContext *avctx)
65 {
66     QtrleEncContext *s = avctx->priv_data;
67
68     if (av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0) {
69         return -1;
70     }
71     s->avctx=avctx;
72     s->logical_width=avctx->width;
73
74     switch (avctx->pix_fmt) {
75     case PIX_FMT_GRAY8:
76         s->logical_width = avctx->width / 4;
77         s->pixel_size = 4;
78         break;
79     case PIX_FMT_RGB555BE:
80         s->pixel_size = 2;
81         break;
82     case PIX_FMT_RGB24:
83         s->pixel_size = 3;
84         break;
85     case PIX_FMT_ARGB:
86         s->pixel_size = 4;
87         break;
88     default:
89         av_log(avctx, AV_LOG_ERROR, "Unsupported colorspace.\n");
90         break;
91     }
92     avctx->bits_per_coded_sample = avctx->pix_fmt == PIX_FMT_GRAY8 ? 40 : s->pixel_size*8;
93
94     s->rlecode_table = av_mallocz(s->logical_width);
95     s->skip_table    = av_mallocz(s->logical_width);
96     s->length_table  = av_mallocz((s->logical_width + 1)*sizeof(int));
97     if (!s->skip_table || !s->length_table || !s->rlecode_table) {
98         av_log(avctx, AV_LOG_ERROR, "Error allocating memory.\n");
99         return -1;
100     }
101     if (avpicture_alloc(&s->previous_frame, avctx->pix_fmt, avctx->width, avctx->height) < 0) {
102         av_log(avctx, AV_LOG_ERROR, "Error allocating picture\n");
103         return -1;
104     }
105
106     s->max_buf_size = s->logical_width*s->avctx->height*s->pixel_size*2 /* image base material */
107                       + 15                                            /* header + footer */
108                       + s->avctx->height*2                            /* skip code+rle end */
109                       + s->logical_width/MAX_RLE_BULK + 1             /* rle codes */;
110     avctx->coded_frame = &s->frame;
111     return 0;
112 }
113
114 /**
115  * Compute the best RLE sequence for a line
116  */
117 static void qtrle_encode_line(QtrleEncContext *s, const AVFrame *p, int line, uint8_t **buf)
118 {
119     int width=s->logical_width;
120     int i;
121     signed char rlecode;
122
123     /* We will use it to compute the best bulk copy sequence */
124     unsigned int av_uninit(bulkcount);
125     /* This will be the number of pixels equal to the preivous frame one's
126      * starting from the ith pixel */
127     unsigned int skipcount;
128     /* This will be the number of consecutive equal pixels in the current
129      * frame, starting from the ith one also */
130     unsigned int av_uninit(repeatcount);
131
132     /* The cost of the three different possibilities */
133     int total_bulk_cost;
134     int total_skip_cost;
135     int total_repeat_cost;
136
137     int temp_cost;
138     int j;
139
140     uint8_t *this_line = p->               data[0] + line*p->               linesize[0] +
141         (width - 1)*s->pixel_size;
142     uint8_t *prev_line = s->previous_frame.data[0] + line*s->previous_frame.linesize[0] +
143         (width - 1)*s->pixel_size;
144
145     s->length_table[width] = 0;
146     skipcount = 0;
147
148     for (i = width - 1; i >= 0; i--) {
149
150         if (!s->frame.key_frame && !memcmp(this_line, prev_line, s->pixel_size))
151             skipcount = FFMIN(skipcount + 1, MAX_RLE_SKIP);
152         else
153             skipcount = 0;
154
155         total_skip_cost  = s->length_table[i + skipcount] + 2;
156         s->skip_table[i] = skipcount;
157
158
159         if (i < width - 1 && !memcmp(this_line, this_line + s->pixel_size, s->pixel_size))
160             repeatcount = FFMIN(repeatcount + 1, MAX_RLE_REPEAT);
161         else
162             repeatcount = 1;
163
164         total_repeat_cost = s->length_table[i + repeatcount] + 1 + s->pixel_size;
165
166         /* skip code is free for the first pixel, it costs one byte for repeat and bulk copy
167          * so let's make it aware */
168         if (i == 0) {
169             total_skip_cost--;
170             total_repeat_cost++;
171         }
172
173         if (repeatcount > 1 && (skipcount == 0 || total_repeat_cost < total_skip_cost)) {
174             /* repeat is the best */
175             s->length_table[i]  = total_repeat_cost;
176             s->rlecode_table[i] = -repeatcount;
177         }
178         else if (skipcount > 0) {
179             /* skip is the best choice here */
180             s->length_table[i]  = total_skip_cost;
181             s->rlecode_table[i] = 0;
182         }
183         else {
184             /* We cannot do neither skip nor repeat
185              * thus we search for the best bulk copy to do */
186
187             int limit = FFMIN(width - i, MAX_RLE_BULK);
188
189             temp_cost = 1 + s->pixel_size + !i;
190             total_bulk_cost = INT_MAX;
191
192             for (j = 1; j <= limit; j++) {
193                 if (s->length_table[i + j] + temp_cost < total_bulk_cost) {
194                     /* We have found a better bulk copy ... */
195                     total_bulk_cost = s->length_table[i + j] + temp_cost;
196                     bulkcount = j;
197                 }
198                 temp_cost += s->pixel_size;
199             }
200
201             s->length_table[i]  = total_bulk_cost;
202             s->rlecode_table[i] = bulkcount;
203         }
204
205         this_line -= s->pixel_size;
206         prev_line -= s->pixel_size;
207     }
208
209     /* Good ! Now we have the best sequence for this line, let's output it */
210
211     /* We do a special case for the first pixel so that we avoid testing it in
212      * the whole loop */
213
214     i=0;
215     this_line = p->               data[0] + line*p->linesize[0];
216
217     if (s->rlecode_table[0] == 0) {
218         bytestream_put_byte(buf, s->skip_table[0] + 1);
219         i += s->skip_table[0];
220     }
221     else bytestream_put_byte(buf, 1);
222
223
224     while (i < width) {
225         rlecode = s->rlecode_table[i];
226         bytestream_put_byte(buf, rlecode);
227         if (rlecode == 0) {
228             /* Write a skip sequence */
229             bytestream_put_byte(buf, s->skip_table[i] + 1);
230             i += s->skip_table[i];
231         }
232         else if (rlecode > 0) {
233             /* bulk copy */
234             if (s->avctx->pix_fmt == PIX_FMT_GRAY8) {
235                 int j;
236                 // QT grayscale colorspace has 0=white and 255=black, we will
237                 // ignore the palette that is included in the AVFrame because
238                 // PIX_FMT_GRAY8 has defined color mapping
239                 for (j = 0; j < rlecode*s->pixel_size; ++j)
240                     bytestream_put_byte(buf, *(this_line + i*s->pixel_size + j) ^ 0xff);
241             } else {
242                 bytestream_put_buffer(buf, this_line + i*s->pixel_size, rlecode*s->pixel_size);
243             }
244             i += rlecode;
245         }
246         else {
247             /* repeat the bits */
248             if (s->avctx->pix_fmt == PIX_FMT_GRAY8) {
249                 int j;
250                 // QT grayscale colorspace has 0=white and 255=black, ...
251                 for (j = 0; j < s->pixel_size; ++j)
252                     bytestream_put_byte(buf, *(this_line + i*s->pixel_size + j) ^ 0xff);
253             } else {
254                 bytestream_put_buffer(buf, this_line + i*s->pixel_size, s->pixel_size);
255             }
256             i -= rlecode;
257         }
258     }
259     bytestream_put_byte(buf, -1); // end RLE line
260 }
261
262 /** Encode frame including header */
263 static int encode_frame(QtrleEncContext *s, const AVFrame *p, uint8_t *buf)
264 {
265     int i;
266     int start_line = 0;
267     int end_line = s->avctx->height;
268     uint8_t *orig_buf = buf;
269
270     if (!s->frame.key_frame) {
271         unsigned line_size = s->logical_width * s->pixel_size;
272         for (start_line = 0; start_line < s->avctx->height; start_line++)
273             if (memcmp(p->data[0] + start_line*p->linesize[0],
274                        s->previous_frame.data[0] + start_line*s->previous_frame.linesize[0],
275                        line_size))
276                 break;
277
278         for (end_line=s->avctx->height; end_line > start_line; end_line--)
279             if (memcmp(p->data[0] + (end_line - 1)*p->linesize[0],
280                        s->previous_frame.data[0] + (end_line - 1)*s->previous_frame.linesize[0],
281                        line_size))
282                 break;
283     }
284
285     bytestream_put_be32(&buf, 0);                         // CHUNK SIZE, patched later
286
287     if ((start_line == 0 && end_line == s->avctx->height) || start_line == s->avctx->height)
288         bytestream_put_be16(&buf, 0);                     // header
289     else {
290         bytestream_put_be16(&buf, 8);                     // header
291         bytestream_put_be16(&buf, start_line);            // starting line
292         bytestream_put_be16(&buf, 0);                     // unknown
293         bytestream_put_be16(&buf, end_line - start_line); // lines to update
294         bytestream_put_be16(&buf, 0);                     // unknown
295     }
296     for (i = start_line; i < end_line; i++)
297         qtrle_encode_line(s, p, i, &buf);
298
299     bytestream_put_byte(&buf, 0);                         // zero skip code = frame finished
300     AV_WB32(orig_buf, buf - orig_buf);                    // patch the chunk size
301     return buf - orig_buf;
302 }
303
304 static int qtrle_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
305                               const AVFrame *pict, int *got_packet)
306 {
307     QtrleEncContext * const s = avctx->priv_data;
308     AVFrame * const p = &s->frame;
309     int ret;
310
311     *p = *pict;
312
313     if ((ret = ff_alloc_packet(pkt, s->max_buf_size)) < 0) {
314         /* Upper bound check for compressed data */
315         av_log(avctx, AV_LOG_ERROR, "Error getting output packet of size %d.\n", s->max_buf_size);
316         return ret;
317     }
318
319     if (avctx->gop_size == 0 || (s->avctx->frame_number % avctx->gop_size) == 0) {
320         /* I-Frame */
321         p->pict_type = AV_PICTURE_TYPE_I;
322         p->key_frame = 1;
323     } else {
324         /* P-Frame */
325         p->pict_type = AV_PICTURE_TYPE_P;
326         p->key_frame = 0;
327     }
328
329     pkt->size = encode_frame(s, pict, pkt->data);
330
331     /* save the current frame */
332     av_picture_copy(&s->previous_frame, (AVPicture *)p, avctx->pix_fmt, avctx->width, avctx->height);
333
334     if (p->key_frame)
335         pkt->flags |= AV_PKT_FLAG_KEY;
336     *got_packet = 1;
337
338     return 0;
339 }
340
341 static av_cold int qtrle_encode_end(AVCodecContext *avctx)
342 {
343     QtrleEncContext *s = avctx->priv_data;
344
345     avpicture_free(&s->previous_frame);
346     av_free(s->rlecode_table);
347     av_free(s->length_table);
348     av_free(s->skip_table);
349     return 0;
350 }
351
352 AVCodec ff_qtrle_encoder = {
353     .name           = "qtrle",
354     .type           = AVMEDIA_TYPE_VIDEO,
355     .id             = CODEC_ID_QTRLE,
356     .priv_data_size = sizeof(QtrleEncContext),
357     .init           = qtrle_encode_init,
358     .encode2        = qtrle_encode_frame,
359     .close          = qtrle_encode_end,
360     .pix_fmts = (const enum PixelFormat[]){PIX_FMT_RGB24, PIX_FMT_RGB555BE, PIX_FMT_ARGB, PIX_FMT_GRAY8, PIX_FMT_NONE},
361     .long_name = NULL_IF_CONFIG_SMALL("QuickTime Animation (RLE) video"),
362 };