2 * HEVC Annex B format parser
4 * Copyright (C) 2012 - 2013 Guillaume Martres
6 * This file is part of Libav.
8 * Libav is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * Libav is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "libavutil/common.h"
28 #define START_CODE 0x000001 ///< start_code_prefix_one_3bytes
31 * Find the end of the current frame in the bitstream.
32 * @return the position of the first byte of the next frame, or END_NOT_FOUND
34 static int hevc_find_frame_end(AVCodecParserContext *s, const uint8_t *buf,
38 ParseContext *pc = s->priv_data;
40 for (i = 0; i < buf_size; i++) {
43 pc->state64 = (pc->state64 << 8) | buf[i];
45 if (((pc->state64 >> 3 * 8) & 0xFFFFFF) != START_CODE)
48 nut = (pc->state64 >> 2 * 8 + 1) & 0x3F;
49 // Beginning of access unit
50 if ((nut >= NAL_VPS && nut <= NAL_AUD) || nut == NAL_SEI_PREFIX ||
51 (nut >= 41 && nut <= 44) || (nut >= 48 && nut <= 55)) {
52 if (pc->frame_start_found) {
53 pc->frame_start_found = 0;
56 } else if (nut <= NAL_RASL_R ||
57 (nut >= NAL_BLA_W_LP && nut <= NAL_CRA_NUT)) {
58 int first_slice_segment_in_pic_flag = buf[i] >> 7;
59 if (first_slice_segment_in_pic_flag) {
60 if (!pc->frame_start_found) {
61 pc->frame_start_found = 1;
62 s->key_frame = nut >= NAL_BLA_W_LP && nut <= NAL_CRA_NUT;
63 } else { // First slice of next frame found
64 pc->frame_start_found = 0;
74 static int hevc_parse(AVCodecParserContext *s, AVCodecContext *avctx,
75 const uint8_t **poutbuf, int *poutbuf_size,
76 const uint8_t *buf, int buf_size)
79 ParseContext *pc = s->priv_data;
81 if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
84 next = hevc_find_frame_end(s, buf, buf_size);
85 if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
93 *poutbuf_size = buf_size;
97 // Split after the parameter sets at the beginning of the stream if they exist.
98 static int hevc_split(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
104 for (i = 0; i < buf_size; i++) {
105 state = (state << 8) | buf[i];
106 if (((state >> 8) & 0xFFFFFF) == START_CODE) {
107 int nut = (state >> 1) & 0x3F;
108 if (nut >= NAL_VPS && nut <= NAL_PPS)
112 else // no parameter set at the beginning of the stream
119 AVCodecParser ff_hevc_parser = {
120 .codec_ids = { AV_CODEC_ID_HEVC },
121 .priv_data_size = sizeof(ParseContext),
122 .parser_parse = hevc_parse,
123 .parser_close = ff_parse_close,