h2645_parse.c 11.9 KB
Newer Older
1
/*
2
 * H.264/HEVC common parsing code
3
 *
4
 * This file is part of FFmpeg.
5
 *
6
 * FFmpeg is free software; you can redistribute it and/or
7 8 9 10
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
11
 * FFmpeg is distributed in the hope that it will be useful,
12 13 14 15 16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with FFmpeg; if not, write to the Free Software
18 19 20 21 22 23 24
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <string.h>

#include "config.h"

25
#include "libavutil/intmath.h"
26 27 28 29
#include "libavutil/intreadwrite.h"
#include "libavutil/mem.h"

#include "hevc.h"
30
#include "h2645_parse.h"
31

32
int ff_h2645_extract_rbsp(const uint8_t *src, int length,
33
                          H2645NAL *nal, int small_padding)
34 35 36
{
    int i, si, di;
    uint8_t *dst;
37
    int64_t padding = small_padding ? 0 : MAX_MBPAIR_SIZE;
38

39
    nal->skipped_bytes = 0;
40 41
#define STARTCODE_TEST                                                  \
        if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {     \
42
            if (src[i + 2] != 3 && src[i + 2] != 0) {                   \
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
                /* startcode, so we must be past the end */             \
                length = i;                                             \
            }                                                           \
            break;                                                      \
        }
#if HAVE_FAST_UNALIGNED
#define FIND_FIRST_ZERO                                                 \
        if (i > 0 && !src[i])                                           \
            i--;                                                        \
        while (src[i])                                                  \
            i++
#if HAVE_FAST_64BIT
    for (i = 0; i + 1 < length; i += 9) {
        if (!((~AV_RN64A(src + i) &
               (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
              0x8000800080008080ULL))
            continue;
        FIND_FIRST_ZERO;
        STARTCODE_TEST;
        i -= 7;
    }
#else
    for (i = 0; i + 1 < length; i += 5) {
        if (!((~AV_RN32A(src + i) &
               (AV_RN32A(src + i) - 0x01000101U)) &
              0x80008080U))
            continue;
        FIND_FIRST_ZERO;
        STARTCODE_TEST;
        i -= 3;
    }
#endif /* HAVE_FAST_64BIT */
#else
    for (i = 0; i + 1 < length; i += 2) {
        if (src[i])
            continue;
        if (i > 0 && src[i - 1] == 0)
            i--;
        STARTCODE_TEST;
    }
#endif /* HAVE_FAST_UNALIGNED */

85
    if (i >= length - 1 && small_padding) { // no escaped 0
86 87 88 89 90
        nal->data     =
        nal->raw_data = src;
        nal->size     =
        nal->raw_size = length;
        return length;
91 92
    } else if (i > length)
        i = length;
93

94 95
    av_fast_padded_malloc(&nal->rbsp_buffer, &nal->rbsp_buffer_size,
                          length + padding);
96 97 98 99 100 101 102 103 104 105 106 107
    if (!nal->rbsp_buffer)
        return AVERROR(ENOMEM);

    dst = nal->rbsp_buffer;

    memcpy(dst, src, i);
    si = di = i;
    while (si + 2 < length) {
        // remove escapes (very rare 1:2^22)
        if (src[si + 2] > 3) {
            dst[di++] = src[si++];
            dst[di++] = src[si++];
108
        } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) {
109 110 111 112 113
            if (src[si + 2] == 3) { // escape
                dst[di++] = 0;
                dst[di++] = 0;
                si       += 3;

114
                if (nal->skipped_bytes_pos) {
115 116 117 118 119 120 121 122 123 124
                    nal->skipped_bytes++;
                    if (nal->skipped_bytes_pos_size < nal->skipped_bytes) {
                        nal->skipped_bytes_pos_size *= 2;
                        av_assert0(nal->skipped_bytes_pos_size >= nal->skipped_bytes);
                        av_reallocp_array(&nal->skipped_bytes_pos,
                                nal->skipped_bytes_pos_size,
                                sizeof(*nal->skipped_bytes_pos));
                        if (!nal->skipped_bytes_pos) {
                            nal->skipped_bytes_pos_size = 0;
                            return AVERROR(ENOMEM);
125
                        }
126 127 128
                    }
                    if (nal->skipped_bytes_pos)
                        nal->skipped_bytes_pos[nal->skipped_bytes-1] = di - 1;
129
                }
130 131 132 133 134 135 136 137 138 139 140
                continue;
            } else // next start code
                goto nsc;
        }

        dst[di++] = src[si++];
    }
    while (si < length)
        dst[di++] = src[si++];

nsc:
141
    memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
142 143 144 145 146 147 148

    nal->data = dst;
    nal->size = di;
    nal->raw_data = src;
    nal->raw_size = si;
    return si;
}
149

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
static const char *nal_unit_name(int nal_type)
{
    switch(nal_type) {
    case NAL_TRAIL_N    : return "TRAIL_N";
    case NAL_TRAIL_R    : return "TRAIL_R";
    case NAL_TSA_N      : return "TSA_N";
    case NAL_TSA_R      : return "TSA_R";
    case NAL_STSA_N     : return "STSA_N";
    case NAL_STSA_R     : return "STSA_R";
    case NAL_RADL_N     : return "RADL_N";
    case NAL_RADL_R     : return "RADL_R";
    case NAL_RASL_N     : return "RASL_N";
    case NAL_RASL_R     : return "RASL_R";
    case NAL_BLA_W_LP   : return "BLA_W_LP";
    case NAL_BLA_W_RADL : return "BLA_W_RADL";
    case NAL_BLA_N_LP   : return "BLA_N_LP";
    case NAL_IDR_W_RADL : return "IDR_W_RADL";
    case NAL_IDR_N_LP   : return "IDR_N_LP";
    case NAL_CRA_NUT    : return "CRA_NUT";
    case NAL_VPS        : return "VPS";
    case NAL_SPS        : return "SPS";
    case NAL_PPS        : return "PPS";
    case NAL_AUD        : return "AUD";
    case NAL_EOS_NUT    : return "EOS_NUT";
    case NAL_EOB_NUT    : return "EOB_NUT";
    case NAL_FD_NUT     : return "FD_NUT";
    case NAL_SEI_PREFIX : return "SEI_PREFIX";
    case NAL_SEI_SUFFIX : return "SEI_SUFFIX";
    default : return "?";
    }
}

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
static int get_bit_length(H2645NAL *nal, int skip_trailing_zeros)
{
    int size = nal->size;
    int v;

    while (skip_trailing_zeros && size > 0 && nal->data[size - 1] == 0)
        size--;

    if (!size)
        return 0;

    v = nal->data[size - 1];

    if (size > INT_MAX / 8)
        return AVERROR(ERANGE);
    size *= 8;

    /* remove the stop bit and following trailing zeros,
     * or nothing for damaged bitstreams */
    if (v)
202
        size -= ff_ctz(v) + 1;
203 204 205 206

    return size;
}

207 208 209 210
/**
 * @return AVERROR_INVALIDDATA if the packet is not a valid NAL unit,
 * 0 if the unit should be skipped, 1 otherwise
 */
211
static int hevc_parse_nal_header(H2645NAL *nal, void *logctx)
212 213 214 215 216 217 218 219 220 221 222 223 224 225
{
    GetBitContext *gb = &nal->gb;
    int nuh_layer_id;

    if (get_bits1(gb) != 0)
        return AVERROR_INVALIDDATA;

    nal->type = get_bits(gb, 6);

    nuh_layer_id   = get_bits(gb, 6);
    nal->temporal_id = get_bits(gb, 3) - 1;
    if (nal->temporal_id < 0)
        return AVERROR_INVALIDDATA;

226
    av_log(logctx, AV_LOG_DEBUG,
227 228
           "nal_unit_type: %d(%s), nuh_layer_id: %d, temporal_id: %d\n",
           nal->type, nal_unit_name(nal->type), nuh_layer_id, nal->temporal_id);
229 230 231 232

    return nuh_layer_id == 0;
}

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
static int h264_parse_nal_header(H2645NAL *nal, void *logctx)
{
    GetBitContext *gb = &nal->gb;

    if (get_bits1(gb) != 0)
        return AVERROR_INVALIDDATA;

    nal->ref_idc = get_bits(gb, 2);
    nal->type    = get_bits(gb, 5);

    av_log(logctx, AV_LOG_DEBUG,
           "nal_unit_type: %d, nal_ref_idc: %d\n",
           nal->type, nal->ref_idc);

    return 1;
}
249

250
int ff_h2645_packet_split(H2645Packet *pkt, const uint8_t *buf, int length,
251
                          void *logctx, int is_nalff, int nal_length_size,
252
                          enum AVCodecID codec_id, int small_padding)
253 254
{
    int consumed, ret = 0;
255
    const uint8_t *next_avc = is_nalff ? buf : buf + length;
256 257 258

    pkt->nb_nals = 0;
    while (length >= 4) {
259
        H2645NAL *nal;
260
        int extract_length = 0;
261
        int skip_trailing_zeros = 1;
262

263
        if (buf == next_avc) {
264 265 266 267 268 269
            int i = 0;
            extract_length = get_nalsize(nal_length_size,
                                         buf, length, &i, logctx);
            if (extract_length < 0)
                return extract_length;

270 271 272
            buf    += nal_length_size;
            length -= nal_length_size;

273
            next_avc = buf + extract_length;
274
        } else {
275 276 277
            if (buf > next_avc)
                av_log(logctx, AV_LOG_WARNING, "Exceeded next NALFF position, re-syncing.\n");

278 279 280 281 282
            /* search start code */
            while (buf[0] != 0 || buf[1] != 0 || buf[2] != 1) {
                ++buf;
                --length;
                if (length < 4) {
283 284 285 286 287
                    if (pkt->nb_nals > 0) {
                        // No more start codes: we discarded some irrelevant
                        // bytes at the end of the packet.
                        return 0;
                    } else {
288
                        av_log(logctx, AV_LOG_ERROR, "No start code is found.\n");
289 290
                        return AVERROR_INVALIDDATA;
                    }
291 292
                } else if (buf >= (next_avc - 3))
                    break;
293 294 295 296
            }

            buf           += 3;
            length        -= 3;
297
            extract_length = FFMIN(length, next_avc - buf);
298 299 300 301 302 303 304 305

            if (buf >= next_avc) {
                /* skip to the start of the next NAL */
                int offset = next_avc - buf;
                buf    += offset;
                length -= offset;
                continue;
            }
306 307 308 309
        }

        if (pkt->nals_allocated < pkt->nb_nals + 1) {
            int new_size = pkt->nals_allocated + 1;
310 311
            void *tmp = av_realloc_array(pkt->nals, new_size, sizeof(*pkt->nals));

312 313 314 315 316
            if (!tmp)
                return AVERROR(ENOMEM);

            pkt->nals = tmp;
            memset(pkt->nals + pkt->nals_allocated, 0,
317 318
                   (new_size - pkt->nals_allocated) * sizeof(*pkt->nals));

319
            nal = &pkt->nals[pkt->nb_nals];
320 321 322
            nal->skipped_bytes_pos_size = 1024; // initial buffer size
            nal->skipped_bytes_pos = av_malloc_array(nal->skipped_bytes_pos_size, sizeof(*nal->skipped_bytes_pos));
            if (!nal->skipped_bytes_pos)
323 324
                return AVERROR(ENOMEM);

325 326
            pkt->nals_allocated = new_size;
        }
327
        nal = &pkt->nals[pkt->nb_nals];
328

329
        consumed = ff_h2645_extract_rbsp(buf, extract_length, nal, small_padding);
330 331 332
        if (consumed < 0)
            return consumed;

333 334 335 336 337
        if (is_nalff && (extract_length != consumed) && extract_length)
            av_log(logctx, AV_LOG_DEBUG,
                   "NALFF: Consumed only %d bytes instead of %d\n",
                   consumed, extract_length);

338
        pkt->nb_nals++;
339

340 341 342 343 344 345 346 347
        /* see commit 3566042a0 */
        if (consumed < length - 3 &&
            buf[consumed]     == 0x00 && buf[consumed + 1] == 0x00 &&
            buf[consumed + 2] == 0x01 && buf[consumed + 3] == 0xE0)
            skip_trailing_zeros = 0;

        nal->size_bits = get_bit_length(nal, skip_trailing_zeros);

348
        ret = init_get_bits(&nal->gb, nal->data, nal->size_bits);
349 350 351
        if (ret < 0)
            return ret;

352 353 354 355
        if (codec_id == AV_CODEC_ID_HEVC)
            ret = hevc_parse_nal_header(nal, logctx);
        else
            ret = h264_parse_nal_header(nal, logctx);
356
        if (ret <= 0 || nal->size <= 0) {
357
            if (ret < 0) {
358
                av_log(logctx, AV_LOG_ERROR, "Invalid NAL unit %d, skipping.\n",
359 360 361 362 363 364 365 366 367 368 369
                       nal->type);
            }
            pkt->nb_nals--;
        }

        buf    += consumed;
        length -= consumed;
    }

    return 0;
}
370

371 372 373
void ff_h2645_packet_uninit(H2645Packet *pkt)
{
    int i;
374
    for (i = 0; i < pkt->nals_allocated; i++) {
375
        av_freep(&pkt->nals[i].rbsp_buffer);
376 377
        av_freep(&pkt->nals[i].skipped_bytes_pos);
    }
378 379 380
    av_freep(&pkt->nals);
    pkt->nals_allocated = 0;
}