4 * This file is part of Libav.
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.
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.
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
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/mem.h"
30 /* FIXME: This is adapted from ff_h264_decode_nal, avoiding duplication
31 * between these functions would be nice. */
32 int ff_hevc_extract_rbsp(const uint8_t *src, int length,
38 #define STARTCODE_TEST \
39 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
40 if (src[i + 2] != 3) { \
41 /* startcode, so we must be past the end */ \
46 #if HAVE_FAST_UNALIGNED
47 #define FIND_FIRST_ZERO \
48 if (i > 0 && !src[i]) \
53 for (i = 0; i + 1 < length; i += 9) {
54 if (!((~AV_RN64A(src + i) &
55 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
56 0x8000800080008080ULL))
63 for (i = 0; i + 1 < length; i += 5) {
64 if (!((~AV_RN32A(src + i) &
65 (AV_RN32A(src + i) - 0x01000101U)) &
72 #endif /* HAVE_FAST_64BIT */
74 for (i = 0; i + 1 < length; i += 2) {
77 if (i > 0 && src[i - 1] == 0)
81 #endif /* HAVE_FAST_UNALIGNED */
83 if (i >= length - 1) { // no escaped 0
87 nal->raw_size = length;
91 av_fast_malloc(&nal->rbsp_buffer, &nal->rbsp_buffer_size,
92 length + FF_INPUT_BUFFER_PADDING_SIZE);
93 if (!nal->rbsp_buffer)
94 return AVERROR(ENOMEM);
96 dst = nal->rbsp_buffer;
100 while (si + 2 < length) {
101 // remove escapes (very rare 1:2^22)
102 if (src[si + 2] > 3) {
103 dst[di++] = src[si++];
104 dst[di++] = src[si++];
105 } else if (src[si] == 0 && src[si + 1] == 0) {
106 if (src[si + 2] == 3) { // escape
112 } else // next start code
116 dst[di++] = src[si++];
119 dst[di++] = src[si++];
122 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);