]> git.sesse.net Git - ffmpeg/blob - libavcodec/hevc_parser.c
Merge commit '7f78155dc6b65be55efb5309b6dd2bb33925a8c4'
[ffmpeg] / libavcodec / hevc_parser.c
1 /*
2  * HEVC Annex B format parser
3  *
4  * Copyright (C) 2012 - 2013 Guillaume Martres
5  *
6  * This file is part of FFmpeg.
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include "libavutil/common.h"
24
25 #include "parser.h"
26 #include "hevc.h"
27 #include "golomb.h"
28
29 #define START_CODE 0x000001 ///< start_code_prefix_one_3bytes
30
31 typedef struct HEVCParseContext {
32     HEVCContext  h;
33     ParseContext pc;
34 } HEVCParseContext;
35
36 /**
37  * Find the end of the current frame in the bitstream.
38  * @return the position of the first byte of the next frame, or END_NOT_FOUND
39  */
40 static int hevc_find_frame_end(AVCodecParserContext *s, const uint8_t *buf,
41                                int buf_size)
42 {
43     int i;
44     ParseContext *pc = &((HEVCParseContext *)s->priv_data)->pc;
45
46     for (i = 0; i < buf_size; i++) {
47         int nut;
48
49         pc->state64 = (pc->state64 << 8) | buf[i];
50
51         if (((pc->state64 >> 3 * 8) & 0xFFFFFF) != START_CODE)
52             continue;
53
54         nut = (pc->state64 >> 2 * 8 + 1) & 0x3F;
55         // Beginning of access unit
56         if ((nut >= NAL_VPS && nut <= NAL_AUD) || nut == NAL_SEI_PREFIX ||
57             (nut >= 41 && nut <= 44) || (nut >= 48 && nut <= 55)) {
58             if (pc->frame_start_found) {
59                 pc->frame_start_found = 0;
60                 return i - 5;
61             }
62         } else if (nut <= NAL_RASL_R ||
63                    (nut >= NAL_BLA_W_LP && nut <= NAL_CRA_NUT)) {
64             int first_slice_segment_in_pic_flag = buf[i] >> 7;
65             if (first_slice_segment_in_pic_flag) {
66                 if (!pc->frame_start_found) {
67                     pc->frame_start_found = 1;
68                 } else { // First slice of next frame found
69                     pc->frame_start_found = 0;
70                     return i - 5;
71                 }
72             }
73         }
74     }
75
76     return END_NOT_FOUND;
77 }
78
79 /**
80  * Parse NAL units of found picture and decode some basic information.
81  *
82  * @param s parser context.
83  * @param avctx codec context.
84  * @param buf buffer with field/frame data.
85  * @param buf_size size of the buffer.
86  */
87 static inline int parse_nal_units(AVCodecParserContext *s, AVCodecContext *avctx,
88                       const uint8_t *buf, int buf_size)
89 {
90     HEVCContext   *h  = &((HEVCParseContext *)s->priv_data)->h;
91     GetBitContext *gb = &h->HEVClc->gb;
92     SliceHeader   *sh = &h->sh;
93     HEVCParamSets *ps = &h->ps;
94     HEVCPacket   *pkt = &h->pkt;
95     const uint8_t *buf_end = buf + buf_size;
96     int state = -1, i;
97     HEVCNAL *nal;
98
99     /* set some sane default values */
100     s->pict_type         = AV_PICTURE_TYPE_I;
101     s->key_frame         = 0;
102     s->picture_structure = AV_PICTURE_STRUCTURE_UNKNOWN;
103
104     h->avctx = avctx;
105
106     if (!buf_size)
107         return 0;
108
109     if (pkt->nals_allocated < 1) {
110         HEVCNAL *tmp = av_realloc_array(pkt->nals, 1, sizeof(*tmp));
111         if (!tmp)
112             return AVERROR(ENOMEM);
113         pkt->nals = tmp;
114         memset(pkt->nals, 0, sizeof(*tmp));
115         pkt->nals_allocated = 1;
116     }
117
118     nal = &pkt->nals[0];
119
120     for (;;) {
121         int src_length, consumed;
122         buf = avpriv_find_start_code(buf, buf_end, &state);
123         if (--buf + 2 >= buf_end)
124             break;
125         src_length = buf_end - buf;
126
127         h->nal_unit_type = (*buf >> 1) & 0x3f;
128         h->temporal_id   = (*(buf + 1) & 0x07) - 1;
129         if (h->nal_unit_type <= NAL_CRA_NUT) {
130             // Do not walk the whole buffer just to decode slice segment header
131             if (src_length > 20)
132                 src_length = 20;
133         }
134
135         consumed = ff_hevc_extract_rbsp(h, buf, src_length, nal);
136         if (consumed < 0)
137             return consumed;
138
139         init_get_bits8(gb, nal->data + 2, nal->size);
140         switch (h->nal_unit_type) {
141         case NAL_VPS:
142             ff_hevc_decode_nal_vps(gb, avctx, ps);
143             break;
144         case NAL_SPS:
145             ff_hevc_decode_nal_sps(gb, avctx, ps, h->apply_defdispwin);
146             break;
147         case NAL_PPS:
148             ff_hevc_decode_nal_pps(gb, avctx, ps);
149             break;
150         case NAL_SEI_PREFIX:
151         case NAL_SEI_SUFFIX:
152             ff_hevc_decode_nal_sei(h);
153             break;
154         case NAL_TRAIL_N:
155         case NAL_TRAIL_R:
156         case NAL_TSA_N:
157         case NAL_TSA_R:
158         case NAL_STSA_N:
159         case NAL_STSA_R:
160         case NAL_RADL_N:
161         case NAL_RADL_R:
162         case NAL_RASL_N:
163         case NAL_RASL_R:
164         case NAL_BLA_W_LP:
165         case NAL_BLA_W_RADL:
166         case NAL_BLA_N_LP:
167         case NAL_IDR_W_RADL:
168         case NAL_IDR_N_LP:
169         case NAL_CRA_NUT:
170             sh->first_slice_in_pic_flag = get_bits1(gb);
171             s->picture_structure = h->picture_struct;
172             s->field_order = h->picture_struct;
173
174             if (IS_IRAP(h)) {
175                 s->key_frame = 1;
176                 sh->no_output_of_prior_pics_flag = get_bits1(gb);
177             }
178
179             sh->pps_id = get_ue_golomb(gb);
180             if (sh->pps_id >= MAX_PPS_COUNT || !ps->pps_list[sh->pps_id]) {
181                 av_log(h->avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id);
182                 return AVERROR_INVALIDDATA;
183             }
184             ps->pps = (HEVCPPS*)ps->pps_list[sh->pps_id]->data;
185
186             if (ps->pps->sps_id >= MAX_SPS_COUNT || !ps->sps_list[ps->pps->sps_id]) {
187                 av_log(h->avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", ps->pps->sps_id);
188                 return AVERROR_INVALIDDATA;
189             }
190             if (ps->sps != (HEVCSPS*)ps->sps_list[ps->pps->sps_id]->data) {
191                 ps->sps = (HEVCSPS*)ps->sps_list[ps->pps->sps_id]->data;
192                 ps->vps = (HEVCVPS*)ps->vps_list[ps->sps->vps_id]->data;
193             }
194
195             if (!sh->first_slice_in_pic_flag) {
196                 int slice_address_length;
197
198                 if (ps->pps->dependent_slice_segments_enabled_flag)
199                     sh->dependent_slice_segment_flag = get_bits1(gb);
200                 else
201                     sh->dependent_slice_segment_flag = 0;
202
203                 slice_address_length = av_ceil_log2_c(ps->sps->ctb_width *
204                                                       ps->sps->ctb_height);
205                 sh->slice_segment_addr = slice_address_length ? get_bits(gb, slice_address_length) : 0;
206                 if (sh->slice_segment_addr >= ps->sps->ctb_width * ps->sps->ctb_height) {
207                     av_log(h->avctx, AV_LOG_ERROR, "Invalid slice segment address: %u.\n",
208                            sh->slice_segment_addr);
209                     return AVERROR_INVALIDDATA;
210                 }
211             } else
212                 sh->dependent_slice_segment_flag = 0;
213
214             if (sh->dependent_slice_segment_flag)
215                 break;
216
217             for (i = 0; i < ps->pps->num_extra_slice_header_bits; i++)
218                 skip_bits(gb, 1); // slice_reserved_undetermined_flag[]
219
220             sh->slice_type = get_ue_golomb(gb);
221             if (!(sh->slice_type == I_SLICE || sh->slice_type == P_SLICE ||
222                   sh->slice_type == B_SLICE)) {
223                 av_log(h->avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n",
224                        sh->slice_type);
225                 return AVERROR_INVALIDDATA;
226             }
227             s->pict_type = sh->slice_type == B_SLICE ? AV_PICTURE_TYPE_B :
228                            sh->slice_type == P_SLICE ? AV_PICTURE_TYPE_P :
229                                                        AV_PICTURE_TYPE_I;
230
231             if (ps->pps->output_flag_present_flag)
232                 sh->pic_output_flag = get_bits1(gb);
233
234             if (ps->sps->separate_colour_plane_flag)
235                 sh->colour_plane_id = get_bits(gb, 2);
236
237             if (!IS_IDR(h)) {
238                 sh->pic_order_cnt_lsb = get_bits(gb, ps->sps->log2_max_poc_lsb);
239                 s->output_picture_number = h->poc = ff_hevc_compute_poc(h, sh->pic_order_cnt_lsb);
240             } else
241                 s->output_picture_number = h->poc = 0;
242
243             if (h->temporal_id == 0 &&
244                 h->nal_unit_type != NAL_TRAIL_N &&
245                 h->nal_unit_type != NAL_TSA_N &&
246                 h->nal_unit_type != NAL_STSA_N &&
247                 h->nal_unit_type != NAL_RADL_N &&
248                 h->nal_unit_type != NAL_RASL_N &&
249                 h->nal_unit_type != NAL_RADL_R &&
250                 h->nal_unit_type != NAL_RASL_R)
251                 h->pocTid0 = h->poc;
252
253             return 0; /* no need to evaluate the rest */
254         }
255         buf += consumed;
256     }
257     /* didn't find a picture! */
258     av_log(h->avctx, AV_LOG_ERROR, "missing picture in access unit\n");
259     return -1;
260 }
261
262 static int hevc_parse(AVCodecParserContext *s,
263                       AVCodecContext *avctx,
264                       const uint8_t **poutbuf, int *poutbuf_size,
265                       const uint8_t *buf, int buf_size)
266 {
267     int next;
268     ParseContext *pc = &((HEVCParseContext *)s->priv_data)->pc;
269
270     if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
271         next = buf_size;
272     } else {
273         next = hevc_find_frame_end(s, buf, buf_size);
274         if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
275             *poutbuf      = NULL;
276             *poutbuf_size = 0;
277             return buf_size;
278         }
279     }
280
281     parse_nal_units(s, avctx, buf, buf_size);
282
283     *poutbuf      = buf;
284     *poutbuf_size = buf_size;
285     return next;
286 }
287
288 // Split after the parameter sets at the beginning of the stream if they exist.
289 static int hevc_split(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
290 {
291     const uint8_t *ptr = buf, *end = buf + buf_size;
292     uint32_t state = -1;
293     int has_ps = 0, nut;
294
295     while (ptr < end) {
296         ptr = avpriv_find_start_code(ptr, end, &state);
297         if ((state >> 8) != START_CODE)
298             break;
299         nut = (state >> 1) & 0x3F;
300         if (nut >= NAL_VPS && nut <= NAL_PPS)
301             has_ps = 1;
302         else if (has_ps)
303             return ptr - 4 - buf;
304         else // no parameter set at the beginning of the stream
305             return 0;
306     }
307     return 0;
308 }
309
310 static int hevc_init(AVCodecParserContext *s)
311 {
312     HEVCContext  *h  = &((HEVCParseContext *)s->priv_data)->h;
313     h->HEVClc = av_mallocz(sizeof(HEVCLocalContext));
314     if (!h->HEVClc)
315         return AVERROR(ENOMEM);
316     h->skipped_bytes_pos_size = INT_MAX;
317
318     return 0;
319 }
320
321 static void hevc_close(AVCodecParserContext *s)
322 {
323     int i;
324     HEVCContext  *h  = &((HEVCParseContext *)s->priv_data)->h;
325     ParseContext *pc = &((HEVCParseContext *)s->priv_data)->pc;
326     HEVCParamSets *ps = &h->ps;
327     HEVCPacket   *pkt = &h->pkt;
328
329     av_freep(&h->skipped_bytes_pos);
330     av_freep(&h->HEVClc);
331     av_freep(&pc->buffer);
332
333     for (i = 0; i < FF_ARRAY_ELEMS(ps->vps_list); i++)
334         av_buffer_unref(&ps->vps_list[i]);
335     for (i = 0; i < FF_ARRAY_ELEMS(ps->sps_list); i++)
336         av_buffer_unref(&ps->sps_list[i]);
337     for (i = 0; i < FF_ARRAY_ELEMS(ps->pps_list); i++)
338         av_buffer_unref(&ps->pps_list[i]);
339
340     ps->sps = NULL;
341
342     for (i = 0; i < pkt->nals_allocated; i++)
343         av_freep(&pkt->nals[i].rbsp_buffer);
344     av_freep(&pkt->nals);
345     pkt->nals_allocated = 0;
346 }
347
348 AVCodecParser ff_hevc_parser = {
349     .codec_ids      = { AV_CODEC_ID_HEVC },
350     .priv_data_size = sizeof(HEVCParseContext),
351     .parser_init    = hevc_init,
352     .parser_parse   = hevc_parse,
353     .parser_close   = hevc_close,
354     .split          = hevc_split,
355 };