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