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