]> git.sesse.net Git - ffmpeg/blob - libavcodec/h2645_parse.c
libopusdec: default to stereo for invalid number of channels
[ffmpeg] / libavcodec / h2645_parse.c
1 /*
2  * H.264/HEVC common parsing code
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <string.h>
22
23 #include "config.h"
24
25 #include "libavutil/intmath.h"
26 #include "libavutil/intreadwrite.h"
27 #include "libavutil/mem.h"
28
29 #include "h2645_parse.h"
30
31 int ff_h2645_extract_rbsp(const uint8_t *src, int length,
32                           H2645NAL *nal)
33 {
34     int i, si, di;
35     uint8_t *dst;
36
37 #define STARTCODE_TEST                                                  \
38         if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {     \
39             if (src[i + 2] != 3) {                                      \
40                 /* startcode, so we must be past the end */             \
41                 length = i;                                             \
42             }                                                           \
43             break;                                                      \
44         }
45 #if HAVE_FAST_UNALIGNED
46 #define FIND_FIRST_ZERO                                                 \
47         if (i > 0 && !src[i])                                           \
48             i--;                                                        \
49         while (src[i])                                                  \
50             i++
51 #if HAVE_FAST_64BIT
52     for (i = 0; i + 1 < length; i += 9) {
53         if (!((~AV_RN64A(src + i) &
54                (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
55               0x8000800080008080ULL))
56             continue;
57         FIND_FIRST_ZERO;
58         STARTCODE_TEST;
59         i -= 7;
60     }
61 #else
62     for (i = 0; i + 1 < length; i += 5) {
63         if (!((~AV_RN32A(src + i) &
64                (AV_RN32A(src + i) - 0x01000101U)) &
65               0x80008080U))
66             continue;
67         FIND_FIRST_ZERO;
68         STARTCODE_TEST;
69         i -= 3;
70     }
71 #endif /* HAVE_FAST_64BIT */
72 #else
73     for (i = 0; i + 1 < length; i += 2) {
74         if (src[i])
75             continue;
76         if (i > 0 && src[i - 1] == 0)
77             i--;
78         STARTCODE_TEST;
79     }
80 #endif /* HAVE_FAST_UNALIGNED */
81
82     if (i >= length - 1) { // no escaped 0
83         nal->data     =
84         nal->raw_data = src;
85         nal->size     =
86         nal->raw_size = length;
87         return length;
88     }
89
90     av_fast_malloc(&nal->rbsp_buffer, &nal->rbsp_buffer_size,
91                    length + AV_INPUT_BUFFER_PADDING_SIZE);
92     if (!nal->rbsp_buffer)
93         return AVERROR(ENOMEM);
94
95     dst = nal->rbsp_buffer;
96
97     memcpy(dst, src, i);
98     si = di = i;
99     while (si + 2 < length) {
100         // remove escapes (very rare 1:2^22)
101         if (src[si + 2] > 3) {
102             dst[di++] = src[si++];
103             dst[di++] = src[si++];
104         } else if (src[si] == 0 && src[si + 1] == 0) {
105             if (src[si + 2] == 3) { // escape
106                 dst[di++] = 0;
107                 dst[di++] = 0;
108                 si       += 3;
109
110                 continue;
111             } else // next start code
112                 goto nsc;
113         }
114
115         dst[di++] = src[si++];
116     }
117     while (si < length)
118         dst[di++] = src[si++];
119
120 nsc:
121     memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
122
123     nal->data = dst;
124     nal->size = di;
125     nal->raw_data = src;
126     nal->raw_size = si;
127     return si;
128 }
129
130 static int get_bit_length(H2645NAL *nal, int skip_trailing_zeros)
131 {
132     int size = nal->size;
133     int v;
134
135     while (skip_trailing_zeros && size > 0 && nal->data[size - 1] == 0)
136         size--;
137
138     if (!size)
139         return 0;
140
141     v = nal->data[size - 1];
142
143     if (size > INT_MAX / 8)
144         return AVERROR(ERANGE);
145     size *= 8;
146
147     /* remove the stop bit and following trailing zeros,
148      * or nothing for damaged bitstreams */
149     if (v)
150         size -= av_ctz(v) + 1;
151
152     return size;
153 }
154
155 /**
156  * @return AVERROR_INVALIDDATA if the packet is not a valid NAL unit,
157  * 0 if the unit should be skipped, 1 otherwise
158  */
159 static int hevc_parse_nal_header(H2645NAL *nal, void *logctx)
160 {
161     GetBitContext *gb = &nal->gb;
162     int nuh_layer_id;
163
164     if (get_bits1(gb) != 0)
165         return AVERROR_INVALIDDATA;
166
167     nal->type = get_bits(gb, 6);
168
169     nuh_layer_id   = get_bits(gb, 6);
170     nal->temporal_id = get_bits(gb, 3) - 1;
171     if (nal->temporal_id < 0)
172         return AVERROR_INVALIDDATA;
173
174     av_log(logctx, AV_LOG_DEBUG,
175            "nal_unit_type: %d, nuh_layer_id: %dtemporal_id: %d\n",
176            nal->type, nuh_layer_id, nal->temporal_id);
177
178     return nuh_layer_id == 0;
179 }
180
181 static int h264_parse_nal_header(H2645NAL *nal, void *logctx)
182 {
183     GetBitContext *gb = &nal->gb;
184
185     if (get_bits1(gb) != 0)
186         return AVERROR_INVALIDDATA;
187
188     nal->ref_idc = get_bits(gb, 2);
189     nal->type    = get_bits(gb, 5);
190
191     av_log(logctx, AV_LOG_DEBUG,
192            "nal_unit_type: %d, nal_ref_idc: %d\n",
193            nal->type, nal->ref_idc);
194
195     return 1;
196 }
197
198 static int find_next_start_code(const uint8_t *buf, const uint8_t *next_avc)
199 {
200     int i = 0;
201
202     if (buf + 3 >= next_avc)
203         return next_avc - buf;
204
205     while (buf + i + 3 < next_avc) {
206         if (buf[i] == 0 && buf[i + 1] == 0 && buf[i + 2] == 1)
207             break;
208         i++;
209     }
210     return i + 3;
211 }
212
213 int ff_h2645_packet_split(H2645Packet *pkt, const uint8_t *buf, int length,
214                           void *logctx, int is_nalff, int nal_length_size,
215                           enum AVCodecID codec_id)
216 {
217     int consumed, ret = 0;
218     const uint8_t *next_avc = buf + (is_nalff ? 0 : length);
219
220     pkt->nb_nals = 0;
221     while (length >= 4) {
222         H2645NAL *nal;
223         int extract_length = 0;
224         int skip_trailing_zeros = 1;
225
226         /*
227          * Only parse an AVC1 length field if one is expected at the current
228          * buffer position. There are unfortunately streams with multiple
229          * NAL units covered by the length field. Those NAL units are delimited
230          * by Annex B start code prefixes. ff_h2645_extract_rbsp() detects it
231          * correctly and consumes only the first NAL unit. The additional NAL
232          * units are handled here in the Annex B parsing code.
233          */
234         if (buf == next_avc) {
235             int i;
236             for (i = 0; i < nal_length_size; i++)
237                 extract_length = (extract_length << 8) | buf[i];
238
239             if (extract_length > length) {
240                 av_log(logctx, AV_LOG_ERROR,
241                        "Invalid NAL unit size (%d > %d).\n",
242                        extract_length, length);
243                 return AVERROR_INVALIDDATA;
244             }
245             buf     += nal_length_size;
246             length  -= nal_length_size;
247             // keep track of the next AVC1 length field
248             next_avc = buf + extract_length;
249         } else {
250             /*
251              * expected to return immediately except for streams with mixed
252              * NAL unit coding
253              */
254             int buf_index = find_next_start_code(buf, next_avc);
255
256             buf    += buf_index;
257             length -= buf_index;
258
259             /*
260              * break if an AVC1 length field is expected at the current buffer
261              * position
262              */
263             if (buf == next_avc)
264                 continue;
265
266             if (length > 0) {
267                 extract_length = length;
268             } else if (pkt->nb_nals == 0) {
269                 av_log(logctx, AV_LOG_ERROR, "No NAL unit found\n");
270                 return AVERROR_INVALIDDATA;
271             } else {
272                 break;
273             }
274         }
275
276         if (pkt->nals_allocated < pkt->nb_nals + 1) {
277             int new_size = pkt->nals_allocated + 1;
278             H2645NAL *tmp = av_realloc_array(pkt->nals, new_size, sizeof(*tmp));
279             if (!tmp)
280                 return AVERROR(ENOMEM);
281
282             pkt->nals = tmp;
283             memset(pkt->nals + pkt->nals_allocated, 0,
284                    (new_size - pkt->nals_allocated) * sizeof(*tmp));
285             pkt->nals_allocated = new_size;
286         }
287         nal = &pkt->nals[pkt->nb_nals++];
288
289         consumed = ff_h2645_extract_rbsp(buf, extract_length, nal);
290         if (consumed < 0)
291             return consumed;
292
293         /* see commit 3566042a0 */
294         if (consumed < length - 3 &&
295             buf[consumed]     == 0x00 && buf[consumed + 1] == 0x00 &&
296             buf[consumed + 2] == 0x01 && buf[consumed + 3] == 0xE0)
297             skip_trailing_zeros = 0;
298
299         nal->size_bits = get_bit_length(nal, skip_trailing_zeros);
300
301         ret = init_get_bits(&nal->gb, nal->data, nal->size_bits);
302         if (ret < 0)
303             return ret;
304
305         if (codec_id == AV_CODEC_ID_HEVC)
306             ret = hevc_parse_nal_header(nal, logctx);
307         else
308             ret = h264_parse_nal_header(nal, logctx);
309         if (ret <= 0) {
310             if (ret < 0) {
311                 av_log(logctx, AV_LOG_ERROR, "Invalid NAL unit %d, skipping.\n",
312                        nal->type);
313             }
314             pkt->nb_nals--;
315         }
316
317         buf    += consumed;
318         length -= consumed;
319     }
320
321     return 0;
322 }
323
324 void ff_h2645_packet_uninit(H2645Packet *pkt)
325 {
326     int i;
327     for (i = 0; i < pkt->nals_allocated; i++)
328         av_freep(&pkt->nals[i].rbsp_buffer);
329     av_freep(&pkt->nals);
330     pkt->nals_allocated = 0;
331 }