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