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