xref: /third_party/ffmpeg/libavcodec/ansi.c (revision cabdff1a)
1/*
2 * ASCII/ANSI art decoder
3 * Copyright (c) 2010 Peter Ross <pross@xvid.org>
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/**
23 * @file
24 * ASCII/ANSI art decoder
25 */
26
27#include "libavutil/common.h"
28#include "libavutil/frame.h"
29#include "libavutil/lfg.h"
30#include "libavutil/xga_font_data.h"
31#include "avcodec.h"
32#include "cga_data.h"
33#include "codec_internal.h"
34#include "internal.h"
35
36#define ATTR_BOLD         0x01  /**< Bold/Bright-foreground (mode 1) */
37#define ATTR_FAINT        0x02  /**< Faint (mode 2) */
38#define ATTR_ITALICS      0x04  /**< Italics (mode 3) */
39#define ATTR_UNDERLINE    0x08  /**< Underline (mode 4) */
40#define ATTR_BLINK        0x10  /**< Blink/Bright-background (mode 5) */
41#define ATTR_REVERSE      0x40  /**< Reverse (mode 7) */
42#define ATTR_CONCEALED    0x80  /**< Concealed (mode 8) */
43
44#define DEFAULT_FG_COLOR     7  /**< CGA color index */
45#define DEFAULT_BG_COLOR     0
46#define DEFAULT_SCREEN_MODE  3  /**< 80x25 */
47
48#define FONT_WIDTH           8  /**< Font width */
49
50/** map ansi color index to cga palette index */
51static const uint8_t ansi_to_cga[16] = {
52    0,  4,  2,  6,  1,  5,  3, 7, 8, 12, 10, 14,  9, 13, 11, 15
53};
54
55typedef struct AnsiContext {
56    AVFrame *frame;
57    int x;                /**< x cursor position (pixels) */
58    int y;                /**< y cursor position (pixels) */
59    int sx;               /**< saved x cursor position (pixels) */
60    int sy;               /**< saved y cursor position (pixels) */
61    const uint8_t* font;  /**< font */
62    int font_height;      /**< font height */
63    int attributes;       /**< attribute flags */
64    int fg;               /**< foreground color */
65    int bg;               /**< background color */
66    int first_frame;
67
68    /* ansi parser state machine */
69    enum {
70        STATE_NORMAL = 0,
71        STATE_ESCAPE,
72        STATE_CODE,
73        STATE_MUSIC_PREAMBLE
74    } state;
75#define MAX_NB_ARGS 4
76    int args[MAX_NB_ARGS];
77    int nb_args;          /**< number of arguments (may exceed MAX_NB_ARGS) */
78} AnsiContext;
79
80static av_cold int decode_init(AVCodecContext *avctx)
81{
82    AnsiContext *s = avctx->priv_data;
83    avctx->pix_fmt = AV_PIX_FMT_PAL8;
84
85    /* defaults */
86    s->font        = avpriv_vga16_font;
87    s->font_height = 16;
88    s->fg          = DEFAULT_FG_COLOR;
89    s->bg          = DEFAULT_BG_COLOR;
90
91    if (!avctx->width || !avctx->height) {
92        int ret = ff_set_dimensions(avctx, 80 << 3, 25 << 4);
93        if (ret < 0)
94            return ret;
95    } else if (avctx->width % FONT_WIDTH || avctx->height % s->font_height) {
96        av_log(avctx, AV_LOG_ERROR, "Invalid dimensions %d %d\n", avctx->width, avctx->height);
97        return AVERROR(EINVAL);
98    }
99
100    s->frame = av_frame_alloc();
101    if (!s->frame)
102        return AVERROR(ENOMEM);
103
104    return 0;
105}
106
107static void set_palette(uint32_t *pal)
108{
109    int r, g, b;
110    memcpy(pal, ff_cga_palette, 16 * 4);
111    pal += 16;
112#define COLOR(x) ((x) * 40 + 55)
113    for (r = 0; r < 6; r++)
114        for (g = 0; g < 6; g++)
115            for (b = 0; b < 6; b++)
116                *pal++ = 0xFF000000 | (COLOR(r) << 16) | (COLOR(g) << 8) | COLOR(b);
117#define GRAY(x) ((x) * 10 + 8)
118    for (g = 0; g < 24; g++)
119        *pal++ = 0xFF000000 | (GRAY(g) << 16) | (GRAY(g) << 8) | GRAY(g);
120}
121
122static void hscroll(AVCodecContext *avctx)
123{
124    AnsiContext *s = avctx->priv_data;
125    int i;
126
127    if (s->y <= avctx->height - 2*s->font_height) {
128        s->y += s->font_height;
129        return;
130    }
131
132    i = 0;
133    for (; i < avctx->height - s->font_height; i++)
134        memcpy(s->frame->data[0] + i * s->frame->linesize[0],
135               s->frame->data[0] + (i + s->font_height) * s->frame->linesize[0],
136               avctx->width);
137    for (; i < avctx->height; i++)
138        memset(s->frame->data[0] + i * s->frame->linesize[0],
139            DEFAULT_BG_COLOR, avctx->width);
140}
141
142static void erase_line(AVCodecContext * avctx, int xoffset, int xlength)
143{
144    AnsiContext *s = avctx->priv_data;
145    int i;
146    for (i = 0; i < s->font_height; i++)
147        memset(s->frame->data[0] + (s->y + i)*s->frame->linesize[0] + xoffset,
148            DEFAULT_BG_COLOR, xlength);
149}
150
151static void erase_screen(AVCodecContext *avctx)
152{
153    AnsiContext *s = avctx->priv_data;
154    int i;
155    for (i = 0; i < avctx->height; i++)
156        memset(s->frame->data[0] + i * s->frame->linesize[0], DEFAULT_BG_COLOR, avctx->width);
157    s->x = s->y = 0;
158}
159
160/**
161 * Draw character to screen
162 */
163static void draw_char(AVCodecContext *avctx, int c)
164{
165    AnsiContext *s = avctx->priv_data;
166    int fg = s->fg;
167    int bg = s->bg;
168
169    if ((s->attributes & ATTR_BOLD))
170        fg += 8;
171    if ((s->attributes & ATTR_BLINK))
172        bg += 8;
173    if ((s->attributes & ATTR_REVERSE))
174        FFSWAP(int, fg, bg);
175    if ((s->attributes & ATTR_CONCEALED))
176        fg = bg;
177    ff_draw_pc_font(s->frame->data[0] + s->y * s->frame->linesize[0] + s->x,
178                    s->frame->linesize[0], s->font, s->font_height, c, fg, bg);
179    s->x += FONT_WIDTH;
180    if (s->x > avctx->width - FONT_WIDTH) {
181        s->x = 0;
182        hscroll(avctx);
183    }
184}
185
186/**
187 * Execute ANSI escape code
188 * @return 0 on success, negative on error
189 */
190static int execute_code(AVCodecContext * avctx, int c)
191{
192    AnsiContext *s = avctx->priv_data;
193    int ret, i;
194    int width  = avctx->width;
195    int height = avctx->height;
196
197    switch(c) {
198    case 'A': //Cursor Up
199        s->y = FFMAX(s->y - (s->nb_args > 0 ? s->args[0]*s->font_height : s->font_height), 0);
200        break;
201    case 'B': //Cursor Down
202        s->y = FFMIN(s->y + (s->nb_args > 0 ? s->args[0]*s->font_height : s->font_height), avctx->height - s->font_height);
203        break;
204    case 'C': //Cursor Right
205        s->x = FFMIN(s->x + (s->nb_args > 0 ? s->args[0]*FONT_WIDTH : FONT_WIDTH), avctx->width  - FONT_WIDTH);
206        break;
207    case 'D': //Cursor Left
208        s->x = FFMAX(s->x - (s->nb_args > 0 ? s->args[0]*FONT_WIDTH : FONT_WIDTH), 0);
209        break;
210    case 'H': //Cursor Position
211    case 'f': //Horizontal and Vertical Position
212        s->y = s->nb_args > 0 ? av_clip((s->args[0] - 1)*s->font_height, 0, avctx->height - s->font_height) : 0;
213        s->x = s->nb_args > 1 ? av_clip((s->args[1] - 1)*FONT_WIDTH,     0, avctx->width  - FONT_WIDTH) : 0;
214        break;
215    case 'h': //set screen mode
216    case 'l': //reset screen mode
217        if (s->nb_args < 2)
218            s->args[0] = DEFAULT_SCREEN_MODE;
219        switch(s->args[0]) {
220        case 0: case 1: case 4: case 5: case 13: case 19: //320x200 (25 rows)
221            s->font = avpriv_cga_font;
222            s->font_height = 8;
223            width  = 40<<3;
224            height = 25<<3;
225            break;
226        case 2: case 3: //640x400 (25 rows)
227            s->font = avpriv_vga16_font;
228            s->font_height = 16;
229            width  = 80<<3;
230            height = 25<<4;
231            break;
232        case 6: case 14: //640x200 (25 rows)
233            s->font = avpriv_cga_font;
234            s->font_height = 8;
235            width  = 80<<3;
236            height = 25<<3;
237            break;
238        case 7: //set line wrapping
239            break;
240        case 15: case 16: //640x350 (43 rows)
241            s->font = avpriv_cga_font;
242            s->font_height = 8;
243            width  = 80<<3;
244            height = 43<<3;
245            break;
246        case 17: case 18: //640x480 (60 rows)
247            s->font = avpriv_cga_font;
248            s->font_height = 8;
249            width  = 80<<3;
250            height = 60<<4;
251            break;
252        default:
253            avpriv_request_sample(avctx, "Unsupported screen mode");
254        }
255        s->x = av_clip(s->x, 0, width  - FONT_WIDTH);
256        s->y = av_clip(s->y, 0, height - s->font_height);
257        if (width != avctx->width || height != avctx->height) {
258            av_frame_unref(s->frame);
259            ret = ff_set_dimensions(avctx, width, height);
260            if (ret < 0)
261                return ret;
262            if ((ret = ff_get_buffer(avctx, s->frame,
263                                     AV_GET_BUFFER_FLAG_REF)) < 0)
264                return ret;
265            s->frame->pict_type           = AV_PICTURE_TYPE_I;
266            s->frame->palette_has_changed = 1;
267            set_palette((uint32_t *)s->frame->data[1]);
268            erase_screen(avctx);
269        } else if (c == 'l') {
270            erase_screen(avctx);
271        }
272        break;
273    case 'J': //Erase in Page
274        switch (s->args[0]) {
275        case 0:
276            erase_line(avctx, s->x, avctx->width - s->x);
277            if (s->y < avctx->height - s->font_height)
278                memset(s->frame->data[0] + (s->y + s->font_height)*s->frame->linesize[0],
279                    DEFAULT_BG_COLOR, (avctx->height - s->y - s->font_height)*s->frame->linesize[0]);
280            break;
281        case 1:
282            erase_line(avctx, 0, s->x);
283            if (s->y > 0)
284                memset(s->frame->data[0], DEFAULT_BG_COLOR, s->y * s->frame->linesize[0]);
285            break;
286        case 2:
287            erase_screen(avctx);
288        }
289        break;
290    case 'K': //Erase in Line
291        switch(s->args[0]) {
292        case 0:
293            erase_line(avctx, s->x, avctx->width - s->x);
294            break;
295        case 1:
296            erase_line(avctx, 0, s->x);
297            break;
298        case 2:
299            erase_line(avctx, 0, avctx->width);
300        }
301        break;
302    case 'm': //Select Graphics Rendition
303        if (s->nb_args == 0) {
304            s->nb_args = 1;
305            s->args[0] = 0;
306        }
307        for (i = 0; i < FFMIN(s->nb_args, MAX_NB_ARGS); i++) {
308            int m = s->args[i];
309            if (m == 0) {
310                s->attributes = 0;
311                s->fg = DEFAULT_FG_COLOR;
312                s->bg = DEFAULT_BG_COLOR;
313            } else if (m == 1 || m == 2 || m == 3 || m == 4 || m == 5 || m == 7 || m == 8) {
314                s->attributes |= 1 << (m - 1);
315            } else if (m >= 30 && m <= 37) {
316                s->fg = ansi_to_cga[m - 30];
317            } else if (m == 38 && i + 2 < FFMIN(s->nb_args, MAX_NB_ARGS) && s->args[i + 1] == 5 && s->args[i + 2] < 256) {
318                int index = s->args[i + 2];
319                s->fg = index < 16 ? ansi_to_cga[index] : index;
320                i += 2;
321            } else if (m == 39) {
322                s->fg = ansi_to_cga[DEFAULT_FG_COLOR];
323            } else if (m >= 40 && m <= 47) {
324                s->bg = ansi_to_cga[m - 40];
325            } else if (m == 48 && i + 2 < FFMIN(s->nb_args, MAX_NB_ARGS) && s->args[i + 1] == 5 && s->args[i + 2] < 256) {
326                int index = s->args[i + 2];
327                s->bg = index < 16 ? ansi_to_cga[index] : index;
328                i += 2;
329            } else if (m == 49) {
330                s->fg = ansi_to_cga[DEFAULT_BG_COLOR];
331            } else {
332                avpriv_request_sample(avctx, "Unsupported rendition parameter");
333            }
334        }
335        break;
336    case 'n': //Device Status Report
337    case 'R': //report current line and column
338        /* ignore */
339        break;
340    case 's': //Save Cursor Position
341        s->sx = s->x;
342        s->sy = s->y;
343        break;
344    case 'u': //Restore Cursor Position
345        s->x = av_clip(s->sx, 0, avctx->width  - FONT_WIDTH);
346        s->y = av_clip(s->sy, 0, avctx->height - s->font_height);
347        break;
348    default:
349        avpriv_request_sample(avctx, "Unknown escape code");
350        break;
351    }
352    s->x = av_clip(s->x, 0, avctx->width  - FONT_WIDTH);
353    s->y = av_clip(s->y, 0, avctx->height - s->font_height);
354    return 0;
355}
356
357static int decode_frame(AVCodecContext *avctx, AVFrame *rframe,
358                        int *got_frame, AVPacket *avpkt)
359{
360    AnsiContext *s = avctx->priv_data;
361    const uint8_t *buf = avpkt->data;
362    int buf_size = avpkt->size;
363    const uint8_t *buf_end   = buf+buf_size;
364    int ret, i, count;
365
366    if ((ret = ff_reget_buffer(avctx, s->frame, 0)) < 0)
367        return ret;
368    if (!avctx->frame_number) {
369        for (i=0; i<avctx->height; i++)
370            memset(s->frame->data[0]+ i*s->frame->linesize[0], 0, avctx->width);
371        memset(s->frame->data[1], 0, AVPALETTE_SIZE);
372    }
373
374    s->frame->pict_type           = AV_PICTURE_TYPE_I;
375    s->frame->palette_has_changed = 1;
376    set_palette((uint32_t *)s->frame->data[1]);
377    if (!s->first_frame) {
378        erase_screen(avctx);
379        s->first_frame = 1;
380    }
381
382    while(buf < buf_end) {
383        switch(s->state) {
384        case STATE_NORMAL:
385            switch (buf[0]) {
386            case 0x00: //NUL
387            case 0x07: //BEL
388            case 0x1A: //SUB
389                /* ignore */
390                break;
391            case 0x08: //BS
392                s->x = FFMAX(s->x - 1, 0);
393                break;
394            case 0x09: //HT
395                i = s->x / FONT_WIDTH;
396                count = ((i + 8) & ~7) - i;
397                for (i = 0; i < count; i++)
398                    draw_char(avctx, ' ');
399                break;
400            case 0x0A: //LF
401                hscroll(avctx);
402            case 0x0D: //CR
403                s->x = 0;
404                break;
405            case 0x0C: //FF
406                erase_screen(avctx);
407                break;
408            case 0x1B: //ESC
409                s->state = STATE_ESCAPE;
410                break;
411            default:
412                draw_char(avctx, buf[0]);
413            }
414            break;
415        case STATE_ESCAPE:
416            if (buf[0] == '[') {
417                s->state   = STATE_CODE;
418                s->nb_args = 0;
419                s->args[0] = -1;
420            } else {
421                s->state = STATE_NORMAL;
422                draw_char(avctx, 0x1B);
423                continue;
424            }
425            break;
426        case STATE_CODE:
427            switch(buf[0]) {
428            case '0': case '1': case '2': case '3': case '4':
429            case '5': case '6': case '7': case '8': case '9':
430                if (s->nb_args < MAX_NB_ARGS && s->args[s->nb_args] < 6553)
431                    s->args[s->nb_args] = FFMAX(s->args[s->nb_args], 0) * 10 + buf[0] - '0';
432                break;
433            case ';':
434                if (s->nb_args < MAX_NB_ARGS)
435                    s->nb_args++;
436                if (s->nb_args < MAX_NB_ARGS)
437                    s->args[s->nb_args] = 0;
438                break;
439            case 'M':
440                s->state = STATE_MUSIC_PREAMBLE;
441                break;
442            case '=': case '?':
443                /* ignore */
444                break;
445            default:
446                if (s->nb_args > MAX_NB_ARGS)
447                    av_log(avctx, AV_LOG_WARNING, "args overflow (%i)\n", s->nb_args);
448                if (s->nb_args < MAX_NB_ARGS && s->args[s->nb_args] >= 0)
449                    s->nb_args++;
450                if ((ret = execute_code(avctx, buf[0])) < 0)
451                    return ret;
452                s->state = STATE_NORMAL;
453            }
454            break;
455        case STATE_MUSIC_PREAMBLE:
456            if (buf[0] == 0x0E || buf[0] == 0x1B)
457                s->state = STATE_NORMAL;
458            /* ignore music data */
459            break;
460        }
461        buf++;
462    }
463
464    *got_frame = 1;
465    if ((ret = av_frame_ref(rframe, s->frame)) < 0)
466        return ret;
467    return buf_size;
468}
469
470static av_cold int decode_close(AVCodecContext *avctx)
471{
472    AnsiContext *s = avctx->priv_data;
473
474    av_frame_free(&s->frame);
475    return 0;
476}
477
478static const FFCodecDefault ansi_defaults[] = {
479    { "max_pixels", "640*480" },
480    { NULL },
481};
482
483const FFCodec ff_ansi_decoder = {
484    .p.name         = "ansi",
485    .p.long_name    = NULL_IF_CONFIG_SMALL("ASCII/ANSI art"),
486    .p.type         = AVMEDIA_TYPE_VIDEO,
487    .p.id           = AV_CODEC_ID_ANSI,
488    .priv_data_size = sizeof(AnsiContext),
489    .init           = decode_init,
490    .close          = decode_close,
491    FF_CODEC_DECODE_CB(decode_frame),
492    .p.capabilities = AV_CODEC_CAP_DR1,
493    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
494    .defaults       = ansi_defaults,
495};
496