]> git.sesse.net Git - ffmpeg/blob - libavcodec/atsc_a53.c
b2d1490c0c2322fd767b1dc0b54e9086053394e9
[ffmpeg] / libavcodec / atsc_a53.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <stddef.h>
20 #include <stdint.h>
21
22 #include "atsc_a53.h"
23 #include "get_bits.h"
24
25 int ff_parse_a53_cc(AVBufferRef **pbuf, const uint8_t *data, int size)
26 {
27     AVBufferRef *buf = *pbuf;
28     GetBitContext gb;
29     size_t new_size, old_size = buf ? buf->size : 0;
30     int ret, cc_count;
31
32     if (size < 3)
33         return AVERROR(EINVAL);
34
35     ret = init_get_bits8(&gb, data, size);
36     if (ret < 0)
37         return ret;
38
39     if (get_bits(&gb, 8) != 0x3) // user_data_type_code
40         return 0;
41
42     skip_bits(&gb, 1); // reserved
43     if (!get_bits(&gb, 1)) // process_cc_data_flag
44         return 0;
45
46     skip_bits(&gb, 1); // zero bit
47     cc_count = get_bits(&gb, 5);
48     if (!cc_count)
49         return 0;
50
51     skip_bits(&gb, 8); // reserved
52
53     /* 3 bytes per CC plus one byte marker_bits at the end */
54     if (cc_count * 3 >= (get_bits_left(&gb) >> 3))
55         return AVERROR(EINVAL);
56
57     new_size = (old_size + cc_count * 3);
58
59     if (new_size > INT_MAX)
60         return AVERROR(EINVAL);
61
62     /* Allow merging of the cc data from two fields. */
63     ret = av_buffer_realloc(pbuf, new_size);
64     if (ret < 0)
65         return ret;
66
67     buf = *pbuf;
68     /* Use of av_buffer_realloc assumes buffer is writeable */
69     for (int i = 0; i < cc_count; i++) {
70         buf->data[old_size++] = get_bits(&gb, 8);
71         buf->data[old_size++] = get_bits(&gb, 8);
72         buf->data[old_size++] = get_bits(&gb, 8);
73     }
74
75     return cc_count;
76 }