2 * Teletext decoding for ffmpeg
3 * Copyright (c) 2005-2010, 2012 Wolfram Gloger
4 * Copyright (c) 2013 Marton Balint
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.
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.
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
22 #include "libavutil/opt.h"
23 #include "libavutil/intreadwrite.h"
27 #define TEXT_MAXSZ (25 * (56 + 1) * 4 + 2)
28 #define VBI_NB_COLORS 40
29 #define RGBA(r,g,b,a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))
30 #define VBI_R(rgba) (((rgba) >> 0) & 0xFF)
31 #define VBI_G(rgba) (((rgba) >> 8) & 0xFF)
32 #define VBI_B(rgba) (((rgba) >> 16) & 0xFF)
33 #define VBI_A(rgba) (((rgba) >> 24) & 0xFF)
35 /* main data structure */
36 typedef struct TeletextContext
43 int format_id; /* 0 = bitmap, 1 = text */
45 int sub_duration; /* in msec */
50 AVSubtitleRect *sub_rect;
57 /* Don't even _think_ about making sliced stack-local! */
58 vbi_sliced sliced[64];
61 /************************************************************************/
64 chop_spaces_utf8(const unsigned char* t, int len)
68 if (*--t != ' ' || (len-1 > 0 && *(t-1) & 0x80))
75 // draw a page as text
77 gen_sub_text(TeletextContext *ctx, vbi_page *page, int chop_top)
79 AVSubtitleRect *sub_rect = ctx->sub_rect;
83 char *vbi_text = av_malloc(TEXT_MAXSZ);
87 return AVERROR(ENOMEM);
89 sz = vbi_print_page_region(page, vbi_text, TEXT_MAXSZ-1, "UTF-8",
90 /*table mode*/ TRUE, FALSE,
92 page->columns, page->rows-chop_top);
94 av_log(ctx, AV_LOG_ERROR, "vbi_print error\n");
96 return AVERROR_EXTERNAL;
100 out = text = av_malloc(TEXT_MAXSZ);
103 return AVERROR(ENOMEM);
105 if (ctx->chop_spaces) {
109 // skip leading spaces and newlines
110 in += strspn(in, " \n");
111 // compute end of row
112 for (nl = 0; in[nl]; ++nl)
113 if (in[nl] == '\n' && (nl==0 || !(in[nl-1] & 0x80)))
117 // skip trailing spaces
118 sz = chop_spaces_utf8(in, nl);
125 strcpy(text, vbi_text);
132 sub_rect->type = SUBTITLE_TEXT;
133 sub_rect->text = text;
134 av_log(ctx, AV_LOG_DEBUG, "subtext:%s:txetbus\n", text);
136 sub_rect->type = SUBTITLE_NONE;
143 fix_transparency(TeletextContext *ctx, vbi_page *page, int chop_top, uint8_t transparent_color, int resx, int resy)
145 AVSubtitleRect *sub_rect = ctx->sub_rect;
148 // Hack for transparency, inspired by VLC code...
149 for (iy = 0; iy < resy; iy++) {
150 uint8_t *pixel = sub_rect->pict.data[0] + iy * sub_rect->pict.linesize[0];
151 vbi_char *vc = page->text + (iy / 10 + chop_top) * page->columns;
152 vbi_char *vcnext = vc + page->columns;
153 for (; vc < vcnext; vc++) {
154 uint8_t *pixelnext = pixel + 12;
155 switch (vc->opacity) {
156 case VBI_TRANSPARENT_SPACE:
157 memset(pixel, transparent_color, 12);
160 case VBI_SEMI_TRANSPARENT:
161 if (!ctx->transparent_bg)
163 case VBI_TRANSPARENT_FULL:
164 for(; pixel < pixelnext; pixel++)
165 if (*pixel == vc->background)
166 *pixel = transparent_color;
174 // draw a page as bitmap
176 gen_sub_bitmap(TeletextContext *ctx, vbi_page *page, int chop_top)
178 AVSubtitleRect *sub_rect = ctx->sub_rect;
179 int resx = page->columns * 12;
180 int resy = (page->rows - chop_top) * 10;
181 uint8_t ci, cmax = 0;
183 vbi_char *vc = page->text + (chop_top * page->columns);
184 vbi_char *vcend = page->text + (page->rows * page->columns);
186 for (; vc < vcend; vc++) {
187 if (vc->opacity != VBI_TRANSPARENT_SPACE) {
188 cmax = VBI_NB_COLORS;
194 av_log(ctx, AV_LOG_DEBUG, "dropping empty page %3x\n", page->pgno);
195 sub_rect->type = SUBTITLE_NONE;
199 if ((ret = avpicture_alloc(&sub_rect->pict, AV_PIX_FMT_PAL8, resx, resy)) < 0)
201 // Yes, we want to allocate the palette on our own because AVSubtitle works this way
202 sub_rect->pict.data[1] = NULL;
204 vbi_draw_vt_page_region(page, VBI_PIXFMT_PAL8,
205 sub_rect->pict.data[0], sub_rect->pict.linesize[0],
206 0, chop_top, page->columns, page->rows - chop_top,
207 /*reveal*/ 1, /*flash*/ 1);
209 fix_transparency(ctx, page, chop_top, cmax, resx, resy);
210 sub_rect->x = ctx->x_offset;
211 sub_rect->y = ctx->y_offset;
214 sub_rect->nb_colors = (int)cmax + 1;
215 sub_rect->pict.data[1] = av_mallocz(AVPALETTE_SIZE);
216 if (!sub_rect->pict.data[1]) {
217 av_freep(&sub_rect->pict.data[0]);
218 return AVERROR(ENOMEM);
220 for (ci = 0; ci < cmax; ci++) {
223 r = VBI_R(page->color_map[ci]);
224 g = VBI_G(page->color_map[ci]);
225 b = VBI_B(page->color_map[ci]);
226 a = VBI_A(page->color_map[ci]);
227 ((uint32_t *)sub_rect->pict.data[1])[ci] = RGBA(r, g, b, a);
229 av_log(ctx, AV_LOG_DEBUG, "palette %0x\n",
230 ((uint32_t *)sub_rect->pict.data[1])[ci]);
233 ((uint32_t *)sub_rect->pict.data[1])[cmax] = RGBA(0, 0, 0, 0);
234 sub_rect->type = SUBTITLE_BITMAP;
239 handler(vbi_event *ev, void *user_data)
241 TeletextContext *ctx = user_data;
250 snprintf(pgno_str, sizeof pgno_str, "%03x", ev->ev.ttx_page.pgno);
251 av_log(ctx, AV_LOG_DEBUG, "decoded page %s.%02x\n",
252 pgno_str, ev->ev.ttx_page.subno & 0xFF);
254 if (strcmp(ctx->pgno, "*") && !strstr(ctx->pgno, pgno_str))
257 /* Fetch the page. */
258 res = vbi_fetch_vt_page(ctx->vbi, &page,
259 ev->ev.ttx_page.pgno,
260 ev->ev.ttx_page.subno,
261 VBI_WST_LEVEL_3p5, 25, TRUE);
267 fprintf(stderr, "\nSaving res=%d dy0=%d dy1=%d...\n",
268 res, page.dirty.y0, page.dirty.y1);
271 if (!vbi_export_stdio(ctx->ex, stderr, &page))
272 fprintf(stderr, "failed: %s\n", vbi_export_errstr(ctx->ex));
275 vpt = vbi_classify_page(ctx->vbi, ev->ev.ttx_page.pgno, &subno, &lang);
276 chop_top = ctx->chop_top ||
277 ((page.rows > 1) && (vpt == VBI_SUBTITLE_PAGE));
279 av_log(ctx, AV_LOG_DEBUG, "%d x %d page chop:%d\n",
280 page.columns, page.rows, chop_top);
282 if (!ctx->sub_rect) {
283 ctx->sub_rect = av_mallocz(sizeof(*ctx->sub_rect));
285 res = (ctx->format_id == 0) ?
286 gen_sub_bitmap(ctx, &page, chop_top) :
287 gen_sub_text (ctx, &page, chop_top);
289 av_freep(&ctx->sub_rect);
292 // FIXME: Multiple teletext pages in a single packet, some kind of buffering should be done instead of dropping the page...
293 av_log(ctx, AV_LOG_WARNING, "Missed page %s.%02x.\n", pgno_str, ev->ev.ttx_page.subno & 0xFF);
296 vbi_unref_page(&page);
300 teletext_decode_frame(AVCodecContext *avctx,
301 void *data, int *data_size,
304 TeletextContext *ctx = avctx->priv_data;
305 AVSubtitle *sub = data;
306 const uint8_t *buf = pkt->data;
307 unsigned int left = pkt->size;
308 uint8_t pesheader[45] = {0x00, 0x00, 0x01, 0xbd, 0x00, 0x00, 0x85, 0x80, 0x24, 0x21, 0x00, 0x01, 0x00, 0x01};
309 int pesheader_size = sizeof(pesheader);
310 const uint8_t *pesheader_buf = pesheader;
313 if (!(ctx->vbi = vbi_decoder_new()))
314 return AVERROR(ENOMEM);
315 if (!vbi_event_handler_add(ctx->vbi, VBI_EVENT_TTX_PAGE, handler, ctx)) {
316 vbi_decoder_delete(ctx->vbi);
318 return AVERROR(ENOMEM);
321 if (!ctx->dx && (!(ctx->dx = vbi_dvb_pes_demux_new (/* callback */ NULL, NULL))))
322 return AVERROR(ENOMEM);
324 // We allow unreasonably big packets, even if the standard only allows a max size of 1472
325 if ((pesheader_size + left) < 184 || (pesheader_size + left) > 65504 || (pesheader_size + left) % 184 != 0)
326 return AVERROR_INVALIDDATA;
328 memset(pesheader + 14, 0xff, pesheader_size - 14);
329 AV_WB16(pesheader + 4, left + pesheader_size - 6);
331 /* PTS is deliberately left as 0 in the PES header, otherwise libzvbi uses
332 * it to detect dropped frames. Unforunatey the guessed packet PTS values
333 * (see mpegts demuxer) are not accurate enough to pass that test. */
334 vbi_dvb_demux_cor(ctx->dx, ctx->sliced, 64, NULL, &pesheader_buf, &pesheader_size);
338 unsigned int lines = vbi_dvb_demux_cor(ctx->dx, ctx->sliced, 64, &pts, &buf, &left);
340 av_log(avctx, AV_LOG_DEBUG,
341 "ctx=%p buf_size=%d left=%u lines=%u pts=%f pkt_pts=%f\n",
342 ctx, pkt->size, left, lines, (double)pts/90000.0, (double)pkt->pts/90000.0);
347 for(i=0; i<lines; ++i)
348 av_log(avctx, AV_LOG_DEBUG,
349 "lines=%d id=%x\n", i, ctx->sliced[i].id);
351 vbi_decode(ctx->vbi, ctx->sliced, lines, (double)pts/90000.0);
352 ctx->lines_processed += lines;
356 // is there a subtitle to pass?
358 sub->format = (ctx->sub_rect->type == SUBTITLE_TEXT ? 1: 0);
359 sub->start_display_time = 0;
360 sub->end_display_time = ctx->sub_duration;
363 if (ctx->sub_rect->type != SUBTITLE_NONE) {
364 sub->rects = av_malloc(sizeof(*sub->rects) * 1);
367 sub->rects[0] = ctx->sub_rect;
370 av_log(avctx, AV_LOG_DEBUG, "sending empty sub\n");
373 if (!sub->rects) // no rect was passed
374 av_free(ctx->sub_rect);
375 ctx->sub_rect = NULL;
384 static int teletext_init_decoder(AVCodecContext *avctx)
386 TeletextContext *ctx = avctx->priv_data;
387 unsigned int maj, min, rev;
389 vbi_version(&maj, &min, &rev);
390 if (!(maj > 0 || min > 2 || min == 2 && rev >= 26)) {
391 av_log(avctx, AV_LOG_ERROR, "decoder needs zvbi version >= 0.2.26.\n");
392 return AVERROR_EXTERNAL;
397 ctx->sub_rect = NULL;
398 if (!strcmp(ctx->format, "bitmap")) {
400 } else if (!strcmp(ctx->format, "text")) {
403 av_log(avctx, AV_LOG_ERROR, "unkown format %s\n", ctx->format);
404 return AVERROR_OPTION_NOT_FOUND;
410 ctx->ex = vbi_export_new("text", &t);
413 av_log(avctx, AV_LOG_VERBOSE, "page filter: %s\n", ctx->pgno);
417 static int teletext_close_decoder(AVCodecContext *avctx)
419 TeletextContext *ctx = avctx->priv_data;
422 av_log(avctx, AV_LOG_DEBUG, "lines_total=%u\n", ctx->lines_processed);
425 vbi_dvb_demux_delete(ctx->dx);
426 vbi_decoder_delete(ctx->vbi);
432 static void teletext_flush(AVCodecContext *avctx)
434 teletext_close_decoder(avctx);
437 #define OFFSET(x) offsetof(TeletextContext, x)
438 #define SD AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_DECODING_PARAM
439 static const AVOption options[] = {
440 {"txt_page", "list of teletext page numbers to decode, * is all", OFFSET(pgno), AV_OPT_TYPE_STRING, {.str = "*"}, 0, 0, SD},
441 {"txt_chop_top", "discards the top teletext line", OFFSET(chop_top), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, SD},
442 {"txt_format", "format of the subtitles (bitmap or text)", OFFSET(format), AV_OPT_TYPE_STRING, {.str = "bitmap"}, 0, 0, SD},
443 {"txt_left", "x offset of generated bitmaps", OFFSET(x_offset), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 65535, SD},
444 {"txt_top", "y offset of generated bitmaps", OFFSET(y_offset), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 65535, SD},
445 {"txt_chop_spaces", "chops leading and trailing spaces from text", OFFSET(chop_spaces), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, SD},
446 {"txt_duration", "display duration of teletext pages in msecs", OFFSET(sub_duration), AV_OPT_TYPE_INT, {.i64 = 30000}, 0, 86400000, SD},
447 {"txt_transparent", "force transparent background of the teletext", OFFSET(transparent_bg), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, SD},
451 static const AVClass teletext_class = {
452 .class_name = "libzvbi_teletextdec",
453 .item_name = av_default_item_name,
455 .version = LIBAVUTIL_VERSION_INT,
458 AVCodec ff_libzvbi_teletext_decoder = {
459 .name = "libzvbi_teletextdec",
460 .long_name = NULL_IF_CONFIG_SMALL("Libzvbi DVB teletext decoder"),
461 .type = AVMEDIA_TYPE_SUBTITLE,
462 .id = AV_CODEC_ID_DVB_TELETEXT,
463 .priv_data_size = sizeof(TeletextContext),
464 .init = teletext_init_decoder,
465 .close = teletext_close_decoder,
466 .decode = teletext_decode_frame,
467 .flush = teletext_flush,
468 .priv_class= &teletext_class,