]> git.sesse.net Git - ffmpeg/blob - libavcodec/hevc_parser.c
avcodec/ffv1dec: Print CRCs at picture debug level
[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 "golomb.h"
26 #include "hevc.h"
27 #include "parser.h"
28
29 #define START_CODE 0x000001 ///< start_code_prefix_one_3bytes
30
31 #define IS_IRAP_NAL(nal) (nal->type >= 16 && nal->type <= 23)
32
33 #define ADVANCED_PARSER CONFIG_HEVC_DECODER
34
35 typedef struct HEVCParserContext {
36     ParseContext pc;
37
38     HEVCPacket pkt;
39     HEVCParamSets ps;
40
41     int parsed_extradata;
42
43 #if ADVANCED_PARSER
44     HEVCContext h;
45 #endif
46 } HEVCParserContext;
47
48 #if !ADVANCED_PARSER
49 static int hevc_parse_slice_header(AVCodecParserContext *s, HEVCNAL *nal,
50                                    AVCodecContext *avctx)
51 {
52     HEVCParserContext *ctx = s->priv_data;
53     GetBitContext *gb = &nal->gb;
54
55     HEVCPPS *pps;
56     HEVCSPS *sps;
57     unsigned int pps_id;
58
59     get_bits1(gb);          // first slice in pic
60     if (IS_IRAP_NAL(nal))
61         get_bits1(gb);      // no output of prior pics
62
63     pps_id = get_ue_golomb_long(gb);
64     if (pps_id >= MAX_PPS_COUNT || !ctx->ps.pps_list[pps_id]) {
65         av_log(avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", pps_id);
66         return AVERROR_INVALIDDATA;
67     }
68     pps = (HEVCPPS*)ctx->ps.pps_list[pps_id]->data;
69     sps = (HEVCSPS*)ctx->ps.sps_list[pps->sps_id]->data;
70
71     /* export the stream parameters */
72     s->coded_width  = sps->width;
73     s->coded_height = sps->height;
74     s->width        = sps->output_width;
75     s->height       = sps->output_height;
76     s->format       = sps->pix_fmt;
77     avctx->profile  = sps->ptl.general_ptl.profile_idc;
78     avctx->level    = sps->ptl.general_ptl.level_idc;
79
80     /* ignore the rest for now*/
81
82     return 0;
83 }
84
85 static int parse_nal_units(AVCodecParserContext *s, const uint8_t *buf,
86                            int buf_size, AVCodecContext *avctx)
87 {
88     HEVCParserContext *ctx = s->priv_data;
89     int ret, i;
90
91     ret = ff_hevc_split_packet(NULL, &ctx->pkt, buf, buf_size, avctx, 0, 0);
92     if (ret < 0)
93         return ret;
94
95     for (i = 0; i < ctx->pkt.nb_nals; i++) {
96         HEVCNAL *nal = &ctx->pkt.nals[i];
97
98         /* ignore everything except parameter sets and VCL NALUs */
99         switch (nal->type) {
100         case NAL_VPS: ff_hevc_decode_nal_vps(&nal->gb, avctx, &ctx->ps);    break;
101         case NAL_SPS: ff_hevc_decode_nal_sps(&nal->gb, avctx, &ctx->ps, 1); break;
102         case NAL_PPS: ff_hevc_decode_nal_pps(&nal->gb, avctx, &ctx->ps);    break;
103         case NAL_TRAIL_R:
104         case NAL_TRAIL_N:
105         case NAL_TSA_N:
106         case NAL_TSA_R:
107         case NAL_STSA_N:
108         case NAL_STSA_R:
109         case NAL_BLA_W_LP:
110         case NAL_BLA_W_RADL:
111         case NAL_BLA_N_LP:
112         case NAL_IDR_W_RADL:
113         case NAL_IDR_N_LP:
114         case NAL_CRA_NUT:
115         case NAL_RADL_N:
116         case NAL_RADL_R:
117         case NAL_RASL_N:
118         case NAL_RASL_R:
119             if (buf == avctx->extradata) {
120                 av_log(avctx, AV_LOG_ERROR, "Invalid NAL unit: %d\n", nal->type);
121                 return AVERROR_INVALIDDATA;
122             }
123             hevc_parse_slice_header(s, nal, avctx);
124             break;
125         }
126     }
127
128     return 0;
129 }
130 #endif
131
132 /**
133  * Find the end of the current frame in the bitstream.
134  * @return the position of the first byte of the next frame, or END_NOT_FOUND
135  */
136 static int hevc_find_frame_end(AVCodecParserContext *s, const uint8_t *buf,
137                                int buf_size)
138 {
139     int i;
140     ParseContext *pc = s->priv_data;
141
142     for (i = 0; i < buf_size; i++) {
143         int nut;
144
145         pc->state64 = (pc->state64 << 8) | buf[i];
146
147         if (((pc->state64 >> 3 * 8) & 0xFFFFFF) != START_CODE)
148             continue;
149
150         nut = (pc->state64 >> 2 * 8 + 1) & 0x3F;
151         // Beginning of access unit
152         if ((nut >= NAL_VPS && nut <= NAL_AUD) || nut == NAL_SEI_PREFIX ||
153             (nut >= 41 && nut <= 44) || (nut >= 48 && nut <= 55)) {
154             if (pc->frame_start_found) {
155                 pc->frame_start_found = 0;
156                 return i - 5;
157             }
158         } else if (nut <= NAL_RASL_R ||
159                    (nut >= NAL_BLA_W_LP && nut <= NAL_CRA_NUT)) {
160             int first_slice_segment_in_pic_flag = buf[i] >> 7;
161             if (first_slice_segment_in_pic_flag) {
162                 if (!pc->frame_start_found) {
163                     pc->frame_start_found = 1;
164                 } else { // First slice of next frame found
165                     pc->frame_start_found = 0;
166                     return i - 5;
167                 }
168             }
169         }
170     }
171
172     return END_NOT_FOUND;
173 }
174
175 #if ADVANCED_PARSER
176 /**
177  * Parse NAL units of found picture and decode some basic information.
178  *
179  * @param s parser context.
180  * @param avctx codec context.
181  * @param buf buffer with field/frame data.
182  * @param buf_size size of the buffer.
183  */
184 static inline int parse_nal_units(AVCodecParserContext *s, const uint8_t *buf,
185                            int buf_size, AVCodecContext *avctx)
186 {
187     HEVCParserContext *ctx = s->priv_data;
188     HEVCContext       *h   = &ctx->h;
189     GetBitContext      *gb;
190     SliceHeader        *sh = &h->sh;
191     HEVCParamSets *ps = &h->ps;
192     HEVCPacket   *pkt = &ctx->pkt;
193     const uint8_t *buf_end = buf + buf_size;
194     int state = -1, i;
195     HEVCNAL *nal;
196     int is_global = buf == avctx->extradata;
197
198     if (!h->HEVClc)
199         h->HEVClc = av_mallocz(sizeof(HEVCLocalContext));
200     if (!h->HEVClc)
201         return AVERROR(ENOMEM);
202
203     gb = &h->HEVClc->gb;
204
205     /* set some sane default values */
206     s->pict_type         = AV_PICTURE_TYPE_I;
207     s->key_frame         = 0;
208     s->picture_structure = AV_PICTURE_STRUCTURE_UNKNOWN;
209
210     h->avctx = avctx;
211
212     if (!buf_size)
213         return 0;
214
215     if (pkt->nals_allocated < 1) {
216         HEVCNAL *tmp = av_realloc_array(pkt->nals, 1, sizeof(*tmp));
217         if (!tmp)
218             return AVERROR(ENOMEM);
219         pkt->nals = tmp;
220         memset(pkt->nals, 0, sizeof(*tmp));
221         pkt->nals_allocated = 1;
222     }
223
224     nal = &pkt->nals[0];
225
226     for (;;) {
227         int src_length, consumed;
228         buf = avpriv_find_start_code(buf, buf_end, &state);
229         if (--buf + 2 >= buf_end)
230             break;
231         src_length = buf_end - buf;
232
233         h->nal_unit_type = (*buf >> 1) & 0x3f;
234         h->temporal_id   = (*(buf + 1) & 0x07) - 1;
235         if (h->nal_unit_type <= NAL_CRA_NUT) {
236             // Do not walk the whole buffer just to decode slice segment header
237             if (src_length > 20)
238                 src_length = 20;
239         }
240
241         consumed = ff_hevc_extract_rbsp(NULL, buf, src_length, nal);
242         if (consumed < 0)
243             return consumed;
244
245         init_get_bits8(gb, nal->data + 2, nal->size);
246         switch (h->nal_unit_type) {
247         case NAL_VPS:
248             ff_hevc_decode_nal_vps(gb, avctx, ps);
249             break;
250         case NAL_SPS:
251             ff_hevc_decode_nal_sps(gb, avctx, ps, 1);
252             break;
253         case NAL_PPS:
254             ff_hevc_decode_nal_pps(gb, avctx, ps);
255             break;
256         case NAL_SEI_PREFIX:
257         case NAL_SEI_SUFFIX:
258             ff_hevc_decode_nal_sei(h);
259             break;
260         case NAL_TRAIL_N:
261         case NAL_TRAIL_R:
262         case NAL_TSA_N:
263         case NAL_TSA_R:
264         case NAL_STSA_N:
265         case NAL_STSA_R:
266         case NAL_RADL_N:
267         case NAL_RADL_R:
268         case NAL_RASL_N:
269         case NAL_RASL_R:
270         case NAL_BLA_W_LP:
271         case NAL_BLA_W_RADL:
272         case NAL_BLA_N_LP:
273         case NAL_IDR_W_RADL:
274         case NAL_IDR_N_LP:
275         case NAL_CRA_NUT:
276
277             if (is_global) {
278                 av_log(avctx, AV_LOG_ERROR, "Invalid NAL unit: %d\n", h->nal_unit_type);
279                 return AVERROR_INVALIDDATA;
280             }
281
282             sh->first_slice_in_pic_flag = get_bits1(gb);
283             s->picture_structure = h->picture_struct;
284             s->field_order = h->picture_struct;
285
286             if (IS_IRAP(h)) {
287                 s->key_frame = 1;
288                 sh->no_output_of_prior_pics_flag = get_bits1(gb);
289             }
290
291             sh->pps_id = get_ue_golomb(gb);
292             if (sh->pps_id >= MAX_PPS_COUNT || !ps->pps_list[sh->pps_id]) {
293                 av_log(avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id);
294                 return AVERROR_INVALIDDATA;
295             }
296             ps->pps = (HEVCPPS*)ps->pps_list[sh->pps_id]->data;
297
298             if (ps->pps->sps_id >= MAX_SPS_COUNT || !ps->sps_list[ps->pps->sps_id]) {
299                 av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", ps->pps->sps_id);
300                 return AVERROR_INVALIDDATA;
301             }
302             if (ps->sps != (HEVCSPS*)ps->sps_list[ps->pps->sps_id]->data) {
303                 ps->sps = (HEVCSPS*)ps->sps_list[ps->pps->sps_id]->data;
304                 ps->vps = (HEVCVPS*)ps->vps_list[ps->sps->vps_id]->data;
305             }
306
307             if (!sh->first_slice_in_pic_flag) {
308                 int slice_address_length;
309
310                 if (ps->pps->dependent_slice_segments_enabled_flag)
311                     sh->dependent_slice_segment_flag = get_bits1(gb);
312                 else
313                     sh->dependent_slice_segment_flag = 0;
314
315                 slice_address_length = av_ceil_log2_c(ps->sps->ctb_width *
316                                                       ps->sps->ctb_height);
317                 sh->slice_segment_addr = slice_address_length ? get_bits(gb, slice_address_length) : 0;
318                 if (sh->slice_segment_addr >= ps->sps->ctb_width * ps->sps->ctb_height) {
319                     av_log(avctx, AV_LOG_ERROR, "Invalid slice segment address: %u.\n",
320                            sh->slice_segment_addr);
321                     return AVERROR_INVALIDDATA;
322                 }
323             } else
324                 sh->dependent_slice_segment_flag = 0;
325
326             if (sh->dependent_slice_segment_flag)
327                 break;
328
329             for (i = 0; i < ps->pps->num_extra_slice_header_bits; i++)
330                 skip_bits(gb, 1); // slice_reserved_undetermined_flag[]
331
332             sh->slice_type = get_ue_golomb(gb);
333             if (!(sh->slice_type == I_SLICE || sh->slice_type == P_SLICE ||
334                   sh->slice_type == B_SLICE)) {
335                 av_log(avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n",
336                        sh->slice_type);
337                 return AVERROR_INVALIDDATA;
338             }
339             s->pict_type = sh->slice_type == B_SLICE ? AV_PICTURE_TYPE_B :
340                            sh->slice_type == P_SLICE ? AV_PICTURE_TYPE_P :
341                                                        AV_PICTURE_TYPE_I;
342
343             if (ps->pps->output_flag_present_flag)
344                 sh->pic_output_flag = get_bits1(gb);
345
346             if (ps->sps->separate_colour_plane_flag)
347                 sh->colour_plane_id = get_bits(gb, 2);
348
349             if (!IS_IDR(h)) {
350                 sh->pic_order_cnt_lsb = get_bits(gb, ps->sps->log2_max_poc_lsb);
351                 s->output_picture_number = h->poc = ff_hevc_compute_poc(h, sh->pic_order_cnt_lsb);
352             } else
353                 s->output_picture_number = h->poc = 0;
354
355             if (h->temporal_id == 0 &&
356                 h->nal_unit_type != NAL_TRAIL_N &&
357                 h->nal_unit_type != NAL_TSA_N &&
358                 h->nal_unit_type != NAL_STSA_N &&
359                 h->nal_unit_type != NAL_RADL_N &&
360                 h->nal_unit_type != NAL_RASL_N &&
361                 h->nal_unit_type != NAL_RADL_R &&
362                 h->nal_unit_type != NAL_RASL_R)
363                 h->pocTid0 = h->poc;
364
365             return 0; /* no need to evaluate the rest */
366         }
367         buf += consumed;
368     }
369     /* didn't find a picture! */
370     if (!is_global)
371         av_log(h->avctx, AV_LOG_ERROR, "missing picture in access unit\n");
372     return -1;
373 }
374 #endif
375
376 static int hevc_parse(AVCodecParserContext *s,
377                       AVCodecContext *avctx,
378                       const uint8_t **poutbuf, int *poutbuf_size,
379                       const uint8_t *buf, int buf_size)
380 {
381     int next;
382     HEVCParserContext *ctx = s->priv_data;
383     ParseContext *pc = &ctx->pc;
384
385     if (avctx->extradata && !ctx->parsed_extradata) {
386         parse_nal_units(s, avctx->extradata, avctx->extradata_size, avctx);
387         ctx->parsed_extradata = 1;
388     }
389
390     if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
391         next = buf_size;
392     } else {
393         next = hevc_find_frame_end(s, buf, buf_size);
394         if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
395             *poutbuf      = NULL;
396             *poutbuf_size = 0;
397             return buf_size;
398         }
399     }
400
401     parse_nal_units(s, buf, buf_size, avctx);
402
403     *poutbuf      = buf;
404     *poutbuf_size = buf_size;
405     return next;
406 }
407
408 // Split after the parameter sets at the beginning of the stream if they exist.
409 static int hevc_split(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
410 {
411     const uint8_t *ptr = buf, *end = buf + buf_size;
412     uint32_t state = -1;
413     int has_ps = 0, nut;
414
415     while (ptr < end) {
416         ptr = avpriv_find_start_code(ptr, end, &state);
417         if ((state >> 8) != START_CODE)
418             break;
419         nut = (state >> 1) & 0x3F;
420         if (nut >= NAL_VPS && nut <= NAL_PPS)
421             has_ps = 1;
422         else if (has_ps)
423             return ptr - 4 - buf;
424         else // no parameter set at the beginning of the stream
425             return 0;
426     }
427     return 0;
428 }
429
430 static void hevc_parser_close(AVCodecParserContext *s)
431 {
432     HEVCParserContext *ctx = s->priv_data;
433     int i;
434
435 #if ADVANCED_PARSER
436     HEVCContext  *h  = &ctx->h;
437
438     for (i = 0; i < FF_ARRAY_ELEMS(h->ps.vps_list); i++)
439         av_buffer_unref(&h->ps.vps_list[i]);
440     for (i = 0; i < FF_ARRAY_ELEMS(h->ps.sps_list); i++)
441         av_buffer_unref(&h->ps.sps_list[i]);
442     for (i = 0; i < FF_ARRAY_ELEMS(h->ps.pps_list); i++)
443         av_buffer_unref(&h->ps.pps_list[i]);
444
445     h->ps.sps = NULL;
446
447     av_freep(&h->HEVClc);
448 #endif
449
450     for (i = 0; i < FF_ARRAY_ELEMS(ctx->ps.vps_list); i++)
451         av_buffer_unref(&ctx->ps.vps_list[i]);
452     for (i = 0; i < FF_ARRAY_ELEMS(ctx->ps.sps_list); i++)
453         av_buffer_unref(&ctx->ps.sps_list[i]);
454     for (i = 0; i < FF_ARRAY_ELEMS(ctx->ps.pps_list); i++)
455         av_buffer_unref(&ctx->ps.pps_list[i]);
456
457     ctx->ps.sps = NULL;
458
459     for (i = 0; i < ctx->pkt.nals_allocated; i++) {
460         av_freep(&ctx->pkt.nals[i].rbsp_buffer);
461         av_freep(&ctx->pkt.nals[i].skipped_bytes_pos);
462     }
463     av_freep(&ctx->pkt.nals);
464     ctx->pkt.nals_allocated = 0;
465
466     av_freep(&ctx->pc.buffer);
467 }
468
469 AVCodecParser ff_hevc_parser = {
470     .codec_ids      = { AV_CODEC_ID_HEVC },
471     .priv_data_size = sizeof(HEVCParserContext),
472     .parser_parse   = hevc_parse,
473     .parser_close   = hevc_parser_close,
474     .split          = hevc_split,
475 };