]> git.sesse.net Git - ffmpeg/blob - libavcodec/a64multienc.c
WMAL: Shift output samples by the specified number of padding zeroes.
[ffmpeg] / libavcodec / a64multienc.c
1 /*
2  * a64 video encoder - multicolor modes
3  * Copyright (c) 2009 Tobias Bindhammer
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  * a64 video encoder - multicolor modes
25  */
26
27 #include "a64enc.h"
28 #include "a64colors.h"
29 #include "a64tables.h"
30 #include "elbg.h"
31 #include "internal.h"
32 #include "libavutil/intreadwrite.h"
33
34 #define DITHERSTEPS   8
35 #define CHARSET_CHARS 256
36 #define INTERLACED    1
37 #define CROP_SCREENS  1
38
39 /* gray gradient */
40 static const int mc_colors[5]={0x0,0xb,0xc,0xf,0x1};
41
42 /* other possible gradients - to be tested */
43 //static const int mc_colors[5]={0x0,0x8,0xa,0xf,0x7};
44 //static const int mc_colors[5]={0x0,0x9,0x8,0xa,0x3};
45
46 static void to_meta_with_crop(AVCodecContext *avctx, AVFrame *p, int *dest)
47 {
48     int blockx, blocky, x, y;
49     int luma = 0;
50     int height = FFMIN(avctx->height, C64YRES);
51     int width  = FFMIN(avctx->width , C64XRES);
52     uint8_t *src = p->data[0];
53
54     for (blocky = 0; blocky < C64YRES; blocky += 8) {
55         for (blockx = 0; blockx < C64XRES; blockx += 8) {
56             for (y = blocky; y < blocky + 8 && y < C64YRES; y++) {
57                 for (x = blockx; x < blockx + 8 && x < C64XRES; x += 2) {
58                     if(x < width && y < height) {
59                         /* build average over 2 pixels */
60                         luma = (src[(x + 0 + y * p->linesize[0])] +
61                                 src[(x + 1 + y * p->linesize[0])]) / 2;
62                         /* write blocks as linear data now so they are suitable for elbg */
63                         dest[0] = luma;
64                     }
65                     dest++;
66                 }
67             }
68         }
69     }
70 }
71
72 static void render_charset(AVCodecContext *avctx, uint8_t *charset,
73                            uint8_t *colrammap)
74 {
75     A64Context *c = avctx->priv_data;
76     uint8_t row1, row2;
77     int charpos, x, y;
78     int a, b;
79     uint8_t pix;
80     int lowdiff, highdiff;
81     int *best_cb = c->mc_best_cb;
82     static uint8_t index1[256];
83     static uint8_t index2[256];
84     static uint8_t dither[256];
85     int i;
86     int distance;
87
88     /* generate lookup-tables for dither and index before looping */
89     i = 0;
90     for (a=0; a < 256; a++) {
91         if(i < c->mc_pal_size -1 && a == c->mc_luma_vals[i + 1]) {
92             distance = c->mc_luma_vals[i + 1] - c->mc_luma_vals[i];
93             for(b = 0; b <= distance; b++) {
94                   dither[c->mc_luma_vals[i] + b] = b * (DITHERSTEPS - 1) / distance;
95             }
96             i++;
97         }
98         if(i >= c->mc_pal_size - 1) dither[a] = 0;
99         index1[a] = i;
100         index2[a] = FFMIN(i + 1, c->mc_pal_size - 1);
101     }
102
103     /* and render charset */
104     for (charpos = 0; charpos < CHARSET_CHARS; charpos++) {
105         lowdiff  = 0;
106         highdiff = 0;
107         for (y = 0; y < 8; y++) {
108             row1 = 0; row2 = 0;
109             for (x = 0; x < 4; x++) {
110                 pix = best_cb[y * 4 + x];
111
112                 /* accumulate error for brightest/darkest color */
113                 if (index1[pix] >= 3)
114                     highdiff += pix - c->mc_luma_vals[3];
115                 if (index1[pix] < 1)
116                     lowdiff += c->mc_luma_vals[1] - pix;
117
118                 row1 <<= 2;
119
120                 if (INTERLACED) {
121                     row2 <<= 2;
122                     if (interlaced_dither_patterns[dither[pix]][(y & 3) * 2 + 0][x & 3])
123                         row1 |= 3-(index2[pix] & 3);
124                     else
125                         row1 |= 3-(index1[pix] & 3);
126
127                     if (interlaced_dither_patterns[dither[pix]][(y & 3) * 2 + 1][x & 3])
128                         row2 |= 3-(index2[pix] & 3);
129                     else
130                         row2 |= 3-(index1[pix] & 3);
131                 }
132                 else {
133                     if (multi_dither_patterns[dither[pix]][(y & 3)][x & 3])
134                         row1 |= 3-(index2[pix] & 3);
135                     else
136                         row1 |= 3-(index1[pix] & 3);
137                 }
138             }
139             charset[y+0x000] = row1;
140             if (INTERLACED) charset[y+0x800] = row2;
141         }
142         /* do we need to adjust pixels? */
143         if (highdiff > 0 && lowdiff > 0 && c->mc_use_5col) {
144             if (lowdiff > highdiff) {
145                 for (x = 0; x < 32; x++)
146                     best_cb[x] = FFMIN(c->mc_luma_vals[3], best_cb[x]);
147             } else {
148                 for (x = 0; x < 32; x++)
149                     best_cb[x] = FFMAX(c->mc_luma_vals[1], best_cb[x]);
150             }
151             charpos--;          /* redo now adjusted char */
152         /* no adjustment needed, all fine */
153         } else {
154             /* advance pointers */
155             best_cb += 32;
156             charset += 8;
157
158             /* remember colorram value */
159             colrammap[charpos] = (highdiff > 0);
160         }
161     }
162 }
163
164 static av_cold int a64multi_close_encoder(AVCodecContext *avctx)
165 {
166     A64Context *c = avctx->priv_data;
167     av_free(c->mc_meta_charset);
168     av_free(c->mc_best_cb);
169     av_free(c->mc_charset);
170     av_free(c->mc_charmap);
171     av_free(c->mc_colram);
172     return 0;
173 }
174
175 static av_cold int a64multi_init_encoder(AVCodecContext *avctx)
176 {
177     A64Context *c = avctx->priv_data;
178     int a;
179     av_lfg_init(&c->randctx, 1);
180
181     if (avctx->global_quality < 1) {
182         c->mc_lifetime = 4;
183     } else {
184         c->mc_lifetime = avctx->global_quality /= FF_QP2LAMBDA;
185     }
186
187     av_log(avctx, AV_LOG_INFO, "charset lifetime set to %d frame(s)\n", c->mc_lifetime);
188
189     c->mc_frame_counter = 0;
190     c->mc_use_5col      = avctx->codec->id == CODEC_ID_A64_MULTI5;
191     c->mc_pal_size      = 4 + c->mc_use_5col;
192
193     /* precalc luma values for later use */
194     for (a = 0; a < c->mc_pal_size; a++) {
195         c->mc_luma_vals[a]=a64_palette[mc_colors[a]][0] * 0.30 +
196                            a64_palette[mc_colors[a]][1] * 0.59 +
197                            a64_palette[mc_colors[a]][2] * 0.11;
198     }
199
200     if (!(c->mc_meta_charset = av_malloc(32000 * c->mc_lifetime * sizeof(int))) ||
201        !(c->mc_best_cb       = av_malloc(CHARSET_CHARS * 32 * sizeof(int)))     ||
202        !(c->mc_charmap       = av_mallocz(1000 * c->mc_lifetime * sizeof(int))) ||
203        !(c->mc_colram        = av_mallocz(CHARSET_CHARS * sizeof(uint8_t)))     ||
204        !(c->mc_charset       = av_malloc(0x800 * (INTERLACED+1) * sizeof(uint8_t)))) {
205         av_log(avctx, AV_LOG_ERROR, "Failed to allocate buffer memory.\n");
206         return AVERROR(ENOMEM);
207     }
208
209     /* set up extradata */
210     if (!(avctx->extradata = av_mallocz(8 * 4 + FF_INPUT_BUFFER_PADDING_SIZE))) {
211         av_log(avctx, AV_LOG_ERROR, "Failed to allocate memory for extradata.\n");
212         return AVERROR(ENOMEM);
213     }
214     avctx->extradata_size = 8 * 4;
215     AV_WB32(avctx->extradata, c->mc_lifetime);
216     AV_WB32(avctx->extradata + 16, INTERLACED);
217
218     avcodec_get_frame_defaults(&c->picture);
219     avctx->coded_frame            = &c->picture;
220     avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
221     avctx->coded_frame->key_frame = 1;
222     if (!avctx->codec_tag)
223          avctx->codec_tag = AV_RL32("a64m");
224
225     c->next_pts = AV_NOPTS_VALUE;
226
227     return 0;
228 }
229
230 static void a64_compress_colram(unsigned char *buf, int *charmap, uint8_t *colram)
231 {
232     int a;
233     uint8_t temp;
234     /* only needs to be done in 5col mode */
235     /* XXX could be squeezed to 0x80 bytes */
236     for (a = 0; a < 256; a++) {
237         temp  = colram[charmap[a + 0x000]] << 0;
238         temp |= colram[charmap[a + 0x100]] << 1;
239         temp |= colram[charmap[a + 0x200]] << 2;
240         if (a < 0xe8) temp |= colram[charmap[a + 0x300]] << 3;
241         buf[a] = temp << 2;
242     }
243 }
244
245 static int a64multi_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
246                                  const AVFrame *pict, int *got_packet)
247 {
248     A64Context *c = avctx->priv_data;
249     AVFrame *const p = &c->picture;
250
251     int frame;
252     int x, y;
253     int b_height;
254     int b_width;
255
256     int req_size, ret;
257     uint8_t *buf;
258
259     int *charmap     = c->mc_charmap;
260     uint8_t *colram  = c->mc_colram;
261     uint8_t *charset = c->mc_charset;
262     int *meta        = c->mc_meta_charset;
263     int *best_cb     = c->mc_best_cb;
264
265     int charset_size = 0x800 * (INTERLACED + 1);
266     int colram_size  = 0x100 * c->mc_use_5col;
267     int screen_size;
268
269     if(CROP_SCREENS) {
270         b_height = FFMIN(avctx->height,C64YRES) >> 3;
271         b_width  = FFMIN(avctx->width ,C64XRES) >> 3;
272         screen_size = b_width * b_height;
273     } else {
274         b_height = C64YRES >> 3;
275         b_width  = C64XRES >> 3;
276         screen_size = 0x400;
277     }
278
279     /* no data, means end encoding asap */
280     if (!pict) {
281         /* all done, end encoding */
282         if (!c->mc_lifetime) return 0;
283         /* no more frames in queue, prepare to flush remaining frames */
284         if (!c->mc_frame_counter) {
285             c->mc_lifetime = 0;
286         }
287         /* still frames in queue so limit lifetime to remaining frames */
288         else c->mc_lifetime = c->mc_frame_counter;
289     /* still new data available */
290     } else {
291         /* fill up mc_meta_charset with data until lifetime exceeds */
292         if (c->mc_frame_counter < c->mc_lifetime) {
293             *p = *pict;
294             p->pict_type = AV_PICTURE_TYPE_I;
295             p->key_frame = 1;
296             to_meta_with_crop(avctx, p, meta + 32000 * c->mc_frame_counter);
297             c->mc_frame_counter++;
298             if (c->next_pts == AV_NOPTS_VALUE)
299                 c->next_pts = pict->pts;
300             /* lifetime is not reached so wait for next frame first */
301             return 0;
302         }
303     }
304
305     /* lifetime reached so now convert X frames at once */
306     if (c->mc_frame_counter == c->mc_lifetime) {
307         req_size = 0;
308         /* any frames to encode? */
309         if (c->mc_lifetime) {
310             req_size = charset_size + c->mc_lifetime*(screen_size + colram_size);
311             if ((ret = ff_alloc_packet(pkt, req_size)) < 0) {
312                 av_log(avctx, AV_LOG_ERROR, "Error getting output packet of size %d.\n", req_size);
313                 return ret;
314             }
315             buf = pkt->data;
316
317             /* calc optimal new charset + charmaps */
318             ff_init_elbg(meta, 32, 1000 * c->mc_lifetime, best_cb, CHARSET_CHARS, 50, charmap, &c->randctx);
319             ff_do_elbg  (meta, 32, 1000 * c->mc_lifetime, best_cb, CHARSET_CHARS, 50, charmap, &c->randctx);
320
321             /* create colorram map and a c64 readable charset */
322             render_charset(avctx, charset, colram);
323
324             /* copy charset to buf */
325             memcpy(buf, charset, charset_size);
326
327             /* advance pointers */
328             buf      += charset_size;
329             charset  += charset_size;
330         }
331
332         /* write x frames to buf */
333         for (frame = 0; frame < c->mc_lifetime; frame++) {
334             /* copy charmap to buf. buf is uchar*, charmap is int*, so no memcpy here, sorry */
335             for (y = 0; y < b_height; y++) {
336                 for (x = 0; x < b_width; x++) {
337                     buf[y * b_width + x] = charmap[y * b_width + x];
338                 }
339             }
340             /* advance pointers */
341             buf += screen_size;
342             req_size += screen_size;
343
344             /* compress and copy colram to buf */
345             if (c->mc_use_5col) {
346                 a64_compress_colram(buf, charmap, colram);
347                 /* advance pointers */
348                 buf += colram_size;
349                 req_size += colram_size;
350             }
351
352             /* advance to next charmap */
353             charmap += 1000;
354         }
355
356         AV_WB32(avctx->extradata + 4,  c->mc_frame_counter);
357         AV_WB32(avctx->extradata + 8,  charset_size);
358         AV_WB32(avctx->extradata + 12, screen_size + colram_size);
359
360         /* reset counter */
361         c->mc_frame_counter = 0;
362
363         pkt->pts = pkt->dts = c->next_pts;
364         c->next_pts         = AV_NOPTS_VALUE;
365
366         pkt->size   = req_size;
367         pkt->flags |= AV_PKT_FLAG_KEY;
368         *got_packet = !!req_size;
369     }
370     return 0;
371 }
372
373 AVCodec ff_a64multi_encoder = {
374     .name           = "a64multi",
375     .type           = AVMEDIA_TYPE_VIDEO,
376     .id             = CODEC_ID_A64_MULTI,
377     .priv_data_size = sizeof(A64Context),
378     .init           = a64multi_init_encoder,
379     .encode2        = a64multi_encode_frame,
380     .close          = a64multi_close_encoder,
381     .pix_fmts       = (const enum PixelFormat[]) {PIX_FMT_GRAY8, PIX_FMT_NONE},
382     .long_name      = NULL_IF_CONFIG_SMALL("Multicolor charset for Commodore 64"),
383     .capabilities   = CODEC_CAP_DELAY,
384 };
385
386 AVCodec ff_a64multi5_encoder = {
387     .name           = "a64multi5",
388     .type           = AVMEDIA_TYPE_VIDEO,
389     .id             = CODEC_ID_A64_MULTI5,
390     .priv_data_size = sizeof(A64Context),
391     .init           = a64multi_init_encoder,
392     .encode2        = a64multi_encode_frame,
393     .close          = a64multi_close_encoder,
394     .pix_fmts       = (const enum PixelFormat[]) {PIX_FMT_GRAY8, PIX_FMT_NONE},
395     .long_name      = NULL_IF_CONFIG_SMALL("Multicolor charset for Commodore 64, extended with 5th color (colram)"),
396     .capabilities   = CODEC_CAP_DELAY,
397 };