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