1/*
2 * Packed Animation File video decoder
3 * Copyright (c) 2012 Paul B Mahol
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "libavutil/imgutils.h"
23
24#include "libavcodec/paf.h"
25#include "avcodec.h"
26#include "bytestream.h"
27#include "copy_block.h"
28#include "internal.h"
29
30
31static const uint8_t block_sequences[16][8] = {
32    { 0, 0, 0, 0, 0, 0, 0, 0 },
33    { 2, 0, 0, 0, 0, 0, 0, 0 },
34    { 5, 7, 0, 0, 0, 0, 0, 0 },
35    { 5, 0, 0, 0, 0, 0, 0, 0 },
36    { 6, 0, 0, 0, 0, 0, 0, 0 },
37    { 5, 7, 5, 7, 0, 0, 0, 0 },
38    { 5, 7, 5, 0, 0, 0, 0, 0 },
39    { 5, 7, 6, 0, 0, 0, 0, 0 },
40    { 5, 5, 0, 0, 0, 0, 0, 0 },
41    { 3, 0, 0, 0, 0, 0, 0, 0 },
42    { 6, 6, 0, 0, 0, 0, 0, 0 },
43    { 2, 4, 0, 0, 0, 0, 0, 0 },
44    { 2, 4, 5, 7, 0, 0, 0, 0 },
45    { 2, 4, 5, 0, 0, 0, 0, 0 },
46    { 2, 4, 6, 0, 0, 0, 0, 0 },
47    { 2, 4, 5, 7, 5, 7, 0, 0 },
48};
49
50typedef struct PAFVideoDecContext {
51    AVFrame  *pic;
52    GetByteContext gb;
53
54    int width;
55    int height;
56
57    int current_frame;
58    uint8_t *frame[4];
59    int frame_size;
60    int video_size;
61
62    uint8_t *opcodes;
63} PAFVideoDecContext;
64
65static av_cold int paf_video_close(AVCodecContext *avctx)
66{
67    PAFVideoDecContext *c = avctx->priv_data;
68    int i;
69
70    av_frame_free(&c->pic);
71
72    for (i = 0; i < 4; i++)
73        av_freep(&c->frame[i]);
74
75    return 0;
76}
77
78static av_cold int paf_video_init(AVCodecContext *avctx)
79{
80    PAFVideoDecContext *c = avctx->priv_data;
81    int i;
82
83    c->width  = avctx->width;
84    c->height = avctx->height;
85
86    if (avctx->height & 3 || avctx->width & 3) {
87        av_log(avctx, AV_LOG_ERROR,
88               "width %d and height %d must be multiplie of 4.\n",
89               avctx->width, avctx->height);
90        return AVERROR_INVALIDDATA;
91    }
92
93    avctx->pix_fmt = AV_PIX_FMT_PAL8;
94
95    c->pic = av_frame_alloc();
96    if (!c->pic)
97        return AVERROR(ENOMEM);
98
99    c->frame_size = avctx->width * FFALIGN(avctx->height, 256);
100    c->video_size = avctx->width * avctx->height;
101    for (i = 0; i < 4; i++) {
102        c->frame[i] = av_mallocz(c->frame_size);
103        if (!c->frame[i]) {
104            paf_video_close(avctx);
105            return AVERROR(ENOMEM);
106        }
107    }
108
109    return 0;
110}
111
112static void read4x4block(PAFVideoDecContext *c, uint8_t *dst, int width)
113{
114    int i;
115
116    for (i = 0; i < 4; i++) {
117        bytestream2_get_buffer(&c->gb, dst, 4);
118        dst += width;
119    }
120}
121
122static void copy_color_mask(uint8_t *dst, int width, uint8_t mask, uint8_t color)
123{
124    int i;
125
126    for (i = 0; i < 4; i++) {
127        if (mask & (1 << 7 - i))
128            dst[i] = color;
129        if (mask & (1 << 3 - i))
130            dst[width + i] = color;
131    }
132}
133
134static void copy_src_mask(uint8_t *dst, int width, uint8_t mask, const uint8_t *src)
135{
136    int i;
137
138    for (i = 0; i < 4; i++) {
139        if (mask & (1 << 7 - i))
140            dst[i] = src[i];
141        if (mask & (1 << 3 - i))
142            dst[width + i] = src[width + i];
143    }
144}
145
146static void set_src_position(PAFVideoDecContext *c,
147                             const uint8_t **p,
148                             const uint8_t **pend)
149{
150    int val  = bytestream2_get_be16(&c->gb);
151    int page = val >> 14;
152    int x    = (val & 0x7F);
153    int y    = ((val >> 7) & 0x7F);
154
155    *p    = c->frame[page] + x * 2 + y * 2 * c->width;
156    *pend = c->frame[page] + c->frame_size;
157}
158
159static int decode_0(PAFVideoDecContext *c, uint8_t *pkt, uint8_t code)
160{
161    uint32_t opcode_size, offset;
162    uint8_t *dst, *dend, mask = 0, color = 0;
163    const uint8_t *src, *send, *opcodes;
164    int i, j, op = 0;
165
166    i = bytestream2_get_byte(&c->gb);
167    if (i) {
168        if (code & 0x10) {
169            int align;
170
171            align = bytestream2_tell(&c->gb) & 3;
172            if (align)
173                bytestream2_skip(&c->gb, 4 - align);
174        }
175        do {
176            int page, val, x, y;
177            val    = bytestream2_get_be16(&c->gb);
178            page   = val >> 14;
179            x      = (val & 0x7F) * 2;
180            y      = ((val >> 7) & 0x7F) * 2;
181            dst    = c->frame[page] + x + y * c->width;
182            dend   = c->frame[page] + c->frame_size;
183            offset = (x & 0x7F) * 2;
184            j      = bytestream2_get_le16(&c->gb) + offset;
185            do {
186                offset++;
187                if (dst + 3 * c->width + 4 > dend)
188                    return AVERROR_INVALIDDATA;
189                read4x4block(c, dst, c->width);
190                if ((offset & 0x3F) == 0)
191                    dst += c->width * 3;
192                dst += 4;
193            } while (offset < j);
194        } while (--i);
195    }
196
197    dst  = c->frame[c->current_frame];
198    dend = c->frame[c->current_frame] + c->frame_size;
199    do {
200        set_src_position(c, &src, &send);
201        if ((src + 3 * c->width + 4 > send) ||
202            (dst + 3 * c->width + 4 > dend))
203            return AVERROR_INVALIDDATA;
204        copy_block4(dst, src, c->width, c->width, 4);
205        i++;
206        if ((i & 0x3F) == 0)
207            dst += c->width * 3;
208        dst += 4;
209    } while (i < c->video_size / 16);
210
211    opcode_size = bytestream2_get_le16(&c->gb);
212    bytestream2_skip(&c->gb, 2);
213
214    if (bytestream2_get_bytes_left(&c->gb) < opcode_size)
215        return AVERROR_INVALIDDATA;
216
217    opcodes = pkt + bytestream2_tell(&c->gb);
218    bytestream2_skipu(&c->gb, opcode_size);
219
220    dst = c->frame[c->current_frame];
221
222    for (i = 0; i < c->height; i += 4, dst += c->width * 3)
223        for (j = 0; j < c->width; j += 4, dst += 4) {
224            int opcode, k = 0;
225            if (op > opcode_size)
226                return AVERROR_INVALIDDATA;
227            if (j & 4) {
228                opcode = opcodes[op] & 15;
229                op++;
230            } else {
231                opcode = opcodes[op] >> 4;
232            }
233
234            while (block_sequences[opcode][k]) {
235                offset = c->width * 2;
236                code   = block_sequences[opcode][k++];
237
238                switch (code) {
239                case 2:
240                    offset = 0;
241                case 3:
242                    color = bytestream2_get_byte(&c->gb);
243                case 4:
244                    mask = bytestream2_get_byte(&c->gb);
245                    copy_color_mask(dst + offset, c->width, mask, color);
246                    break;
247                case 5:
248                    offset = 0;
249                case 6:
250                    set_src_position(c, &src, &send);
251                case 7:
252                    if (src + offset + c->width + 4 > send)
253                        return AVERROR_INVALIDDATA;
254                    mask = bytestream2_get_byte(&c->gb);
255                    copy_src_mask(dst + offset, c->width, mask, src + offset);
256                    break;
257                }
258            }
259        }
260
261    return 0;
262}
263
264static int paf_video_decode(AVCodecContext *avctx, void *data,
265                            int *got_frame, AVPacket *pkt)
266{
267    PAFVideoDecContext *c = avctx->priv_data;
268    uint8_t code, *dst, *end;
269    int i, frame, ret;
270
271    if ((ret = ff_reget_buffer(avctx, c->pic)) < 0)
272        return ret;
273
274    bytestream2_init(&c->gb, pkt->data, pkt->size);
275
276    code = bytestream2_get_byte(&c->gb);
277    if (code & 0x20) {  // frame is keyframe
278        for (i = 0; i < 4; i++)
279            memset(c->frame[i], 0, c->frame_size);
280
281        memset(c->pic->data[1], 0, AVPALETTE_SIZE);
282        c->current_frame  = 0;
283        c->pic->key_frame = 1;
284        c->pic->pict_type = AV_PICTURE_TYPE_I;
285    } else {
286        c->pic->key_frame = 0;
287        c->pic->pict_type = AV_PICTURE_TYPE_P;
288    }
289
290    if (code & 0x40) {  // palette update
291        uint32_t *out = (uint32_t *)c->pic->data[1];
292        int index, count;
293
294        index = bytestream2_get_byte(&c->gb);
295        count = bytestream2_get_byte(&c->gb) + 1;
296
297        if (index + count > 256)
298            return AVERROR_INVALIDDATA;
299        if (bytestream2_get_bytes_left(&c->gb) < 3 * count)
300            return AVERROR_INVALIDDATA;
301
302        out += index;
303        for (i = 0; i < count; i++) {
304            unsigned r, g, b;
305
306            r = bytestream2_get_byteu(&c->gb);
307            r = r << 2 | r >> 4;
308            g = bytestream2_get_byteu(&c->gb);
309            g = g << 2 | g >> 4;
310            b = bytestream2_get_byteu(&c->gb);
311            b = b << 2 | b >> 4;
312            *out++ = (0xFFU << 24) | (r << 16) | (g << 8) | b;
313        }
314        c->pic->palette_has_changed = 1;
315    }
316
317    switch (code & 0x0F) {
318    case 0:
319        /* Block-based motion compensation using 4x4 blocks with either
320         * horizontal or vertical vectors; might incorporate VQ as well. */
321        if ((ret = decode_0(c, pkt->data, code)) < 0)
322            return ret;
323        break;
324    case 1:
325        /* Uncompressed data. This mode specifies that (width * height) bytes
326         * should be copied directly from the encoded buffer into the output. */
327        dst = c->frame[c->current_frame];
328        // possibly chunk length data
329        bytestream2_skip(&c->gb, 2);
330        if (bytestream2_get_bytes_left(&c->gb) < c->video_size)
331            return AVERROR_INVALIDDATA;
332        bytestream2_get_bufferu(&c->gb, dst, c->video_size);
333        break;
334    case 2:
335        /* Copy reference frame: Consume the next byte in the stream as the
336         * reference frame (which should be 0, 1, 2, or 3, and should not be
337         * the same as the current frame number). */
338        frame = bytestream2_get_byte(&c->gb);
339        if (frame > 3)
340            return AVERROR_INVALIDDATA;
341        if (frame != c->current_frame)
342            memcpy(c->frame[c->current_frame], c->frame[frame], c->frame_size);
343        break;
344    case 4:
345        /* Run length encoding.*/
346        dst = c->frame[c->current_frame];
347        end = dst + c->video_size;
348
349        bytestream2_skip(&c->gb, 2);
350
351        while (dst < end) {
352            int8_t code;
353            int count;
354
355            if (bytestream2_get_bytes_left(&c->gb) < 2)
356                return AVERROR_INVALIDDATA;
357
358            code  = bytestream2_get_byteu(&c->gb);
359            count = FFABS(code) + 1;
360
361            if (dst + count > end)
362                return AVERROR_INVALIDDATA;
363            if (code < 0)
364                memset(dst, bytestream2_get_byteu(&c->gb), count);
365            else
366                bytestream2_get_buffer(&c->gb, dst, count);
367            dst += count;
368        }
369        break;
370    default:
371        avpriv_request_sample(avctx, "unknown/invalid code");
372        return AVERROR_INVALIDDATA;
373    }
374
375    av_image_copy_plane(c->pic->data[0], c->pic->linesize[0],
376                        c->frame[c->current_frame], c->width,
377                        c->width, c->height);
378
379    c->current_frame = (c->current_frame + 1) & 3;
380    if ((ret = av_frame_ref(data, c->pic)) < 0)
381        return ret;
382
383    *got_frame = 1;
384
385    return pkt->size;
386}
387
388AVCodec ff_paf_video_decoder = {
389    .name           = "paf_video",
390    .long_name      = NULL_IF_CONFIG_SMALL("Amazing Studio Packed Animation File Video"),
391    .type           = AVMEDIA_TYPE_VIDEO,
392    .id             = AV_CODEC_ID_PAF_VIDEO,
393    .priv_data_size = sizeof(PAFVideoDecContext),
394    .init           = paf_video_init,
395    .close          = paf_video_close,
396    .decode         = paf_video_decode,
397    .capabilities   = CODEC_CAP_DR1,
398};
399