2 * HEVC Annex B format parser
4 * Copyright (C) 2012 - 2013 Guillaume Martres
6 * This file is part of FFmpeg.
8 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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"
27 #define START_CODE 0x000001 ///< start_code_prefix_one_3bytes
30 * Find the end of the current frame in the bitstream.
31 * @return the position of the first byte of the next frame, or END_NOT_FOUND
33 static int hevc_find_frame_end(AVCodecParserContext *s, const uint8_t *buf, int buf_size)
36 ParseContext *pc = s->priv_data;
38 for (i = 0; i < buf_size; i++) {
41 pc->state64 = (pc->state64 << 8) | buf[i];
43 if (((pc->state64 >> 3 * 8) & 0xFFFFFF) != START_CODE)
46 nut = (pc->state64 >> 2 * 8 + 1) & 0x3F;
47 // Beginning of access unit
48 if ((nut >= NAL_VPS && nut <= NAL_AUD) || nut == NAL_SEI_PREFIX ||
49 (nut >= 41 && nut <= 44) || (nut >= 48 && nut <= 55)) {
50 if (pc->frame_start_found) {
51 pc->frame_start_found = 0;
54 } else if (nut <= NAL_RASL_R ||
55 (nut >= NAL_BLA_W_LP && nut <= NAL_CRA_NUT)) {
56 int first_slice_segment_in_pic_flag = buf[i] >> 7;
57 if (first_slice_segment_in_pic_flag) {
58 if (!pc->frame_start_found) {
59 pc->frame_start_found = 1;
60 s->key_frame = nut >= NAL_BLA_W_LP && nut <= NAL_CRA_NUT;
61 } else { // First slice of next frame found
62 pc->frame_start_found = 0;
72 static int hevc_parse(AVCodecParserContext *s,
73 AVCodecContext *avctx,
74 const uint8_t **poutbuf, int *poutbuf_size,
75 const uint8_t *buf, int buf_size)
78 ParseContext *pc = s->priv_data;
80 if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
83 next = hevc_find_frame_end(s, buf, buf_size);
84 if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
92 *poutbuf_size = buf_size;
96 // Split after the parameter sets at the beginning of the stream if they exist.
97 static int hevc_split(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
103 for (i = 0; i < buf_size; i++) {
104 state = (state << 8) | buf[i];
105 if (((state >> 8) & 0xFFFFFF) == START_CODE) {
106 int nut = (state >> 1) & 0x3F;
107 if (nut >= NAL_VPS && nut <= NAL_PPS) {
111 } 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,