]> git.sesse.net Git - ffmpeg/blob - libavcodec/libzvbi-teletextdec.c
libzvbi-teletextdec: use AVBPrint for whitespace cleanup
[ffmpeg] / libavcodec / libzvbi-teletextdec.c
1 /*
2  * Teletext decoding for ffmpeg
3  * Copyright (c) 2005-2010, 2012 Wolfram Gloger
4  * Copyright (c) 2013 Marton Balint
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "avcodec.h"
22 #include "libavutil/opt.h"
23 #include "libavutil/bprint.h"
24 #include "libavutil/intreadwrite.h"
25
26 #include <libzvbi.h>
27
28 #define TEXT_MAXSZ    (25 * (56 + 1) * 4 + 2)
29 #define VBI_NB_COLORS 40
30 #define RGBA(r,g,b,a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))
31 #define VBI_R(rgba)   (((rgba) >> 0) & 0xFF)
32 #define VBI_G(rgba)   (((rgba) >> 8) & 0xFF)
33 #define VBI_B(rgba)   (((rgba) >> 16) & 0xFF)
34 #define VBI_A(rgba)   (((rgba) >> 24) & 0xFF)
35 #define MAX_BUFFERED_PAGES 25
36
37 typedef struct TeletextPage
38 {
39     AVSubtitleRect *sub_rect;
40     int pgno;
41     int subno;
42     int64_t pts;
43 } TeletextPage;
44
45 /* main data structure */
46 typedef struct TeletextContext
47 {
48     AVClass        *class;
49     char           *pgno;
50     int             x_offset;
51     int             y_offset;
52     int             format_id; /* 0 = bitmap, 1 = text */
53     int             chop_top;
54     int             sub_duration; /* in msec */
55     int             transparent_bg;
56     int             chop_spaces;
57
58     int             lines_processed;
59     TeletextPage    *pages;
60     int             nb_pages;
61     int64_t         pts;
62
63     vbi_decoder *   vbi;
64     vbi_dvb_demux * dx;
65 #ifdef DEBUG
66     vbi_export *    ex;
67 #endif
68     /* Don't even _think_ about making sliced stack-local! */
69     vbi_sliced      sliced[64];
70 } TeletextContext;
71
72 /************************************************************************/
73
74 static int
75 chop_spaces_utf8(const unsigned char* t, int len)
76 {
77     t += len;
78     while (len > 0) {
79         if (*--t != ' ' || (len-1 > 0 && *(t-1) & 0x80))
80             break;
81         --len;
82     }
83     return len;
84 }
85
86 static void
87 subtitle_rect_free(AVSubtitleRect **sub_rect)
88 {
89     av_freep(&(*sub_rect)->pict.data[0]);
90     av_freep(&(*sub_rect)->pict.data[1]);
91     av_freep(&(*sub_rect)->text);
92     av_freep(sub_rect);
93 }
94
95 // draw a page as text
96 static int
97 gen_sub_text(TeletextContext *ctx, AVSubtitleRect *sub_rect, vbi_page *page, int chop_top)
98 {
99     const char *in;
100     AVBPrint buf;
101     char *vbi_text = av_malloc(TEXT_MAXSZ);
102     int sz;
103
104     if (!vbi_text)
105         return AVERROR(ENOMEM);
106
107     sz = vbi_print_page_region(page, vbi_text, TEXT_MAXSZ-1, "UTF-8",
108                                    /*table mode*/ TRUE, FALSE,
109                                    0,             chop_top,
110                                    page->columns, page->rows-chop_top);
111     if (sz <= 0) {
112         av_log(ctx, AV_LOG_ERROR, "vbi_print error\n");
113         av_free(vbi_text);
114         return AVERROR_EXTERNAL;
115     }
116     vbi_text[sz] = '\0';
117     in  = vbi_text;
118     av_bprint_init(&buf, 0, TEXT_MAXSZ);
119
120     if (ctx->chop_spaces) {
121         for (;;) {
122             int nl, sz;
123
124             // skip leading spaces and newlines
125             in += strspn(in, " \n");
126             // compute end of row
127             for (nl = 0; in[nl]; ++nl)
128                 if (in[nl] == '\n' && (nl==0 || !(in[nl-1] & 0x80)))
129                     break;
130             if (!in[nl])
131                 break;
132             // skip trailing spaces
133             sz = chop_spaces_utf8(in, nl);
134             av_bprint_append_data(&buf, in, sz);
135             av_bprintf(&buf, "\n");
136             in += nl;
137         }
138     } else {
139         av_bprintf(&buf, "%s\n", vbi_text);
140     }
141     av_free(vbi_text);
142
143     if (!av_bprint_is_complete(&buf)) {
144         av_bprint_finalize(&buf, NULL);
145         return AVERROR(ENOMEM);
146     }
147
148     if (buf.len) {
149         int ret;
150         sub_rect->type = SUBTITLE_TEXT;
151         if ((ret = av_bprint_finalize(&buf, &sub_rect->text)) < 0)
152             return ret;
153         av_log(ctx, AV_LOG_DEBUG, "subtext:%s:txetbus\n", sub_rect->text);
154     } else {
155         sub_rect->type = SUBTITLE_NONE;
156         av_bprint_finalize(&buf, NULL);
157     }
158     return 0;
159 }
160
161 static void
162 fix_transparency(TeletextContext *ctx, AVSubtitleRect *sub_rect, vbi_page *page, int chop_top, uint8_t transparent_color, int resx, int resy)
163 {
164     int iy;
165
166     // Hack for transparency, inspired by VLC code...
167     for (iy = 0; iy < resy; iy++) {
168         uint8_t *pixel = sub_rect->pict.data[0] + iy * sub_rect->pict.linesize[0];
169         vbi_char *vc = page->text + (iy / 10 + chop_top) * page->columns;
170         vbi_char *vcnext = vc + page->columns;
171         for (; vc < vcnext; vc++) {
172             uint8_t *pixelnext = pixel + 12;
173             switch (vc->opacity) {
174                 case VBI_TRANSPARENT_SPACE:
175                     memset(pixel, transparent_color, 12);
176                     break;
177                 case VBI_OPAQUE:
178                 case VBI_SEMI_TRANSPARENT:
179                     if (!ctx->transparent_bg)
180                         break;
181                 case VBI_TRANSPARENT_FULL:
182                     for(; pixel < pixelnext; pixel++)
183                         if (*pixel == vc->background)
184                             *pixel = transparent_color;
185                     break;
186             }
187             pixel = pixelnext;
188         }
189     }
190 }
191
192 // draw a page as bitmap
193 static int
194 gen_sub_bitmap(TeletextContext *ctx, AVSubtitleRect *sub_rect, vbi_page *page, int chop_top)
195 {
196     int resx = page->columns * 12;
197     int resy = (page->rows - chop_top) * 10;
198     uint8_t ci, cmax = 0;
199     int ret;
200     vbi_char *vc = page->text + (chop_top * page->columns);
201     vbi_char *vcend = page->text + (page->rows * page->columns);
202
203     for (; vc < vcend; vc++) {
204         if (vc->opacity != VBI_TRANSPARENT_SPACE) {
205             cmax = VBI_NB_COLORS;
206             break;
207         }
208     }
209
210     if (cmax == 0) {
211         av_log(ctx, AV_LOG_DEBUG, "dropping empty page %3x\n", page->pgno);
212         sub_rect->type = SUBTITLE_NONE;
213         return 0;
214     }
215
216     if ((ret = avpicture_alloc(&sub_rect->pict, AV_PIX_FMT_PAL8, resx, resy)) < 0)
217         return ret;
218     // Yes, we want to allocate the palette on our own because AVSubtitle works this way
219     sub_rect->pict.data[1] = NULL;
220
221     vbi_draw_vt_page_region(page, VBI_PIXFMT_PAL8,
222                             sub_rect->pict.data[0], sub_rect->pict.linesize[0],
223                             0, chop_top, page->columns, page->rows - chop_top,
224                             /*reveal*/ 1, /*flash*/ 1);
225
226     fix_transparency(ctx, sub_rect, page, chop_top, cmax, resx, resy);
227     sub_rect->x = ctx->x_offset;
228     sub_rect->y = ctx->y_offset;
229     sub_rect->w = resx;
230     sub_rect->h = resy;
231     sub_rect->nb_colors = (int)cmax + 1;
232     sub_rect->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
233     if (!sub_rect->pict.data[1]) {
234         av_freep(&sub_rect->pict.data[0]);
235         return AVERROR(ENOMEM);
236     }
237     for (ci = 0; ci < cmax; ci++) {
238         int r, g, b, a;
239
240         r = VBI_R(page->color_map[ci]);
241         g = VBI_G(page->color_map[ci]);
242         b = VBI_B(page->color_map[ci]);
243         a = VBI_A(page->color_map[ci]);
244         ((uint32_t *)sub_rect->pict.data[1])[ci] = RGBA(r, g, b, a);
245 #ifdef DEBUG
246         av_log(ctx, AV_LOG_DEBUG, "palette %0x\n",
247                ((uint32_t *)sub_rect->pict.data[1])[ci]);
248 #endif
249     }
250     ((uint32_t *)sub_rect->pict.data[1])[cmax] = RGBA(0, 0, 0, 0);
251     sub_rect->type = SUBTITLE_BITMAP;
252     return 0;
253 }
254
255 static void
256 handler(vbi_event *ev, void *user_data)
257 {
258     TeletextContext *ctx = user_data;
259     TeletextPage *new_pages;
260     vbi_page page;
261     int res;
262     char pgno_str[12];
263     vbi_subno subno;
264     vbi_page_type vpt;
265     int chop_top;
266     char *lang;
267
268     snprintf(pgno_str, sizeof pgno_str, "%03x", ev->ev.ttx_page.pgno);
269     av_log(ctx, AV_LOG_DEBUG, "decoded page %s.%02x\n",
270            pgno_str, ev->ev.ttx_page.subno & 0xFF);
271
272     if (strcmp(ctx->pgno, "*") && !strstr(ctx->pgno, pgno_str))
273         return;
274
275     /* Fetch the page.  */
276     res = vbi_fetch_vt_page(ctx->vbi, &page,
277                             ev->ev.ttx_page.pgno,
278                             ev->ev.ttx_page.subno,
279                             VBI_WST_LEVEL_3p5, 25, TRUE);
280
281     if (!res)
282         return;
283
284 #ifdef DEBUG
285     fprintf(stderr, "\nSaving res=%d dy0=%d dy1=%d...\n",
286             res, page.dirty.y0, page.dirty.y1);
287     fflush(stderr);
288
289     if (!vbi_export_stdio(ctx->ex, stderr, &page))
290         fprintf(stderr, "failed: %s\n", vbi_export_errstr(ctx->ex));
291 #endif
292
293     vpt = vbi_classify_page(ctx->vbi, ev->ev.ttx_page.pgno, &subno, &lang);
294     chop_top = ctx->chop_top ||
295         ((page.rows > 1) && (vpt == VBI_SUBTITLE_PAGE));
296
297     av_log(ctx, AV_LOG_DEBUG, "%d x %d page chop:%d\n",
298            page.columns, page.rows, chop_top);
299
300     if (ctx->nb_pages < MAX_BUFFERED_PAGES) {
301         if ((new_pages = av_realloc_array(ctx->pages, ctx->nb_pages + 1, sizeof(TeletextPage)))) {
302             TeletextPage *cur_page = new_pages + ctx->nb_pages;
303             ctx->pages = new_pages;
304             cur_page->sub_rect = av_mallocz(sizeof(*cur_page->sub_rect));
305             cur_page->pts = ctx->pts;
306             cur_page->pgno = ev->ev.ttx_page.pgno;
307             cur_page->subno = ev->ev.ttx_page.subno;
308             if (cur_page->sub_rect) {
309                 res = (ctx->format_id == 0) ?
310                     gen_sub_bitmap(ctx, cur_page->sub_rect, &page, chop_top) :
311                     gen_sub_text  (ctx, cur_page->sub_rect, &page, chop_top);
312                 if (res)
313                     av_freep(&cur_page->sub_rect);
314                 else
315                     ctx->pages[ctx->nb_pages++] = *cur_page;
316             }
317         } else {
318             av_log(ctx, AV_LOG_ERROR, "Failed to allocate memory to to buffer pages\n");
319         }
320     } else {
321         //TODO: If multiple packets contain more than one page, pages may got queued up, and this may happen...
322         av_log(ctx, AV_LOG_ERROR, "Buffered too many pages, dropping page %s.\n", pgno_str);
323     }
324
325     vbi_unref_page(&page);
326 }
327
328 static int
329 teletext_decode_frame(AVCodecContext *avctx,
330                       void *data, int *data_size,
331                       AVPacket *pkt)
332 {
333     TeletextContext *ctx = avctx->priv_data;
334     AVSubtitle      *sub = data;
335     const uint8_t   *buf = pkt->data;
336     int             left = pkt->size;
337     uint8_t         pesheader[45] = {0x00, 0x00, 0x01, 0xbd, 0x00, 0x00, 0x85, 0x80, 0x24, 0x21, 0x00, 0x01, 0x00, 0x01};
338     int             pesheader_size = sizeof(pesheader);
339     const uint8_t   *pesheader_buf = pesheader;
340     int             ret = 0;
341
342     if (!ctx->vbi) {
343         if (!(ctx->vbi = vbi_decoder_new()))
344             return AVERROR(ENOMEM);
345         if (!vbi_event_handler_add(ctx->vbi, VBI_EVENT_TTX_PAGE, handler, ctx)) {
346             vbi_decoder_delete(ctx->vbi);
347             ctx->vbi = NULL;
348             return AVERROR(ENOMEM);
349         }
350     }
351     if (!ctx->dx && (!(ctx->dx = vbi_dvb_pes_demux_new (/* callback */ NULL, NULL))))
352         return AVERROR(ENOMEM);
353
354     if (avctx->pkt_timebase.den && pkt->pts != AV_NOPTS_VALUE)
355         ctx->pts = av_rescale_q(pkt->pts, avctx->pkt_timebase, AV_TIME_BASE_Q);
356
357     if (left) {
358         // We allow unreasonably big packets, even if the standard only allows a max size of 1472
359         if ((pesheader_size + left) < 184 || (pesheader_size + left) > 65504 || (pesheader_size + left) % 184 != 0)
360             return AVERROR_INVALIDDATA;
361
362         memset(pesheader + 14, 0xff, pesheader_size - 14);
363         AV_WB16(pesheader + 4, left + pesheader_size - 6);
364
365         /* PTS is deliberately left as 0 in the PES header, otherwise libzvbi uses
366          * it to detect dropped frames. Unforunatey the guessed packet PTS values
367          * (see mpegts demuxer) are not accurate enough to pass that test. */
368         vbi_dvb_demux_cor(ctx->dx, ctx->sliced, 64, NULL, &pesheader_buf, &pesheader_size);
369
370         while (left > 0) {
371             int64_t pts = 0;
372             unsigned int lines = vbi_dvb_demux_cor(ctx->dx, ctx->sliced, 64, &pts, &buf, &left);
373 #ifdef DEBUG
374             av_log(avctx, AV_LOG_DEBUG,
375                    "ctx=%p buf_size=%d left=%u lines=%u pts=%f pkt_pts=%f\n",
376                    ctx, pkt->size, left, lines, (double)pts/90000.0, (double)pkt->pts/90000.0);
377 #endif
378             if (lines > 0) {
379 #ifdef DEBUGx
380                 int i;
381                 for(i=0; i<lines; ++i)
382                     av_log(avctx, AV_LOG_DEBUG,
383                            "lines=%d id=%x\n", i, ctx->sliced[i].id);
384 #endif
385                 vbi_decode(ctx->vbi, ctx->sliced, lines, (double)pts/90000.0);
386                 ctx->lines_processed += lines;
387             }
388         }
389         ctx->pts = AV_NOPTS_VALUE;
390         ret = pkt->size;
391     }
392
393     // is there a subtitle to pass?
394     if (ctx->nb_pages) {
395         int i;
396         sub->format = (ctx->pages->sub_rect->type == SUBTITLE_TEXT ? 1: 0);
397         sub->start_display_time = 0;
398         sub->end_display_time = ctx->sub_duration;
399         sub->num_rects = 0;
400         sub->pts = ctx->pages->pts;
401
402         if (ctx->pages->sub_rect->type != SUBTITLE_NONE) {
403             sub->rects = av_malloc(sizeof(*sub->rects) * 1);
404             if (sub->rects) {
405                 sub->num_rects = 1;
406                 sub->rects[0] = ctx->pages->sub_rect;
407             }
408         } else {
409             av_log(avctx, AV_LOG_DEBUG, "sending empty sub\n");
410             sub->rects = NULL;
411         }
412         if (!sub->rects) // no rect was passed
413             subtitle_rect_free(&ctx->pages->sub_rect);
414
415         for (i = 0; i < ctx->nb_pages - 1; i++)
416             ctx->pages[i] = ctx->pages[i + 1];
417         ctx->nb_pages--;
418
419         *data_size = 1;
420     } else
421         *data_size = 0;
422
423     return ret;
424 }
425
426 static int teletext_init_decoder(AVCodecContext *avctx)
427 {
428     TeletextContext *ctx = avctx->priv_data;
429     unsigned int maj, min, rev;
430
431     vbi_version(&maj, &min, &rev);
432     if (!(maj > 0 || min > 2 || min == 2 && rev >= 26)) {
433         av_log(avctx, AV_LOG_ERROR, "decoder needs zvbi version >= 0.2.26.\n");
434         return AVERROR_EXTERNAL;
435     }
436
437     ctx->dx = NULL;
438     ctx->vbi = NULL;
439     ctx->pts = AV_NOPTS_VALUE;
440
441 #ifdef DEBUG
442     {
443         char *t;
444         ctx->ex = vbi_export_new("text", &t);
445     }
446 #endif
447     av_log(avctx, AV_LOG_VERBOSE, "page filter: %s\n", ctx->pgno);
448     return 0;
449 }
450
451 static int teletext_close_decoder(AVCodecContext *avctx)
452 {
453     TeletextContext *ctx = avctx->priv_data;
454
455 #ifdef DEBUG
456     av_log(avctx, AV_LOG_DEBUG, "lines_total=%u\n", ctx->lines_processed);
457 #endif
458     while (ctx->nb_pages)
459         subtitle_rect_free(&ctx->pages[--ctx->nb_pages].sub_rect);
460     av_freep(&ctx->pages);
461
462     vbi_dvb_demux_delete(ctx->dx);
463     vbi_decoder_delete(ctx->vbi);
464     ctx->dx = NULL;
465     ctx->vbi = NULL;
466     ctx->pts = AV_NOPTS_VALUE;
467     return 0;
468 }
469
470 static void teletext_flush(AVCodecContext *avctx)
471 {
472     teletext_close_decoder(avctx);
473 }
474
475 #define OFFSET(x) offsetof(TeletextContext, x)
476 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
477 static const AVOption options[] = {
478     {"txt_page",        "list of teletext page numbers to decode, * is all", OFFSET(pgno),           AV_OPT_TYPE_STRING, {.str = "*"},      0, 0,        SD},
479     {"txt_chop_top",    "discards the top teletext line",                    OFFSET(chop_top),       AV_OPT_TYPE_INT,    {.i64 = 1},        0, 1,        SD},
480     {"txt_format",      "format of the subtitles (bitmap or text)",          OFFSET(format_id),      AV_OPT_TYPE_INT,    {.i64 = 0},        0, 1,        SD,  "txt_format"},
481     {"bitmap",          NULL,                                                0,                      AV_OPT_TYPE_CONST,  {.i64 = 0},        0, 0,        SD,  "txt_format"},
482     {"text",            NULL,                                                0,                      AV_OPT_TYPE_CONST,  {.i64 = 1},        0, 0,        SD,  "txt_format"},
483     {"txt_left",        "x offset of generated bitmaps",                     OFFSET(x_offset),       AV_OPT_TYPE_INT,    {.i64 = 0},        0, 65535,    SD},
484     {"txt_top",         "y offset of generated bitmaps",                     OFFSET(y_offset),       AV_OPT_TYPE_INT,    {.i64 = 0},        0, 65535,    SD},
485     {"txt_chop_spaces", "chops leading and trailing spaces from text",       OFFSET(chop_spaces),    AV_OPT_TYPE_INT,    {.i64 = 1},        0, 1,        SD},
486     {"txt_duration",    "display duration of teletext pages in msecs",       OFFSET(sub_duration),   AV_OPT_TYPE_INT,    {.i64 = 30000},    0, 86400000, SD},
487     {"txt_transparent", "force transparent background of the teletext",      OFFSET(transparent_bg), AV_OPT_TYPE_INT,    {.i64 = 0},        0, 1,        SD},
488     { NULL },
489 };
490
491 static const AVClass teletext_class = {
492     .class_name = "libzvbi_teletextdec",
493     .item_name  = av_default_item_name,
494     .option     = options,
495     .version    = LIBAVUTIL_VERSION_INT,
496 };
497
498 AVCodec ff_libzvbi_teletext_decoder = {
499     .name      = "libzvbi_teletextdec",
500     .long_name = NULL_IF_CONFIG_SMALL("Libzvbi DVB teletext decoder"),
501     .type      = AVMEDIA_TYPE_SUBTITLE,
502     .id        = AV_CODEC_ID_DVB_TELETEXT,
503     .priv_data_size = sizeof(TeletextContext),
504     .init      = teletext_init_decoder,
505     .close     = teletext_close_decoder,
506     .decode    = teletext_decode_frame,
507     .capabilities = CODEC_CAP_DELAY,
508     .flush     = teletext_flush,
509     .priv_class= &teletext_class,
510 };