]> git.sesse.net Git - ffmpeg/blob - libavcodec/iff.c
avcodec/dsd: Fix "warning: ctables defined but not used [-Wunused-variable]"
[ffmpeg] / libavcodec / iff.c
1 /*
2  * IFF ACBM/ANIM/DEEP/ILBM/PBM bitmap decoder
3  * Copyright (c) 2010 Peter Ross <pross@xvid.org>
4  * Copyright (c) 2010 Sebastian Vater <cdgs.basty@googlemail.com>
5  * Copyright (c) 2016 Paul B Mahol
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 /**
25  * @file
26  * IFF ACBM/ANIM/DEEP/ILBM/PBM bitmap decoder
27  */
28
29 #include <stdint.h>
30
31 #include "libavutil/imgutils.h"
32 #include "bytestream.h"
33 #include "avcodec.h"
34 #include "internal.h"
35 #include "mathops.h"
36
37 // TODO: masking bits
38 typedef enum {
39     MASK_NONE,
40     MASK_HAS_MASK,
41     MASK_HAS_TRANSPARENT_COLOR,
42     MASK_LASSO
43 } mask_type;
44
45 typedef struct IffContext {
46     AVFrame *frame;
47     int planesize;
48     uint8_t * planebuf;
49     uint8_t * ham_buf;      ///< temporary buffer for planar to chunky conversation
50     uint32_t *ham_palbuf;   ///< HAM decode table
51     uint32_t *mask_buf;     ///< temporary buffer for palette indices
52     uint32_t *mask_palbuf;  ///< masking palette table
53     unsigned  compression;  ///< delta compression method used
54     unsigned  is_short;     ///< short compression method used
55     unsigned  bpp;          ///< bits per plane to decode (differs from bits_per_coded_sample if HAM)
56     unsigned  ham;          ///< 0 if non-HAM or number of hold bits (6 for bpp > 6, 4 otherwise)
57     unsigned  flags;        ///< 1 for EHB, 0 is no extra half darkening
58     unsigned  transparency; ///< TODO: transparency color index in palette
59     unsigned  masking;      ///< TODO: masking method used
60     int init; // 1 if buffer and palette data already initialized, 0 otherwise
61     int16_t   tvdc[16];     ///< TVDC lookup table
62     GetByteContext gb;
63     uint8_t *video[2];
64     unsigned video_size;
65     uint32_t *pal[2];
66     int first;
67 } IffContext;
68
69 #define LUT8_PART(plane, v)                             \
70     AV_LE2NE64C(UINT64_C(0x0000000)<<32 | v) << plane,  \
71     AV_LE2NE64C(UINT64_C(0x1000000)<<32 | v) << plane,  \
72     AV_LE2NE64C(UINT64_C(0x0010000)<<32 | v) << plane,  \
73     AV_LE2NE64C(UINT64_C(0x1010000)<<32 | v) << plane,  \
74     AV_LE2NE64C(UINT64_C(0x0000100)<<32 | v) << plane,  \
75     AV_LE2NE64C(UINT64_C(0x1000100)<<32 | v) << plane,  \
76     AV_LE2NE64C(UINT64_C(0x0010100)<<32 | v) << plane,  \
77     AV_LE2NE64C(UINT64_C(0x1010100)<<32 | v) << plane,  \
78     AV_LE2NE64C(UINT64_C(0x0000001)<<32 | v) << plane,  \
79     AV_LE2NE64C(UINT64_C(0x1000001)<<32 | v) << plane,  \
80     AV_LE2NE64C(UINT64_C(0x0010001)<<32 | v) << plane,  \
81     AV_LE2NE64C(UINT64_C(0x1010001)<<32 | v) << plane,  \
82     AV_LE2NE64C(UINT64_C(0x0000101)<<32 | v) << plane,  \
83     AV_LE2NE64C(UINT64_C(0x1000101)<<32 | v) << plane,  \
84     AV_LE2NE64C(UINT64_C(0x0010101)<<32 | v) << plane,  \
85     AV_LE2NE64C(UINT64_C(0x1010101)<<32 | v) << plane
86
87 #define LUT8(plane) {                           \
88     LUT8_PART(plane, 0x0000000),                \
89     LUT8_PART(plane, 0x1000000),                \
90     LUT8_PART(plane, 0x0010000),                \
91     LUT8_PART(plane, 0x1010000),                \
92     LUT8_PART(plane, 0x0000100),                \
93     LUT8_PART(plane, 0x1000100),                \
94     LUT8_PART(plane, 0x0010100),                \
95     LUT8_PART(plane, 0x1010100),                \
96     LUT8_PART(plane, 0x0000001),                \
97     LUT8_PART(plane, 0x1000001),                \
98     LUT8_PART(plane, 0x0010001),                \
99     LUT8_PART(plane, 0x1010001),                \
100     LUT8_PART(plane, 0x0000101),                \
101     LUT8_PART(plane, 0x1000101),                \
102     LUT8_PART(plane, 0x0010101),                \
103     LUT8_PART(plane, 0x1010101),                \
104 }
105
106 // 8 planes * 8-bit mask
107 static const uint64_t plane8_lut[8][256] = {
108     LUT8(0), LUT8(1), LUT8(2), LUT8(3),
109     LUT8(4), LUT8(5), LUT8(6), LUT8(7),
110 };
111
112 #define LUT32(plane) {                                \
113              0,          0,          0,          0,   \
114              0,          0,          0, 1 << plane,   \
115              0,          0, 1 << plane,          0,   \
116              0,          0, 1 << plane, 1 << plane,   \
117              0, 1 << plane,          0,          0,   \
118              0, 1 << plane,          0, 1 << plane,   \
119              0, 1 << plane, 1 << plane,          0,   \
120              0, 1 << plane, 1 << plane, 1 << plane,   \
121     1 << plane,          0,          0,          0,   \
122     1 << plane,          0,          0, 1 << plane,   \
123     1 << plane,          0, 1 << plane,          0,   \
124     1 << plane,          0, 1 << plane, 1 << plane,   \
125     1 << plane, 1 << plane,          0,          0,   \
126     1 << plane, 1 << plane,          0, 1 << plane,   \
127     1 << plane, 1 << plane, 1 << plane,          0,   \
128     1 << plane, 1 << plane, 1 << plane, 1 << plane,   \
129 }
130
131 // 32 planes * 4-bit mask * 4 lookup tables each
132 static const uint32_t plane32_lut[32][16*4] = {
133     LUT32( 0), LUT32( 1), LUT32( 2), LUT32( 3),
134     LUT32( 4), LUT32( 5), LUT32( 6), LUT32( 7),
135     LUT32( 8), LUT32( 9), LUT32(10), LUT32(11),
136     LUT32(12), LUT32(13), LUT32(14), LUT32(15),
137     LUT32(16), LUT32(17), LUT32(18), LUT32(19),
138     LUT32(20), LUT32(21), LUT32(22), LUT32(23),
139     LUT32(24), LUT32(25), LUT32(26), LUT32(27),
140     LUT32(28), LUT32(29), LUT32(30), LUT32(31),
141 };
142
143 // Gray to RGB, required for palette table of grayscale images with bpp < 8
144 static av_always_inline uint32_t gray2rgb(const uint32_t x) {
145     return x << 16 | x << 8 | x;
146 }
147
148 /**
149  * Convert CMAP buffer (stored in extradata) to lavc palette format
150  */
151 static int cmap_read_palette(AVCodecContext *avctx, uint32_t *pal)
152 {
153     IffContext *s = avctx->priv_data;
154     int count, i;
155     const uint8_t *const palette = avctx->extradata + AV_RB16(avctx->extradata);
156     int palette_size = avctx->extradata_size - AV_RB16(avctx->extradata);
157
158     if (avctx->bits_per_coded_sample > 8) {
159         av_log(avctx, AV_LOG_ERROR, "bits_per_coded_sample > 8 not supported\n");
160         return AVERROR_INVALIDDATA;
161     }
162
163     count = 1 << avctx->bits_per_coded_sample;
164     // If extradata is smaller than actually needed, fill the remaining with black.
165     count = FFMIN(palette_size / 3, count);
166     if (count) {
167         for (i = 0; i < count; i++)
168             pal[i] = 0xFF000000 | AV_RB24(palette + i*3);
169         if (s->flags && count >= 32) { // EHB
170             for (i = 0; i < 32; i++)
171                 pal[i + 32] = 0xFF000000 | (AV_RB24(palette + i*3) & 0xFEFEFE) >> 1;
172             count = FFMAX(count, 64);
173         }
174     } else { // Create gray-scale color palette for bps < 8
175         count = 1 << avctx->bits_per_coded_sample;
176
177         for (i = 0; i < count; i++)
178             pal[i] = 0xFF000000 | gray2rgb((i * 255) >> avctx->bits_per_coded_sample);
179     }
180     if (s->masking == MASK_HAS_MASK) {
181         memcpy(pal + (1 << avctx->bits_per_coded_sample), pal, count * 4);
182         for (i = 0; i < count; i++)
183             pal[i] &= 0xFFFFFF;
184     } else if (s->masking == MASK_HAS_TRANSPARENT_COLOR &&
185         s->transparency < 1 << avctx->bits_per_coded_sample)
186         pal[s->transparency] &= 0xFFFFFF;
187     return 0;
188 }
189
190 /**
191  * Extracts the IFF extra context and updates internal
192  * decoder structures.
193  *
194  * @param avctx the AVCodecContext where to extract extra context to
195  * @param avpkt the AVPacket to extract extra context from or NULL to use avctx
196  * @return >= 0 in case of success, a negative error code otherwise
197  */
198 static int extract_header(AVCodecContext *const avctx,
199                           const AVPacket *const avpkt)
200 {
201     IffContext *s = avctx->priv_data;
202     const uint8_t *buf;
203     unsigned buf_size = 0;
204     int i, palette_size;
205
206     if (avctx->extradata_size < 2) {
207         av_log(avctx, AV_LOG_ERROR, "not enough extradata\n");
208         return AVERROR_INVALIDDATA;
209     }
210     palette_size = avctx->extradata_size - AV_RB16(avctx->extradata);
211
212     if (avpkt && avctx->codec_tag == MKTAG('A', 'N', 'I', 'M')) {
213         uint32_t chunk_id;
214         uint64_t data_size;
215         GetByteContext *gb = &s->gb;
216
217         bytestream2_skip(gb, 4);
218         while (bytestream2_get_bytes_left(gb) >= 1) {
219             chunk_id  = bytestream2_get_le32(gb);
220             data_size = bytestream2_get_be32(gb);
221
222             if (chunk_id == MKTAG('B', 'M', 'H', 'D')) {
223                 bytestream2_skip(gb, data_size + (data_size & 1));
224             } else if (chunk_id == MKTAG('A', 'N', 'H', 'D')) {
225                 if (data_size < 40)
226                     return AVERROR_INVALIDDATA;
227
228                 s->compression = (bytestream2_get_byte(gb) << 8) | (s->compression & 0xFF);
229                 bytestream2_skip(gb, 19);
230                 s->is_short = !(bytestream2_get_be32(gb) & 1);
231                 data_size -= 24;
232                 bytestream2_skip(gb, data_size + (data_size & 1));
233             } else if (chunk_id == MKTAG('D', 'L', 'T', 'A') ||
234                        chunk_id == MKTAG('B', 'O', 'D', 'Y')) {
235                 if (chunk_id == MKTAG('B','O','D','Y'))
236                     s->compression &= 0xFF;
237                 break;
238             } else if (chunk_id == MKTAG('C', 'M', 'A', 'P')) {
239                 int count = data_size / 3;
240                 uint32_t *pal = s->pal[0];
241
242                 if (count > 256)
243                     return AVERROR_INVALIDDATA;
244                 if (s->ham) {
245                     for (i = 0; i < count; i++)
246                         pal[i] = 0xFF000000 | bytestream2_get_le24(gb);
247                 } else {
248                     for (i = 0; i < count; i++)
249                         pal[i] = 0xFF000000 | bytestream2_get_be24(gb);
250                 }
251                 bytestream2_skip(gb, data_size & 1);
252             } else {
253                 bytestream2_skip(gb, data_size + (data_size&1));
254             }
255         }
256     } else if (!avpkt) {
257         buf = avctx->extradata;
258         buf_size = bytestream_get_be16(&buf);
259         if (buf_size <= 1 || palette_size < 0) {
260             av_log(avctx, AV_LOG_ERROR,
261                    "Invalid palette size received: %u -> palette data offset: %d\n",
262                    buf_size, palette_size);
263             return AVERROR_INVALIDDATA;
264         }
265     }
266
267     if (buf_size >= 41) {
268         s->compression  = bytestream_get_byte(&buf);
269         s->bpp          = bytestream_get_byte(&buf);
270         s->ham          = bytestream_get_byte(&buf);
271         s->flags        = bytestream_get_byte(&buf);
272         s->transparency = bytestream_get_be16(&buf);
273         s->masking      = bytestream_get_byte(&buf);
274         for (i = 0; i < 16; i++)
275             s->tvdc[i] = bytestream_get_be16(&buf);
276
277         if (s->masking == MASK_HAS_MASK) {
278             if (s->bpp >= 8 && !s->ham) {
279                 avctx->pix_fmt = AV_PIX_FMT_RGB32;
280                 av_freep(&s->mask_buf);
281                 av_freep(&s->mask_palbuf);
282                 s->mask_buf = av_malloc((s->planesize * 32) + AV_INPUT_BUFFER_PADDING_SIZE);
283                 if (!s->mask_buf)
284                     return AVERROR(ENOMEM);
285                 if (s->bpp > 16) {
286                     av_log(avctx, AV_LOG_ERROR, "bpp %d too large for palette\n", s->bpp);
287                     av_freep(&s->mask_buf);
288                     return AVERROR(ENOMEM);
289                 }
290                 s->mask_palbuf = av_malloc((2 << s->bpp) * sizeof(uint32_t) + AV_INPUT_BUFFER_PADDING_SIZE);
291                 if (!s->mask_palbuf) {
292                     av_freep(&s->mask_buf);
293                     return AVERROR(ENOMEM);
294                 }
295             }
296             s->bpp++;
297         } else if (s->masking != MASK_NONE && s->masking != MASK_HAS_TRANSPARENT_COLOR) {
298             av_log(avctx, AV_LOG_ERROR, "Masking not supported\n");
299             return AVERROR_PATCHWELCOME;
300         }
301         if (!s->bpp || s->bpp > 32) {
302             av_log(avctx, AV_LOG_ERROR, "Invalid number of bitplanes: %u\n", s->bpp);
303             return AVERROR_INVALIDDATA;
304         } else if (s->ham >= 8) {
305             av_log(avctx, AV_LOG_ERROR, "Invalid number of hold bits for HAM: %u\n", s->ham);
306             return AVERROR_INVALIDDATA;
307         }
308
309         av_freep(&s->ham_buf);
310         av_freep(&s->ham_palbuf);
311
312         if (s->ham) {
313             int i, count = FFMIN(palette_size / 3, 1 << s->ham);
314             int ham_count;
315             const uint8_t *const palette = avctx->extradata + AV_RB16(avctx->extradata);
316
317             s->ham_buf = av_malloc((s->planesize * 8) + AV_INPUT_BUFFER_PADDING_SIZE);
318             if (!s->ham_buf)
319                 return AVERROR(ENOMEM);
320
321             ham_count = 8 * (1 << s->ham);
322             s->ham_palbuf = av_malloc((ham_count << !!(s->masking == MASK_HAS_MASK)) * sizeof (uint32_t) + AV_INPUT_BUFFER_PADDING_SIZE);
323             if (!s->ham_palbuf) {
324                 av_freep(&s->ham_buf);
325                 return AVERROR(ENOMEM);
326             }
327
328             if (count) { // HAM with color palette attached
329                 // prefill with black and palette and set HAM take direct value mask to zero
330                 memset(s->ham_palbuf, 0, (1 << s->ham) * 2 * sizeof (uint32_t));
331                 for (i=0; i < count; i++) {
332                     s->ham_palbuf[i*2+1] = 0xFF000000 | AV_RL24(palette + i*3);
333                 }
334                 count = 1 << s->ham;
335             } else { // HAM with grayscale color palette
336                 count = 1 << s->ham;
337                 for (i=0; i < count; i++) {
338                     s->ham_palbuf[i*2]   = 0xFF000000; // take direct color value from palette
339                     s->ham_palbuf[i*2+1] = 0xFF000000 | av_le2ne32(gray2rgb((i * 255) >> s->ham));
340                 }
341             }
342             for (i=0; i < count; i++) {
343                 uint32_t tmp = i << (8 - s->ham);
344                 tmp |= tmp >> s->ham;
345                 s->ham_palbuf[(i+count)*2]     = 0xFF00FFFF; // just modify blue color component
346                 s->ham_palbuf[(i+count*2)*2]   = 0xFFFFFF00; // just modify red color component
347                 s->ham_palbuf[(i+count*3)*2]   = 0xFFFF00FF; // just modify green color component
348                 s->ham_palbuf[(i+count)*2+1]   = 0xFF000000 | tmp << 16;
349                 s->ham_palbuf[(i+count*2)*2+1] = 0xFF000000 | tmp;
350                 s->ham_palbuf[(i+count*3)*2+1] = 0xFF000000 | tmp << 8;
351             }
352             if (s->masking == MASK_HAS_MASK) {
353                 for (i = 0; i < ham_count; i++)
354                     s->ham_palbuf[(1 << s->bpp) + i] = s->ham_palbuf[i] | 0xFF000000;
355             }
356         }
357     }
358
359     return 0;
360 }
361
362 static av_cold int decode_end(AVCodecContext *avctx)
363 {
364     IffContext *s = avctx->priv_data;
365     av_freep(&s->planebuf);
366     av_freep(&s->ham_buf);
367     av_freep(&s->ham_palbuf);
368     av_freep(&s->video[0]);
369     av_freep(&s->video[1]);
370     av_freep(&s->pal[0]);
371     av_freep(&s->pal[1]);
372     return 0;
373 }
374
375 static av_cold int decode_init(AVCodecContext *avctx)
376 {
377     IffContext *s = avctx->priv_data;
378     int err;
379
380     if (avctx->bits_per_coded_sample <= 8) {
381         int palette_size;
382
383         if (avctx->extradata_size >= 2)
384             palette_size = avctx->extradata_size - AV_RB16(avctx->extradata);
385         else
386             palette_size = 0;
387         avctx->pix_fmt = (avctx->bits_per_coded_sample < 8) ||
388                          (avctx->extradata_size >= 2 && palette_size) ? AV_PIX_FMT_PAL8 : AV_PIX_FMT_GRAY8;
389     } else if (avctx->bits_per_coded_sample <= 32) {
390         if (avctx->codec_tag == MKTAG('R', 'G', 'B', '8')) {
391             avctx->pix_fmt = AV_PIX_FMT_RGB32;
392         } else if (avctx->codec_tag == MKTAG('R', 'G', 'B', 'N')) {
393             avctx->pix_fmt = AV_PIX_FMT_RGB444;
394         } else if (avctx->codec_tag != MKTAG('D', 'E', 'E', 'P')) {
395             if (avctx->bits_per_coded_sample == 24) {
396                 avctx->pix_fmt = AV_PIX_FMT_0BGR32;
397             } else if (avctx->bits_per_coded_sample == 32) {
398                 avctx->pix_fmt = AV_PIX_FMT_BGR32;
399             } else {
400                 avpriv_request_sample(avctx, "unknown bits_per_coded_sample");
401                 return AVERROR_PATCHWELCOME;
402             }
403         }
404     } else {
405         return AVERROR_INVALIDDATA;
406     }
407
408     if ((err = av_image_check_size(avctx->width, avctx->height, 0, avctx)))
409         return err;
410     s->planesize = FFALIGN(avctx->width, 16) >> 3; // Align plane size in bits to word-boundary
411     s->planebuf  = av_malloc(s->planesize + AV_INPUT_BUFFER_PADDING_SIZE);
412     if (!s->planebuf)
413         return AVERROR(ENOMEM);
414
415     s->bpp = avctx->bits_per_coded_sample;
416
417     if (avctx->codec_tag == MKTAG('A', 'N', 'I', 'M')) {
418         s->video_size = FFALIGN(avctx->width, 2) * avctx->height * s->bpp;
419         s->video[0] = av_calloc(FFALIGN(avctx->width, 2) * avctx->height, s->bpp);
420         s->video[1] = av_calloc(FFALIGN(avctx->width, 2) * avctx->height, s->bpp);
421         s->pal[0] = av_calloc(256, sizeof(*s->pal[0]));
422         s->pal[1] = av_calloc(256, sizeof(*s->pal[1]));
423         if (!s->video[0] || !s->video[1] || !s->pal[0] || !s->pal[1])
424             return AVERROR(ENOMEM);
425         s->first = 1;
426     }
427
428     if ((err = extract_header(avctx, NULL)) < 0)
429         return err;
430
431     return 0;
432 }
433
434 /**
435  * Decode interleaved plane buffer up to 8bpp
436  * @param dst Destination buffer
437  * @param buf Source buffer
438  * @param buf_size
439  * @param plane plane number to decode as
440  */
441 static void decodeplane8(uint8_t *dst, const uint8_t *buf, int buf_size, int plane)
442 {
443     const uint64_t *lut = plane8_lut[plane];
444     if (plane >= 8) {
445         av_log(NULL, AV_LOG_WARNING, "Ignoring extra planes beyond 8\n");
446         return;
447     }
448     do {
449         uint64_t v = AV_RN64A(dst) | lut[*buf++];
450         AV_WN64A(dst, v);
451         dst += 8;
452     } while (--buf_size);
453 }
454
455 /**
456  * Decode interleaved plane buffer up to 24bpp
457  * @param dst Destination buffer
458  * @param buf Source buffer
459  * @param buf_size
460  * @param plane plane number to decode as
461  */
462 static void decodeplane32(uint32_t *dst, const uint8_t *buf, int buf_size, int plane)
463 {
464     const uint32_t *lut = plane32_lut[plane];
465     do {
466         unsigned mask = (*buf >> 2) & ~3;
467         dst[0] |= lut[mask++];
468         dst[1] |= lut[mask++];
469         dst[2] |= lut[mask++];
470         dst[3] |= lut[mask];
471         mask    = (*buf++ << 2) & 0x3F;
472         dst[4] |= lut[mask++];
473         dst[5] |= lut[mask++];
474         dst[6] |= lut[mask++];
475         dst[7] |= lut[mask];
476         dst    += 8;
477     } while (--buf_size);
478 }
479
480 #define DECODE_HAM_PLANE32(x)       \
481     first       = buf[x] << 1;      \
482     second      = buf[(x)+1] << 1;  \
483     delta      &= pal[first++];     \
484     delta      |= pal[first];       \
485     dst[x]      = delta;            \
486     delta      &= pal[second++];    \
487     delta      |= pal[second];      \
488     dst[(x)+1]  = delta
489
490 /**
491  * Converts one line of HAM6/8-encoded chunky buffer to 24bpp.
492  *
493  * @param dst the destination 24bpp buffer
494  * @param buf the source 8bpp chunky buffer
495  * @param pal the HAM decode table
496  * @param buf_size the plane size in bytes
497  */
498 static void decode_ham_plane32(uint32_t *dst, const uint8_t  *buf,
499                                const uint32_t *const pal, unsigned buf_size)
500 {
501     uint32_t delta = pal[1]; /* first palette entry */
502     do {
503         uint32_t first, second;
504         DECODE_HAM_PLANE32(0);
505         DECODE_HAM_PLANE32(2);
506         DECODE_HAM_PLANE32(4);
507         DECODE_HAM_PLANE32(6);
508         buf += 8;
509         dst += 8;
510     } while (--buf_size);
511 }
512
513 static void lookup_pal_indicies(uint32_t *dst, const uint32_t *buf,
514                          const uint32_t *const pal, unsigned width)
515 {
516     do {
517         *dst++ = pal[*buf++];
518     } while (--width);
519 }
520
521 /**
522  * Decode one complete byterun1 encoded line.
523  *
524  * @param dst the destination buffer where to store decompressed bitstream
525  * @param dst_size the destination plane size in bytes
526  * @param buf the source byterun1 compressed bitstream
527  * @param buf_end the EOF of source byterun1 compressed bitstream
528  * @return number of consumed bytes in byterun1 compressed bitstream
529  */
530 static int decode_byterun(uint8_t *dst, int dst_size,
531                           GetByteContext *gb)
532 {
533     unsigned x;
534     for (x = 0; x < dst_size && bytestream2_get_bytes_left(gb) > 0;) {
535         unsigned length;
536         const int8_t value = bytestream2_get_byte(gb);
537         if (value >= 0) {
538             length = FFMIN3(value + 1, dst_size - x, bytestream2_get_bytes_left(gb));
539             bytestream2_get_buffer(gb, dst + x, length);
540         } else if (value > -128) {
541             length = FFMIN(-value + 1, dst_size - x);
542             memset(dst + x, bytestream2_get_byte(gb), length);
543         } else { // noop
544             continue;
545         }
546         x += length;
547     }
548     if (x < dst_size) {
549         av_log(NULL, AV_LOG_WARNING, "decode_byterun ended before plane size\n");
550         memset(dst+x, 0, dst_size - x);
551     }
552     return bytestream2_tell(gb);
553 }
554
555 #define DECODE_RGBX_COMMON(type) \
556     if (!length) { \
557         length = bytestream2_get_byte(gb); \
558         if (!length) { \
559             length = bytestream2_get_be16(gb); \
560             if (!length) \
561                 return; \
562         } \
563     } \
564     for (i = 0; i < length; i++) { \
565         *(type *)(dst + y*linesize + x * sizeof(type)) = pixel; \
566         x += 1; \
567         if (x >= width) { \
568             y += 1; \
569             if (y >= height) \
570                 return; \
571             x = 0; \
572         } \
573     }
574
575 /**
576  * Decode RGB8 buffer
577  * @param[out] dst Destination buffer
578  * @param width Width of destination buffer (pixels)
579  * @param height Height of destination buffer (pixels)
580  * @param linesize Line size of destination buffer (bytes)
581  */
582 static void decode_rgb8(GetByteContext *gb, uint8_t *dst, int width, int height, int linesize)
583 {
584     int x = 0, y = 0, i, length;
585     while (bytestream2_get_bytes_left(gb) >= 4) {
586         uint32_t pixel = 0xFF000000 | bytestream2_get_be24(gb);
587         length = bytestream2_get_byte(gb) & 0x7F;
588         DECODE_RGBX_COMMON(uint32_t)
589     }
590 }
591
592 /**
593  * Decode RGBN buffer
594  * @param[out] dst Destination buffer
595  * @param width Width of destination buffer (pixels)
596  * @param height Height of destination buffer (pixels)
597  * @param linesize Line size of destination buffer (bytes)
598  */
599 static void decode_rgbn(GetByteContext *gb, uint8_t *dst, int width, int height, int linesize)
600 {
601     int x = 0, y = 0, i, length;
602     while (bytestream2_get_bytes_left(gb) >= 2) {
603         uint32_t pixel = bytestream2_get_be16u(gb);
604         length = pixel & 0x7;
605         pixel >>= 4;
606         DECODE_RGBX_COMMON(uint16_t)
607     }
608 }
609
610 /**
611  * Decode DEEP RLE 32-bit buffer
612  * @param[out] dst Destination buffer
613  * @param[in] src Source buffer
614  * @param src_size Source buffer size (bytes)
615  * @param width Width of destination buffer (pixels)
616  * @param height Height of destination buffer (pixels)
617  * @param linesize Line size of destination buffer (bytes)
618  */
619 static void decode_deep_rle32(uint8_t *dst, const uint8_t *src, int src_size, int width, int height, int linesize)
620 {
621     const uint8_t *src_end = src + src_size;
622     int x = 0, y = 0, i;
623     while (src + 5 <= src_end) {
624         int opcode;
625         opcode = *(int8_t *)src++;
626         if (opcode >= 0) {
627             int size = opcode + 1;
628             for (i = 0; i < size; i++) {
629                 int length = FFMIN(size - i, width);
630                 memcpy(dst + y*linesize + x * 4, src, length * 4);
631                 src += length * 4;
632                 x += length;
633                 i += length;
634                 if (x >= width) {
635                     x = 0;
636                     y += 1;
637                     if (y >= height)
638                         return;
639                 }
640             }
641         } else {
642             int size = -opcode + 1;
643             uint32_t pixel = AV_RN32(src);
644             for (i = 0; i < size; i++) {
645                 *(uint32_t *)(dst + y*linesize + x * 4) = pixel;
646                 x += 1;
647                 if (x >= width) {
648                     x = 0;
649                     y += 1;
650                     if (y >= height)
651                         return;
652                 }
653             }
654             src += 4;
655         }
656     }
657 }
658
659 /**
660  * Decode DEEP TVDC 32-bit buffer
661  * @param[out] dst Destination buffer
662  * @param[in] src Source buffer
663  * @param src_size Source buffer size (bytes)
664  * @param width Width of destination buffer (pixels)
665  * @param height Height of destination buffer (pixels)
666  * @param linesize Line size of destination buffer (bytes)
667  * @param[int] tvdc TVDC lookup table
668  */
669 static void decode_deep_tvdc32(uint8_t *dst, const uint8_t *src, int src_size, int width, int height, int linesize, const int16_t *tvdc)
670 {
671     int x = 0, y = 0, plane = 0;
672     int8_t pixel = 0;
673     int i, j;
674
675     for (i = 0; i < src_size * 2;) {
676 #define GETNIBBLE ((i & 1) ?  (src[i>>1] & 0xF) : (src[i>>1] >> 4))
677         int d = tvdc[GETNIBBLE];
678         i++;
679         if (d) {
680             pixel += d;
681             dst[y * linesize + x*4 + plane] = pixel;
682             x++;
683         } else {
684             if (i >= src_size * 2)
685                 return;
686             d = GETNIBBLE + 1;
687             i++;
688             d = FFMIN(d, width - x);
689             for (j = 0; j < d; j++) {
690                 dst[y * linesize + x*4 + plane] = pixel;
691                 x++;
692             }
693         }
694         if (x >= width) {
695             plane++;
696             if (plane >= 4) {
697                 y++;
698                 if (y >= height)
699                     return;
700                 plane = 0;
701             }
702             x = 0;
703             pixel = 0;
704             i = (i + 1) & ~1;
705         }
706     }
707 }
708
709 static void decode_short_horizontal_delta(uint8_t *dst,
710                                           const uint8_t *buf, const uint8_t *buf_end,
711                                           int w, int bpp, int dst_size)
712 {
713     int planepitch = FFALIGN(w, 16) >> 3;
714     int pitch = planepitch * bpp;
715     GetByteContext ptrs, gb;
716     PutByteContext pb;
717     unsigned ofssrc, pos;
718     int i, k;
719
720     bytestream2_init(&ptrs, buf, buf_end - buf);
721     bytestream2_init_writer(&pb, dst, dst_size);
722
723     for (k = 0; k < bpp; k++) {
724         ofssrc = bytestream2_get_be32(&ptrs);
725         pos = 0;
726
727         if (!ofssrc)
728             continue;
729
730         if (ofssrc >= buf_end - buf)
731             continue;
732
733         bytestream2_init(&gb, buf + ofssrc, buf_end - (buf + ofssrc));
734         while (bytestream2_peek_be16(&gb) != 0xFFFF && bytestream2_get_bytes_left(&gb) > 3) {
735             int16_t offset = bytestream2_get_be16(&gb);
736             unsigned noffset;
737
738             if (offset >= 0) {
739                 unsigned data = bytestream2_get_be16(&gb);
740
741                 pos += offset * 2;
742                 noffset = (pos / planepitch) * pitch + (pos % planepitch) + k * planepitch;
743                 bytestream2_seek_p(&pb, noffset, SEEK_SET);
744                 bytestream2_put_be16(&pb, data);
745             } else {
746                 uint16_t count = bytestream2_get_be16(&gb);
747
748                 pos += 2 * -(offset + 2);
749                 for (i = 0; i < count; i++) {
750                     uint16_t data = bytestream2_get_be16(&gb);
751
752                     pos += 2;
753                     noffset = (pos / planepitch) * pitch + (pos % planepitch) + k * planepitch;
754                     bytestream2_seek_p(&pb, noffset, SEEK_SET);
755                     bytestream2_put_be16(&pb, data);
756                 }
757             }
758         }
759     }
760 }
761
762 static void decode_byte_vertical_delta(uint8_t *dst,
763                                        const uint8_t *buf, const uint8_t *buf_end,
764                                        int w, int bpp, int dst_size)
765 {
766     int ncolumns = ((w + 15) / 16) * 2;
767     int dstpitch = ncolumns * bpp;
768     unsigned ofsdst, ofssrc, opcode, x;
769     GetByteContext ptrs, gb;
770     PutByteContext pb;
771     int i, j, k;
772
773     bytestream2_init(&ptrs, buf, buf_end - buf);
774     bytestream2_init_writer(&pb, dst, dst_size);
775
776     for (k = 0; k < bpp; k++) {
777         ofssrc = bytestream2_get_be32(&ptrs);
778
779         if (!ofssrc)
780             continue;
781
782         if (ofssrc >= buf_end - buf)
783             continue;
784
785         bytestream2_init(&gb, buf + ofssrc, buf_end - (buf + ofssrc));
786         for (j = 0; j < ncolumns; j++) {
787             ofsdst = j + k * ncolumns;
788
789             i = bytestream2_get_byte(&gb);
790             while (i > 0) {
791                 opcode = bytestream2_get_byte(&gb);
792
793                 if (opcode == 0) {
794                     opcode  = bytestream2_get_byte(&gb);
795                     x = bytestream2_get_byte(&gb);
796
797                     while (opcode) {
798                         bytestream2_seek_p(&pb, ofsdst, SEEK_SET);
799                         bytestream2_put_byte(&pb, x);
800                         ofsdst += dstpitch;
801                         opcode--;
802                     }
803                 } else if (opcode < 0x80) {
804                     ofsdst += opcode * dstpitch;
805                 } else {
806                     opcode &= 0x7f;
807
808                     while (opcode) {
809                         bytestream2_seek_p(&pb, ofsdst, SEEK_SET);
810                         bytestream2_put_byte(&pb, bytestream2_get_byte(&gb));
811                         ofsdst += dstpitch;
812                         opcode--;
813                     }
814                 }
815                 i--;
816             }
817         }
818     }
819 }
820
821 static void decode_delta_j(uint8_t *dst,
822                            const uint8_t *buf, const uint8_t *buf_end,
823                            int w, int h, int bpp, int dst_size)
824 {
825     int32_t pitch;
826     uint8_t *ptr;
827     uint32_t type, flag, cols, groups, rows, bytes;
828     uint32_t offset;
829     int planepitch_byte = (w + 7) / 8;
830     int planepitch = ((w + 15) / 16) * 2;
831     int kludge_j, b, g, r, d;
832     GetByteContext gb;
833
834     pitch = planepitch * bpp;
835     kludge_j = w < 320 ? (320 - w) / 8 / 2 : 0;
836
837     bytestream2_init(&gb, buf, buf_end - buf);
838
839     while (bytestream2_get_bytes_left(&gb) >= 2) {
840         type = bytestream2_get_be16(&gb);
841
842         switch (type) {
843         case 0:
844             return;
845         case 1:
846             flag   = bytestream2_get_be16(&gb);
847             cols   = bytestream2_get_be16(&gb);
848             groups = bytestream2_get_be16(&gb);
849
850             for (g = 0; g < groups; g++) {
851                 offset = bytestream2_get_be16(&gb);
852
853                 if (kludge_j)
854                     offset = ((offset / (320 / 8)) * pitch) + (offset % (320 / 8)) - kludge_j;
855                 else
856                     offset = ((offset / planepitch_byte) * pitch) + (offset % planepitch_byte);
857
858                 for (b = 0; b < cols; b++) {
859                     for (d = 0; d < bpp; d++) {
860                         uint8_t value = bytestream2_get_byte(&gb);
861
862                         if (offset >= dst_size)
863                             return;
864                         ptr = dst + offset;
865
866                         if (flag)
867                             ptr[0] ^= value;
868                         else
869                             ptr[0]  = value;
870
871                         offset += planepitch;
872                     }
873                 }
874                 if ((cols * bpp) & 1)
875                     bytestream2_skip(&gb, 1);
876             }
877             break;
878         case 2:
879             flag   = bytestream2_get_be16(&gb);
880             rows   = bytestream2_get_be16(&gb);
881             bytes  = bytestream2_get_be16(&gb);
882             groups = bytestream2_get_be16(&gb);
883
884             for (g = 0; g < groups; g++) {
885                 offset = bytestream2_get_be16(&gb);
886
887                 if (kludge_j)
888                     offset = ((offset / (320 / 8)) * pitch) + (offset % (320/ 8)) - kludge_j;
889                 else
890                     offset = ((offset / planepitch_byte) * pitch) + (offset % planepitch_byte);
891
892                 for (r = 0; r < rows; r++) {
893                     for (d = 0; d < bpp; d++) {
894                         unsigned noffset = offset + (r * pitch) + d * planepitch;
895
896                         for (b = 0; b < bytes; b++) {
897                             uint8_t value = bytestream2_get_byte(&gb);
898
899                             if (noffset >= dst_size)
900                                 return;
901                             ptr = dst + noffset;
902
903                             if (flag)
904                                 ptr[0] ^= value;
905                             else
906                                 ptr[0]  = value;
907
908                             noffset++;
909                         }
910                     }
911                 }
912                 if ((rows * bytes * bpp) & 1)
913                     bytestream2_skip(&gb, 1);
914             }
915             break;
916         default:
917             return;
918         }
919     }
920 }
921
922 static void decode_short_vertical_delta(uint8_t *dst,
923                                         const uint8_t *buf, const uint8_t *buf_end,
924                                         int w, int bpp, int dst_size)
925 {
926     int ncolumns = (w + 15) >> 4;
927     int dstpitch = ncolumns * bpp * 2;
928     unsigned ofsdst, ofssrc, ofsdata, opcode, x;
929     GetByteContext ptrs, gb, dptrs, dgb;
930     PutByteContext pb;
931     int i, j, k;
932
933     if (buf_end - buf <= 64)
934         return;
935
936     bytestream2_init(&ptrs, buf, buf_end - buf);
937     bytestream2_init(&dptrs, buf + 32, (buf_end - buf) - 32);
938     bytestream2_init_writer(&pb, dst, dst_size);
939
940     for (k = 0; k < bpp; k++) {
941         ofssrc = bytestream2_get_be32(&ptrs);
942         ofsdata = bytestream2_get_be32(&dptrs);
943
944         if (!ofssrc)
945             continue;
946
947         if (ofssrc >= buf_end - buf)
948             return;
949
950         if (ofsdata >= buf_end - buf)
951             return;
952
953         bytestream2_init(&gb, buf + ofssrc, buf_end - (buf + ofssrc));
954         bytestream2_init(&dgb, buf + ofsdata, buf_end - (buf + ofsdata));
955         for (j = 0; j < ncolumns; j++) {
956             ofsdst = (j + k * ncolumns) * 2;
957
958             i = bytestream2_get_byte(&gb);
959             while (i > 0) {
960                 opcode = bytestream2_get_byte(&gb);
961
962                 if (opcode == 0) {
963                     opcode = bytestream2_get_byte(&gb);
964                     x = bytestream2_get_be16(&dgb);
965
966                     while (opcode) {
967                         bytestream2_seek_p(&pb, ofsdst, SEEK_SET);
968                         bytestream2_put_be16(&pb, x);
969                         ofsdst += dstpitch;
970                         opcode--;
971                     }
972                 } else if (opcode < 0x80) {
973                     ofsdst += opcode * dstpitch;
974                 } else {
975                     opcode &= 0x7f;
976
977                     while (opcode) {
978                         bytestream2_seek_p(&pb, ofsdst, SEEK_SET);
979                         bytestream2_put_be16(&pb, bytestream2_get_be16(&dgb));
980                         ofsdst += dstpitch;
981                         opcode--;
982                     }
983                 }
984                 i--;
985             }
986         }
987     }
988 }
989
990 static void decode_long_vertical_delta(uint8_t *dst,
991                                        const uint8_t *buf, const uint8_t *buf_end,
992                                        int w, int bpp, int dst_size)
993 {
994     int ncolumns = (w + 31) >> 5;
995     int dstpitch = ((w + 15) / 16 * 2) * bpp;
996     unsigned ofsdst, ofssrc, ofsdata, opcode, x;
997     GetByteContext ptrs, gb, dptrs, dgb;
998     PutByteContext pb;
999     int i, j, k, h;
1000
1001     if (buf_end - buf <= 64)
1002         return;
1003
1004     h = (((w + 15) / 16 * 2) != ((w + 31) / 32 * 4)) ? 1 : 0;
1005     bytestream2_init(&ptrs, buf, buf_end - buf);
1006     bytestream2_init(&dptrs, buf + 32, (buf_end - buf) - 32);
1007     bytestream2_init_writer(&pb, dst, dst_size);
1008
1009     for (k = 0; k < bpp; k++) {
1010         ofssrc = bytestream2_get_be32(&ptrs);
1011         ofsdata = bytestream2_get_be32(&dptrs);
1012
1013         if (!ofssrc)
1014             continue;
1015
1016         if (ofssrc >= buf_end - buf)
1017             return;
1018
1019         if (ofsdata >= buf_end - buf)
1020             return;
1021
1022         bytestream2_init(&gb, buf + ofssrc, buf_end - (buf + ofssrc));
1023         bytestream2_init(&dgb, buf + ofsdata, buf_end - (buf + ofsdata));
1024         for (j = 0; j < ncolumns; j++) {
1025             ofsdst = (j + k * ncolumns) * 4 - h * (2 * k);
1026
1027             i = bytestream2_get_byte(&gb);
1028             while (i > 0) {
1029                 opcode = bytestream2_get_byte(&gb);
1030
1031                 if (opcode == 0) {
1032                     opcode = bytestream2_get_byte(&gb);
1033                     if (h && (j == (ncolumns - 1))) {
1034                         x = bytestream2_get_be16(&dgb);
1035                         bytestream2_skip(&dgb, 2);
1036                     } else {
1037                         x = bytestream2_get_be32(&dgb);
1038                     }
1039
1040                     while (opcode) {
1041                         bytestream2_seek_p(&pb, ofsdst, SEEK_SET);
1042                         if (h && (j == (ncolumns - 1))) {
1043                             bytestream2_put_be16(&pb, x);
1044                         } else {
1045                             bytestream2_put_be32(&pb, x);
1046                         }
1047                         ofsdst += dstpitch;
1048                         opcode--;
1049                     }
1050                 } else if (opcode < 0x80) {
1051                     ofsdst += opcode * dstpitch;
1052                 } else {
1053                     opcode &= 0x7f;
1054
1055                     while (opcode) {
1056                         bytestream2_seek_p(&pb, ofsdst, SEEK_SET);
1057                         if (h && (j == (ncolumns - 1))) {
1058                             bytestream2_put_be16(&pb, bytestream2_get_be16(&dgb));
1059                             bytestream2_skip(&dgb, 2);
1060                         } else {
1061                             bytestream2_put_be32(&pb, bytestream2_get_be32(&dgb));
1062                         }
1063                         ofsdst += dstpitch;
1064                         opcode--;
1065                     }
1066                 }
1067                 i--;
1068             }
1069         }
1070     }
1071 }
1072
1073 static void decode_short_vertical_delta2(uint8_t *dst,
1074                                          const uint8_t *buf, const uint8_t *buf_end,
1075                                          int w, int bpp, int dst_size)
1076 {
1077     int ncolumns = (w + 15) >> 4;
1078     int dstpitch = ncolumns * bpp * 2;
1079     unsigned ofsdst, ofssrc, opcode, x;
1080     GetByteContext ptrs, gb;
1081     PutByteContext pb;
1082     int i, j, k;
1083
1084     bytestream2_init(&ptrs, buf, buf_end - buf);
1085     bytestream2_init_writer(&pb, dst, dst_size);
1086
1087     for (k = 0; k < bpp; k++) {
1088         ofssrc = bytestream2_get_be32(&ptrs);
1089
1090         if (!ofssrc)
1091             continue;
1092
1093         if (ofssrc >= buf_end - buf)
1094             continue;
1095
1096         bytestream2_init(&gb, buf + ofssrc, buf_end - (buf + ofssrc));
1097         for (j = 0; j < ncolumns; j++) {
1098             ofsdst = (j + k * ncolumns) * 2;
1099
1100             i = bytestream2_get_be16(&gb);
1101             while (i > 0 && bytestream2_get_bytes_left(&gb) > 4) {
1102                 opcode = bytestream2_get_be16(&gb);
1103
1104                 if (opcode == 0) {
1105                     opcode = bytestream2_get_be16(&gb);
1106                     x = bytestream2_get_be16(&gb);
1107
1108                     while (opcode && bytestream2_get_bytes_left_p(&pb) > 1) {
1109                         bytestream2_seek_p(&pb, ofsdst, SEEK_SET);
1110                         bytestream2_put_be16(&pb, x);
1111                         ofsdst += dstpitch;
1112                         opcode--;
1113                     }
1114                 } else if (opcode < 0x8000) {
1115                     ofsdst += opcode * dstpitch;
1116                 } else {
1117                     opcode &= 0x7fff;
1118
1119                     while (opcode && bytestream2_get_bytes_left(&gb) > 1 &&
1120                            bytestream2_get_bytes_left_p(&pb) > 1) {
1121                         bytestream2_seek_p(&pb, ofsdst, SEEK_SET);
1122                         bytestream2_put_be16(&pb, bytestream2_get_be16(&gb));
1123                         ofsdst += dstpitch;
1124                         opcode--;
1125                     }
1126                 }
1127                 i--;
1128             }
1129         }
1130     }
1131 }
1132
1133 static void decode_long_vertical_delta2(uint8_t *dst,
1134                                         const uint8_t *buf, const uint8_t *buf_end,
1135                                         int w, int bpp, int dst_size)
1136 {
1137     int ncolumns = (w + 31) >> 5;
1138     int dstpitch = ((w + 15) / 16 * 2) * bpp;
1139     unsigned ofsdst, ofssrc, opcode, x;
1140     unsigned skip = 0x80000000, mask = skip - 1;
1141     GetByteContext ptrs, gb;
1142     PutByteContext pb;
1143     int i, j, k, h;
1144
1145     h = (((w + 15) / 16 * 2) != ((w + 31) / 32 * 4)) ? 1 : 0;
1146     bytestream2_init(&ptrs, buf, buf_end - buf);
1147     bytestream2_init_writer(&pb, dst, dst_size);
1148
1149     for (k = 0; k < bpp; k++) {
1150         ofssrc = bytestream2_get_be32(&ptrs);
1151
1152         if (!ofssrc)
1153             continue;
1154
1155         if (ofssrc >= buf_end - buf)
1156             continue;
1157
1158         bytestream2_init(&gb, buf + ofssrc, buf_end - (buf + ofssrc));
1159         for (j = 0; j < ncolumns; j++) {
1160             ofsdst = (j + k * ncolumns) * 4 - h * (2 * k);
1161
1162             if (h && (j == (ncolumns - 1))) {
1163                 skip = 0x8000;
1164                 mask = skip - 1;
1165             }
1166
1167             i = bytestream2_get_be32(&gb);
1168             while (i > 0 && bytestream2_get_bytes_left(&gb) > 4) {
1169                 opcode = bytestream2_get_be32(&gb);
1170
1171                 if (opcode == 0) {
1172                     if (h && (j == ncolumns - 1)) {
1173                         opcode = bytestream2_get_be16(&gb);
1174                         x = bytestream2_get_be16(&gb);
1175                     } else {
1176                         opcode = bytestream2_get_be32(&gb);
1177                         x = bytestream2_get_be32(&gb);
1178                     }
1179
1180                     while (opcode && bytestream2_get_bytes_left_p(&pb) > 1) {
1181                         bytestream2_seek_p(&pb, ofsdst, SEEK_SET);
1182                         if (h && (j == ncolumns - 1))
1183                             bytestream2_put_be16(&pb, x);
1184                         else
1185                             bytestream2_put_be32(&pb, x);
1186                         ofsdst += dstpitch;
1187                         opcode--;
1188                     }
1189                 } else if (opcode < skip) {
1190                     ofsdst += opcode * dstpitch;
1191                 } else {
1192                     opcode &= mask;
1193
1194                     while (opcode && bytestream2_get_bytes_left(&gb) > 1 &&
1195                            bytestream2_get_bytes_left_p(&pb) > 1) {
1196                         bytestream2_seek_p(&pb, ofsdst, SEEK_SET);
1197                         if (h && (j == ncolumns - 1)) {
1198                             bytestream2_put_be16(&pb, bytestream2_get_be16(&gb));
1199                         } else {
1200                             bytestream2_put_be32(&pb, bytestream2_get_be32(&gb));
1201                         }
1202                         ofsdst += dstpitch;
1203                         opcode--;
1204                     }
1205                 }
1206                 i--;
1207             }
1208         }
1209     }
1210 }
1211
1212 static void decode_delta_l(uint8_t *dst,
1213                            const uint8_t *buf, const uint8_t *buf_end,
1214                            int w, int flag, int bpp, int dst_size)
1215 {
1216     GetByteContext off0, off1, dgb, ogb;
1217     PutByteContext pb;
1218     unsigned poff0, poff1;
1219     int i, k, dstpitch;
1220     int planepitch_byte = (w + 7) / 8;
1221     int planepitch = ((w + 15) / 16) * 2;
1222     int pitch = planepitch * bpp;
1223
1224     if (buf_end - buf <= 64)
1225         return;
1226
1227     bytestream2_init(&off0, buf, buf_end - buf);
1228     bytestream2_init(&off1, buf + 32, buf_end - (buf + 32));
1229     bytestream2_init_writer(&pb, dst, dst_size);
1230
1231     dstpitch = flag ? (((w + 7) / 8) * bpp): 2;
1232
1233     for (k = 0; k < bpp; k++) {
1234         poff0 = bytestream2_get_be32(&off0);
1235         poff1 = bytestream2_get_be32(&off1);
1236
1237         if (!poff0)
1238             continue;
1239
1240         if (2LL * poff0 >= buf_end - buf)
1241             return;
1242
1243         if (2LL * poff1 >= buf_end - buf)
1244             return;
1245
1246         bytestream2_init(&dgb, buf + 2 * poff0, buf_end - (buf + 2 * poff0));
1247         bytestream2_init(&ogb, buf + 2 * poff1, buf_end - (buf + 2 * poff1));
1248
1249         while ((bytestream2_peek_be16(&ogb)) != 0xFFFF && bytestream2_get_bytes_left(&ogb) >= 4) {
1250             uint32_t offset = bytestream2_get_be16(&ogb);
1251             int16_t cnt = bytestream2_get_be16(&ogb);
1252             uint16_t data;
1253
1254             offset = ((2 * offset) / planepitch_byte) * pitch + ((2 * offset) % planepitch_byte) + k * planepitch;
1255             if (cnt < 0) {
1256                 bytestream2_seek_p(&pb, offset, SEEK_SET);
1257                 cnt = -cnt;
1258                 data = bytestream2_get_be16(&dgb);
1259                 for (i = 0; i < cnt; i++) {
1260                     bytestream2_put_be16(&pb, data);
1261                     bytestream2_skip_p(&pb, dstpitch - 2);
1262                 }
1263             } else {
1264                 bytestream2_seek_p(&pb, offset, SEEK_SET);
1265                 for (i = 0; i < cnt; i++) {
1266                     data = bytestream2_get_be16(&dgb);
1267                     bytestream2_put_be16(&pb, data);
1268                     bytestream2_skip_p(&pb, dstpitch - 2);
1269                 }
1270             }
1271         }
1272     }
1273 }
1274
1275 static int unsupported(AVCodecContext *avctx)
1276 {
1277     IffContext *s = avctx->priv_data;
1278     avpriv_request_sample(avctx, "bitmap (compression 0x%0x, bpp %i, ham %i)", s->compression, s->bpp, s->ham);
1279     return AVERROR_INVALIDDATA;
1280 }
1281
1282 static int decode_frame(AVCodecContext *avctx,
1283                         void *data, int *got_frame,
1284                         AVPacket *avpkt)
1285 {
1286     IffContext *s          = avctx->priv_data;
1287     AVFrame *frame         = data;
1288     const uint8_t *buf     = avpkt->data;
1289     int buf_size           = avpkt->size;
1290     const uint8_t *buf_end = buf + buf_size;
1291     int y, plane, res;
1292     GetByteContext *gb = &s->gb;
1293     const AVPixFmtDescriptor *desc;
1294
1295     bytestream2_init(gb, avpkt->data, avpkt->size);
1296
1297     if ((res = extract_header(avctx, avpkt)) < 0)
1298         return res;
1299
1300     if ((res = ff_get_buffer(avctx, frame, 0)) < 0)
1301         return res;
1302     s->frame = frame;
1303
1304     buf      += bytestream2_tell(gb);
1305     buf_size -= bytestream2_tell(gb);
1306     desc = av_pix_fmt_desc_get(avctx->pix_fmt);
1307
1308     if (!s->init && avctx->bits_per_coded_sample <= 8 &&
1309         avctx->pix_fmt == AV_PIX_FMT_PAL8) {
1310         if ((res = cmap_read_palette(avctx, (uint32_t *)frame->data[1])) < 0)
1311             return res;
1312     } else if (!s->init && avctx->bits_per_coded_sample <= 8 &&
1313                avctx->pix_fmt == AV_PIX_FMT_RGB32) {
1314         if ((res = cmap_read_palette(avctx, s->mask_palbuf)) < 0)
1315             return res;
1316     }
1317     s->init = 1;
1318
1319     if (s->compression <= 0xff && avctx->codec_tag == MKTAG('A', 'N', 'I', 'M')) {
1320         if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
1321             memcpy(s->pal[0], s->frame->data[1], 256 * 4);
1322     }
1323
1324     if (s->compression > 0xff && s->first) {
1325         memcpy(s->video[1], s->video[0], s->video_size);
1326         memcpy(s->pal[1], s->pal[0], 256 * 4);
1327         s->first = 0;
1328     }
1329
1330     switch (s->compression) {
1331     case 0x0:
1332         if (avctx->codec_tag == MKTAG('A', 'C', 'B', 'M')) {
1333             if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
1334                 memset(frame->data[0], 0, avctx->height * frame->linesize[0]);
1335                 for (plane = 0; plane < s->bpp; plane++) {
1336                     for (y = 0; y < avctx->height && buf < buf_end; y++) {
1337                         uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1338                         decodeplane8(row, buf, FFMIN(s->planesize, buf_end - buf), plane);
1339                         buf += s->planesize;
1340                     }
1341                 }
1342             } else if (s->ham) { // HAM to AV_PIX_FMT_BGR32
1343                 memset(frame->data[0], 0, avctx->height * frame->linesize[0]);
1344                 for (y = 0; y < avctx->height; y++) {
1345                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1346                     memset(s->ham_buf, 0, s->planesize * 8);
1347                     for (plane = 0; plane < s->bpp; plane++) {
1348                         const uint8_t * start = buf + (plane * avctx->height + y) * s->planesize;
1349                         if (start >= buf_end)
1350                             break;
1351                         decodeplane8(s->ham_buf, start, FFMIN(s->planesize, buf_end - start), plane);
1352                     }
1353                     decode_ham_plane32((uint32_t *)row, s->ham_buf, s->ham_palbuf, s->planesize);
1354                 }
1355             } else
1356                 return unsupported(avctx);
1357         } else if (avctx->codec_tag == MKTAG('D', 'E', 'E', 'P')) {
1358             int raw_width = avctx->width * (av_get_bits_per_pixel(desc) >> 3);
1359             int x;
1360             for (y = 0; y < avctx->height && buf < buf_end; y++) {
1361                 uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1362                 memcpy(row, buf, FFMIN(raw_width, buf_end - buf));
1363                 buf += raw_width;
1364                 if (avctx->pix_fmt == AV_PIX_FMT_BGR32) {
1365                     for (x = 0; x < avctx->width; x++)
1366                         row[4 * x + 3] = row[4 * x + 3] & 0xF0 | (row[4 * x + 3] >> 4);
1367                 }
1368             }
1369         } else if (avctx->codec_tag == MKTAG('I', 'L', 'B', 'M') || // interleaved
1370                    avctx->codec_tag == MKTAG('A', 'N', 'I', 'M')) {
1371             if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
1372                 if (avctx->codec_tag == MKTAG('A', 'N', 'I', 'M'))
1373                     memcpy(s->video[0], buf, FFMIN(buf_end - buf, s->video_size));
1374                 for (y = 0; y < avctx->height; y++) {
1375                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1376                     memset(row, 0, avctx->width);
1377                     for (plane = 0; plane < s->bpp && buf < buf_end; plane++) {
1378                         decodeplane8(row, buf, FFMIN(s->planesize, buf_end - buf), plane);
1379                         buf += s->planesize;
1380                     }
1381                 }
1382             } else if (s->ham) { // HAM to AV_PIX_FMT_BGR32
1383                 for (y = 0; y < avctx->height; y++) {
1384                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1385                     memset(s->ham_buf, 0, s->planesize * 8);
1386                     for (plane = 0; plane < s->bpp && buf < buf_end; plane++) {
1387                         decodeplane8(s->ham_buf, buf, FFMIN(s->planesize, buf_end - buf), plane);
1388                         buf += s->planesize;
1389                     }
1390                     decode_ham_plane32((uint32_t *)row, s->ham_buf, s->ham_palbuf, s->planesize);
1391                 }
1392             } else { // AV_PIX_FMT_BGR32
1393                 for (y = 0; y < avctx->height; y++) {
1394                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1395                     memset(row, 0, avctx->width << 2);
1396                     for (plane = 0; plane < s->bpp && buf < buf_end; plane++) {
1397                         decodeplane32((uint32_t *)row, buf,
1398                                       FFMIN(s->planesize, buf_end - buf), plane);
1399                         buf += s->planesize;
1400                     }
1401                 }
1402             }
1403         } else if (avctx->codec_tag == MKTAG('P', 'B', 'M', ' ')) { // IFF-PBM
1404             if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
1405                 for (y = 0; y < avctx->height && buf_end > buf; y++) {
1406                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1407                     memcpy(row, buf, FFMIN(avctx->width, buf_end - buf));
1408                     buf += avctx->width + (avctx->width % 2); // padding if odd
1409                 }
1410             } else if (s->ham) { // IFF-PBM: HAM to AV_PIX_FMT_BGR32
1411                 for (y = 0; y < avctx->height && buf_end > buf; y++) {
1412                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1413                     memcpy(s->ham_buf, buf, FFMIN(avctx->width, buf_end - buf));
1414                     buf += avctx->width + (avctx->width & 1); // padding if odd
1415                     decode_ham_plane32((uint32_t *)row, s->ham_buf, s->ham_palbuf, s->planesize);
1416                 }
1417             } else
1418                 return unsupported(avctx);
1419         }
1420         break;
1421     case 0x1:
1422         if (avctx->codec_tag == MKTAG('I', 'L', 'B', 'M') || // interleaved
1423             avctx->codec_tag == MKTAG('A', 'N', 'I', 'M')) {
1424             if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
1425                 uint8_t *video = s->video[0];
1426
1427                 for (y = 0; y < avctx->height; y++) {
1428                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1429                     memset(row, 0, avctx->width);
1430                     for (plane = 0; plane < s->bpp; plane++) {
1431                         buf += decode_byterun(s->planebuf, s->planesize, gb);
1432                         if (avctx->codec_tag == MKTAG('A', 'N', 'I', 'M')) {
1433                             memcpy(video, s->planebuf, s->planesize);
1434                             video += s->planesize;
1435                         }
1436                         decodeplane8(row, s->planebuf, s->planesize, plane);
1437                     }
1438                 }
1439             } else if (avctx->bits_per_coded_sample <= 8) { //8-bit (+ mask) to AV_PIX_FMT_BGR32
1440                 for (y = 0; y < avctx->height; y++) {
1441                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1442                     memset(s->mask_buf, 0, avctx->width * sizeof(uint32_t));
1443                     for (plane = 0; plane < s->bpp; plane++) {
1444                         buf += decode_byterun(s->planebuf, s->planesize, gb);
1445                         decodeplane32(s->mask_buf, s->planebuf, s->planesize, plane);
1446                     }
1447                     lookup_pal_indicies((uint32_t *)row, s->mask_buf, s->mask_palbuf, avctx->width);
1448                 }
1449             } else if (s->ham) { // HAM to AV_PIX_FMT_BGR32
1450                 uint8_t *video = s->video[0];
1451                 for (y = 0; y < avctx->height; y++) {
1452                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1453                     memset(s->ham_buf, 0, s->planesize * 8);
1454                     for (plane = 0; plane < s->bpp; plane++) {
1455                         buf += decode_byterun(s->planebuf, s->planesize, gb);
1456                         if (avctx->codec_tag == MKTAG('A', 'N', 'I', 'M')) {
1457                             memcpy(video, s->planebuf, s->planesize);
1458                             video += s->planesize;
1459                         }
1460                         decodeplane8(s->ham_buf, s->planebuf, s->planesize, plane);
1461                     }
1462                     decode_ham_plane32((uint32_t *)row, s->ham_buf, s->ham_palbuf, s->planesize);
1463                 }
1464             } else { // AV_PIX_FMT_BGR32
1465                 for (y = 0; y < avctx->height; y++) {
1466                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1467                     memset(row, 0, avctx->width << 2);
1468                     for (plane = 0; plane < s->bpp; plane++) {
1469                         buf += decode_byterun(s->planebuf, s->planesize, gb);
1470                         decodeplane32((uint32_t *)row, s->planebuf, s->planesize, plane);
1471                     }
1472                 }
1473             }
1474         } else if (avctx->codec_tag == MKTAG('P', 'B', 'M', ' ')) { // IFF-PBM
1475             if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
1476                 for (y = 0; y < avctx->height; y++) {
1477                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1478                     buf += decode_byterun(row, avctx->width, gb);
1479                 }
1480             } else if (s->ham) { // IFF-PBM: HAM to AV_PIX_FMT_BGR32
1481                 for (y = 0; y < avctx->height; y++) {
1482                     uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1483                     buf += decode_byterun(s->ham_buf, avctx->width, gb);
1484                     decode_ham_plane32((uint32_t *)row, s->ham_buf, s->ham_palbuf, s->planesize);
1485                 }
1486             } else
1487                 return unsupported(avctx);
1488         } else if (avctx->codec_tag == MKTAG('D', 'E', 'E', 'P')) { // IFF-DEEP
1489             if (av_get_bits_per_pixel(desc) == 32)
1490                 decode_deep_rle32(frame->data[0], buf, buf_size, avctx->width, avctx->height, frame->linesize[0]);
1491             else
1492                 return unsupported(avctx);
1493         }
1494         break;
1495     case 0x4:
1496         if (avctx->codec_tag == MKTAG('R', 'G', 'B', '8') && avctx->pix_fmt == AV_PIX_FMT_RGB32)
1497             decode_rgb8(gb, frame->data[0], avctx->width, avctx->height, frame->linesize[0]);
1498         else if (avctx->codec_tag == MKTAG('R', 'G', 'B', 'N') && avctx->pix_fmt == AV_PIX_FMT_RGB444)
1499             decode_rgbn(gb, frame->data[0], avctx->width, avctx->height, frame->linesize[0]);
1500         else
1501             return unsupported(avctx);
1502         break;
1503     case 0x5:
1504         if (avctx->codec_tag == MKTAG('D', 'E', 'E', 'P')) {
1505             if (av_get_bits_per_pixel(desc) == 32)
1506                 decode_deep_tvdc32(frame->data[0], buf, buf_size, avctx->width, avctx->height, frame->linesize[0], s->tvdc);
1507             else
1508                 return unsupported(avctx);
1509         } else
1510             return unsupported(avctx);
1511         break;
1512     case 0x300:
1513     case 0x301:
1514         decode_short_horizontal_delta(s->video[0], buf, buf_end, avctx->width, s->bpp, s->video_size);
1515         break;
1516     case 0x500:
1517     case 0x501:
1518         decode_byte_vertical_delta(s->video[0], buf, buf_end, avctx->width, s->bpp, s->video_size);
1519         break;
1520     case 0x700:
1521     case 0x701:
1522         if (s->is_short)
1523             decode_short_vertical_delta(s->video[0], buf, buf_end, avctx->width, s->bpp, s->video_size);
1524         else
1525             decode_long_vertical_delta(s->video[0], buf, buf_end, avctx->width, s->bpp, s->video_size);
1526         break;
1527     case 0x800:
1528     case 0x801:
1529         if (s->is_short)
1530             decode_short_vertical_delta2(s->video[0], buf, buf_end, avctx->width, s->bpp, s->video_size);
1531         else
1532             decode_long_vertical_delta2(s->video[0], buf, buf_end, avctx->width, s->bpp, s->video_size);
1533         break;
1534     case 0x4a00:
1535     case 0x4a01:
1536         decode_delta_j(s->video[0], buf, buf_end, avctx->width, avctx->height, s->bpp, s->video_size);
1537         break;
1538     case 0x6c00:
1539     case 0x6c01:
1540         decode_delta_l(s->video[0], buf, buf_end, avctx->width, s->is_short, s->bpp, s->video_size);
1541         break;
1542     default:
1543         return unsupported(avctx);
1544     }
1545
1546     if (s->compression > 0xff) {
1547         if (avctx->pix_fmt == AV_PIX_FMT_PAL8 || avctx->pix_fmt == AV_PIX_FMT_GRAY8) {
1548             buf = s->video[0];
1549             for (y = 0; y < avctx->height; y++) {
1550                 uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1551                 memset(row, 0, avctx->width);
1552                 for (plane = 0; plane < s->bpp; plane++) {
1553                     decodeplane8(row, buf, s->planesize, plane);
1554                     buf += s->planesize;
1555                 }
1556             }
1557             memcpy(frame->data[1], s->pal[0], 256 * 4);
1558         } else if (s->ham) {
1559             int i, count = 1 << s->ham;
1560
1561             buf = s->video[0];
1562             memset(s->ham_palbuf, 0, (1 << s->ham) * 2 * sizeof(uint32_t));
1563             for (i = 0; i < count; i++) {
1564                 s->ham_palbuf[i*2+1] = s->pal[0][i];
1565             }
1566             for (i = 0; i < count; i++) {
1567                 uint32_t tmp = i << (8 - s->ham);
1568                 tmp |= tmp >> s->ham;
1569                 s->ham_palbuf[(i+count)*2]     = 0xFF00FFFF;
1570                 s->ham_palbuf[(i+count*2)*2]   = 0xFFFFFF00;
1571                 s->ham_palbuf[(i+count*3)*2]   = 0xFFFF00FF;
1572                 s->ham_palbuf[(i+count)*2+1]   = 0xFF000000 | tmp << 16;
1573                 s->ham_palbuf[(i+count*2)*2+1] = 0xFF000000 | tmp;
1574                 s->ham_palbuf[(i+count*3)*2+1] = 0xFF000000 | tmp << 8;
1575             }
1576             if (s->masking == MASK_HAS_MASK) {
1577                 for (i = 0; i < 8 * (1 << s->ham); i++)
1578                     s->ham_palbuf[(1 << s->bpp) + i] = s->ham_palbuf[i] | 0xFF000000;
1579             }
1580             for (y = 0; y < avctx->height; y++) {
1581                 uint8_t *row = &frame->data[0][y * frame->linesize[0]];
1582                 memset(s->ham_buf, 0, s->planesize * 8);
1583                 for (plane = 0; plane < s->bpp; plane++) {
1584                     decodeplane8(s->ham_buf, buf, s->planesize, plane);
1585                     buf += s->planesize;
1586                 }
1587                 decode_ham_plane32((uint32_t *)row, s->ham_buf, s->ham_palbuf, s->planesize);
1588             }
1589         } else {
1590             return unsupported(avctx);
1591         }
1592
1593         FFSWAP(uint8_t *, s->video[0], s->video[1]);
1594         FFSWAP(uint32_t *, s->pal[0], s->pal[1]);
1595     }
1596
1597     if (avpkt->flags & AV_PKT_FLAG_KEY) {
1598         frame->key_frame = 1;
1599         frame->pict_type = AV_PICTURE_TYPE_I;
1600     } else {
1601         frame->key_frame = 0;
1602         frame->pict_type = AV_PICTURE_TYPE_P;
1603     }
1604
1605     *got_frame = 1;
1606
1607     return buf_size;
1608 }
1609
1610 #if CONFIG_IFF_ILBM_DECODER
1611 AVCodec ff_iff_ilbm_decoder = {
1612     .name           = "iff",
1613     .long_name      = NULL_IF_CONFIG_SMALL("IFF ACBM/ANIM/DEEP/ILBM/PBM"),
1614     .type           = AVMEDIA_TYPE_VIDEO,
1615     .id             = AV_CODEC_ID_IFF_ILBM,
1616     .priv_data_size = sizeof(IffContext),
1617     .init           = decode_init,
1618     .close          = decode_end,
1619     .decode         = decode_frame,
1620     .capabilities   = AV_CODEC_CAP_DR1,
1621 };
1622 #endif