2 * Kega Game Video (KGV1) decoder
3 * Copyright (c) 2010 Daniel Verkamp
5 * This file is part of FFmpeg.
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.
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.
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
24 * Kega Game Video decoder
27 #include "libavutil/intreadwrite.h"
28 #include "libavutil/imgutils.h"
32 AVCodecContext *avctx;
37 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
39 const uint8_t *buf = avpkt->data;
40 const uint8_t *buf_end = buf + avpkt->size;
41 KgvContext * const c = avctx->priv_data;
44 int outcnt = 0, maxcnt;
54 if (av_image_check_size(w, h, 0, avctx))
57 if (w != avctx->width || h != avctx->height)
58 avcodec_set_dimensions(avctx, w, h);
62 out = av_realloc(c->cur, w * h * 2);
67 prev = av_realloc(c->prev, w * h * 2);
72 for (i = 0; i < 7; i++)
75 while (outcnt < maxcnt && buf_end - 2 > buf) {
76 int code = AV_RL16(buf);
79 if (!(code & 0x8000)) {
80 out[outcnt++] = code; // rgb555 pixel coded directly
85 if ((code & 0x6000) == 0x6000) {
86 // copy from previous frame
87 int oidx = (code >> 10) & 7;
90 count = (code & 0x3FF) + 3;
92 if (offsets[oidx] < 0) {
93 if (buf_end - 3 < buf)
95 offsets[oidx] = AV_RL24(buf);
99 start = (outcnt + offsets[oidx]) % maxcnt;
101 if (maxcnt - start < count)
106 // copy from earlier in this frame
107 int offset = (code & 0x1FFF) + 1;
109 if (!(code & 0x6000)) {
111 } else if ((code & 0x6000) == 0x2000) {
114 if (buf_end - 1 < buf)
122 inp = out + outcnt - offset;
125 if (maxcnt - outcnt < count)
128 for (i = 0; i < count; i++)
129 out[outcnt++] = inp[i];
134 av_log(avctx, AV_LOG_DEBUG, "frame finished with %d diff\n", outcnt - maxcnt);
136 c->pic.data[0] = (uint8_t *)c->cur;
137 c->pic.linesize[0] = w * 2;
139 *data_size = sizeof(AVFrame);
140 *(AVFrame*)data = c->pic;
142 FFSWAP(uint16_t *, c->cur, c->prev);
147 static av_cold int decode_init(AVCodecContext *avctx)
149 KgvContext * const c = avctx->priv_data;
152 avctx->pix_fmt = PIX_FMT_RGB555;
153 avcodec_get_frame_defaults(&c->pic);
158 static av_cold int decode_end(AVCodecContext *avctx)
160 KgvContext * const c = avctx->priv_data;
168 AVCodec ff_kgv1_decoder = {
170 .type = AVMEDIA_TYPE_VIDEO,
172 .priv_data_size = sizeof(KgvContext),
175 .decode = decode_frame,
176 .long_name = NULL_IF_CONFIG_SMALL("Kega Game Video"),