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