1/*
2 * CD Graphics Video Decoder
3 * Copyright (c) 2009 Michael Tison
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 "avcodec.h"
23#include "bytestream.h"
24#include "codec_internal.h"
25#include "internal.h"
26
27/**
28 * @file
29 * @brief CD Graphics Video Decoder
30 * @author Michael Tison
31 * @see http://wiki.multimedia.cx/index.php?title=CD_Graphics
32 * @see http://www.ccs.neu.edu/home/bchafy/cdb/info/cdg
33 */
34
35/// default screen sizes
36#define CDG_FULL_WIDTH           300
37#define CDG_FULL_HEIGHT          216
38#define CDG_DISPLAY_WIDTH        294
39#define CDG_DISPLAY_HEIGHT       204
40#define CDG_BORDER_WIDTH           6
41#define CDG_BORDER_HEIGHT         12
42
43/// masks
44#define CDG_COMMAND             0x09
45#define CDG_MASK                0x3F
46
47/// instruction codes
48#define CDG_INST_MEMORY_PRESET     1
49#define CDG_INST_BORDER_PRESET     2
50#define CDG_INST_TILE_BLOCK        6
51#define CDG_INST_SCROLL_PRESET    20
52#define CDG_INST_SCROLL_COPY      24
53#define CDG_INST_TRANSPARENT_COL  28
54#define CDG_INST_LOAD_PAL_LO      30
55#define CDG_INST_LOAD_PAL_HIGH    31
56#define CDG_INST_TILE_BLOCK_XOR   38
57
58/// data sizes
59#define CDG_PACKET_SIZE           24
60#define CDG_DATA_SIZE             16
61#define CDG_TILE_HEIGHT           12
62#define CDG_TILE_WIDTH             6
63#define CDG_MINIMUM_PKT_SIZE       6
64#define CDG_MINIMUM_SCROLL_SIZE    3
65#define CDG_HEADER_SIZE            8
66#define CDG_PALETTE_SIZE          16
67
68typedef struct CDGraphicsContext {
69    AVFrame *frame;
70    int hscroll;
71    int vscroll;
72    uint8_t alpha[CDG_PALETTE_SIZE];
73    int cleared;
74} CDGraphicsContext;
75
76static av_cold int cdg_decode_init(AVCodecContext *avctx)
77{
78    CDGraphicsContext *cc = avctx->priv_data;
79
80    cc->frame = av_frame_alloc();
81    if (!cc->frame)
82        return AVERROR(ENOMEM);
83
84    for (int i = 0; i < CDG_PALETTE_SIZE; i++)
85        cc->alpha[i] = 0xFFU;
86
87    avctx->pix_fmt = AV_PIX_FMT_PAL8;
88    return ff_set_dimensions(avctx, CDG_FULL_WIDTH, CDG_FULL_HEIGHT);
89}
90
91static void cdg_border_preset(CDGraphicsContext *cc, uint8_t *data)
92{
93    int y;
94    int lsize    = cc->frame->linesize[0];
95    uint8_t *buf = cc->frame->data[0];
96    int color    = data[0] & 0x0F;
97
98    if (!(data[1] & 0x0F)) {
99        /// fill the top and bottom borders
100        memset(buf, color, CDG_BORDER_HEIGHT * lsize);
101        memset(buf + (CDG_FULL_HEIGHT - CDG_BORDER_HEIGHT) * lsize,
102               color, CDG_BORDER_HEIGHT * lsize);
103
104        /// fill the side borders
105        for (y = CDG_BORDER_HEIGHT; y < CDG_FULL_HEIGHT - CDG_BORDER_HEIGHT; y++) {
106            memset(buf + y * lsize, color, CDG_BORDER_WIDTH);
107            memset(buf + CDG_FULL_WIDTH - CDG_BORDER_WIDTH + y * lsize,
108                   color, CDG_BORDER_WIDTH);
109        }
110    }
111}
112
113static void cdg_load_palette(CDGraphicsContext *cc, uint8_t *data, int low)
114{
115    uint8_t r, g, b;
116    uint16_t color;
117    int i;
118    int array_offset  = low ? 0 : 8;
119    uint32_t *palette = (uint32_t *) cc->frame->data[1];
120
121    for (i = 0; i < 8; i++) {
122        color = (data[2 * i] << 6) + (data[2 * i + 1] & 0x3F);
123        r = ((color >> 8) & 0x000F) * 17;
124        g = ((color >> 4) & 0x000F) * 17;
125        b = ((color     ) & 0x000F) * 17;
126        palette[i + array_offset] = (uint32_t)cc->alpha[i + array_offset] << 24 | r << 16 | g << 8 | b;
127    }
128    cc->frame->palette_has_changed = 1;
129}
130
131static int cdg_tile_block(CDGraphicsContext *cc, uint8_t *data, int b)
132{
133    unsigned ci, ri;
134    int color;
135    int x, y;
136    int ai;
137    int stride   = cc->frame->linesize[0];
138    uint8_t *buf = cc->frame->data[0];
139
140    ri = (data[2] & 0x1F) * CDG_TILE_HEIGHT + cc->vscroll;
141    ci = (data[3] & 0x3F) * CDG_TILE_WIDTH  + cc->hscroll;
142
143    if (ri > (CDG_FULL_HEIGHT - CDG_TILE_HEIGHT))
144        return AVERROR(EINVAL);
145    if (ci > (CDG_FULL_WIDTH - CDG_TILE_WIDTH))
146        return AVERROR(EINVAL);
147
148    for (y = 0; y < CDG_TILE_HEIGHT; y++) {
149        for (x = 0; x < CDG_TILE_WIDTH; x++) {
150            if (!((data[4 + y] >> (5 - x)) & 0x01))
151                color = data[0] & 0x0F;
152            else
153                color = data[1] & 0x0F;
154
155            ai = ci + x + (stride * (ri + y));
156            if (b)
157                color ^= buf[ai];
158            buf[ai] = color;
159        }
160    }
161
162    return 0;
163}
164
165#define UP    2
166#define DOWN  1
167#define LEFT  2
168#define RIGHT 1
169
170static void cdg_copy_rect_buf(int out_tl_x, int out_tl_y, uint8_t *out,
171                              int in_tl_x, int in_tl_y, uint8_t *in,
172                              int w, int h, int stride)
173{
174    int y;
175
176    in  += in_tl_x  + in_tl_y  * stride;
177    out += out_tl_x + out_tl_y * stride;
178    for (y = 0; y < h; y++)
179        memcpy(out + y * stride, in + y * stride, w);
180}
181
182static void cdg_fill_rect_preset(int tl_x, int tl_y, uint8_t *out,
183                                 int color, int w, int h, int stride)
184{
185    int y;
186
187    for (y = tl_y; y < tl_y + h; y++)
188        memset(out + tl_x + y * stride, color, w);
189}
190
191static void cdg_fill_wrapper(int out_tl_x, int out_tl_y, uint8_t *out,
192                             int in_tl_x, int in_tl_y, uint8_t *in,
193                             int color, int w, int h, int stride, int roll)
194{
195    if (roll) {
196        cdg_copy_rect_buf(out_tl_x, out_tl_y, out, in_tl_x, in_tl_y,
197                          in, w, h, stride);
198    } else {
199        cdg_fill_rect_preset(out_tl_x, out_tl_y, out, color, w, h, stride);
200    }
201}
202
203static void cdg_scroll(CDGraphicsContext *cc, uint8_t *data,
204                       AVFrame *new_frame, int roll_over)
205{
206    int color;
207    int hscmd, h_off, hinc, vscmd, v_off, vinc;
208    int y;
209    int stride   = cc->frame->linesize[0];
210    uint8_t *in  = cc->frame->data[0];
211    uint8_t *out = new_frame->data[0];
212
213    color =  data[0] & 0x0F;
214    hscmd = (data[1] & 0x30) >> 4;
215    vscmd = (data[2] & 0x30) >> 4;
216
217    h_off =  FFMIN(data[1] & 0x07, CDG_BORDER_WIDTH  - 1);
218    v_off =  FFMIN(data[2] & 0x0F, CDG_BORDER_HEIGHT - 1);
219
220    /// find the difference and save the offset for cdg_tile_block usage
221    hinc = h_off - cc->hscroll;
222    vinc = cc->vscroll - v_off;
223    cc->hscroll = h_off;
224    cc->vscroll = v_off;
225
226    if (vscmd == UP)
227        vinc -= 12;
228    if (vscmd == DOWN)
229        vinc += 12;
230    if (hscmd == LEFT)
231        hinc -= 6;
232    if (hscmd == RIGHT)
233        hinc += 6;
234
235    if (!hinc && !vinc)
236        return;
237
238    memcpy(new_frame->data[1], cc->frame->data[1], CDG_PALETTE_SIZE * 4);
239
240    for (y = FFMAX(0, vinc); y < FFMIN(CDG_FULL_HEIGHT + vinc, CDG_FULL_HEIGHT); y++)
241        memcpy(out + FFMAX(0, hinc) + stride * y,
242               in + FFMAX(0, hinc) - hinc + (y - vinc) * stride,
243               FFABS(stride) - FFABS(hinc));
244
245    if (vinc > 0)
246        cdg_fill_wrapper(0, 0, out,
247                         0, CDG_FULL_HEIGHT - vinc, in, color,
248                         stride, vinc, stride, roll_over);
249    else if (vinc < 0)
250        cdg_fill_wrapper(0, CDG_FULL_HEIGHT + vinc, out,
251                         0, 0, in, color,
252                         stride, -1 * vinc, stride, roll_over);
253
254    if (hinc > 0)
255        cdg_fill_wrapper(0, 0, out,
256                         CDG_FULL_WIDTH - hinc, 0, in, color,
257                         hinc, CDG_FULL_HEIGHT, stride, roll_over);
258    else if (hinc < 0)
259        cdg_fill_wrapper(CDG_FULL_WIDTH + hinc, 0, out,
260                         0, 0, in, color,
261                         -1 * hinc, CDG_FULL_HEIGHT, stride, roll_over);
262
263}
264
265static int cdg_decode_frame(AVCodecContext *avctx, AVFrame *frame,
266                            int *got_frame, AVPacket *avpkt)
267{
268    GetByteContext gb;
269    int buf_size       = avpkt->size;
270    int ret;
271    uint8_t command, inst;
272    uint8_t cdg_data[CDG_DATA_SIZE] = {0};
273    CDGraphicsContext *cc = avctx->priv_data;
274
275    if (buf_size < CDG_MINIMUM_PKT_SIZE) {
276        av_log(avctx, AV_LOG_ERROR, "buffer too small for decoder\n");
277        return AVERROR(EINVAL);
278    }
279    if (buf_size > CDG_HEADER_SIZE + CDG_DATA_SIZE) {
280        av_log(avctx, AV_LOG_ERROR, "buffer too big for decoder\n");
281        return AVERROR(EINVAL);
282    }
283
284    bytestream2_init(&gb, avpkt->data, avpkt->size);
285
286    if ((ret = ff_reget_buffer(avctx, cc->frame, 0)) < 0)
287        return ret;
288    if (!cc->cleared) {
289        memset(cc->frame->data[0], 0, cc->frame->linesize[0] * avctx->height);
290        memset(cc->frame->data[1], 0, AVPALETTE_SIZE);
291        cc->cleared = 1;
292    }
293
294    command = bytestream2_get_byte(&gb);
295    inst    = bytestream2_get_byte(&gb);
296    inst    &= CDG_MASK;
297    bytestream2_skip(&gb, 2);
298    bytestream2_get_buffer(&gb, cdg_data, sizeof(cdg_data));
299
300    if ((command & CDG_MASK) == CDG_COMMAND) {
301        switch (inst) {
302        case CDG_INST_MEMORY_PRESET:
303            if (!(cdg_data[1] & 0x0F))
304                memset(cc->frame->data[0], cdg_data[0] & 0x0F,
305                       cc->frame->linesize[0] * CDG_FULL_HEIGHT);
306            break;
307        case CDG_INST_LOAD_PAL_LO:
308        case CDG_INST_LOAD_PAL_HIGH:
309            if (buf_size - CDG_HEADER_SIZE < CDG_DATA_SIZE) {
310                av_log(avctx, AV_LOG_ERROR, "buffer too small for loading palette\n");
311                return AVERROR(EINVAL);
312            }
313
314            cdg_load_palette(cc, cdg_data, inst == CDG_INST_LOAD_PAL_LO);
315            break;
316        case CDG_INST_BORDER_PRESET:
317            cdg_border_preset(cc, cdg_data);
318            break;
319        case CDG_INST_TILE_BLOCK_XOR:
320        case CDG_INST_TILE_BLOCK:
321            if (buf_size - CDG_HEADER_SIZE < CDG_DATA_SIZE) {
322                av_log(avctx, AV_LOG_ERROR, "buffer too small for drawing tile\n");
323                return AVERROR(EINVAL);
324            }
325
326            ret = cdg_tile_block(cc, cdg_data, inst == CDG_INST_TILE_BLOCK_XOR);
327            if (ret) {
328                av_log(avctx, AV_LOG_ERROR, "tile is out of range\n");
329                return ret;
330            }
331            break;
332        case CDG_INST_SCROLL_PRESET:
333        case CDG_INST_SCROLL_COPY:
334            if (buf_size - CDG_HEADER_SIZE < CDG_MINIMUM_SCROLL_SIZE) {
335                av_log(avctx, AV_LOG_ERROR, "buffer too small for scrolling\n");
336                return AVERROR(EINVAL);
337            }
338
339            if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)
340                return ret;
341
342            cdg_scroll(cc, cdg_data, frame, inst == CDG_INST_SCROLL_COPY);
343            av_frame_unref(cc->frame);
344            ret = av_frame_ref(cc->frame, frame);
345            if (ret < 0)
346                return ret;
347            break;
348        case CDG_INST_TRANSPARENT_COL:
349            for (int i = 0; i < CDG_PALETTE_SIZE; i++)
350                cc->alpha[i] = 255 - ((cdg_data[i] & 0x3f) << 2);
351            break;
352        default:
353            break;
354        }
355
356        if (!frame->data[0]) {
357            ret = av_frame_ref(frame, cc->frame);
358            if (ret < 0)
359                return ret;
360        }
361        *got_frame = 1;
362    } else {
363        *got_frame = 0;
364    }
365
366    return avpkt->size;
367}
368
369static void cdg_decode_flush(AVCodecContext *avctx)
370{
371    CDGraphicsContext *cc = avctx->priv_data;
372
373    if (!cc->frame->data[0])
374        return;
375
376    memset(cc->frame->data[0], 0, cc->frame->linesize[0] * avctx->height);
377    if (!avctx->frame_number)
378        memset(cc->frame->data[1], 0, AVPALETTE_SIZE);
379}
380
381static av_cold int cdg_decode_end(AVCodecContext *avctx)
382{
383    CDGraphicsContext *cc = avctx->priv_data;
384
385    av_frame_free(&cc->frame);
386
387    return 0;
388}
389
390const FFCodec ff_cdgraphics_decoder = {
391    .p.name         = "cdgraphics",
392    .p.long_name    = NULL_IF_CONFIG_SMALL("CD Graphics video"),
393    .p.type         = AVMEDIA_TYPE_VIDEO,
394    .p.id           = AV_CODEC_ID_CDGRAPHICS,
395    .priv_data_size = sizeof(CDGraphicsContext),
396    .init           = cdg_decode_init,
397    .close          = cdg_decode_end,
398    FF_CODEC_DECODE_CB(cdg_decode_frame),
399    .flush          = cdg_decode_flush,
400    .p.capabilities = AV_CODEC_CAP_DR1,
401    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
402};
403