1/*
2 * Canopus Lossless Codec decoder
3 *
4 * Copyright (c) 2012-2013 Derek Buitenhuis
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include <inttypes.h>
24
25#include "libavutil/intreadwrite.h"
26#include "bswapdsp.h"
27#include "get_bits.h"
28#include "avcodec.h"
29#include "internal.h"
30
31typedef struct CLLCContext {
32    AVCodecContext *avctx;
33    BswapDSPContext bdsp;
34
35    uint8_t *swapped_buf;
36    int      swapped_buf_size;
37} CLLCContext;
38
39static int read_code_table(CLLCContext *ctx, GetBitContext *gb, VLC *vlc)
40{
41    uint8_t symbols[256];
42    uint8_t bits[256];
43    uint16_t codes[256];
44    int num_lens, num_codes, num_codes_sum, prefix;
45    int i, j, count;
46
47    prefix        = 0;
48    count         = 0;
49    num_codes_sum = 0;
50
51    num_lens = get_bits(gb, 5);
52
53    for (i = 0; i < num_lens; i++) {
54        num_codes      = get_bits(gb, 9);
55        num_codes_sum += num_codes;
56
57        if (num_codes_sum > 256) {
58            vlc->table = NULL;
59
60            av_log(ctx->avctx, AV_LOG_ERROR,
61                   "Too many VLCs (%d) to be read.\n", num_codes_sum);
62            return AVERROR_INVALIDDATA;
63        }
64
65        for (j = 0; j < num_codes; j++) {
66            symbols[count] = get_bits(gb, 8);
67            bits[count]    = i + 1;
68            codes[count]   = prefix++;
69
70            count++;
71        }
72
73        prefix <<= 1;
74    }
75
76    return ff_init_vlc_sparse(vlc, 7, count, bits, 1, 1,
77                              codes, 2, 2, symbols, 1, 1, 0);
78}
79
80/*
81 * Unlike the RGB24 read/restore, which reads in a component at a time,
82 * ARGB read/restore reads in ARGB quads.
83 */
84static int read_argb_line(CLLCContext *ctx, GetBitContext *gb, int *top_left,
85                          VLC *vlc, uint8_t *outbuf)
86{
87    uint8_t *dst;
88    int pred[4];
89    int code;
90    int i;
91
92    OPEN_READER(bits, gb);
93
94    dst     = outbuf;
95    pred[0] = top_left[0];
96    pred[1] = top_left[1];
97    pred[2] = top_left[2];
98    pred[3] = top_left[3];
99
100    for (i = 0; i < ctx->avctx->width; i++) {
101        /* Always get the alpha component */
102        UPDATE_CACHE(bits, gb);
103        GET_VLC(code, bits, gb, vlc[0].table, 7, 2);
104
105        pred[0] += code;
106        dst[0]   = pred[0];
107
108        /* Skip the components if they are  entirely transparent */
109        if (dst[0]) {
110            /* Red */
111            UPDATE_CACHE(bits, gb);
112            GET_VLC(code, bits, gb, vlc[1].table, 7, 2);
113
114            pred[1] += code;
115            dst[1]   = pred[1];
116
117            /* Green */
118            UPDATE_CACHE(bits, gb);
119            GET_VLC(code, bits, gb, vlc[2].table, 7, 2);
120
121            pred[2] += code;
122            dst[2]   = pred[2];
123
124            /* Blue */
125            UPDATE_CACHE(bits, gb);
126            GET_VLC(code, bits, gb, vlc[3].table, 7, 2);
127
128            pred[3] += code;
129            dst[3]   = pred[3];
130        } else {
131            dst[1] = 0;
132            dst[2] = 0;
133            dst[3] = 0;
134        }
135
136        dst += 4;
137    }
138
139    CLOSE_READER(bits, gb);
140
141    top_left[0]  = outbuf[0];
142
143    /* Only stash components if they are not transparent */
144    if (top_left[0]) {
145        top_left[1] = outbuf[1];
146        top_left[2] = outbuf[2];
147        top_left[3] = outbuf[3];
148    }
149
150    return 0;
151}
152
153static int read_rgb24_component_line(CLLCContext *ctx, GetBitContext *gb,
154                                     int *top_left, VLC *vlc, uint8_t *outbuf)
155{
156    uint8_t *dst;
157    int pred, code;
158    int i;
159
160    OPEN_READER(bits, gb);
161
162    dst  = outbuf;
163    pred = *top_left;
164
165    /* Simultaneously read and restore the line */
166    for (i = 0; i < ctx->avctx->width; i++) {
167        UPDATE_CACHE(bits, gb);
168        GET_VLC(code, bits, gb, vlc->table, 7, 2);
169
170        pred  += code;
171        dst[0] = pred;
172        dst   += 3;
173    }
174
175    CLOSE_READER(bits, gb);
176
177    /* Stash the first pixel */
178    *top_left = outbuf[0];
179
180    return 0;
181}
182
183static int read_yuv_component_line(CLLCContext *ctx, GetBitContext *gb,
184                                   int *top_left, VLC *vlc, uint8_t *outbuf,
185                                   int is_chroma)
186{
187    int pred, code;
188    int i;
189
190    OPEN_READER(bits, gb);
191
192    pred = *top_left;
193
194    /* Simultaneously read and restore the line */
195    for (i = 0; i < ctx->avctx->width >> is_chroma; i++) {
196        UPDATE_CACHE(bits, gb);
197        GET_VLC(code, bits, gb, vlc->table, 7, 2);
198
199        pred     += code;
200        outbuf[i] = pred;
201    }
202
203    CLOSE_READER(bits, gb);
204
205    /* Stash the first pixel */
206    *top_left = outbuf[0];
207
208    return 0;
209}
210
211static int decode_argb_frame(CLLCContext *ctx, GetBitContext *gb, AVFrame *pic)
212{
213    AVCodecContext *avctx = ctx->avctx;
214    uint8_t *dst;
215    int pred[4];
216    int ret;
217    int i, j;
218    VLC vlc[4];
219
220    pred[0] = 0;
221    pred[1] = 0x80;
222    pred[2] = 0x80;
223    pred[3] = 0x80;
224
225    dst = pic->data[0];
226
227    skip_bits(gb, 16);
228
229    /* Read in code table for each plane */
230    for (i = 0; i < 4; i++) {
231        ret = read_code_table(ctx, gb, &vlc[i]);
232        if (ret < 0) {
233            for (j = 0; j <= i; j++)
234                ff_free_vlc(&vlc[j]);
235
236            av_log(ctx->avctx, AV_LOG_ERROR,
237                   "Could not read code table %d.\n", i);
238            return ret;
239        }
240    }
241
242    /* Read in and restore every line */
243    for (i = 0; i < avctx->height; i++) {
244        read_argb_line(ctx, gb, pred, vlc, dst);
245
246        dst += pic->linesize[0];
247    }
248
249    for (i = 0; i < 4; i++)
250        ff_free_vlc(&vlc[i]);
251
252    return 0;
253}
254
255static int decode_rgb24_frame(CLLCContext *ctx, GetBitContext *gb, AVFrame *pic)
256{
257    AVCodecContext *avctx = ctx->avctx;
258    uint8_t *dst;
259    int pred[3];
260    int ret;
261    int i, j;
262    VLC vlc[3];
263
264    pred[0] = 0x80;
265    pred[1] = 0x80;
266    pred[2] = 0x80;
267
268    dst = pic->data[0];
269
270    skip_bits(gb, 16);
271
272    /* Read in code table for each plane */
273    for (i = 0; i < 3; i++) {
274        ret = read_code_table(ctx, gb, &vlc[i]);
275        if (ret < 0) {
276            for (j = 0; j <= i; j++)
277                ff_free_vlc(&vlc[j]);
278
279            av_log(ctx->avctx, AV_LOG_ERROR,
280                   "Could not read code table %d.\n", i);
281            return ret;
282        }
283    }
284
285    /* Read in and restore every line */
286    for (i = 0; i < avctx->height; i++) {
287        for (j = 0; j < 3; j++)
288            read_rgb24_component_line(ctx, gb, &pred[j], &vlc[j], &dst[j]);
289
290        dst += pic->linesize[0];
291    }
292
293    for (i = 0; i < 3; i++)
294        ff_free_vlc(&vlc[i]);
295
296    return 0;
297}
298
299static int decode_yuv_frame(CLLCContext *ctx, GetBitContext *gb, AVFrame *pic)
300{
301    AVCodecContext *avctx = ctx->avctx;
302    uint8_t block;
303    uint8_t *dst[3];
304    int pred[3];
305    int ret;
306    int i, j;
307    VLC vlc[2];
308
309    pred[0] = 0x80;
310    pred[1] = 0x80;
311    pred[2] = 0x80;
312
313    dst[0] = pic->data[0];
314    dst[1] = pic->data[1];
315    dst[2] = pic->data[2];
316
317    skip_bits(gb, 8);
318
319    block = get_bits(gb, 8);
320    if (block) {
321        avpriv_request_sample(ctx->avctx, "Blocked YUV");
322        return AVERROR_PATCHWELCOME;
323    }
324
325    /* Read in code table for luma and chroma */
326    for (i = 0; i < 2; i++) {
327        ret = read_code_table(ctx, gb, &vlc[i]);
328        if (ret < 0) {
329            for (j = 0; j <= i; j++)
330                ff_free_vlc(&vlc[j]);
331
332            av_log(ctx->avctx, AV_LOG_ERROR,
333                   "Could not read code table %d.\n", i);
334            return ret;
335        }
336    }
337
338    /* Read in and restore every line */
339    for (i = 0; i < avctx->height; i++) {
340        read_yuv_component_line(ctx, gb, &pred[0], &vlc[0], dst[0], 0); /* Y */
341        read_yuv_component_line(ctx, gb, &pred[1], &vlc[1], dst[1], 1); /* U */
342        read_yuv_component_line(ctx, gb, &pred[2], &vlc[1], dst[2], 1); /* V */
343
344        for (j = 0; j < 3; j++)
345            dst[j] += pic->linesize[j];
346    }
347
348    for (i = 0; i < 2; i++)
349        ff_free_vlc(&vlc[i]);
350
351    return 0;
352}
353
354static int cllc_decode_frame(AVCodecContext *avctx, void *data,
355                             int *got_picture_ptr, AVPacket *avpkt)
356{
357    CLLCContext *ctx = avctx->priv_data;
358    AVFrame *pic = data;
359    uint8_t *src = avpkt->data;
360    uint32_t info_tag, info_offset;
361    int data_size;
362    GetBitContext gb;
363    int coding_type, ret;
364
365    /* Skip the INFO header if present */
366    info_offset = 0;
367    info_tag    = AV_RL32(src);
368    if (info_tag == MKTAG('I', 'N', 'F', 'O')) {
369        info_offset = AV_RL32(src + 4);
370        if (info_offset > UINT32_MAX - 8 || info_offset + 8 > avpkt->size) {
371            av_log(avctx, AV_LOG_ERROR,
372                   "Invalid INFO header offset: 0x%08"PRIX32" is too large.\n",
373                   info_offset);
374            return AVERROR_INVALIDDATA;
375        }
376
377        info_offset += 8;
378        src         += info_offset;
379
380        av_log(avctx, AV_LOG_DEBUG, "Skipping INFO chunk.\n");
381    }
382
383    data_size = (avpkt->size - info_offset) & ~1;
384
385    /* Make sure our bswap16'd buffer is big enough */
386    av_fast_padded_malloc(&ctx->swapped_buf,
387                          &ctx->swapped_buf_size, data_size);
388    if (!ctx->swapped_buf) {
389        av_log(avctx, AV_LOG_ERROR, "Could not allocate swapped buffer.\n");
390        return AVERROR(ENOMEM);
391    }
392
393    /* bswap16 the buffer since CLLC's bitreader works in 16-bit words */
394    ctx->bdsp.bswap16_buf((uint16_t *) ctx->swapped_buf, (uint16_t *) src,
395                          data_size / 2);
396
397    init_get_bits(&gb, ctx->swapped_buf, data_size * 8);
398
399    /*
400     * Read in coding type. The types are as follows:
401     *
402     * 0 - YUY2
403     * 1 - BGR24 (Triples)
404     * 2 - BGR24 (Quads)
405     * 3 - BGRA
406     */
407    coding_type = (AV_RL32(src) >> 8) & 0xFF;
408    av_log(avctx, AV_LOG_DEBUG, "Frame coding type: %d\n", coding_type);
409
410    switch (coding_type) {
411    case 0:
412        avctx->pix_fmt             = AV_PIX_FMT_YUV422P;
413        avctx->bits_per_raw_sample = 8;
414
415        if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)
416            return ret;
417
418        ret = decode_yuv_frame(ctx, &gb, pic);
419        if (ret < 0)
420            return ret;
421
422        break;
423    case 1:
424    case 2:
425        avctx->pix_fmt             = AV_PIX_FMT_RGB24;
426        avctx->bits_per_raw_sample = 8;
427
428        if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)
429            return ret;
430
431        ret = decode_rgb24_frame(ctx, &gb, pic);
432        if (ret < 0)
433            return ret;
434
435        break;
436    case 3:
437        avctx->pix_fmt             = AV_PIX_FMT_ARGB;
438        avctx->bits_per_raw_sample = 8;
439
440        if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)
441            return ret;
442
443        ret = decode_argb_frame(ctx, &gb, pic);
444        if (ret < 0)
445            return ret;
446
447        break;
448    default:
449        av_log(avctx, AV_LOG_ERROR, "Unknown coding type: %d.\n", coding_type);
450        return AVERROR_INVALIDDATA;
451    }
452
453    pic->key_frame = 1;
454    pic->pict_type = AV_PICTURE_TYPE_I;
455
456    *got_picture_ptr = 1;
457
458    return avpkt->size;
459}
460
461static av_cold int cllc_decode_close(AVCodecContext *avctx)
462{
463    CLLCContext *ctx = avctx->priv_data;
464
465    av_freep(&ctx->swapped_buf);
466
467    return 0;
468}
469
470static av_cold int cllc_decode_init(AVCodecContext *avctx)
471{
472    CLLCContext *ctx = avctx->priv_data;
473
474    /* Initialize various context values */
475    ctx->avctx            = avctx;
476    ctx->swapped_buf      = NULL;
477    ctx->swapped_buf_size = 0;
478
479    ff_bswapdsp_init(&ctx->bdsp);
480
481    return 0;
482}
483
484AVCodec ff_cllc_decoder = {
485    .name           = "cllc",
486    .long_name      = NULL_IF_CONFIG_SMALL("Canopus Lossless Codec"),
487    .type           = AVMEDIA_TYPE_VIDEO,
488    .id             = AV_CODEC_ID_CLLC,
489    .priv_data_size = sizeof(CLLCContext),
490    .init           = cllc_decode_init,
491    .decode         = cllc_decode_frame,
492    .close          = cllc_decode_close,
493    .capabilities   = CODEC_CAP_DR1,
494};
495