1/*
2 * Delphine Software International CIN Audio/Video Decoders
3 * Copyright (c) 2006 Gregory Montoir (cyx@users.sourceforge.net)
4 *
5 * This file is part of Libav.
6 *
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22/**
23 * @file
24 * Delphine Software International CIN audio/video decoders
25 */
26
27#include "avcodec.h"
28#include "bytestream.h"
29#include "mathops.h"
30
31
32typedef enum CinVideoBitmapIndex {
33    CIN_CUR_BMP = 0, /* current */
34    CIN_PRE_BMP = 1, /* previous */
35    CIN_INT_BMP = 2  /* intermediate */
36} CinVideoBitmapIndex;
37
38typedef struct CinVideoContext {
39    AVCodecContext *avctx;
40    AVFrame frame;
41    unsigned int bitmap_size;
42    uint32_t palette[256];
43    uint8_t *bitmap_table[3];
44} CinVideoContext;
45
46typedef struct CinAudioContext {
47    AVFrame frame;
48    int initial_decode_frame;
49    int delta;
50} CinAudioContext;
51
52
53/* table defining a geometric sequence with multiplier = 32767 ^ (1 / 128) */
54static const int16_t cinaudio_delta16_table[256] = {
55         0,      0,      0,      0,      0,      0,      0,      0,
56         0,      0,      0,      0,      0,      0,      0,      0,
57         0,      0,      0, -30210, -27853, -25680, -23677, -21829,
58    -20126, -18556, -17108, -15774, -14543, -13408, -12362, -11398,
59    -10508,  -9689,  -8933,  -8236,  -7593,  -7001,  -6455,  -5951,
60     -5487,  -5059,  -4664,  -4300,  -3964,  -3655,  -3370,  -3107,
61     -2865,  -2641,  -2435,  -2245,  -2070,  -1908,  -1759,  -1622,
62     -1495,  -1379,  -1271,  -1172,  -1080,   -996,   -918,   -847,
63      -781,   -720,   -663,   -612,   -564,   -520,   -479,   -442,
64      -407,   -376,   -346,   -319,   -294,   -271,   -250,   -230,
65      -212,   -196,   -181,   -166,   -153,   -141,   -130,   -120,
66      -111,   -102,    -94,    -87,    -80,    -74,    -68,    -62,
67       -58,    -53,    -49,    -45,    -41,    -38,    -35,    -32,
68       -30,    -27,    -25,    -23,    -21,    -20,    -18,    -17,
69       -15,    -14,    -13,    -12,    -11,    -10,     -9,     -8,
70        -7,     -6,     -5,     -4,     -3,     -2,     -1,      0,
71         0,      1,      2,      3,      4,      5,      6,      7,
72         8,      9,     10,     11,     12,     13,     14,     15,
73        17,     18,     20,     21,     23,     25,     27,     30,
74        32,     35,     38,     41,     45,     49,     53,     58,
75        62,     68,     74,     80,     87,     94,    102,    111,
76       120,    130,    141,    153,    166,    181,    196,    212,
77       230,    250,    271,    294,    319,    346,    376,    407,
78       442,    479,    520,    564,    612,    663,    720,    781,
79       847,    918,    996,   1080,   1172,   1271,   1379,   1495,
80      1622,   1759,   1908,   2070,   2245,   2435,   2641,   2865,
81      3107,   3370,   3655,   3964,   4300,   4664,   5059,   5487,
82      5951,   6455,   7001,   7593,   8236,   8933,   9689,  10508,
83     11398,  12362,  13408,  14543,  15774,  17108,  18556,  20126,
84     21829,  23677,  25680,  27853,  30210,      0,      0,      0,
85         0,      0,      0,      0,      0,      0,      0,      0,
86         0,      0,      0,      0,      0,      0,      0,      0
87};
88
89
90static av_cold int cinvideo_decode_init(AVCodecContext *avctx)
91{
92    CinVideoContext *cin = avctx->priv_data;
93    unsigned int i;
94
95    cin->avctx = avctx;
96    avctx->pix_fmt = PIX_FMT_PAL8;
97
98    cin->frame.data[0] = NULL;
99
100    cin->bitmap_size = avctx->width * avctx->height;
101    for (i = 0; i < 3; ++i) {
102        cin->bitmap_table[i] = av_mallocz(cin->bitmap_size);
103        if (!cin->bitmap_table[i])
104            av_log(avctx, AV_LOG_ERROR, "Can't allocate bitmap buffers.\n");
105    }
106
107    return 0;
108}
109
110static void cin_apply_delta_data(const unsigned char *src, unsigned char *dst, int size)
111{
112    while (size--)
113        *dst++ += *src++;
114}
115
116static int cin_decode_huffman(const unsigned char *src, int src_size, unsigned char *dst, int dst_size)
117{
118    int b, huff_code = 0;
119    unsigned char huff_code_table[15];
120    unsigned char *dst_cur = dst;
121    unsigned char *dst_end = dst + dst_size;
122    const unsigned char *src_end = src + src_size;
123
124    memcpy(huff_code_table, src, 15); src += 15; src_size -= 15;
125
126    while (src < src_end) {
127        huff_code = *src++;
128        if ((huff_code >> 4) == 15) {
129            b = huff_code << 4;
130            huff_code = *src++;
131            *dst_cur++ = b | (huff_code >> 4);
132        } else
133            *dst_cur++ = huff_code_table[huff_code >> 4];
134        if (dst_cur >= dst_end)
135            break;
136
137        huff_code &= 15;
138        if (huff_code == 15) {
139            *dst_cur++ = *src++;
140        } else
141            *dst_cur++ = huff_code_table[huff_code];
142        if (dst_cur >= dst_end)
143            break;
144    }
145
146    return dst_cur - dst;
147}
148
149static int cin_decode_lzss(const unsigned char *src, int src_size, unsigned char *dst, int dst_size)
150{
151    uint16_t cmd;
152    int i, sz, offset, code;
153    unsigned char *dst_end = dst + dst_size, *dst_start = dst;
154    const unsigned char *src_end = src + src_size;
155
156    while (src < src_end && dst < dst_end) {
157        code = *src++;
158        for (i = 0; i < 8 && src < src_end && dst < dst_end; ++i) {
159            if (code & (1 << i)) {
160                *dst++ = *src++;
161            } else {
162                cmd = AV_RL16(src); src += 2;
163                offset = cmd >> 4;
164                if ((int) (dst - dst_start) < offset + 1)
165                    return AVERROR_INVALIDDATA;
166                sz = (cmd & 0xF) + 2;
167                /* don't use memcpy/memmove here as the decoding routine (ab)uses */
168                /* buffer overlappings to repeat bytes in the destination */
169                sz = FFMIN(sz, dst_end - dst);
170                while (sz--) {
171                    *dst = *(dst - offset - 1);
172                    ++dst;
173                }
174            }
175        }
176    }
177
178    return 0;
179}
180
181static void cin_decode_rle(const unsigned char *src, int src_size, unsigned char *dst, int dst_size)
182{
183    int len, code;
184    unsigned char *dst_end = dst + dst_size;
185    const unsigned char *src_end = src + src_size;
186
187    while (src < src_end && dst < dst_end) {
188        code = *src++;
189        if (code & 0x80) {
190            len = code - 0x7F;
191            memset(dst, *src++, FFMIN(len, dst_end - dst));
192        } else {
193            len = code + 1;
194            memcpy(dst, src, FFMIN(len, dst_end - dst));
195            src += len;
196        }
197        dst += len;
198    }
199}
200
201static int cinvideo_decode_frame(AVCodecContext *avctx,
202                                 void *data, int *data_size,
203                                 AVPacket *avpkt)
204{
205    const uint8_t *buf = avpkt->data;
206    int buf_size = avpkt->size;
207    CinVideoContext *cin = avctx->priv_data;
208    int i, y, palette_type, palette_colors_count, bitmap_frame_type, bitmap_frame_size, res = 0;
209
210    palette_type = buf[0];
211    palette_colors_count = AV_RL16(buf+1);
212    bitmap_frame_type = buf[3];
213    buf += 4;
214
215    bitmap_frame_size = buf_size - 4;
216
217    /* handle palette */
218    if (bitmap_frame_size < palette_colors_count * (3 + (palette_type != 0)))
219        return AVERROR_INVALIDDATA;
220    if (palette_type == 0) {
221        if (palette_colors_count > 256)
222            return AVERROR_INVALIDDATA;
223        for (i = 0; i < palette_colors_count; ++i) {
224            cin->palette[i] = bytestream_get_le24(&buf);
225            bitmap_frame_size -= 3;
226        }
227    } else {
228        for (i = 0; i < palette_colors_count; ++i) {
229            cin->palette[buf[0]] = AV_RL24(buf+1);
230            buf += 4;
231            bitmap_frame_size -= 4;
232        }
233    }
234
235    /* note: the decoding routines below assumes that surface.width = surface.pitch */
236    switch (bitmap_frame_type) {
237    case 9:
238        cin_decode_rle(buf, bitmap_frame_size,
239          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);
240        break;
241    case 34:
242        cin_decode_rle(buf, bitmap_frame_size,
243          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);
244        cin_apply_delta_data(cin->bitmap_table[CIN_PRE_BMP],
245          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);
246        break;
247    case 35:
248        cin_decode_huffman(buf, bitmap_frame_size,
249          cin->bitmap_table[CIN_INT_BMP], cin->bitmap_size);
250        cin_decode_rle(cin->bitmap_table[CIN_INT_BMP], bitmap_frame_size,
251          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);
252        break;
253    case 36:
254        bitmap_frame_size = cin_decode_huffman(buf, bitmap_frame_size,
255          cin->bitmap_table[CIN_INT_BMP], cin->bitmap_size);
256        cin_decode_rle(cin->bitmap_table[CIN_INT_BMP], bitmap_frame_size,
257          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);
258        cin_apply_delta_data(cin->bitmap_table[CIN_PRE_BMP],
259          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);
260        break;
261    case 37:
262        cin_decode_huffman(buf, bitmap_frame_size,
263          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);
264        break;
265    case 38:
266        res = cin_decode_lzss(buf, bitmap_frame_size,
267                              cin->bitmap_table[CIN_CUR_BMP],
268                              cin->bitmap_size);
269        if (res < 0)
270            return res;
271        break;
272    case 39:
273        res = cin_decode_lzss(buf, bitmap_frame_size,
274                              cin->bitmap_table[CIN_CUR_BMP],
275                              cin->bitmap_size);
276        if (res < 0)
277            return res;
278        cin_apply_delta_data(cin->bitmap_table[CIN_PRE_BMP],
279          cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_size);
280        break;
281    }
282
283    cin->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
284    if (avctx->reget_buffer(avctx, &cin->frame)) {
285        av_log(cin->avctx, AV_LOG_ERROR, "delphinecinvideo: reget_buffer() failed to allocate a frame\n");
286        return -1;
287    }
288
289    memcpy(cin->frame.data[1], cin->palette, sizeof(cin->palette));
290    cin->frame.palette_has_changed = 1;
291    for (y = 0; y < cin->avctx->height; ++y)
292        memcpy(cin->frame.data[0] + (cin->avctx->height - 1 - y) * cin->frame.linesize[0],
293          cin->bitmap_table[CIN_CUR_BMP] + y * cin->avctx->width,
294          cin->avctx->width);
295
296    FFSWAP(uint8_t *, cin->bitmap_table[CIN_CUR_BMP], cin->bitmap_table[CIN_PRE_BMP]);
297
298    *data_size = sizeof(AVFrame);
299    *(AVFrame *)data = cin->frame;
300
301    return buf_size;
302}
303
304static av_cold int cinvideo_decode_end(AVCodecContext *avctx)
305{
306    CinVideoContext *cin = avctx->priv_data;
307    int i;
308
309    if (cin->frame.data[0])
310        avctx->release_buffer(avctx, &cin->frame);
311
312    for (i = 0; i < 3; ++i)
313        av_free(cin->bitmap_table[i]);
314
315    return 0;
316}
317
318static av_cold int cinaudio_decode_init(AVCodecContext *avctx)
319{
320    CinAudioContext *cin = avctx->priv_data;
321
322    if (avctx->channels != 1) {
323        av_log_ask_for_sample(avctx, "Number of channels is not supported\n");
324        return AVERROR_PATCHWELCOME;
325    }
326
327    cin->initial_decode_frame = 1;
328    cin->delta = 0;
329    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
330
331    avcodec_get_frame_defaults(&cin->frame);
332    avctx->coded_frame = &cin->frame;
333
334    return 0;
335}
336
337static int cinaudio_decode_frame(AVCodecContext *avctx, void *data,
338                                 int *got_frame_ptr, AVPacket *avpkt)
339{
340    const uint8_t *buf = avpkt->data;
341    CinAudioContext *cin = avctx->priv_data;
342    const uint8_t *buf_end = buf + avpkt->size;
343    int16_t *samples;
344    int delta, ret;
345
346    /* get output buffer */
347    cin->frame.nb_samples = avpkt->size - cin->initial_decode_frame;
348    if ((ret = avctx->get_buffer(avctx, &cin->frame)) < 0) {
349        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
350        return ret;
351    }
352    samples = (int16_t *)cin->frame.data[0];
353
354    delta = cin->delta;
355    if (cin->initial_decode_frame) {
356        cin->initial_decode_frame = 0;
357        delta = sign_extend(AV_RL16(buf), 16);
358        buf += 2;
359        *samples++ = delta;
360    }
361    while (buf < buf_end) {
362        delta += cinaudio_delta16_table[*buf++];
363        delta = av_clip_int16(delta);
364        *samples++ = delta;
365    }
366    cin->delta = delta;
367
368    *got_frame_ptr   = 1;
369    *(AVFrame *)data = cin->frame;
370
371    return avpkt->size;
372}
373
374
375AVCodec ff_dsicinvideo_decoder = {
376    .name           = "dsicinvideo",
377    .type           = AVMEDIA_TYPE_VIDEO,
378    .id             = CODEC_ID_DSICINVIDEO,
379    .priv_data_size = sizeof(CinVideoContext),
380    .init           = cinvideo_decode_init,
381    .close          = cinvideo_decode_end,
382    .decode         = cinvideo_decode_frame,
383    .capabilities   = CODEC_CAP_DR1,
384    .long_name = NULL_IF_CONFIG_SMALL("Delphine Software International CIN video"),
385};
386
387AVCodec ff_dsicinaudio_decoder = {
388    .name           = "dsicinaudio",
389    .type           = AVMEDIA_TYPE_AUDIO,
390    .id             = CODEC_ID_DSICINAUDIO,
391    .priv_data_size = sizeof(CinAudioContext),
392    .init           = cinaudio_decode_init,
393    .decode         = cinaudio_decode_frame,
394    .capabilities   = CODEC_CAP_DR1,
395    .long_name = NULL_IF_CONFIG_SMALL("Delphine Software International CIN audio"),
396};
397