]> git.sesse.net Git - ffmpeg/blob - libavcodec/movtextdec.c
lavc/movtextdec: add alpha default to ass header colors
[ffmpeg] / libavcodec / movtextdec.c
1 /*
2  * 3GPP TS 26.245 Timed Text decoder
3  * Copyright (c) 2012  Philip Langdale <philipl@overt.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 #include "avcodec.h"
23 #include "ass.h"
24 #include "libavutil/avstring.h"
25 #include "libavutil/common.h"
26 #include "libavutil/bprint.h"
27 #include "libavutil/intreadwrite.h"
28 #include "libavutil/mem.h"
29
30 #define STYLE_FLAG_BOLD         (1<<0)
31 #define STYLE_FLAG_ITALIC       (1<<1)
32 #define STYLE_FLAG_UNDERLINE    (1<<2)
33
34 #define BOX_SIZE_INITIAL    40
35
36 #define STYL_BOX   (1<<0)
37 #define HLIT_BOX   (1<<1)
38 #define HCLR_BOX   (1<<2)
39 #define TWRP_BOX   (1<<3)
40
41 #define BOTTOM_LEFT     1
42 #define BOTTOM_CENTER   2
43 #define BOTTOM_RIGHT    3
44 #define MIDDLE_LEFT     4
45 #define MIDDLE_CENTER   5
46 #define MIDDLE_RIGHT    6
47 #define TOP_LEFT        7
48 #define TOP_CENTER      8
49 #define TOP_RIGHT       9
50
51 #define RGB_TO_BGR(c) (((c) & 0xff) << 16 | ((c) & 0xff00) | (((c) >> 16) & 0xff))
52
53 typedef struct {
54     uint16_t fontID;
55     const char *font;
56     uint8_t fontsize;
57     int color;
58     uint8_t alpha;
59     int back_color;
60     uint8_t back_alpha;
61     uint8_t bold;
62     uint8_t italic;
63     uint8_t underline;
64     int alignment;
65 } MovTextDefault;
66
67 typedef struct {
68     uint16_t fontID;
69     char *font;
70 } FontRecord;
71
72 typedef struct {
73     uint16_t style_start;
74     uint16_t style_end;
75     uint8_t style_flag;
76     uint8_t bold;
77     uint8_t italic;
78     uint8_t underline;
79     uint8_t fontsize;
80     uint16_t style_fontID;
81 } StyleBox;
82
83 typedef struct {
84     uint16_t hlit_start;
85     uint16_t hlit_end;
86 } HighlightBox;
87
88 typedef struct {
89    uint8_t hlit_color[4];
90 } HilightcolorBox;
91
92 typedef struct {
93     uint8_t wrap_flag;
94 } TextWrapBox;
95
96 typedef struct {
97     StyleBox **s;
98     StyleBox *s_temp;
99     HighlightBox h;
100     HilightcolorBox c;
101     FontRecord **ftab;
102     FontRecord *ftab_temp;
103     TextWrapBox w;
104     MovTextDefault d;
105     uint8_t box_flags;
106     uint16_t style_entries, ftab_entries;
107     uint64_t tracksize;
108     int size_var;
109     int count_s, count_f;
110     int readorder;
111 } MovTextContext;
112
113 typedef struct {
114     uint32_t type;
115     size_t base_size;
116     int (*decode)(const uint8_t *tsmb, MovTextContext *m, AVPacket *avpkt);
117 } Box;
118
119 static void mov_text_cleanup(MovTextContext *m)
120 {
121     int i;
122     if (m->box_flags & STYL_BOX) {
123         for(i = 0; i < m->count_s; i++) {
124             av_freep(&m->s[i]);
125         }
126         av_freep(&m->s);
127         m->count_s = 0;
128         m->style_entries = 0;
129     }
130 }
131
132 static void mov_text_cleanup_ftab(MovTextContext *m)
133 {
134     int i;
135     if (m->ftab_temp)
136         av_freep(&m->ftab_temp->font);
137     av_freep(&m->ftab_temp);
138     if (m->ftab) {
139         for(i = 0; i < m->count_f; i++) {
140             av_freep(&m->ftab[i]->font);
141             av_freep(&m->ftab[i]);
142         }
143     }
144     av_freep(&m->ftab);
145 }
146
147 static int mov_text_tx3g(AVCodecContext *avctx, MovTextContext *m)
148 {
149     uint8_t *tx3g_ptr = avctx->extradata;
150     int i, box_size, font_length;
151     int8_t v_align, h_align;
152     StyleBox s_default;
153
154     m->count_f = 0;
155     m->ftab_entries = 0;
156     box_size = BOX_SIZE_INITIAL; /* Size till ftab_entries */
157     if (avctx->extradata_size < box_size)
158         return -1;
159
160     // Display Flags
161     tx3g_ptr += 4;
162     // Alignment
163     h_align = *tx3g_ptr++;
164     v_align = *tx3g_ptr++;
165     if (h_align == 0) {
166         if (v_align == 0)
167             m->d.alignment = TOP_LEFT;
168         if (v_align == 1)
169             m->d.alignment = MIDDLE_LEFT;
170         if (v_align == -1)
171             m->d.alignment = BOTTOM_LEFT;
172     }
173     if (h_align == 1) {
174         if (v_align == 0)
175             m->d.alignment = TOP_CENTER;
176         if (v_align == 1)
177             m->d.alignment = MIDDLE_CENTER;
178         if (v_align == -1)
179             m->d.alignment = BOTTOM_CENTER;
180     }
181     if (h_align == -1) {
182         if (v_align == 0)
183             m->d.alignment = TOP_RIGHT;
184         if (v_align == 1)
185             m->d.alignment = MIDDLE_RIGHT;
186         if (v_align == -1)
187             m->d.alignment = BOTTOM_RIGHT;
188     }
189     // Background Color
190     m->d.back_color = AV_RB24(tx3g_ptr);
191     tx3g_ptr += 3;
192     m->d.back_alpha = AV_RB8(tx3g_ptr);
193     tx3g_ptr += 1;
194     // BoxRecord
195     tx3g_ptr += 8;
196     // StyleRecord
197     tx3g_ptr += 4;
198     // fontID
199     m->d.fontID = AV_RB16(tx3g_ptr);
200     tx3g_ptr += 2;
201     // face-style-flags
202     s_default.style_flag = *tx3g_ptr++;
203     m->d.bold = !!(s_default.style_flag & STYLE_FLAG_BOLD);
204     m->d.italic = !!(s_default.style_flag & STYLE_FLAG_ITALIC);
205     m->d.underline = !!(s_default.style_flag & STYLE_FLAG_UNDERLINE);
206     // fontsize
207     m->d.fontsize = *tx3g_ptr++;
208     // Primary color
209     m->d.color = AV_RB24(tx3g_ptr);
210     tx3g_ptr += 3;
211     m->d.alpha = AV_RB8(tx3g_ptr);
212     tx3g_ptr += 1;
213     // FontRecord
214     // FontRecord Size
215     tx3g_ptr += 4;
216     // ftab
217     tx3g_ptr += 4;
218
219     m->ftab_entries = AV_RB16(tx3g_ptr);
220     tx3g_ptr += 2;
221
222     for (i = 0; i < m->ftab_entries; i++) {
223
224         box_size += 3;
225         if (avctx->extradata_size < box_size) {
226             mov_text_cleanup_ftab(m);
227             m->ftab_entries = 0;
228             return -1;
229         }
230         m->ftab_temp = av_mallocz(sizeof(*m->ftab_temp));
231         if (!m->ftab_temp) {
232             mov_text_cleanup_ftab(m);
233             return AVERROR(ENOMEM);
234         }
235         m->ftab_temp->fontID = AV_RB16(tx3g_ptr);
236         tx3g_ptr += 2;
237         font_length = *tx3g_ptr++;
238
239         box_size = box_size + font_length;
240         if (avctx->extradata_size < box_size) {
241             mov_text_cleanup_ftab(m);
242             m->ftab_entries = 0;
243             return -1;
244         }
245         m->ftab_temp->font = av_malloc(font_length + 1);
246         if (!m->ftab_temp->font) {
247             mov_text_cleanup_ftab(m);
248             return AVERROR(ENOMEM);
249         }
250         memcpy(m->ftab_temp->font, tx3g_ptr, font_length);
251         m->ftab_temp->font[font_length] = '\0';
252         av_dynarray_add(&m->ftab, &m->count_f, m->ftab_temp);
253         if (!m->ftab) {
254             mov_text_cleanup_ftab(m);
255             return AVERROR(ENOMEM);
256         }
257         m->ftab_temp = NULL;
258         tx3g_ptr = tx3g_ptr + font_length;
259     }
260     // In case of broken header, init default font
261     m->d.font = ASS_DEFAULT_FONT;
262     for (i = 0; i < m->ftab_entries; i++) {
263         if (m->d.fontID == m->ftab[i]->fontID)
264             m->d.font = m->ftab[i]->font;
265     }
266     return 0;
267 }
268
269 static int decode_twrp(const uint8_t *tsmb, MovTextContext *m, AVPacket *avpkt)
270 {
271     m->box_flags |= TWRP_BOX;
272     m->w.wrap_flag = *tsmb++;
273     return 0;
274 }
275
276 static int decode_hlit(const uint8_t *tsmb, MovTextContext *m, AVPacket *avpkt)
277 {
278     m->box_flags |= HLIT_BOX;
279     m->h.hlit_start = AV_RB16(tsmb);
280     tsmb += 2;
281     m->h.hlit_end = AV_RB16(tsmb);
282     tsmb += 2;
283     return 0;
284 }
285
286 static int decode_hclr(const uint8_t *tsmb, MovTextContext *m, AVPacket *avpkt)
287 {
288     m->box_flags |= HCLR_BOX;
289     memcpy(m->c.hlit_color, tsmb, 4);
290     tsmb += 4;
291     return 0;
292 }
293
294 static int decode_styl(const uint8_t *tsmb, MovTextContext *m, AVPacket *avpkt)
295 {
296     int i;
297     int style_entries = AV_RB16(tsmb);
298     tsmb += 2;
299     // A single style record is of length 12 bytes.
300     if (m->tracksize + m->size_var + 2 + style_entries * 12 > avpkt->size)
301         return -1;
302
303     m->style_entries = style_entries;
304
305     m->box_flags |= STYL_BOX;
306     for(i = 0; i < m->style_entries; i++) {
307         m->s_temp = av_malloc(sizeof(*m->s_temp));
308         if (!m->s_temp) {
309             mov_text_cleanup(m);
310             return AVERROR(ENOMEM);
311         }
312         m->s_temp->style_start = AV_RB16(tsmb);
313         tsmb += 2;
314         m->s_temp->style_end = AV_RB16(tsmb);
315
316         if (   m->s_temp->style_end < m->s_temp->style_start
317             || (m->count_s && m->s_temp->style_start < m->s[m->count_s - 1]->style_end)) {
318             av_freep(&m->s_temp);
319             mov_text_cleanup(m);
320             return AVERROR(ENOMEM);
321         }
322
323         tsmb += 2;
324         m->s_temp->style_fontID = AV_RB16(tsmb);
325         tsmb += 2;
326         m->s_temp->style_flag = AV_RB8(tsmb);
327         m->s_temp->bold = !!(m->s_temp->style_flag & STYLE_FLAG_BOLD);
328         m->s_temp->italic = !!(m->s_temp->style_flag & STYLE_FLAG_ITALIC);
329         m->s_temp->underline = !!(m->s_temp->style_flag & STYLE_FLAG_UNDERLINE);
330         tsmb++;
331         m->s_temp->fontsize = AV_RB8(tsmb);
332         av_dynarray_add(&m->s, &m->count_s, m->s_temp);
333         if(!m->s) {
334             mov_text_cleanup(m);
335             return AVERROR(ENOMEM);
336         }
337         tsmb++;
338         // text-color-rgba
339         tsmb += 4;
340     }
341     return 0;
342 }
343
344 static const Box box_types[] = {
345     { MKBETAG('s','t','y','l'), 2, decode_styl },
346     { MKBETAG('h','l','i','t'), 4, decode_hlit },
347     { MKBETAG('h','c','l','r'), 4, decode_hclr },
348     { MKBETAG('t','w','r','p'), 1, decode_twrp }
349 };
350
351 const static size_t box_count = FF_ARRAY_ELEMS(box_types);
352
353 // Return byte length of the UTF-8 sequence starting at text[0]. 0 on error.
354 static int get_utf8_length_at(const char *text, const char *text_end)
355 {
356     const char *start = text;
357     int err = 0;
358     uint32_t c;
359     GET_UTF8(c, text < text_end ? (uint8_t)*text++ : (err = 1, 0), goto error;);
360     if (err)
361         goto error;
362     return text - start;
363 error:
364     return 0;
365 }
366
367 static int text_to_ass(AVBPrint *buf, const char *text, const char *text_end,
368                        AVCodecContext *avctx)
369 {
370     MovTextContext *m = avctx->priv_data;
371     int i = 0;
372     int text_pos = 0;
373     int style_active = 0;
374     int entry = 0;
375
376     if (text < text_end && m->box_flags & TWRP_BOX) {
377         if (m->w.wrap_flag == 1) {
378             av_bprintf(buf, "{\\q1}"); /* End of line wrap */
379         } else {
380             av_bprintf(buf, "{\\q2}"); /* No wrap */
381         }
382     }
383
384     while (text < text_end) {
385         int len;
386
387         if ((m->box_flags & STYL_BOX) && entry < m->style_entries) {
388             if (text_pos == m->s[entry]->style_start) {
389                 style_active = 1;
390                 if (m->s[entry]->bold ^ m->d.bold)
391                     av_bprintf(buf, "{\\b%d}", m->s[entry]->bold);
392                 if (m->s[entry]->italic ^ m->d.italic)
393                     av_bprintf(buf, "{\\i%d}", m->s[entry]->italic);
394                 if (m->s[entry]->underline ^ m->d.underline)
395                     av_bprintf(buf, "{\\u%d}", m->s[entry]->underline);
396                 if (m->s[entry]->fontsize != m->d.fontsize)
397                     av_bprintf(buf, "{\\fs%d}", m->s[entry]->fontsize);
398                 if (m->s[entry]->style_fontID != m->d.fontID)
399                     for (i = 0; i < m->ftab_entries; i++) {
400                         if (m->s[entry]->style_fontID == m->ftab[i]->fontID)
401                             av_bprintf(buf, "{\\fn%s}", m->ftab[i]->font);
402                     }
403             }
404             if (text_pos == m->s[entry]->style_end) {
405                 if (style_active) {
406                     av_bprintf(buf, "{\\r}");
407                     style_active = 0;
408                 }
409                 entry++;
410             }
411         }
412         if (m->box_flags & HLIT_BOX) {
413             if (text_pos == m->h.hlit_start) {
414                 /* If hclr box is present, set the secondary color to the color
415                  * specified. Otherwise, set primary color to white and secondary
416                  * color to black. These colors will come from TextSampleModifier
417                  * boxes in future and inverse video technique for highlight will
418                  * be implemented.
419                  */
420                 if (m->box_flags & HCLR_BOX) {
421                     av_bprintf(buf, "{\\2c&H%02x%02x%02x&}", m->c.hlit_color[2],
422                                 m->c.hlit_color[1], m->c.hlit_color[0]);
423                 } else {
424                     av_bprintf(buf, "{\\1c&H000000&}{\\2c&HFFFFFF&}");
425                 }
426             }
427             if (text_pos == m->h.hlit_end) {
428                 if (m->box_flags & HCLR_BOX) {
429                     av_bprintf(buf, "{\\2c&H000000&}");
430                 } else {
431                     av_bprintf(buf, "{\\1c&HFFFFFF&}{\\2c&H000000&}");
432                 }
433             }
434         }
435
436         len = get_utf8_length_at(text, text_end);
437         if (len < 1) {
438             av_log(avctx, AV_LOG_ERROR, "invalid UTF-8 byte in subtitle\n");
439             len = 1;
440         }
441         for (i = 0; i < len; i++) {
442             switch (*text) {
443             case '\r':
444                 break;
445             case '\n':
446                 av_bprintf(buf, "\\N");
447                 break;
448             default:
449                 av_bprint_chars(buf, *text, 1);
450                 break;
451             }
452             text++;
453         }
454         text_pos++;
455     }
456
457     return 0;
458 }
459
460 static int mov_text_init(AVCodecContext *avctx) {
461     /*
462      * TODO: Handle the default text style.
463      * NB: Most players ignore styles completely, with the result that
464      * it's very common to find files where the default style is broken
465      * and respecting it results in a worse experience than ignoring it.
466      */
467     int ret;
468     MovTextContext *m = avctx->priv_data;
469     ret = mov_text_tx3g(avctx, m);
470     if (ret == 0) {
471         return ff_ass_subtitle_header(avctx, m->d.font, m->d.fontsize,
472                     (255 - m->d.alpha) << 24 | RGB_TO_BGR(m->d.color),
473                     (255 - m->d.back_alpha) << 24 | RGB_TO_BGR(m->d.back_color),
474                     m->d.bold, m->d.italic, m->d.underline,
475                     ASS_DEFAULT_BORDERSTYLE, m->d.alignment);
476     } else
477         return ff_ass_subtitle_header_default(avctx);
478 }
479
480 static int mov_text_decode_frame(AVCodecContext *avctx,
481                             void *data, int *got_sub_ptr, AVPacket *avpkt)
482 {
483     AVSubtitle *sub = data;
484     MovTextContext *m = avctx->priv_data;
485     int ret;
486     AVBPrint buf;
487     char *ptr = avpkt->data;
488     char *end;
489     int text_length, tsmb_type, ret_tsmb;
490     uint64_t tsmb_size;
491     const uint8_t *tsmb;
492     size_t i;
493
494     if (!ptr || avpkt->size < 2)
495         return AVERROR_INVALIDDATA;
496
497     /*
498      * A packet of size two with value zero is an empty subtitle
499      * used to mark the end of the previous non-empty subtitle.
500      * We can just drop them here as we have duration information
501      * already. If the value is non-zero, then it's technically a
502      * bad packet.
503      */
504     if (avpkt->size == 2)
505         return AV_RB16(ptr) == 0 ? 0 : AVERROR_INVALIDDATA;
506
507     /*
508      * The first two bytes of the packet are the length of the text string
509      * In complex cases, there are style descriptors appended to the string
510      * so we can't just assume the packet size is the string size.
511      */
512     text_length = AV_RB16(ptr);
513     end = ptr + FFMIN(2 + text_length, avpkt->size);
514     ptr += 2;
515
516     mov_text_cleanup(m);
517
518     tsmb_size = 0;
519     m->tracksize = 2 + text_length;
520     m->style_entries = 0;
521     m->box_flags = 0;
522     m->count_s = 0;
523     // Note that the spec recommends lines be no longer than 2048 characters.
524     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
525     if (text_length + 2 != avpkt->size) {
526         while (m->tracksize + 8 <= avpkt->size) {
527             // A box is a minimum of 8 bytes.
528             tsmb = ptr + m->tracksize - 2;
529             tsmb_size = AV_RB32(tsmb);
530             tsmb += 4;
531             tsmb_type = AV_RB32(tsmb);
532             tsmb += 4;
533
534             if (tsmb_size == 1) {
535                 if (m->tracksize + 16 > avpkt->size)
536                     break;
537                 tsmb_size = AV_RB64(tsmb);
538                 tsmb += 8;
539                 m->size_var = 16;
540             } else
541                 m->size_var = 8;
542             //size_var is equal to 8 or 16 depending on the size of box
543
544             if (tsmb_size == 0) {
545                 av_log(avctx, AV_LOG_ERROR, "tsmb_size is 0\n");
546                 return AVERROR_INVALIDDATA;
547             }
548
549             if (tsmb_size > avpkt->size - m->tracksize)
550                 break;
551
552             for (i = 0; i < box_count; i++) {
553                 if (tsmb_type == box_types[i].type) {
554                     if (m->tracksize + m->size_var + box_types[i].base_size > avpkt->size)
555                         break;
556                     ret_tsmb = box_types[i].decode(tsmb, m, avpkt);
557                     if (ret_tsmb == -1)
558                         break;
559                 }
560             }
561             m->tracksize = m->tracksize + tsmb_size;
562         }
563         text_to_ass(&buf, ptr, end, avctx);
564         mov_text_cleanup(m);
565     } else
566         text_to_ass(&buf, ptr, end, avctx);
567
568     ret = ff_ass_add_rect(sub, buf.str, m->readorder++, 0, NULL, NULL);
569     av_bprint_finalize(&buf, NULL);
570     if (ret < 0)
571         return ret;
572     *got_sub_ptr = sub->num_rects > 0;
573     return avpkt->size;
574 }
575
576 static int mov_text_decode_close(AVCodecContext *avctx)
577 {
578     MovTextContext *m = avctx->priv_data;
579     mov_text_cleanup_ftab(m);
580     mov_text_cleanup(m);
581     return 0;
582 }
583
584 static void mov_text_flush(AVCodecContext *avctx)
585 {
586     MovTextContext *m = avctx->priv_data;
587     if (!(avctx->flags2 & AV_CODEC_FLAG2_RO_FLUSH_NOOP))
588         m->readorder = 0;
589 }
590
591 AVCodec ff_movtext_decoder = {
592     .name         = "mov_text",
593     .long_name    = NULL_IF_CONFIG_SMALL("3GPP Timed Text subtitle"),
594     .type         = AVMEDIA_TYPE_SUBTITLE,
595     .id           = AV_CODEC_ID_MOV_TEXT,
596     .priv_data_size = sizeof(MovTextContext),
597     .init         = mov_text_init,
598     .decode       = mov_text_decode_frame,
599     .close        = mov_text_decode_close,
600     .flush        = mov_text_flush,
601 };