1 /*****************************************************************************
2  * hevc.c
3  *****************************************************************************
4  * Copyright (C) 2013-2017 L-SMASH project
5  *
6  * Authors: Yusuke Nakamura <muken.the.vfrmaniac@gmail.com>
7  *
8  * Permission to use, copy, modify, and/or distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  *****************************************************************************/
20 
21 /* This file is available under an ISC license. */
22 
23 #include "common/internal.h" /* must be placed first */
24 
25 #include <string.h>
26 #include <stdlib.h>
27 #include <inttypes.h>
28 
29 #include "core/box.h"
30 
31 /***************************************************************************
32     ITU-T Recommendation H.265 (04/13)
33     ISO/IEC 14496-15:2014
34 ***************************************************************************/
35 #include "hevc.h"
36 #include "nalu.h"
37 
38 #define IF_EXCEED_INT32( x ) if( (x) < INT32_MIN || (x) > INT32_MAX )
39 #define HEVC_POC_DEBUG_PRINT 0
40 
41 #define HEVC_MIN_NALU_HEADER_LENGTH 2
42 #define HEVC_MAX_VPS_ID             15
43 #define HEVC_MAX_SPS_ID             15
44 #define HEVC_MAX_PPS_ID             63
45 #define HEVC_MAX_DPB_SIZE           16
46 #define HVCC_CONFIGURATION_VERSION  1
47 
48 typedef enum
49 {
50     HEVC_SLICE_TYPE_B = 0,
51     HEVC_SLICE_TYPE_P = 1,
52     HEVC_SLICE_TYPE_I = 2,
53 } hevc_slice_type;
54 
hevc_alloc_parameter_arrays(void)55 static lsmash_hevc_parameter_arrays_t *hevc_alloc_parameter_arrays( void )
56 {
57     lsmash_hevc_parameter_arrays_t *parameter_arrays = lsmash_malloc_zero( sizeof(lsmash_hevc_parameter_arrays_t) );
58     if( !parameter_arrays )
59         return NULL;
60     parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_VPS       ].array_completeness = 1;
61     parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_VPS       ].NAL_unit_type      = HEVC_NALU_TYPE_VPS;
62     parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_SPS       ].array_completeness = 1;
63     parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_SPS       ].NAL_unit_type      = HEVC_NALU_TYPE_SPS;
64     parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_PPS       ].array_completeness = 1;
65     parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_PPS       ].NAL_unit_type      = HEVC_NALU_TYPE_PPS;
66     parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_PREFIX_SEI].array_completeness = 0;
67     parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_PREFIX_SEI].NAL_unit_type      = HEVC_NALU_TYPE_PREFIX_SEI;
68     parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_SUFFIX_SEI].array_completeness = 0;
69     parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_SUFFIX_SEI].NAL_unit_type      = HEVC_NALU_TYPE_SUFFIX_SEI;
70     for( int i = 0; i < HEVC_DCR_NALU_TYPE_NUM; i++ )
71         lsmash_list_init( parameter_arrays->ps_array[i].list, isom_remove_dcr_ps );
72     return parameter_arrays;
73 }
74 
hevc_alloc_parameter_arrays_if_needed(lsmash_hevc_specific_parameters_t * param)75 static int hevc_alloc_parameter_arrays_if_needed
76 (
77     lsmash_hevc_specific_parameters_t *param
78 )
79 {
80     assert( param );
81     if( param->parameter_arrays )
82         return 0;
83     lsmash_hevc_parameter_arrays_t *parameter_arrays = hevc_alloc_parameter_arrays();
84     if( !parameter_arrays )
85         return LSMASH_ERR_MEMORY_ALLOC;
86     param->parameter_arrays = parameter_arrays;
87     return 0;
88 }
89 
hevc_deallocate_parameter_arrays(lsmash_hevc_specific_parameters_t * param)90 static void hevc_deallocate_parameter_arrays
91 (
92     lsmash_hevc_specific_parameters_t *param
93 )
94 {
95     if( !param || !param->parameter_arrays )
96         return;
97     for( int i = 0; i < HEVC_DCR_NALU_TYPE_NUM; i++ )
98         lsmash_list_remove_entries( param->parameter_arrays->ps_array[i].list );
99     lsmash_freep( &param->parameter_arrays );
100 }
101 
lsmash_destroy_hevc_parameter_arrays(lsmash_hevc_specific_parameters_t * param)102 void lsmash_destroy_hevc_parameter_arrays
103 (
104     lsmash_hevc_specific_parameters_t *param
105 )
106 {
107     hevc_deallocate_parameter_arrays( param );
108 }
109 
hevc_destruct_specific_data(void * data)110 void hevc_destruct_specific_data
111 (
112     void *data
113 )
114 {
115     if( !data )
116         return;
117     hevc_deallocate_parameter_arrays( data );
118     lsmash_free( data );
119 }
120 
hevc_remove_pps(hevc_pps_t * pps)121 static void hevc_remove_pps
122 (
123     hevc_pps_t *pps
124 )
125 {
126     if( !pps )
127         return;
128     lsmash_free( pps->colWidth );
129     lsmash_free( pps->rowHeight );
130     lsmash_free( pps );
131 }
132 
hevc_cleanup_parser(hevc_info_t * info)133 void hevc_cleanup_parser
134 (
135     hevc_info_t *info
136 )
137 {
138     if( !info )
139         return;
140     lsmash_list_remove_entries( info->vps_list );
141     lsmash_list_remove_entries( info->sps_list );
142     lsmash_list_remove_entries( info->pps_list );
143     hevc_deallocate_parameter_arrays( &info->hvcC_param );
144     hevc_deallocate_parameter_arrays( &info->hvcC_param_next );
145     lsmash_destroy_multiple_buffers( info->buffer.bank );
146     lsmash_bits_adhoc_cleanup( info->bits );
147     info->bits = NULL;
148 }
149 
hevc_setup_parser(hevc_info_t * info,int parse_only)150 int hevc_setup_parser
151 (
152     hevc_info_t *info,
153     int          parse_only
154 )
155 {
156     assert( info );
157     memset( info, 0, sizeof(hevc_info_t) );
158     info->hvcC_param     .lengthSizeMinusOne = NALU_DEFAULT_NALU_LENGTH_SIZE - 1;
159     info->hvcC_param_next.lengthSizeMinusOne = NALU_DEFAULT_NALU_LENGTH_SIZE - 1;
160     hevc_stream_buffer_t *sb = &info->buffer;
161     sb->bank = lsmash_create_multiple_buffers( parse_only ? 1 : 3, NALU_DEFAULT_BUFFER_SIZE );
162     if( !sb->bank )
163         return LSMASH_ERR_MEMORY_ALLOC;
164     sb->rbsp = lsmash_withdraw_buffer( sb->bank, 1 );
165     if( !parse_only )
166     {
167         info->au.data            = lsmash_withdraw_buffer( sb->bank, 2 );
168         info->au.incomplete_data = lsmash_withdraw_buffer( sb->bank, 3 );
169     }
170     info->bits = lsmash_bits_adhoc_create();
171     if( !info->bits )
172     {
173         lsmash_destroy_multiple_buffers( sb->bank );
174         return LSMASH_ERR_MEMORY_ALLOC;
175     }
176     lsmash_list_init_simple( info->vps_list );
177     lsmash_list_init_simple( info->sps_list );
178     lsmash_list_init( info->pps_list, hevc_remove_pps );
179     info->prev_nalu_type = HEVC_NALU_TYPE_UNKNOWN;
180     return 0;
181 }
182 
hevc_check_nalu_header(lsmash_bs_t * bs,hevc_nalu_header_t * nuh,int use_long_start_code)183 static int hevc_check_nalu_header
184 (
185     lsmash_bs_t        *bs,
186     hevc_nalu_header_t *nuh,
187     int                 use_long_start_code
188 )
189 {
190     /* Check if the enough length of NALU header on the buffer. */
191     int start_code_length = use_long_start_code ? NALU_LONG_START_CODE_LENGTH : NALU_SHORT_START_CODE_LENGTH;
192     if( lsmash_bs_is_end( bs, start_code_length + 1 ) )
193         return LSMASH_ERR_NAMELESS;
194     /* Read NALU header. */
195     uint16_t temp16 = lsmash_bs_show_be16( bs, start_code_length );
196     nuh->forbidden_zero_bit       = (temp16 >> 15) & 0x01;
197     nuh->nal_unit_type            = (temp16 >>  9) & 0x3f;
198     nuh->nuh_layer_id             = (temp16 >>  3) & 0x3f;
199     uint8_t nuh_temporal_id_plus1 =  temp16        & 0x07;
200     if( nuh->forbidden_zero_bit || nuh_temporal_id_plus1 == 0 )
201         return LSMASH_ERR_INVALID_DATA;
202     nuh->TemporalId = nuh_temporal_id_plus1 - 1;
203     nuh->length     = HEVC_MIN_NALU_HEADER_LENGTH;
204     /* nuh_layer_id shall be 0 in the specification we refer to. */
205     if( nuh->nuh_layer_id )
206         return LSMASH_ERR_NAMELESS;
207     if( nuh->TemporalId == 0 )
208     {
209         /* For TSA_N, TSA_R, STSA_N and STSA_R, TemporalId shall not be equal to 0. */
210         if( nuh->nal_unit_type >= HEVC_NALU_TYPE_TSA_N
211          && nuh->nal_unit_type <= HEVC_NALU_TYPE_STSA_R )
212             return LSMASH_ERR_INVALID_DATA;
213     }
214     else
215     {
216         /* For BLA_W_LP to RSV_IRAP_VCL23, TemporalId shall be equal to 0. */
217         if( nuh->nal_unit_type >= HEVC_NALU_TYPE_BLA_W_LP
218          && nuh->nal_unit_type <= HEVC_NALU_TYPE_RSV_IRAP_VCL23 )
219             return LSMASH_ERR_INVALID_DATA;
220         /* For VPS, SPS, EOS and EOB, TemporalId shall be equal to 0. */
221         if( nuh->nal_unit_type >= HEVC_NALU_TYPE_VPS
222          && nuh->nal_unit_type <= HEVC_NALU_TYPE_EOB
223          && nuh->nal_unit_type != HEVC_NALU_TYPE_PPS
224          && nuh->nal_unit_type != HEVC_NALU_TYPE_AUD )
225             return LSMASH_ERR_INVALID_DATA;
226     }
227     /* VPS, SPS and PPS require long start code (0x00000001).
228      * Also AU delimiter requires it too because this type of NALU shall be the first NALU of any AU if present. */
229     if( !use_long_start_code
230      && nuh->nal_unit_type >= HEVC_NALU_TYPE_VPS
231      && nuh->nal_unit_type <= HEVC_NALU_TYPE_AUD )
232         return LSMASH_ERR_INVALID_DATA;
233     return 0;
234 }
235 
hevc_find_next_start_code(lsmash_bs_t * bs,hevc_nalu_header_t * nuh,uint64_t * start_code_length,uint64_t * trailing_zero_bytes)236 uint64_t hevc_find_next_start_code
237 (
238     lsmash_bs_t        *bs,
239     hevc_nalu_header_t *nuh,
240     uint64_t           *start_code_length,
241     uint64_t           *trailing_zero_bytes
242 )
243 {
244     uint64_t length = 0;    /* the length of the latest NALU */
245     uint64_t count  = 0;    /* the number of the trailing zero bytes after the latest NALU */
246     /* Check the type of the current start code. */
247     int long_start_code
248         = (!lsmash_bs_is_end( bs, NALU_LONG_START_CODE_LENGTH )  && 0x00000001 == lsmash_bs_show_be32( bs, 0 )) ? 1
249         : (!lsmash_bs_is_end( bs, NALU_SHORT_START_CODE_LENGTH ) && 0x000001   == lsmash_bs_show_be24( bs, 0 )) ? 0
250         :                                                                                                        -1;
251     if( long_start_code >= 0 && hevc_check_nalu_header( bs, nuh, long_start_code ) == 0 )
252     {
253         *start_code_length = long_start_code ? NALU_LONG_START_CODE_LENGTH : NALU_SHORT_START_CODE_LENGTH;
254         uint64_t distance = *start_code_length + nuh->length;
255         /* Find the start code of the next NALU and get the distance from the start code of the latest NALU. */
256         if( !lsmash_bs_is_end( bs, distance + NALU_SHORT_START_CODE_LENGTH ) )
257         {
258             uint32_t sync_bytes = lsmash_bs_show_be24( bs, distance );
259             while( 0x000001 != sync_bytes )
260             {
261                 if( lsmash_bs_is_end( bs, ++distance + NALU_SHORT_START_CODE_LENGTH ) )
262                 {
263                     distance = lsmash_bs_get_remaining_buffer_size( bs );
264                     break;
265                 }
266                 sync_bytes <<= 8;
267                 sync_bytes  |= lsmash_bs_show_byte( bs, distance + NALU_SHORT_START_CODE_LENGTH - 1 );
268                 sync_bytes  &= 0xFFFFFF;
269             }
270         }
271         else
272             distance = lsmash_bs_get_remaining_buffer_size( bs );
273         /* Any NALU has no consecutive zero bytes at the end. */
274         while( 0x00 == lsmash_bs_show_byte( bs, distance - 1 ) )
275         {
276             --distance;
277             ++count;
278         }
279         /* Remove the length of the start code. */
280         length = distance - *start_code_length;
281         /* If there are one or more trailing zero bytes, we treat the last one byte as a part of the next start code.
282          * This makes the next start code a long start code. */
283         if( count )
284             --count;
285     }
286     else
287     {
288         /* No start code. */
289         nuh->forbidden_zero_bit = 1;    /* shall be 0, so invalid */
290         nuh->nal_unit_type      = HEVC_NALU_TYPE_UNKNOWN;
291         nuh->nuh_layer_id       = 0;    /* arbitrary */
292         nuh->TemporalId         = 0;    /* arbitrary */
293         nuh->length             = 0;
294         *start_code_length = 0;
295         length = NALU_NO_START_CODE_FOUND;
296     }
297     *trailing_zero_bytes = count;
298     return length;
299 }
300 
hevc_get_vps(lsmash_entry_list_t * vps_list,uint8_t vps_id)301 static hevc_vps_t *hevc_get_vps
302 (
303     lsmash_entry_list_t *vps_list,
304     uint8_t              vps_id
305 )
306 {
307     if( !vps_list || vps_id > HEVC_MAX_VPS_ID )
308         return NULL;
309     for( lsmash_entry_t *entry = vps_list->head; entry; entry = entry->next )
310     {
311         hevc_vps_t *vps = (hevc_vps_t *)entry->data;
312         if( !vps )
313             return NULL;
314         if( vps->video_parameter_set_id == vps_id )
315             return vps;
316     }
317     hevc_vps_t *vps = lsmash_malloc_zero( sizeof(hevc_vps_t) );
318     if( !vps )
319         return NULL;
320     vps->video_parameter_set_id = vps_id;
321     if( lsmash_list_add_entry( vps_list, vps ) < 0 )
322     {
323         lsmash_free( vps );
324         return NULL;
325     }
326     return vps;
327 }
328 
hevc_get_sps(lsmash_entry_list_t * sps_list,uint8_t sps_id)329 static hevc_sps_t *hevc_get_sps
330 (
331     lsmash_entry_list_t *sps_list,
332     uint8_t              sps_id
333 )
334 {
335     if( !sps_list || sps_id > HEVC_MAX_SPS_ID )
336         return NULL;
337     for( lsmash_entry_t *entry = sps_list->head; entry; entry = entry->next )
338     {
339         hevc_sps_t *sps = (hevc_sps_t *)entry->data;
340         if( !sps )
341             return NULL;
342         if( sps->seq_parameter_set_id == sps_id )
343             return sps;
344     }
345     hevc_sps_t *sps = lsmash_malloc_zero( sizeof(hevc_sps_t) );
346     if( !sps )
347         return NULL;
348     sps->seq_parameter_set_id = sps_id;
349     if( lsmash_list_add_entry( sps_list, sps ) < 0 )
350     {
351         lsmash_free( sps );
352         return NULL;
353     }
354     return sps;
355 }
356 
hevc_get_pps(lsmash_entry_list_t * pps_list,uint8_t pps_id)357 static hevc_pps_t *hevc_get_pps
358 (
359     lsmash_entry_list_t *pps_list,
360     uint8_t              pps_id
361 )
362 {
363     if( !pps_list || pps_id > HEVC_MAX_PPS_ID )
364         return NULL;
365     for( lsmash_entry_t *entry = pps_list->head; entry; entry = entry->next )
366     {
367         hevc_pps_t *pps = (hevc_pps_t *)entry->data;
368         if( !pps )
369             return NULL;
370         if( pps->pic_parameter_set_id == pps_id )
371             return pps;
372     }
373     hevc_pps_t *pps = lsmash_malloc_zero( sizeof(hevc_pps_t) );
374     if( !pps )
375         return NULL;
376     pps->pic_parameter_set_id = pps_id;
377     if( lsmash_list_add_entry( pps_list, pps ) < 0 )
378     {
379         lsmash_free( pps );
380         return NULL;
381     }
382     return pps;
383 }
384 
hevc_calculate_poc(hevc_info_t * info,hevc_picture_info_t * picture,hevc_picture_info_t * prev_picture)385 int hevc_calculate_poc
386 (
387     hevc_info_t         *info,
388     hevc_picture_info_t *picture,
389     hevc_picture_info_t *prev_picture
390 )
391 {
392 #if HEVC_POC_DEBUG_PRINT
393     fprintf( stderr, "PictureOrderCount\n" );
394 #endif
395     hevc_pps_t *pps = hevc_get_pps( info->pps_list, picture->pic_parameter_set_id );
396     if( !pps )
397         return LSMASH_ERR_NAMELESS;
398     hevc_sps_t *sps = hevc_get_sps( info->sps_list, pps->seq_parameter_set_id );
399     if( !sps )
400         return LSMASH_ERR_NAMELESS;
401     /* 8.3.1 Decoding process for picture order count
402      * This process needs to be invoked only for the first slice segment of a picture. */
403     int NoRaslOutputFlag;
404     if( picture->irap )
405     {
406         /* 8.1 General decoding process
407          * If the current picture is an IDR picture, a BLA picture, the first picture in the
408          * bitstream in decoding order, or the first picture that follows an end of sequence
409          * NAL unit in decoding order, the variable NoRaslOutputFlag is set equal to 1.
410          *
411          * Note that not only the end of sequence NAL unit but the end of bistream NAL unit as
412          * well specify that the current access unit is the last access unit in the coded video
413          * sequence in decoding order. */
414         NoRaslOutputFlag = picture->idr || picture->broken_link || info->eos;
415         if( info->eos )
416             info->eos = 0;
417     }
418     else
419         NoRaslOutputFlag = 0;
420     int64_t poc_msb;
421     int32_t poc_lsb = picture->poc_lsb;
422     if( picture->irap && NoRaslOutputFlag )
423         poc_msb = 0;
424     else
425     {
426         int32_t prev_poc_msb = picture->idr ? 0 : prev_picture->tid0_poc_msb;
427         int32_t prev_poc_lsb = picture->idr ? 0 : prev_picture->tid0_poc_lsb;
428         int32_t max_poc_lsb  = 1 << sps->log2_max_pic_order_cnt_lsb;
429         if( (poc_lsb < prev_poc_lsb)
430          && ((prev_poc_lsb - poc_lsb) >= (max_poc_lsb / 2)) )
431             poc_msb = prev_poc_msb + max_poc_lsb;
432         else if( (poc_lsb > prev_poc_lsb)
433          && ((poc_lsb - prev_poc_lsb) > (max_poc_lsb / 2)) )
434             poc_msb = prev_poc_msb - max_poc_lsb;
435         else
436             poc_msb = prev_poc_msb;
437     }
438     picture->poc = poc_msb + poc_lsb;
439     if( picture->TemporalId == 0 && (!picture->radl || !picture->rasl || !picture->sublayer_nonref) )
440     {
441         picture->tid0_poc_msb = poc_msb;
442         picture->tid0_poc_lsb = poc_lsb;
443     }
444 #if HEVC_POC_DEBUG_PRINT
445     fprintf( stderr, "    prevPicOrderCntMsb: %"PRId32"\n", prev_poc_msb );
446     fprintf( stderr, "    prevPicOrderCntLsb: %"PRId32"\n", prev_poc_lsb );
447     fprintf( stderr, "    PicOrderCntMsb: %"PRId64"\n",     poc_msb );
448     fprintf( stderr, "    pic_order_cnt_lsb: %"PRId32"\n",  poc_lsb );
449     fprintf( stderr, "    MaxPicOrderCntLsb: %"PRIu64"\n",  max_poc_lsb );
450     fprintf( stderr, "    POC: %"PRId32"\n", picture->poc );
451 #endif
452     return 0;
453 }
454 
hevc_activate_vps(hevc_info_t * info,uint8_t video_parameter_set_id)455 static inline int hevc_activate_vps
456 (
457     hevc_info_t *info,
458     uint8_t      video_parameter_set_id
459 )
460 {
461     hevc_vps_t *vps = hevc_get_vps( info->vps_list, video_parameter_set_id );
462     if( !vps )
463         return LSMASH_ERR_NAMELESS;
464     info->vps = *vps;
465     return 0;
466 }
467 
hevc_activate_sps(hevc_info_t * info,uint8_t seq_parameter_set_id)468 static inline int hevc_activate_sps
469 (
470     hevc_info_t *info,
471     uint8_t      seq_parameter_set_id
472 )
473 {
474     hevc_sps_t *sps = hevc_get_sps( info->sps_list, seq_parameter_set_id );
475     if( !sps )
476         return LSMASH_ERR_NAMELESS;
477     info->sps = *sps;
478     return 0;
479 }
480 
hevc_parse_scaling_list_data(lsmash_bits_t * bits)481 static void hevc_parse_scaling_list_data
482 (
483     lsmash_bits_t *bits
484 )
485 {
486     for( int sizeId = 0; sizeId < 4; sizeId++ )
487         for( int matrixId = 0; matrixId < (sizeId == 3 ? 2 : 6); matrixId++ )
488         {
489             if( !lsmash_bits_get( bits, 1 ) )       /* scaling_list_pred_mode_flag[sizeId][matrixId] */
490                 nalu_get_exp_golomb_ue( bits );     /* scaling_list_pred_matrix_id_delta[sizeId][matrixId] */
491             else
492             {
493                 int coefNum = LSMASH_MIN( 64, 1 << (4 + (sizeId << 1)) );
494                 if( sizeId > 1 )
495                     nalu_get_exp_golomb_se( bits ); /* scaling_list_dc_coef_minus8[sizeId - 2][matrixId] */
496                 for( int i = 0; i < coefNum; i++ )
497                     nalu_get_exp_golomb_se( bits ); /* scaling_list_delta_coef */
498             }
499         }
500 }
501 
hevc_short_term_ref_pic_set(lsmash_bits_t * bits,hevc_sps_t * sps,int stRpsIdx)502 static int hevc_short_term_ref_pic_set
503 (
504     lsmash_bits_t *bits,
505     hevc_sps_t    *sps,
506     int            stRpsIdx
507 )
508 {
509     int inter_ref_pic_set_prediction_flag = stRpsIdx != 0 ? lsmash_bits_get( bits, 1 ) : 0;
510     if( inter_ref_pic_set_prediction_flag )
511     {
512         /* delta_idx_minus1 is always 0 in SPS since stRpsIdx must not be equal to num_short_term_ref_pic_sets. */
513         uint64_t delta_idx_minus1     = stRpsIdx == sps->num_short_term_ref_pic_sets ? nalu_get_exp_golomb_ue( bits ) : 0;
514         int      delta_rps_sign       = lsmash_bits_get( bits, 1 );
515         uint64_t abs_delta_rps_minus1 = nalu_get_exp_golomb_ue( bits );
516         int RefRpsIdx = stRpsIdx - (delta_idx_minus1 + 1);
517         int deltaRps  = (delta_rps_sign ? -1 : 1) * (abs_delta_rps_minus1 + 1);
518         hevc_st_rps_t *st_rps  = &sps->st_rps[stRpsIdx];
519         hevc_st_rps_t *ref_rps = &sps->st_rps[RefRpsIdx];
520         uint8_t used_by_curr_pic_flag[32];
521         uint8_t use_delta_flag       [32];
522         for( int j = 0; j <= ref_rps->NumDeltaPocs; j++ )
523         {
524             used_by_curr_pic_flag[j] = lsmash_bits_get( bits, 1 );
525             use_delta_flag       [j] = !used_by_curr_pic_flag[j] ? lsmash_bits_get( bits, 1 ) : 1;
526         }
527         /* NumNegativePics */
528         int i = 0;
529         for( int j = ref_rps->NumPositivePics - 1; j >= 0; j-- )
530         {
531             int dPoc = ref_rps->DeltaPocS1[j] + deltaRps;
532             if( dPoc < 0 && use_delta_flag[ ref_rps->NumNegativePics + j ] )
533             {
534                 st_rps->DeltaPocS0     [i  ] = dPoc;
535                 st_rps->UsedByCurrPicS0[i++] = used_by_curr_pic_flag[ ref_rps->NumNegativePics + j ];
536             }
537         }
538         if( deltaRps < 0 && use_delta_flag[ ref_rps->NumDeltaPocs ] )
539         {
540             st_rps->DeltaPocS0     [i  ] = deltaRps;
541             st_rps->UsedByCurrPicS0[i++] = used_by_curr_pic_flag[ ref_rps->NumDeltaPocs ];
542         }
543         for( int j = 0; j < ref_rps->NumNegativePics; j++ )
544         {
545             int dPoc = ref_rps->DeltaPocS0[j] + deltaRps;
546             if( dPoc < 0 && use_delta_flag[j] )
547             {
548                 st_rps->DeltaPocS0     [i  ] = dPoc;
549                 st_rps->UsedByCurrPicS0[i++] = used_by_curr_pic_flag[j];
550             }
551         }
552         st_rps->NumNegativePics = i;
553         /* NumPositivePics */
554         i = 0;
555         for( int j = ref_rps->NumNegativePics - 1; j >= 0; j-- )
556         {
557             int dPoc = ref_rps->DeltaPocS0[j] + deltaRps;
558             if( dPoc > 0 && use_delta_flag[j] )
559             {
560                 st_rps->DeltaPocS1     [i  ] = dPoc;
561                 st_rps->UsedByCurrPicS1[i++] = used_by_curr_pic_flag[j];
562             }
563         }
564         if( deltaRps > 0 && use_delta_flag[ ref_rps->NumDeltaPocs ] )
565         {
566             st_rps->DeltaPocS1     [i  ] = deltaRps;
567             st_rps->UsedByCurrPicS1[i++] = used_by_curr_pic_flag[ ref_rps->NumDeltaPocs ];
568         }
569         for( int j = 0; j < ref_rps->NumPositivePics; j++ )
570         {
571             int dPoc = ref_rps->DeltaPocS1[j] + deltaRps;
572             if( dPoc > 0 && use_delta_flag[ ref_rps->NumNegativePics + j ] )
573             {
574                 st_rps->DeltaPocS1     [i  ] = dPoc;
575                 st_rps->UsedByCurrPicS1[i++] = used_by_curr_pic_flag[ ref_rps->NumNegativePics + j ];
576             }
577         }
578         st_rps->NumPositivePics = i;
579         /* NumDeltaPocs */
580         st_rps->NumDeltaPocs = st_rps->NumNegativePics + st_rps->NumPositivePics;
581     }
582     else
583     {
584         uint64_t num_negative_pics = nalu_get_exp_golomb_ue( bits );
585         uint64_t num_positive_pics = nalu_get_exp_golomb_ue( bits );
586         if( num_negative_pics >= HEVC_MAX_DPB_SIZE || num_positive_pics >= HEVC_MAX_DPB_SIZE )
587             return LSMASH_ERR_INVALID_DATA;
588         hevc_st_rps_t *st_rps = &sps->st_rps[stRpsIdx];
589         st_rps->NumNegativePics = num_negative_pics;
590         st_rps->NumPositivePics = num_positive_pics;
591         st_rps->NumDeltaPocs    = st_rps->NumNegativePics + st_rps->NumPositivePics;
592         for( int i = 0; i < num_negative_pics; i++ )
593         {
594             uint64_t delta_poc_s0_minus1 = nalu_get_exp_golomb_ue( bits );
595             if( i == 0 )
596                 st_rps->DeltaPocS0[i] = -(signed)(delta_poc_s0_minus1 + 1);
597             else
598                 st_rps->DeltaPocS0[i] = st_rps->DeltaPocS0[i - 1] - (delta_poc_s0_minus1 + 1);
599             st_rps->UsedByCurrPicS0[i] = lsmash_bits_get( bits, 1 );    /* used_by_curr_pic_s0_flag */
600         }
601         for( int i = 0; i < num_positive_pics; i++ )
602         {
603             uint64_t delta_poc_s1_minus1 = nalu_get_exp_golomb_ue( bits );
604             if( i == 0 )
605                 st_rps->DeltaPocS1[i] = +(delta_poc_s1_minus1 + 1);
606             else
607                 st_rps->DeltaPocS1[i] = st_rps->DeltaPocS1[i - 1] + (delta_poc_s1_minus1 + 1);
608             st_rps->UsedByCurrPicS0[i] = lsmash_bits_get( bits, 1 );    /* used_by_curr_pic_s1_flag */
609         }
610     }
611     return 0;
612 }
613 
hevc_parse_sub_layer_hrd_parameters(lsmash_bits_t * bits,int CpbCnt,int sub_pic_hrd_params_present_flag)614 static inline void hevc_parse_sub_layer_hrd_parameters
615 (
616     lsmash_bits_t *bits,
617     int            CpbCnt,
618     int            sub_pic_hrd_params_present_flag
619 )
620 {
621     for( int i = 0; i <= CpbCnt; i++ )
622     {
623         nalu_get_exp_golomb_ue( bits );         /* bit_rate_value_minus1[i] */
624         nalu_get_exp_golomb_ue( bits );         /* cpb_size_value_minus1[i] */
625         if( sub_pic_hrd_params_present_flag )
626         {
627             nalu_get_exp_golomb_ue( bits );     /* cpb_size_du_value_minus1[i] */
628             nalu_get_exp_golomb_ue( bits );     /* bit_rate_du_value_minus1[i] */
629         }
630         lsmash_bits_get( bits, 1 );             /* cbr_flag[i] */
631     }
632 }
633 
hevc_parse_hrd_parameters(lsmash_bits_t * bits,hevc_hrd_t * hrd,int commonInfPresentFlag,int maxNumSubLayersMinus1)634 static void hevc_parse_hrd_parameters
635 (
636     lsmash_bits_t *bits,
637     hevc_hrd_t    *hrd,
638     int            commonInfPresentFlag,
639     int            maxNumSubLayersMinus1
640 )
641 {
642     /* The specification we refer to doesn't define the implicit value of some fields.
643      * According to JCTVC-HM reference software,
644      *   the implicit value of nal_hrd_parameters_present_flag is to be equal to 0,
645      *   the implicit value of vcl_hrd_parameters_present_flag is to be equal to 0. */
646     int nal_hrd_parameters_present_flag = 0;
647     int vcl_hrd_parameters_present_flag = 0;
648     memset( hrd, 0, sizeof(hevc_hrd_t) );
649     if( commonInfPresentFlag )
650     {
651         nal_hrd_parameters_present_flag = lsmash_bits_get( bits, 1 );
652         vcl_hrd_parameters_present_flag = lsmash_bits_get( bits, 1 );
653         if( nal_hrd_parameters_present_flag
654          || vcl_hrd_parameters_present_flag )
655         {
656             hrd->CpbDpbDelaysPresentFlag         = 1;
657             hrd->sub_pic_hrd_params_present_flag = lsmash_bits_get( bits, 1 );
658             if( hrd->sub_pic_hrd_params_present_flag )
659             {
660                 lsmash_bits_get( bits, 8 );     /* tick_divisor_minus2 */
661                 hrd->du_cpb_removal_delay_increment_length     = lsmash_bits_get( bits, 5 ) + 1;
662                 hrd->sub_pic_cpb_params_in_pic_timing_sei_flag = lsmash_bits_get( bits, 1 );
663                 hrd->dpb_output_delay_du_length                = lsmash_bits_get( bits, 5 ) + 1;
664             }
665             lsmash_bits_get( bits, 4 );         /* bit_rate_scale */
666             lsmash_bits_get( bits, 4 );         /* cpb_size_scale */
667             if( hrd->sub_pic_hrd_params_present_flag )
668                 lsmash_bits_get( bits, 4 );     /* cpb_size_du_scale */
669             lsmash_bits_get( bits, 5 );         /* initial_cpb_removal_delay_length_minus1 */
670             hrd->au_cpb_removal_delay_length = lsmash_bits_get( bits, 5 ) + 1;
671             hrd->dpb_output_delay_length     = lsmash_bits_get( bits, 5 ) + 1;
672         }
673     }
674     for( int i = 0; i <= maxNumSubLayersMinus1; i++ )
675     {
676         hrd->fixed_pic_rate_general_flag[i]     =                                        lsmash_bits_get( bits, 1 );
677         uint8_t  fixed_pic_rate_within_cvs_flag = !hrd->fixed_pic_rate_general_flag[i] ? lsmash_bits_get( bits, 1 )         : 1;
678         uint8_t  low_delay_hrd_flag             = !fixed_pic_rate_within_cvs_flag      ? lsmash_bits_get( bits, 1 )         : 0;
679         hrd->elemental_duration_in_tc[i]        =  fixed_pic_rate_within_cvs_flag      ? nalu_get_exp_golomb_ue( bits ) + 1 : 0;
680         uint8_t  cpb_cnt_minus1                 = !low_delay_hrd_flag                  ? nalu_get_exp_golomb_ue( bits )     : 0;
681         if( nal_hrd_parameters_present_flag )
682             hevc_parse_sub_layer_hrd_parameters( bits, cpb_cnt_minus1, hrd->sub_pic_hrd_params_present_flag );
683         if( vcl_hrd_parameters_present_flag )
684             hevc_parse_sub_layer_hrd_parameters( bits, cpb_cnt_minus1, hrd->sub_pic_hrd_params_present_flag );
685     }
686 }
687 
hevc_parse_profile_tier_level_common(lsmash_bits_t * bits,hevc_ptl_common_t * ptlc,int profile_present,int level_present)688 static inline void hevc_parse_profile_tier_level_common
689 (
690     lsmash_bits_t     *bits,
691     hevc_ptl_common_t *ptlc,
692     int                profile_present,
693     int                level_present
694 )
695 {
696     if( profile_present )
697     {
698         ptlc->profile_space               = lsmash_bits_get( bits,  2 );
699         ptlc->tier_flag                   = lsmash_bits_get( bits,  1 );
700         ptlc->profile_idc                 = lsmash_bits_get( bits,  5 );
701         ptlc->profile_compatibility_flags = lsmash_bits_get( bits, 32 );
702         ptlc->progressive_source_flag     = lsmash_bits_get( bits,  1 );
703         ptlc->interlaced_source_flag      = lsmash_bits_get( bits,  1 );
704         ptlc->non_packed_constraint_flag  = lsmash_bits_get( bits,  1 );
705         ptlc->frame_only_constraint_flag  = lsmash_bits_get( bits,  1 );
706         ptlc->reserved_zero_44bits        = lsmash_bits_get( bits, 44 );
707     }
708     if( level_present )
709         ptlc->level_idc                   = lsmash_bits_get( bits,  8 );
710 }
711 
hevc_parse_profile_tier_level(lsmash_bits_t * bits,hevc_ptl_t * ptl,int maxNumSubLayersMinus1)712 static void hevc_parse_profile_tier_level
713 (
714     lsmash_bits_t *bits,
715     hevc_ptl_t    *ptl,
716     int            maxNumSubLayersMinus1
717 )
718 {
719     hevc_parse_profile_tier_level_common( bits, &ptl->general, 1, 1 );
720     if( maxNumSubLayersMinus1 == 0 )
721         return;
722     assert( maxNumSubLayersMinus1 <= 6 );
723     int sub_layer_profile_present_flag[6] = { 0 };
724     int sub_layer_level_present_flag  [6] = { 0 };
725     for( int i = 0; i < maxNumSubLayersMinus1; i++ )
726     {
727         sub_layer_profile_present_flag[i] = lsmash_bits_get( bits, 1 );
728         sub_layer_level_present_flag  [i] = lsmash_bits_get( bits, 1 );
729     }
730     for( int i = maxNumSubLayersMinus1; i < 8; i++ )
731         lsmash_bits_get( bits, 2 );     /* reserved_zero_2bits[i] */
732     for( int i = 0; i < maxNumSubLayersMinus1; i++ )
733         hevc_parse_profile_tier_level_common( bits, &ptl->sub_layer[i], sub_layer_profile_present_flag[i], sub_layer_level_present_flag[i] );
734 }
735 
hevc_parse_vps_minimally(lsmash_bits_t * bits,hevc_vps_t * vps,uint8_t * rbsp_buffer,uint8_t * ebsp,uint64_t ebsp_size)736 static int hevc_parse_vps_minimally
737 (
738     lsmash_bits_t *bits,
739     hevc_vps_t    *vps,
740     uint8_t       *rbsp_buffer,
741     uint8_t       *ebsp,
742     uint64_t       ebsp_size
743 )
744 {
745     int err = nalu_import_rbsp_from_ebsp( bits, rbsp_buffer, ebsp, ebsp_size );
746     if( err < 0 )
747         return err;
748     memset( vps, 0, sizeof(hevc_vps_t) );
749     vps->video_parameter_set_id = lsmash_bits_get( bits, 4 );
750     /* vps_reserved_three_2bits shall be 3 in the specification we refer to. */
751     if( lsmash_bits_get( bits, 2 ) != 3 )
752         return LSMASH_ERR_NAMELESS;
753     /* vps_max_layers_minus1 shall be 0 in the specification we refer to. */
754     if( lsmash_bits_get( bits, 6 ) != 0 )
755         return LSMASH_ERR_NAMELESS;
756     vps->max_sub_layers_minus1    = lsmash_bits_get( bits, 3 );
757     vps->temporal_id_nesting_flag = lsmash_bits_get( bits, 1 );
758     /* When vps_max_sub_layers_minus1 is equal to 0, vps_temporal_id_nesting_flag shall be equal to 1. */
759     if( (vps->max_sub_layers_minus1 | vps->temporal_id_nesting_flag) == 0 )
760         return LSMASH_ERR_INVALID_DATA;
761     /* vps_reserved_0xffff_16bits shall be 0xFFFF in the specification we refer to. */
762     if( lsmash_bits_get( bits, 16 ) != 0xFFFF )
763         return LSMASH_ERR_NAMELESS;
764     hevc_parse_profile_tier_level( bits, &vps->ptl, vps->max_sub_layers_minus1 );
765     vps->frame_field_info_present_flag = vps->ptl.general.progressive_source_flag
766                                       && vps->ptl.general.interlaced_source_flag;
767     int sub_layer_ordering_info_present_flag = lsmash_bits_get( bits, 1 );
768     for( int i = sub_layer_ordering_info_present_flag ? 0 : vps->max_sub_layers_minus1; i <= vps->max_sub_layers_minus1; i++ )
769     {
770         nalu_get_exp_golomb_ue( bits );  /* max_dec_pic_buffering_minus1[i] */
771         nalu_get_exp_golomb_ue( bits );  /* max_num_reorder_pics        [i] */
772         nalu_get_exp_golomb_ue( bits );  /* max_latency_increase_plus1  [i] */
773     }
774     uint8_t  max_layer_id          = lsmash_bits_get( bits, 6 );
775     uint16_t num_layer_sets_minus1 = nalu_get_exp_golomb_ue( bits );
776     for( int i = 1; i <= num_layer_sets_minus1; i++ )
777         for( int j = 0; j <= max_layer_id; j++ )
778             lsmash_bits_get( bits, 1 );     /* layer_id_included_flag[i][j] */
779     return bits->bs->error ? LSMASH_ERR_NAMELESS : 0;
780 }
781 
hevc_parse_vps(hevc_info_t * info,uint8_t * rbsp_buffer,uint8_t * ebsp,uint64_t ebsp_size)782 int hevc_parse_vps
783 (
784     hevc_info_t *info,
785     uint8_t     *rbsp_buffer,
786     uint8_t     *ebsp,
787     uint64_t     ebsp_size
788 )
789 {
790     lsmash_bits_t *bits = info->bits;
791     hevc_vps_t *vps;
792     {
793         /* Parse VPS minimally for configuration records. */
794         hevc_vps_t min_vps;
795         int err = hevc_parse_vps_minimally( bits, &min_vps, rbsp_buffer, ebsp, ebsp_size );
796         if( err < 0 )
797             return err;
798         vps = hevc_get_vps( info->vps_list, min_vps.video_parameter_set_id );
799         if( !vps )
800             return LSMASH_ERR_NAMELESS;
801         *vps = min_vps;
802     }
803     vps->timing_info_present_flag = lsmash_bits_get( bits, 1 );
804     if( vps->timing_info_present_flag )
805     {
806         lsmash_bits_get( bits, 32 );        /* num_units_in_tick */
807         lsmash_bits_get( bits, 32 );        /* time_scale */
808         if( lsmash_bits_get( bits,  1 ) )   /* poc_proportional_to_timing_flag */
809             nalu_get_exp_golomb_ue( bits ); /* num_ticks_poc_diff_one_minus1 */
810         vps->num_hrd_parameters = nalu_get_exp_golomb_ue( bits );
811         for( int i = 0; i < vps->num_hrd_parameters; i++ )
812         {
813             nalu_get_exp_golomb_ue( bits );     /* hrd_layer_set_idx[i] */
814             int cprms_present_flag = i > 0 ? lsmash_bits_get( bits, 1 ) : 1;
815             /* Although the value of vps_num_hrd_parameters is required to be less than or equal to 1 in the spec
816              * we refer to, decoders shall allow other values of vps_num_hrd_parameters in the range of 0 to 1024,
817              * inclusive, to appear in the syntax. */
818             if( i <= 1 )
819                 hevc_parse_hrd_parameters( bits, &vps->hrd[i], cprms_present_flag, vps->max_sub_layers_minus1 );
820             else
821             {
822                 hevc_hrd_t dummy_hrd;
823                 hevc_parse_hrd_parameters( bits, &dummy_hrd,   cprms_present_flag, vps->max_sub_layers_minus1 );
824             }
825         }
826     }
827     /* Skip VPS extension. */
828     lsmash_bits_empty( bits );
829     if( bits->bs->error )
830         return LSMASH_ERR_NAMELESS;
831     vps->present = 1;
832     info->vps = *vps;
833     return 0;
834 }
835 
hevc_parse_sps_minimally(lsmash_bits_t * bits,hevc_sps_t * sps,uint8_t * rbsp_buffer,uint8_t * ebsp,uint64_t ebsp_size)836 static int hevc_parse_sps_minimally
837 (
838     lsmash_bits_t *bits,
839     hevc_sps_t    *sps,
840     uint8_t       *rbsp_buffer,
841     uint8_t       *ebsp,
842     uint64_t       ebsp_size
843 )
844 {
845     int err = nalu_import_rbsp_from_ebsp( bits, rbsp_buffer, ebsp, ebsp_size );
846     if( err < 0 )
847         return err;
848     memset( sps, 0, sizeof(hevc_sps_t) );
849     sps->video_parameter_set_id   = lsmash_bits_get( bits, 4 );
850     sps->max_sub_layers_minus1    = lsmash_bits_get( bits, 3 );
851     sps->temporal_id_nesting_flag = lsmash_bits_get( bits, 1 );
852     hevc_parse_profile_tier_level( bits, &sps->ptl, sps->max_sub_layers_minus1 );
853     sps->seq_parameter_set_id = nalu_get_exp_golomb_ue( bits );
854     sps->chroma_format_idc    = nalu_get_exp_golomb_ue( bits );
855     if( sps->chroma_format_idc == 3 )
856         sps->separate_colour_plane_flag = lsmash_bits_get( bits, 1 );
857     static const int SubWidthC [] = { 1, 2, 2, 1 };
858     static const int SubHeightC[] = { 1, 2, 1, 1 };
859     uint64_t pic_width_in_luma_samples  = nalu_get_exp_golomb_ue( bits );
860     uint64_t pic_height_in_luma_samples = nalu_get_exp_golomb_ue( bits );
861     sps->cropped_width  = pic_width_in_luma_samples;
862     sps->cropped_height = pic_height_in_luma_samples;
863     if( lsmash_bits_get( bits, 1 ) )    /* conformance_window_flag */
864     {
865         uint64_t conf_win_left_offset   = nalu_get_exp_golomb_ue( bits );
866         uint64_t conf_win_right_offset  = nalu_get_exp_golomb_ue( bits );
867         uint64_t conf_win_top_offset    = nalu_get_exp_golomb_ue( bits );
868         uint64_t conf_win_bottom_offset = nalu_get_exp_golomb_ue( bits );
869         sps->cropped_width  -= (conf_win_left_offset + conf_win_right_offset)  * SubWidthC [ sps->chroma_format_idc ];
870         sps->cropped_height -= (conf_win_top_offset  + conf_win_bottom_offset) * SubHeightC[ sps->chroma_format_idc ];
871     }
872     sps->bit_depth_luma_minus8               = nalu_get_exp_golomb_ue( bits );
873     sps->bit_depth_chroma_minus8             = nalu_get_exp_golomb_ue( bits );
874     sps->log2_max_pic_order_cnt_lsb          = nalu_get_exp_golomb_ue( bits ) + 4;
875     int sub_layer_ordering_info_present_flag = lsmash_bits_get( bits, 1 );
876     for( int i = sub_layer_ordering_info_present_flag ? 0 : sps->max_sub_layers_minus1; i <= sps->max_sub_layers_minus1; i++ )
877     {
878         nalu_get_exp_golomb_ue( bits );  /* max_dec_pic_buffering_minus1[i] */
879         nalu_get_exp_golomb_ue( bits );  /* max_num_reorder_pics        [i] */
880         nalu_get_exp_golomb_ue( bits );  /* max_latency_increase_plus1  [i] */
881     }
882     uint64_t log2_min_luma_coding_block_size_minus3   = nalu_get_exp_golomb_ue( bits );
883     uint64_t log2_diff_max_min_luma_coding_block_size = nalu_get_exp_golomb_ue( bits );
884     nalu_get_exp_golomb_ue( bits );         /* log2_min_transform_block_size_minus2 */
885     nalu_get_exp_golomb_ue( bits );         /* log2_diff_max_min_transform_block_size */
886     nalu_get_exp_golomb_ue( bits );         /* max_transform_hierarchy_depth_inter */
887     nalu_get_exp_golomb_ue( bits );         /* max_transform_hierarchy_depth_intra */
888     {
889         int MinCbLog2SizeY = log2_min_luma_coding_block_size_minus3 + 3;
890         int MinCbSizeY     = 1 << MinCbLog2SizeY;
891         if( pic_width_in_luma_samples  == 0 || pic_width_in_luma_samples  % MinCbSizeY
892          || pic_height_in_luma_samples == 0 || pic_height_in_luma_samples % MinCbSizeY )
893             return LSMASH_ERR_INVALID_DATA; /* Both shall be an integer multiple of MinCbSizeY. */
894         int CtbLog2SizeY = MinCbLog2SizeY + log2_diff_max_min_luma_coding_block_size;
895         int CtbSizeY     = 1 << CtbLog2SizeY;
896         sps->PicWidthInCtbsY  = (pic_width_in_luma_samples  - 1) / CtbSizeY + 1;
897         sps->PicHeightInCtbsY = (pic_height_in_luma_samples - 1) / CtbSizeY + 1;
898         sps->PicSizeInCtbsY   = sps->PicWidthInCtbsY * sps->PicHeightInCtbsY;
899     }
900     if( lsmash_bits_get( bits, 1 )          /* scaling_list_enabled_flag */
901      && lsmash_bits_get( bits, 1 ) )        /* sps_scaling_list_data_present_flag */
902         hevc_parse_scaling_list_data( bits );
903     lsmash_bits_get( bits, 1 );             /* amp_enabled_flag */
904     lsmash_bits_get( bits, 1 );             /* sample_adaptive_offset_enabled_flag */
905     if( lsmash_bits_get( bits, 1 ) )        /* pcm_enabled_flag */
906     {
907         lsmash_bits_get( bits, 4 );         /* pcm_sample_bit_depth_luma_minus1 */
908         lsmash_bits_get( bits, 4 );         /* pcm_sample_bit_depth_chroma_minus1 */
909         nalu_get_exp_golomb_ue( bits );     /* log2_min_pcm_luma_coding_block_size_minus3 */
910         nalu_get_exp_golomb_ue( bits );     /* log2_diff_max_min_pcm_luma_coding_block_size */
911         lsmash_bits_get( bits, 1 );         /* pcm_loop_filter_disabled_flag */
912     }
913     sps->num_short_term_ref_pic_sets = nalu_get_exp_golomb_ue( bits );
914     for( int i = 0; i < sps->num_short_term_ref_pic_sets; i++ )
915         if( (err = hevc_short_term_ref_pic_set( bits, sps, i )) < 0 )
916             return err;
917     sps->long_term_ref_pics_present_flag = lsmash_bits_get( bits, 1 );
918     if( sps->long_term_ref_pics_present_flag )
919     {
920         sps->num_long_term_ref_pics_sps = nalu_get_exp_golomb_ue( bits );
921         for( int i = 0; i < sps->num_long_term_ref_pics_sps; i++ )
922         {
923             lsmash_bits_get( bits, sps->log2_max_pic_order_cnt_lsb );   /* lt_ref_pic_poc_lsb_sps      [i] */
924             lsmash_bits_get( bits, 1 );                                 /* used_by_curr_pic_lt_sps_flag[i] */
925         }
926     }
927     sps->temporal_mvp_enabled_flag = lsmash_bits_get( bits, 1 );
928     lsmash_bits_get( bits, 1 );                     /* strong_intra_smoothing_enabled_flag */
929     sps->vui.present = lsmash_bits_get( bits, 1 );  /* vui_parameters_present_flag */
930     if( sps->vui.present )
931     {
932         /* vui_parameters() */
933         if( lsmash_bits_get( bits, 1 ) )    /* aspect_ratio_info_present_flag */
934         {
935             uint8_t aspect_ratio_idc = lsmash_bits_get( bits, 8 );
936             if( aspect_ratio_idc == 255 )
937             {
938                 /* EXTENDED_SAR */
939                 sps->vui.sar_width  = lsmash_bits_get( bits, 16 );
940                 sps->vui.sar_height = lsmash_bits_get( bits, 16 );
941             }
942             else
943             {
944                 static const struct
945                 {
946                     uint16_t sar_width;
947                     uint16_t sar_height;
948                 } pre_defined_sar[] =
949                     {
950                         {  0,  0 }, {  1,  1 }, { 12, 11 }, {  10, 11 }, { 16, 11 },
951                         { 40, 33 }, { 24, 11 }, { 20, 11 }, {  32, 11 }, { 80, 33 },
952                         { 18, 11 }, { 15, 11 }, { 64, 33 }, { 160, 99 }, {  4,  3 },
953                         {  3,  2 }, {  2,  1 }
954                     };
955                 if( aspect_ratio_idc < (sizeof(pre_defined_sar) / sizeof(pre_defined_sar[0])) )
956                 {
957                     sps->vui.sar_width  = pre_defined_sar[ aspect_ratio_idc ].sar_width;
958                     sps->vui.sar_height = pre_defined_sar[ aspect_ratio_idc ].sar_height;
959                 }
960                 else
961                 {
962                     /* Behavior when unknown aspect_ratio_idc is detected is not specified in the specification. */
963                     sps->vui.sar_width  = 0;
964                     sps->vui.sar_height = 0;
965                 }
966             }
967         }
968         else
969         {
970             sps->vui.sar_width  = 0;
971             sps->vui.sar_height = 0;
972         }
973         if( lsmash_bits_get( bits, 1 ) )    /* overscan_info_present_flag */
974             lsmash_bits_get( bits, 1 );     /* overscan_appropriate_flag */
975         if( lsmash_bits_get( bits, 1 ) )    /* video_signal_type_present_flag */
976         {
977             lsmash_bits_get( bits, 3 );     /* video_format */
978             sps->vui.video_full_range_flag           = lsmash_bits_get( bits, 1 );
979             sps->vui.colour_description_present_flag = lsmash_bits_get( bits, 1 );
980             if( sps->vui.colour_description_present_flag )
981             {
982                 sps->vui.colour_primaries         = lsmash_bits_get( bits, 8 );
983                 sps->vui.transfer_characteristics = lsmash_bits_get( bits, 8 );
984                 sps->vui.matrix_coeffs            = lsmash_bits_get( bits, 8 );
985             }
986             else
987             {
988                 sps->vui.colour_primaries         = 2;
989                 sps->vui.transfer_characteristics = 2;
990                 sps->vui.matrix_coeffs            = 2;
991             }
992         }
993         if( lsmash_bits_get( bits, 1 ) )    /* chroma_loc_info_present_flag */
994         {
995             nalu_get_exp_golomb_ue( bits ); /* chroma_sample_loc_type_top_field */
996             nalu_get_exp_golomb_ue( bits ); /* chroma_sample_loc_type_bottom_field */
997         }
998         lsmash_bits_get( bits, 1 );         /* neutral_chroma_indication_flag */
999         sps->vui.field_seq_flag                = lsmash_bits_get( bits, 1 );
1000         sps->vui.frame_field_info_present_flag = lsmash_bits_get( bits, 1 );
1001         if( sps->vui.field_seq_flag )
1002             /* cropped_height indicates in a frame. */
1003             sps->cropped_height *= 2;
1004         if( lsmash_bits_get( bits, 1 ) )    /* default_display_window_flag */
1005         {
1006             /* default display window
1007              *   A rectangular region for display specified by these values is not considered
1008              *   as cropped visual presentation size which decoder delivers.
1009              *   Maybe, these values shall be indicated by the clean aperture on container level. */
1010             sps->vui.def_disp_win_offset.left   = (lsmash_rational_u32_t){ nalu_get_exp_golomb_ue( bits ) * SubWidthC [ sps->chroma_format_idc ], 1 };
1011             sps->vui.def_disp_win_offset.right  = (lsmash_rational_u32_t){ nalu_get_exp_golomb_ue( bits ) * SubWidthC [ sps->chroma_format_idc ], 1 };
1012             sps->vui.def_disp_win_offset.top    = (lsmash_rational_u32_t){ nalu_get_exp_golomb_ue( bits ) * SubHeightC[ sps->chroma_format_idc ], 1 };
1013             sps->vui.def_disp_win_offset.bottom = (lsmash_rational_u32_t){ nalu_get_exp_golomb_ue( bits ) * SubHeightC[ sps->chroma_format_idc ], 1 };
1014         }
1015         if( lsmash_bits_get( bits, 1 ) )    /* vui_timing_info_present_flag */
1016         {
1017             sps->vui.num_units_in_tick = lsmash_bits_get( bits, 32 );
1018             sps->vui.time_scale        = lsmash_bits_get( bits, 32 );
1019             if( lsmash_bits_get( bits, 1 ) )    /* vui_poc_proportional_to_timing_flag */
1020                 nalu_get_exp_golomb_ue( bits ); /* vui_num_ticks_poc_diff_one_minus1 */
1021             if( lsmash_bits_get( bits, 1 ) )    /* vui_hrd_parameters_present_flag */
1022                 hevc_parse_hrd_parameters( bits, &sps->vui.hrd, 1, sps->max_sub_layers_minus1 );
1023         }
1024         else
1025         {
1026             sps->vui.num_units_in_tick = 1;     /* arbitrary */
1027             sps->vui.time_scale        = 25;    /* arbitrary */
1028         }
1029         if( lsmash_bits_get( bits, 1 ) )    /* bitstream_restriction_flag */
1030         {
1031             lsmash_bits_get( bits, 1 );     /* tiles_fixed_structure_flag */
1032             lsmash_bits_get( bits, 1 );     /* motion_vectors_over_pic_boundaries_flag */
1033             lsmash_bits_get( bits, 1 );     /* restricted_ref_pic_lists_flag */
1034             sps->vui.min_spatial_segmentation_idc = nalu_get_exp_golomb_ue( bits );
1035             nalu_get_exp_golomb_ue( bits ); /* max_bytes_per_pic_denom */
1036             nalu_get_exp_golomb_ue( bits ); /* max_bits_per_min_cu_denom */
1037             nalu_get_exp_golomb_ue( bits ); /* log2_max_mv_length_horizontal */
1038             nalu_get_exp_golomb_ue( bits ); /* log2_max_mv_length_vertical */
1039         }
1040         else
1041             sps->vui.min_spatial_segmentation_idc = 0;
1042     }
1043     else
1044     {
1045         sps->vui.sar_width                     = 0;
1046         sps->vui.sar_height                    = 0;
1047         sps->vui.colour_primaries              = 2;
1048         sps->vui.transfer_characteristics      = 2;
1049         sps->vui.matrix_coeffs                 = 2;
1050         sps->vui.field_seq_flag                = 0;
1051         sps->vui.frame_field_info_present_flag = sps->ptl.general.progressive_source_flag
1052                                               && sps->ptl.general.interlaced_source_flag;
1053         sps->vui.num_units_in_tick             = 1;     /* arbitrary */
1054         sps->vui.time_scale                    = 25;    /* arbitrary */
1055         sps->vui.min_spatial_segmentation_idc  = 0;
1056     }
1057     return bits->bs->error ? LSMASH_ERR_NAMELESS : 0;
1058 }
1059 
hevc_parse_sps(hevc_info_t * info,uint8_t * rbsp_buffer,uint8_t * ebsp,uint64_t ebsp_size)1060 int hevc_parse_sps
1061 (
1062     hevc_info_t *info,
1063     uint8_t     *rbsp_buffer,
1064     uint8_t     *ebsp,
1065     uint64_t     ebsp_size
1066 )
1067 {
1068     lsmash_bits_t *bits = info->bits;
1069     hevc_sps_t *sps;
1070     {
1071         /* Parse SPS minimally for configuration records. */
1072         hevc_sps_t min_sps;
1073         int err = hevc_parse_sps_minimally( bits, &min_sps, rbsp_buffer, ebsp, ebsp_size );
1074         if( err < 0 )
1075             return err;
1076         sps = hevc_get_sps( info->sps_list, min_sps.seq_parameter_set_id );
1077         if( !sps )
1078             return LSMASH_ERR_NAMELESS;
1079         *sps = min_sps;
1080     }
1081     /* Skip SPS extension. */
1082     lsmash_bits_empty( bits );
1083     if( bits->bs->error )
1084         return LSMASH_ERR_NAMELESS;
1085     sps->present = 1;
1086     info->sps = *sps;
1087     hevc_activate_vps( info, info->sps.video_parameter_set_id );
1088     return 0;
1089 }
1090 
hevc_allocate_tile_sizes(hevc_pps_t * pps,uint32_t num_tile_columns,uint32_t num_tile_rows)1091 static int hevc_allocate_tile_sizes
1092 (
1093     hevc_pps_t *pps,
1094     uint32_t    num_tile_columns,
1095     uint32_t    num_tile_rows
1096 )
1097 {
1098     /* Allocate columns and rows of tiles. */
1099     size_t col_alloc_size = 2 * num_tile_columns * sizeof(uint32_t);
1100     if( col_alloc_size > pps->col_alloc_size )
1101     {
1102         void *temp = lsmash_realloc( pps->colWidth, col_alloc_size );
1103         if( !temp )
1104             return LSMASH_ERR_MEMORY_ALLOC;
1105         pps->col_alloc_size = col_alloc_size;
1106         pps->colWidth       = temp;
1107     }
1108     size_t row_alloc_size = 2 * num_tile_rows * sizeof(uint32_t);
1109     if( row_alloc_size > pps->row_alloc_size )
1110     {
1111         void *temp = lsmash_realloc( pps->rowHeight, row_alloc_size );
1112         if( !temp )
1113             return LSMASH_ERR_MEMORY_ALLOC;
1114         pps->row_alloc_size = row_alloc_size;
1115         pps->rowHeight      = temp;
1116     }
1117     pps->colBd = pps->colWidth  + num_tile_columns;
1118     pps->rowBd = pps->rowHeight + num_tile_rows;
1119     return 0;
1120 }
1121 
hevc_parse_pps_minimally(lsmash_bits_t * bits,hevc_pps_t * pps,uint8_t * rbsp_buffer,uint8_t * ebsp,uint64_t ebsp_size)1122 static int hevc_parse_pps_minimally
1123 (
1124     lsmash_bits_t *bits,
1125     hevc_pps_t    *pps,
1126     uint8_t       *rbsp_buffer,
1127     uint8_t       *ebsp,
1128     uint64_t       ebsp_size
1129 )
1130 {
1131     int err = nalu_import_rbsp_from_ebsp( bits, rbsp_buffer, ebsp, ebsp_size );
1132     if( err < 0 )
1133         return err;
1134     memset( pps, 0, SIZEOF_PPS_EXCLUDING_HEAP );
1135     pps->pic_parameter_set_id                  = nalu_get_exp_golomb_ue( bits );
1136     pps->seq_parameter_set_id                  = nalu_get_exp_golomb_ue( bits );
1137     pps->dependent_slice_segments_enabled_flag = lsmash_bits_get( bits, 1 );
1138     pps->output_flag_present_flag              = lsmash_bits_get( bits, 1 );
1139     pps->num_extra_slice_header_bits           = lsmash_bits_get( bits, 3 );
1140     lsmash_bits_get( bits, 1 );         /* sign_data_hiding_enabled_flag */
1141     lsmash_bits_get( bits, 1 );         /* cabac_init_present_flag */
1142     nalu_get_exp_golomb_ue( bits );     /* num_ref_idx_l0_default_active_minus1 */
1143     nalu_get_exp_golomb_ue( bits );     /* num_ref_idx_l1_default_active_minus1 */
1144     nalu_get_exp_golomb_se( bits );     /* init_qp_minus26 */
1145     lsmash_bits_get( bits, 1 );         /* constrained_intra_pred_flag */
1146     lsmash_bits_get( bits, 1 );         /* transform_skip_enabled_flag */
1147     if( lsmash_bits_get( bits, 1 ) )    /* cu_qp_delta_enabled_flag */
1148         nalu_get_exp_golomb_ue( bits ); /* diff_cu_qp_delta_depth */
1149     nalu_get_exp_golomb_se( bits );     /* cb_qp_offset */
1150     nalu_get_exp_golomb_se( bits );     /* cr_qp_offset */
1151     lsmash_bits_get( bits, 1 );         /* slice_chroma_qp_offsets_present_flag */
1152     lsmash_bits_get( bits, 1 );         /* weighted_pred_flag */
1153     lsmash_bits_get( bits, 1 );         /* weighted_bipred_flag */
1154     lsmash_bits_get( bits, 1 )          /* transquant_bypass_enabled_flag */;
1155     pps->tiles_enabled_flag               = lsmash_bits_get( bits, 1 );
1156     pps->entropy_coding_sync_enabled_flag = lsmash_bits_get( bits, 1 );
1157     return bits->bs->error ? LSMASH_ERR_NAMELESS : 0;
1158 }
1159 
hevc_parse_pps(hevc_info_t * info,uint8_t * rbsp_buffer,uint8_t * ebsp,uint64_t ebsp_size)1160 int hevc_parse_pps
1161 (
1162     hevc_info_t *info,
1163     uint8_t     *rbsp_buffer,
1164     uint8_t     *ebsp,
1165     uint64_t     ebsp_size
1166 )
1167 {
1168     int err;
1169     lsmash_bits_t *bits = info->bits;
1170     hevc_pps_t *pps;
1171     {
1172         /* Parse PPS minimally for configuration records. */
1173         hevc_pps_t min_pps;
1174         if( (err = hevc_parse_pps_minimally( bits, &min_pps, rbsp_buffer, ebsp, ebsp_size )) < 0 )
1175             return err;
1176         pps = hevc_get_pps( info->pps_list, min_pps.pic_parameter_set_id );
1177         if( !pps )
1178             return LSMASH_ERR_NAMELESS;
1179         memcpy( pps, &min_pps, SIZEOF_PPS_EXCLUDING_HEAP );
1180     }
1181     hevc_sps_t temp_sps = info->sps;
1182     if( (err = hevc_activate_sps( info, pps->seq_parameter_set_id )) < 0 )
1183         return err;
1184     hevc_sps_t *sps = &info->sps;
1185     if( pps->tiles_enabled_flag )
1186     {
1187         pps->num_tile_columns_minus1 = nalu_get_exp_golomb_ue( bits );
1188         pps->num_tile_rows_minus1    = nalu_get_exp_golomb_ue( bits );
1189         if( pps->num_tile_columns_minus1 >= sps->PicWidthInCtbsY
1190          || pps->num_tile_rows_minus1    >= sps->PicHeightInCtbsY )
1191         {
1192             err = LSMASH_ERR_INVALID_DATA;
1193             goto fail;
1194         }
1195         if( (err = hevc_allocate_tile_sizes( pps, pps->num_tile_columns_minus1 + 1, pps->num_tile_rows_minus1 + 1 )) < 0 )
1196             goto fail;
1197         if( lsmash_bits_get( bits, 1 ) )        /* uniform_spacing_flag */
1198         {
1199             for( int i = 0; i <= pps->num_tile_columns_minus1; i++ )
1200                 pps->colWidth[i] = ((i + 1) * sps->PicWidthInCtbsY) / (pps->num_tile_columns_minus1 + 1)
1201                                  - ( i      * sps->PicWidthInCtbsY) / (pps->num_tile_columns_minus1 + 1);
1202             for( int j = 0; j <= pps->num_tile_rows_minus1; j++ )
1203                 pps->rowHeight[j] = ((j + 1) * sps->PicHeightInCtbsY) / (pps->num_tile_rows_minus1 + 1)
1204                                   - ( j      * sps->PicHeightInCtbsY) / (pps->num_tile_rows_minus1 + 1);
1205         }
1206         else
1207         {
1208             pps->colWidth[ pps->num_tile_columns_minus1 ] = sps->PicWidthInCtbsY;
1209             for( uint64_t i = 0; i < pps->num_tile_columns_minus1; i++ )
1210             {
1211                 pps->colWidth[i] = nalu_get_exp_golomb_ue( bits ) + 1;      /* column_width_minus1[i] */
1212                 pps->colWidth[ pps->num_tile_columns_minus1 ] -= pps->colWidth[i];
1213             }
1214             pps->rowHeight[ pps->num_tile_rows_minus1 ] = sps->PicHeightInCtbsY;
1215             for( uint64_t j = 0; j < pps->num_tile_rows_minus1; j++ )
1216             {
1217                 pps->rowHeight[j] = nalu_get_exp_golomb_ue( bits ) + 1;     /* row_height_minus1  [j] */
1218                 pps->rowHeight[ pps->num_tile_rows_minus1 ] -= pps->rowHeight[j];
1219             }
1220         }
1221         pps->colBd[0] = 0;
1222         for( uint64_t i = 0; i < pps->num_tile_columns_minus1; i++ )
1223             pps->colBd[i + 1] = pps->colBd[i] + pps->colWidth[i];
1224         pps->rowBd[0] = 0;
1225         for( uint64_t j = 0; j < pps->num_tile_rows_minus1; j++ )
1226             pps->rowBd[j + 1] = pps->rowBd[j] + pps->rowHeight[j];
1227         lsmash_bits_get( bits, 1 );             /* loop_filter_across_tiles_enabled_flag */
1228     }
1229     else
1230     {
1231         pps->num_tile_columns_minus1 = 0;
1232         pps->num_tile_rows_minus1    = 0;
1233         if( (err = hevc_allocate_tile_sizes( pps, 1, 1 )) < 0 )
1234             goto fail;
1235         pps->colWidth [0] = sps->PicWidthInCtbsY;
1236         pps->rowHeight[0] = sps->PicHeightInCtbsY;
1237         pps->colBd    [0] = 0;
1238         pps->rowBd    [0] = 0;
1239     }
1240     /* */
1241     /* Skip PPS extension. */
1242     lsmash_bits_empty( bits );
1243     if( bits->bs->error )
1244         goto fail;
1245     pps->present = 1;
1246     info->pps = *pps;
1247     hevc_activate_vps( info, info->sps.video_parameter_set_id );
1248     return 0;
1249 fail:
1250     /* Revert SPS. */
1251     info->sps = temp_sps;
1252     return err;
1253 }
1254 
hevc_parse_sei(lsmash_bits_t * bits,hevc_vps_t * vps,hevc_sps_t * sps,hevc_sei_t * sei,hevc_nalu_header_t * nuh,uint8_t * rbsp_buffer,uint8_t * ebsp,uint64_t ebsp_size)1255 int hevc_parse_sei
1256 (
1257     lsmash_bits_t      *bits,
1258     hevc_vps_t         *vps,
1259     hevc_sps_t         *sps,
1260     hevc_sei_t         *sei,
1261     hevc_nalu_header_t *nuh,
1262     uint8_t            *rbsp_buffer,
1263     uint8_t            *ebsp,
1264     uint64_t            ebsp_size
1265 )
1266 {
1267     int err = nalu_import_rbsp_from_ebsp( bits, rbsp_buffer, ebsp, ebsp_size );
1268     if( err < 0 )
1269         return err;
1270     uint8_t *rbsp_start = rbsp_buffer;
1271     uint64_t rbsp_pos = 0;
1272     do
1273     {
1274         /* sei_message() */
1275         uint32_t payloadType = 0;
1276         for( uint8_t temp = lsmash_bits_get( bits, 8 ); ; temp = lsmash_bits_get( bits, 8 ) )
1277         {
1278             /* 0xff     : ff_byte
1279              * otherwise: last_payload_type_byte */
1280             payloadType += temp;
1281             ++rbsp_pos;
1282             if( temp != 0xff )
1283                 break;
1284         }
1285         uint32_t payloadSize = 0;
1286         for( uint8_t temp = lsmash_bits_get( bits, 8 ); ; temp = lsmash_bits_get( bits, 8 ) )
1287         {
1288             /* 0xff     : ff_byte
1289              * otherwise: last_payload_size_byte */
1290             payloadSize += temp;
1291             ++rbsp_pos;
1292             if( temp != 0xff )
1293                 break;
1294         }
1295         if( nuh->nal_unit_type == HEVC_NALU_TYPE_PREFIX_SEI )
1296         {
1297             if( payloadType == 1 )
1298             {
1299                 /* pic_timing */
1300                 hevc_hrd_t *hrd = sps ? &sps->vui.hrd : vps ? &vps->hrd[0] : NULL;
1301                 if( !hrd )
1302                     goto skip_sei_message;  /* Any active VPS or SPS is not found. */
1303                 sei->pic_timing.present = 1;
1304                 if( (sps && sps->vui.frame_field_info_present_flag) || vps->frame_field_info_present_flag )
1305                 {
1306                     sei->pic_timing.pic_struct = lsmash_bits_get( bits, 4 );
1307                     lsmash_bits_get( bits, 2 );     /* source_scan_type */
1308                     lsmash_bits_get( bits, 1 );     /* duplicate_flag */
1309                 }
1310                 if( hrd->CpbDpbDelaysPresentFlag )
1311                 {
1312                     lsmash_bits_get( bits, hrd->au_cpb_removal_delay_length );      /* au_cpb_removal_delay_minus1 */
1313                     lsmash_bits_get( bits, hrd->dpb_output_delay_length );          /* pic_dpb_output_delay */
1314                     if( hrd->sub_pic_hrd_params_present_flag )
1315                     {
1316                         lsmash_bits_get( bits, hrd->dpb_output_delay_du_length );   /* pic_dpb_output_du_delay */
1317                         if( hrd->sub_pic_cpb_params_in_pic_timing_sei_flag )
1318                         {
1319                             uint64_t num_decoding_units_minus1 = nalu_get_exp_golomb_ue( bits );
1320                             int du_common_cpb_removal_delay_flag = lsmash_bits_get( bits, 1 );
1321                             if( du_common_cpb_removal_delay_flag )
1322                                 /* du_common_cpb_removal_delay_increment_minus1 */
1323                                 lsmash_bits_get( bits, hrd->du_cpb_removal_delay_increment_length );
1324                             for( uint64_t i = 0; i <= num_decoding_units_minus1; i++ )
1325                             {
1326                                 nalu_get_exp_golomb_ue( bits );         /* num_nalus_in_du_minus1 */
1327                                 if( !du_common_cpb_removal_delay_flag && i < num_decoding_units_minus1 )
1328                                     nalu_get_exp_golomb_ue( bits );     /* du_cpb_removal_delay_increment_minus1 */
1329                             }
1330                         }
1331                     }
1332                 }
1333             }
1334             else if( payloadType == 3 )
1335             {
1336                 /* filler_payload
1337                  * FIXME: remove if array_completeness equal to 1. */
1338                 return LSMASH_ERR_PATCH_WELCOME;
1339             }
1340             else if( payloadType == 6 )
1341             {
1342                 /* recovery_point */
1343                 sei->recovery_point.present          = 1;
1344                 sei->recovery_point.recovery_poc_cnt = nalu_get_exp_golomb_se( bits );
1345                 lsmash_bits_get( bits, 1 );     /* exact_match_flag */
1346                 sei->recovery_point.broken_link_flag = lsmash_bits_get( bits, 1 );
1347             }
1348             else
1349                 goto skip_sei_message;
1350         }
1351         else if( nuh->nal_unit_type == HEVC_NALU_TYPE_SUFFIX_SEI )
1352         {
1353             if( payloadType == 3 )
1354             {
1355                 /* filler_payload
1356                  * FIXME: remove if array_completeness equal to 1. */
1357                 return LSMASH_ERR_PATCH_WELCOME;
1358             }
1359             else
1360                 goto skip_sei_message;
1361         }
1362         else
1363         {
1364 skip_sei_message:
1365             lsmash_bits_get( bits, payloadSize * 8 );
1366         }
1367         lsmash_bits_get_align( bits );
1368         rbsp_pos += payloadSize;
1369     } while( *(rbsp_start + rbsp_pos) != 0x80 );        /* All SEI messages are byte aligned at their end.
1370                                                          * Therefore, 0x80 shall be rbsp_trailing_bits(). */
1371     lsmash_bits_empty( bits );
1372     return bits->bs->error ? LSMASH_ERR_NAMELESS : 0;
1373 }
1374 
hevc_parse_slice_segment_header(hevc_info_t * info,hevc_nalu_header_t * nuh,uint8_t * rbsp_buffer,uint8_t * ebsp,uint64_t ebsp_size)1375 int hevc_parse_slice_segment_header
1376 (
1377     hevc_info_t        *info,
1378     hevc_nalu_header_t *nuh,
1379     uint8_t            *rbsp_buffer,
1380     uint8_t            *ebsp,
1381     uint64_t            ebsp_size
1382 )
1383 {
1384     lsmash_bits_t *bits = info->bits;
1385     int err = nalu_import_rbsp_from_ebsp( bits, rbsp_buffer, ebsp, LSMASH_MIN( ebsp_size, 50 ) );
1386     if( err < 0 )
1387         return err;
1388     hevc_slice_info_t *slice = &info->slice;
1389     memset( slice, 0, sizeof(hevc_slice_info_t) );
1390     slice->nalu_type  = nuh->nal_unit_type;
1391     slice->TemporalId = nuh->TemporalId;
1392     slice->first_slice_segment_in_pic_flag = lsmash_bits_get( bits, 1 );
1393     if( nuh->nal_unit_type >= HEVC_NALU_TYPE_BLA_W_LP
1394      && nuh->nal_unit_type <= HEVC_NALU_TYPE_RSV_IRAP_VCL23 )
1395         lsmash_bits_get( bits, 1 );     /* no_output_of_prior_pics_flag */
1396     slice->pic_parameter_set_id = nalu_get_exp_golomb_ue( bits );
1397     /* Get PPS by slice_pic_parameter_set_id. */
1398     hevc_pps_t *pps = hevc_get_pps( info->pps_list, slice->pic_parameter_set_id );
1399     if( !pps )
1400         return LSMASH_ERR_NAMELESS;
1401     /* Get SPS by pps_seq_parameter_set_id. */
1402     hevc_sps_t *sps = hevc_get_sps( info->sps_list, pps->seq_parameter_set_id );
1403     if( !sps )
1404         return LSMASH_ERR_NAMELESS;
1405     slice->video_parameter_set_id = sps->video_parameter_set_id;
1406     slice->seq_parameter_set_id   = pps->seq_parameter_set_id;
1407     if( !slice->first_slice_segment_in_pic_flag )
1408     {
1409         slice->dependent_slice_segment_flag = pps->dependent_slice_segments_enabled_flag ? lsmash_bits_get( bits, 1 ) : 0;
1410         slice->segment_address              = lsmash_bits_get( bits, lsmash_ceil_log2( sps->PicSizeInCtbsY ) );
1411     }
1412     else
1413     {
1414         slice->dependent_slice_segment_flag = 0;
1415         slice->segment_address              = 0;
1416     }
1417     if( !slice->dependent_slice_segment_flag )
1418     {
1419         /* independent slice segment
1420          * The values of the slice segment header of dependent slice segment are inferred from the values
1421          * for the preceding independent slice segment in decoding order, if some of the values are not present. */
1422         for( int i = 0; i < pps->num_extra_slice_header_bits; i++ )
1423             lsmash_bits_get( bits, 1 );         /* slice_reserved_flag[i] */
1424         slice->type = nalu_get_exp_golomb_ue( bits );
1425         if( pps->output_flag_present_flag )
1426             lsmash_bits_get( bits, 1 );         /* pic_output_flag */
1427         if( sps->separate_colour_plane_flag )
1428             lsmash_bits_get( bits, 1 );         /* colour_plane_id */
1429         if( nuh->nal_unit_type != HEVC_NALU_TYPE_IDR_W_RADL
1430          && nuh->nal_unit_type != HEVC_NALU_TYPE_IDR_N_LP )
1431         {
1432             slice->pic_order_cnt_lsb = lsmash_bits_get( bits, sps->log2_max_pic_order_cnt_lsb );
1433             if( !lsmash_bits_get( bits, 1 ) )   /* short_term_ref_pic_set_sps_flag */
1434             {
1435                 if( (err = hevc_short_term_ref_pic_set( bits, sps, sps->num_short_term_ref_pic_sets )) < 0 )
1436                     return err;
1437             }
1438             else
1439             {
1440                 int length = lsmash_ceil_log2( sps->num_short_term_ref_pic_sets );
1441                 if( length > 0 )
1442                     lsmash_bits_get( bits, length );                                /* short_term_ref_pic_set_idx */
1443             }
1444             if( sps->long_term_ref_pics_present_flag )
1445             {
1446                 uint64_t num_long_term_sps  = sps->num_long_term_ref_pics_sps > 0 ? nalu_get_exp_golomb_ue( bits ) : 0;
1447                 uint64_t num_long_term_pics = nalu_get_exp_golomb_ue( bits );
1448                 for( uint64_t i = 0; i < num_long_term_sps + num_long_term_pics; i++ )
1449                 {
1450                     if( i < num_long_term_sps )
1451                     {
1452                         int length = lsmash_ceil_log2( sps->num_long_term_ref_pics_sps );
1453                         if( length > 0 )
1454                             lsmash_bits_get( bits, length );                        /* lt_idx_sps[i] */
1455                     }
1456                     else
1457                     {
1458                         lsmash_bits_get( bits, sps->log2_max_pic_order_cnt_lsb );   /* poc_lsb_lt              [i] */
1459                         lsmash_bits_get( bits, 1 );                                 /* used_by_curr_pic_lt_flag[i] */
1460                     }
1461                     if( lsmash_bits_get( bits, 1 ) )                                /* delta_poc_msb_present_flag[i] */
1462                         nalu_get_exp_golomb_ue( bits );                             /* delta_poc_msb_cycle_lt    [i] */
1463                 }
1464             }
1465             if( sps->temporal_mvp_enabled_flag )
1466                 lsmash_bits_get( bits, 1 );                                         /* slice_temporal_mvp_enabled_flag */
1467         }
1468         else
1469             /* For IDR-pictures, slice_pic_order_cnt_lsb is inferred to be 0. */
1470             slice->pic_order_cnt_lsb = 0;
1471     }
1472     lsmash_bits_empty( bits );
1473     if( bits->bs->error )
1474         return LSMASH_ERR_NAMELESS;
1475     info->sps = *sps;
1476     info->pps = *pps;
1477     return 0;
1478 }
1479 
hevc_get_vps_id(uint8_t * ps_ebsp,uint32_t ps_ebsp_length,uint8_t * ps_id)1480 static int hevc_get_vps_id
1481 (
1482     uint8_t *ps_ebsp,
1483     uint32_t ps_ebsp_length,
1484     uint8_t *ps_id
1485 )
1486 {
1487     /* the number of bits of vps_id = 4
1488      * (4 - 1) / 8 + 1 = 1 bytes */
1489     *ps_id = (*ps_ebsp >> 4) & 0x0F;    /* vps_video_parameter_set_id */
1490     return 0;
1491 }
1492 
hevc_get_sps_id(uint8_t * ps_ebsp,uint32_t ps_ebsp_length,uint8_t * ps_id)1493 static int hevc_get_sps_id
1494 (
1495     uint8_t *ps_ebsp,
1496     uint32_t ps_ebsp_length,
1497     uint8_t *ps_id
1498 )
1499 {
1500     /* the maximum number of bits of sps_id = 9: 0b00001XXXX
1501      * (8 + 688 + 9 - 1) / 8 + 1 = 89 bytes
1502      * Here more additional bytes because there might be emulation_prevention_three_byte(s). */
1503     lsmash_bits_t bits = { 0 };
1504     lsmash_bs_t   bs   = { 0 };
1505     uint8_t rbsp_buffer[128];
1506     uint8_t buffer     [128];
1507     bs.buffer.data  = buffer;
1508     bs.buffer.alloc = 128;
1509     lsmash_bits_init( &bits, &bs );
1510     int err = nalu_import_rbsp_from_ebsp( &bits, rbsp_buffer, ps_ebsp, LSMASH_MIN( ps_ebsp_length, 128 ) );
1511     if( err < 0 )
1512         return err;
1513     /* Skip sps_video_parameter_set_id and sps_temporal_id_nesting_flag. */
1514     uint8_t sps_max_sub_layers_minus1 = (lsmash_bits_get( &bits, 8 ) >> 1) & 0x07;
1515     /* profile_tier_level() costs at most 688 bits. */
1516     hevc_ptl_t sps_ptl;
1517     hevc_parse_profile_tier_level( &bits, &sps_ptl, sps_max_sub_layers_minus1 );
1518     uint64_t sps_seq_parameter_set_id = nalu_get_exp_golomb_ue( &bits );
1519     if( sps_seq_parameter_set_id > HEVC_MAX_SPS_ID )
1520         return LSMASH_ERR_INVALID_DATA;
1521     *ps_id = sps_seq_parameter_set_id;
1522     return bs.error ? LSMASH_ERR_NAMELESS : 0;
1523 }
1524 
hevc_get_pps_id(uint8_t * ps_ebsp,uint32_t ps_ebsp_length,uint8_t * ps_id)1525 static int hevc_get_pps_id
1526 (
1527     uint8_t *ps_ebsp,
1528     uint32_t ps_ebsp_length,
1529     uint8_t *ps_id
1530 )
1531 {
1532     /* the maximum number of bits of pps_id = 13: 0b0000001XXXXXX
1533      * (13 - 1) / 8 + 1 = 2 bytes
1534      * Why +1? Because there might be an emulation_prevention_three_byte. */
1535     lsmash_bits_t bits = { 0 };
1536     lsmash_bs_t   bs   = { 0 };
1537     uint8_t rbsp_buffer[3];
1538     uint8_t buffer     [3];
1539     bs.buffer.data  = buffer;
1540     bs.buffer.alloc = 3;
1541     lsmash_bits_init( &bits, &bs );
1542     int err = nalu_import_rbsp_from_ebsp( &bits, rbsp_buffer, ps_ebsp, LSMASH_MIN( ps_ebsp_length, 3 ) );
1543     if( err < 0 )
1544         return err;
1545     uint64_t pic_parameter_set_id = nalu_get_exp_golomb_ue( &bits );
1546     if( pic_parameter_set_id > HEVC_MAX_PPS_ID )
1547         return LSMASH_ERR_INVALID_DATA;
1548     *ps_id = pic_parameter_set_id;
1549     return bs.error ? LSMASH_ERR_NAMELESS : 0;
1550 }
1551 
hevc_get_ps_id(uint8_t * ps_ebsp,uint32_t ps_ebsp_length,uint8_t * ps_id,lsmash_hevc_dcr_nalu_type ps_type)1552 static inline int hevc_get_ps_id
1553 (
1554     uint8_t                  *ps_ebsp,
1555     uint32_t                  ps_ebsp_length,
1556     uint8_t                  *ps_id,
1557     lsmash_hevc_dcr_nalu_type ps_type
1558 )
1559 {
1560     int (*get_ps_id)( uint8_t *ps_ebsp, uint32_t ps_ebsp_length, uint8_t *ps_id )
1561         = ps_type == HEVC_DCR_NALU_TYPE_VPS ? hevc_get_vps_id
1562         : ps_type == HEVC_DCR_NALU_TYPE_SPS ? hevc_get_sps_id
1563         : ps_type == HEVC_DCR_NALU_TYPE_PPS ? hevc_get_pps_id
1564         :                                     NULL;
1565     return get_ps_id ? get_ps_id( ps_ebsp, ps_ebsp_length, ps_id ) : LSMASH_ERR_INVALID_DATA;
1566 }
1567 
hevc_get_parameter_set_array(lsmash_hevc_specific_parameters_t * param,lsmash_hevc_dcr_nalu_type ps_type)1568 static inline hevc_parameter_array_t *hevc_get_parameter_set_array
1569 (
1570     lsmash_hevc_specific_parameters_t *param,
1571     lsmash_hevc_dcr_nalu_type          ps_type
1572 )
1573 {
1574     if( !param->parameter_arrays )
1575         return NULL;
1576     if( ps_type >= HEVC_DCR_NALU_TYPE_NUM )
1577         return NULL;
1578     return &param->parameter_arrays->ps_array[ps_type];
1579 }
1580 
hevc_get_parameter_set_list(lsmash_hevc_specific_parameters_t * param,lsmash_hevc_dcr_nalu_type ps_type)1581 static inline lsmash_entry_list_t *hevc_get_parameter_set_list
1582 (
1583     lsmash_hevc_specific_parameters_t *param,
1584     lsmash_hevc_dcr_nalu_type          ps_type
1585 )
1586 {
1587     if( !param->parameter_arrays )
1588         return NULL;
1589     if( ps_type >= HEVC_DCR_NALU_TYPE_NUM )
1590         return NULL;
1591     return param->parameter_arrays->ps_array[ps_type].list;
1592 }
1593 
hevc_get_ps_entry_from_param(lsmash_hevc_specific_parameters_t * param,lsmash_hevc_dcr_nalu_type ps_type,uint8_t ps_id)1594 static lsmash_entry_t *hevc_get_ps_entry_from_param
1595 (
1596     lsmash_hevc_specific_parameters_t *param,
1597     lsmash_hevc_dcr_nalu_type          ps_type,
1598     uint8_t                            ps_id
1599 )
1600 {
1601     int (*get_ps_id)( uint8_t *ps_ebsp, uint32_t ps_ebsp_length, uint8_t *ps_id )
1602         = ps_type == HEVC_DCR_NALU_TYPE_VPS ? hevc_get_vps_id
1603         : ps_type == HEVC_DCR_NALU_TYPE_SPS ? hevc_get_sps_id
1604         : ps_type == HEVC_DCR_NALU_TYPE_PPS ? hevc_get_pps_id
1605         :                                     NULL;
1606     if( !get_ps_id )
1607         return NULL;
1608     lsmash_entry_list_t *list = hevc_get_parameter_set_list( param, ps_type );
1609     if( !list )
1610         return NULL;
1611     for( lsmash_entry_t *entry = list->head; entry; entry = entry->next )
1612     {
1613         isom_dcr_ps_entry_t *ps = (isom_dcr_ps_entry_t *)entry->data;
1614         if( !ps )
1615             return NULL;
1616         uint8_t param_ps_id;
1617         if( get_ps_id( ps->nalUnit       + HEVC_MIN_NALU_HEADER_LENGTH,
1618                        ps->nalUnitLength - HEVC_MIN_NALU_HEADER_LENGTH, &param_ps_id ) < 0 )
1619             return NULL;
1620         if( ps_id == param_ps_id )
1621             return entry;
1622     }
1623     return NULL;
1624 }
1625 
hevc_update_picture_type(hevc_picture_info_t * picture,hevc_slice_info_t * slice)1626 static inline void  hevc_update_picture_type
1627 (
1628     hevc_picture_info_t *picture,
1629     hevc_slice_info_t   *slice
1630 )
1631 {
1632     if( picture->type == HEVC_PICTURE_TYPE_I_P )
1633     {
1634         if( slice->type == HEVC_SLICE_TYPE_B )
1635             picture->type = HEVC_PICTURE_TYPE_I_P_B;
1636     }
1637     else if( picture->type == HEVC_PICTURE_TYPE_I )
1638     {
1639         if( slice->type == HEVC_SLICE_TYPE_P )
1640             picture->type = HEVC_PICTURE_TYPE_I_P;
1641         else if( slice->type == HEVC_SLICE_TYPE_B )
1642             picture->type = HEVC_PICTURE_TYPE_I_P_B;
1643     }
1644     else if( picture->type == HEVC_PICTURE_TYPE_NONE )
1645     {
1646         if( slice->type == HEVC_SLICE_TYPE_P )
1647             picture->type = HEVC_PICTURE_TYPE_I_P;
1648         else if( slice->type == HEVC_SLICE_TYPE_B )
1649             picture->type = HEVC_PICTURE_TYPE_I_P_B;
1650         else if( slice->type == HEVC_SLICE_TYPE_I )
1651             picture->type = HEVC_PICTURE_TYPE_I;
1652     }
1653 #if 0
1654     fprintf( stderr, "Picture type = %s\n", picture->type == HEVC_PICTURE_TYPE_I_P   ? "P"
1655                                           : picture->type == HEVC_PICTURE_TYPE_I_P_B ? "B"
1656                                           : picture->type == HEVC_PICTURE_TYPE_I     ? "I" );
1657 #endif
1658 }
1659 
1660 /* Shall be called at least once per picture. */
hevc_update_picture_info_for_slice(hevc_info_t * info,hevc_picture_info_t * picture,hevc_slice_info_t * slice)1661 void hevc_update_picture_info_for_slice
1662 (
1663     hevc_info_t         *info,
1664     hevc_picture_info_t *picture,
1665     hevc_slice_info_t   *slice
1666 )
1667 {
1668     assert( info );
1669     picture->has_primary |= !slice->dependent_slice_segment_flag;
1670     hevc_update_picture_type( picture, slice );
1671     /* Mark 'used' on active parameter sets. */
1672     uint8_t ps_id[3] = { slice->video_parameter_set_id, slice->seq_parameter_set_id, slice->pic_parameter_set_id };
1673     for( int i = 0; i < 3; i++ )
1674     {
1675         lsmash_hevc_dcr_nalu_type ps_type = (lsmash_hevc_dcr_nalu_type)i;
1676         lsmash_entry_t *entry = hevc_get_ps_entry_from_param( &info->hvcC_param, ps_type, ps_id[i] );
1677         if( entry && entry->data )
1678         {
1679             isom_dcr_ps_entry_t *ps = (isom_dcr_ps_entry_t *)entry->data;
1680             if( ps->unused )
1681                 lsmash_append_hevc_dcr_nalu( &info->hvcC_param, ps_type, ps->nalUnit, ps->nalUnitLength );
1682         }
1683     }
1684     /* Discard this slice info. */
1685     slice->present = 0;
1686 }
1687 
1688 /* Shall be called exactly once per picture. */
hevc_update_picture_info(hevc_info_t * info,hevc_picture_info_t * picture,hevc_slice_info_t * slice,hevc_sps_t * sps,hevc_sei_t * sei)1689 void hevc_update_picture_info
1690 (
1691     hevc_info_t         *info,
1692     hevc_picture_info_t *picture,
1693     hevc_slice_info_t   *slice,
1694     hevc_sps_t          *sps,
1695     hevc_sei_t          *sei
1696 )
1697 {
1698     picture->irap                 = slice->nalu_type >= HEVC_NALU_TYPE_BLA_W_LP    && slice->nalu_type <= HEVC_NALU_TYPE_CRA;
1699     picture->idr                  = slice->nalu_type == HEVC_NALU_TYPE_IDR_W_RADL  || slice->nalu_type == HEVC_NALU_TYPE_IDR_N_LP;
1700     picture->broken_link          = slice->nalu_type >= HEVC_NALU_TYPE_BLA_W_LP    && slice->nalu_type <= HEVC_NALU_TYPE_BLA_N_LP;
1701     picture->radl                 = slice->nalu_type == HEVC_NALU_TYPE_RADL_N      || slice->nalu_type == HEVC_NALU_TYPE_RADL_R;
1702     picture->rasl                 = slice->nalu_type == HEVC_NALU_TYPE_RASL_N      || slice->nalu_type == HEVC_NALU_TYPE_RASL_R;
1703     picture->sublayer_nonref      = slice->nalu_type <= HEVC_NALU_TYPE_RSV_VCL_R15 && ((slice->nalu_type & 0x01) == 0);
1704     picture->closed_rap           = slice->nalu_type >= HEVC_NALU_TYPE_BLA_W_RADL  && slice->nalu_type <= HEVC_NALU_TYPE_IDR_N_LP;
1705     picture->random_accessible    = picture->irap;
1706     picture->TemporalId           = slice->TemporalId;
1707     picture->pic_parameter_set_id = slice->pic_parameter_set_id;
1708     picture->poc_lsb              = slice->pic_order_cnt_lsb;
1709     hevc_update_picture_info_for_slice( info, picture, slice );
1710     picture->independent = (picture->type == HEVC_PICTURE_TYPE_I);
1711     picture->field_coded = sps->vui.field_seq_flag;
1712     if( sei->pic_timing.present )
1713     {
1714         if( sei->pic_timing.pic_struct < 13 )
1715         {
1716             static const uint8_t delta[13] = { 2, 1, 1, 2, 2, 3, 3, 4, 6, 1, 1, 1, 1 };
1717             picture->delta = delta[ sei->pic_timing.pic_struct ];
1718         }
1719         else
1720             /* Reserved values in the spec we refer to. */
1721             picture->delta = picture->field_coded ? 1 : 2;
1722         sei->pic_timing.present = 0;
1723     }
1724     else
1725         picture->delta = picture->field_coded ? 1 : 2;
1726     if( sei->recovery_point.present )
1727     {
1728         picture->random_accessible |= sei->recovery_point.present;
1729         picture->recovery_poc_cnt   = sei->recovery_point.recovery_poc_cnt;
1730         picture->broken_link       |= sei->recovery_point.broken_link_flag;
1731         sei->recovery_point.present = 0;
1732     }
1733     else
1734         picture->recovery_poc_cnt = 0;
1735 }
1736 
hevc_get_ctb_address_in_tile_scan(hevc_sps_t * sps,hevc_pps_t * pps,uint64_t segment_address,uint64_t * TileId)1737 static uint64_t hevc_get_ctb_address_in_tile_scan
1738 (
1739     hevc_sps_t *sps,
1740     hevc_pps_t *pps,
1741     uint64_t    segment_address,
1742     uint64_t   *TileId
1743 )
1744 {
1745     uint64_t tbX = segment_address % sps->PicWidthInCtbsY;
1746     uint64_t tbY = segment_address / sps->PicWidthInCtbsY;
1747     uint32_t tileX = pps->num_tile_columns_minus1;
1748     for( uint32_t i = 0; i <= pps->num_tile_columns_minus1; i++ )
1749         if( tbX >= pps->colBd[i] )
1750             tileX = i;
1751     uint32_t tileY = pps->num_tile_rows_minus1;
1752     for( uint32_t j = 0; j <= pps->num_tile_rows_minus1; j++ )
1753         if( tbY >= pps->rowBd[j] )
1754             tileY = j;
1755     uint64_t CtbAddrInTs = 0;
1756     for( uint32_t i = 0; i < tileX; i++ )
1757         CtbAddrInTs += pps->rowHeight[tileY] * pps->colWidth[i];
1758     for( uint32_t j = 0; j < tileY; j++ )
1759         CtbAddrInTs += sps->PicWidthInCtbsY * pps->rowHeight[j];
1760     CtbAddrInTs += (tbY - pps->rowBd[tileY]) * pps->colWidth[tileX] + tbX - pps->colBd[tileX];
1761     *TileId = (uint64_t)tileY * (pps->num_tile_columns_minus1 + 1) + tileX;
1762     return CtbAddrInTs;
1763 }
1764 
hevc_find_au_delimit_by_slice_info(hevc_info_t * info,hevc_slice_info_t * slice,hevc_slice_info_t * prev_slice)1765 int hevc_find_au_delimit_by_slice_info
1766 (
1767     hevc_info_t       *info,
1768     hevc_slice_info_t *slice,
1769     hevc_slice_info_t *prev_slice
1770 )
1771 {
1772     /* 7.4.2.4.5 Order of VCL NAL units and association to coded pictures
1773      *  - The first VCL NAL unit of the coded picture shall have first_slice_segment_in_pic_flag equal to 1. */
1774     if( slice->first_slice_segment_in_pic_flag )
1775         return 1;
1776     /* The value of TemporalId shall be the same for all VCL NAL units of an access unit. */
1777     if( slice->TemporalId != prev_slice->TemporalId )
1778         return 1;
1779     /* 7.4.2.4.5 Order of VCL NAL units and association to coded pictures
1780      * When either of the following conditions is true, both the current and the previous coded slice segment NAL units
1781      * shall belong to the same coded picture.
1782      *  - TileId[ CtbAddrRsToTs[ prev_slice->segment_address ] ] <  TileId[ CtbAddrRsToTs[ slice->segment_address ] ]
1783      *  - TileId[ CtbAddrRsToTs[ prev_slice->segment_address ] ] == TileId[ CtbAddrRsToTs[ slice->segment_address ] ]
1784      *   &&       CtbAddrRsToTs[ prev_slice->segment_address ]   <          CtbAddrRsToTs[ slice->segment_address ]
1785      */
1786     hevc_pps_t *prev_pps = hevc_get_pps( info->pps_list, prev_slice->pic_parameter_set_id );
1787     if( !prev_pps )
1788         return 0;
1789     hevc_sps_t *prev_sps = hevc_get_sps( info->sps_list, prev_pps->seq_parameter_set_id );
1790     if( !prev_sps )
1791         return 0;
1792     uint64_t currTileId;
1793     uint64_t prevTileId;
1794     uint64_t currCtbAddrInTs = hevc_get_ctb_address_in_tile_scan( &info->sps, &info->pps,      slice->segment_address, &currTileId );
1795     uint64_t prevCtbAddrInTs = hevc_get_ctb_address_in_tile_scan(   prev_sps,   prev_pps, prev_slice->segment_address, &prevTileId );
1796     if( prevTileId < currTileId )
1797         return 0;
1798     if( prevTileId == currTileId && prevCtbAddrInTs < currCtbAddrInTs )
1799         return 0;
1800     return 1;
1801 }
1802 
hevc_find_au_delimit_by_nalu_type(uint8_t nalu_type,uint8_t prev_nalu_type)1803 int hevc_find_au_delimit_by_nalu_type
1804 (
1805     uint8_t nalu_type,
1806     uint8_t prev_nalu_type
1807 )
1808 {
1809     /* 7.4.2.4.4 Order of NAL units and coded pictures and their association to access units */
1810     if( prev_nalu_type <= HEVC_NALU_TYPE_RSV_VCL31 )
1811         /* The first of any of the following NAL units after the last VCL NAL unit of a coded picture
1812          * specifies the start of a new access unit:
1813          *   - access unit delimiter NAL unit (when present)
1814          *   - VPS NAL unit (when present)
1815          *   - SPS NAL unit (when present)
1816          *   - PPS NAL unit (when present)
1817          *   - Prefix SEI NAL unit (when present)
1818          *   - NAL units with nal_unit_type in the range of RSV_NVCL41..RSV_NVCL44 (when present)
1819          *   - NAL units with nal_unit_type in the range of UNSPEC48..UNSPEC55 (when present)
1820          *   - first VCL NAL unit of a coded picture (always present) */
1821         return (nalu_type >= HEVC_NALU_TYPE_VPS        && nalu_type <= HEVC_NALU_TYPE_AUD)
1822             || (nalu_type == HEVC_NALU_TYPE_PREFIX_SEI)
1823             || (nalu_type >= HEVC_NALU_TYPE_RSV_NVCL41 && nalu_type <= HEVC_NALU_TYPE_RSV_NVCL44)
1824             || (nalu_type >= HEVC_NALU_TYPE_UNSPEC48   && nalu_type <= HEVC_NALU_TYPE_UNSPEC55);
1825     else if( prev_nalu_type == HEVC_NALU_TYPE_EOS )
1826         /* An end of sequence NAL unit shall be the last NAL unit in the access unit unless the next
1827          * NAL unit is an end of bitstream NAL unit. */
1828         return (nalu_type != HEVC_NALU_TYPE_EOB);
1829     else
1830         /* An end of bitstream NAL unit shall be the last NAL unit in the access unit.
1831          * Thus, the next NAL unit shall be the first NAL unit in the next access unit. */
1832         return (prev_nalu_type == HEVC_NALU_TYPE_EOB);
1833 }
1834 
hevc_supplement_buffer(hevc_stream_buffer_t * sb,hevc_access_unit_t * au,uint32_t size)1835 int hevc_supplement_buffer
1836 (
1837     hevc_stream_buffer_t *sb,
1838     hevc_access_unit_t   *au,
1839     uint32_t              size
1840 )
1841 {
1842     lsmash_multiple_buffers_t *bank = lsmash_resize_multiple_buffers( sb->bank, size );
1843     if( !bank )
1844         return LSMASH_ERR_MEMORY_ALLOC;
1845     sb->bank = bank;
1846     sb->rbsp = lsmash_withdraw_buffer( bank, 1 );
1847     if( au && bank->number_of_buffers == 3 )
1848     {
1849         au->data            = lsmash_withdraw_buffer( bank, 2 );
1850         au->incomplete_data = lsmash_withdraw_buffer( bank, 3 );
1851     }
1852     return 0;
1853 }
1854 
hevc_bs_put_parameter_sets(lsmash_bs_t * bs,lsmash_entry_list_t * dcr_ps_list,uint32_t max_dcr_ps_count)1855 static void hevc_bs_put_parameter_sets
1856 (
1857     lsmash_bs_t         *bs,
1858     lsmash_entry_list_t *dcr_ps_list,
1859     uint32_t             max_dcr_ps_count
1860 )
1861 {
1862     uint32_t dcr_ps_count = 0;
1863     for( lsmash_entry_t *entry = dcr_ps_list->head; entry && dcr_ps_count < max_dcr_ps_count; entry = entry->next )
1864     {
1865         isom_dcr_ps_entry_t *ps = (isom_dcr_ps_entry_t *)entry->data;
1866         if( ps && !ps->unused )
1867         {
1868             lsmash_bs_put_be16( bs, ps->nalUnitLength );
1869             lsmash_bs_put_bytes( bs, ps->nalUnitLength, ps->nalUnit );
1870         }
1871         else
1872             continue;
1873         ++dcr_ps_count;
1874     }
1875 }
1876 
lsmash_create_hevc_specific_info(lsmash_hevc_specific_parameters_t * param,uint32_t * data_length)1877 uint8_t *lsmash_create_hevc_specific_info
1878 (
1879     lsmash_hevc_specific_parameters_t *param,
1880     uint32_t                          *data_length
1881 )
1882 {
1883     if( !param || !param->parameter_arrays || !data_length )
1884         return NULL;
1885     if( param->lengthSizeMinusOne != 0
1886      && param->lengthSizeMinusOne != 1
1887      && param->lengthSizeMinusOne != 3 )
1888         return NULL;
1889     hevc_parameter_array_t *param_arrays[HEVC_DCR_NALU_TYPE_NUM];
1890     lsmash_entry_list_t    *dcr_ps_list [HEVC_DCR_NALU_TYPE_NUM];
1891     for( int i = 0; i < HEVC_DCR_NALU_TYPE_NUM; i++ )
1892     {
1893         param_arrays[i] = &param->parameter_arrays->ps_array[i];
1894         dcr_ps_list [i] = param_arrays[i]->list;
1895     }
1896     /* VPS, SPS and PPS are mandatory. */
1897     if( !dcr_ps_list[0] || !dcr_ps_list[0]->head || dcr_ps_list[0]->entry_count == 0
1898      || !dcr_ps_list[1] || !dcr_ps_list[1]->head || dcr_ps_list[1]->entry_count == 0
1899      || !dcr_ps_list[2] || !dcr_ps_list[2]->head || dcr_ps_list[2]->entry_count == 0 )
1900         return NULL;
1901     /* Calculate enough buffer size. */
1902     static const uint32_t max_dcr_ps_count[HEVC_DCR_NALU_TYPE_NUM] =
1903         {
1904             HEVC_MAX_VPS_ID + 1,
1905             HEVC_MAX_SPS_ID + 1,
1906             HEVC_MAX_PPS_ID + 1,
1907             UINT16_MAX,
1908             UINT16_MAX
1909         };
1910     uint32_t ps_count[HEVC_DCR_NALU_TYPE_NUM] = { 0 };
1911     for( int i = 0; i < HEVC_DCR_NALU_TYPE_NUM; i++ )
1912         if( dcr_ps_list[i] )
1913             for( lsmash_entry_t *entry = dcr_ps_list[i]->head; entry && ps_count[i] < max_dcr_ps_count[i]; entry = entry->next )
1914             {
1915                 isom_dcr_ps_entry_t *ps = (isom_dcr_ps_entry_t *)entry->data;
1916                 if( !ps )
1917                     return NULL;
1918                 if( ps->unused )
1919                     continue;
1920                 ++ps_count[i];
1921             }
1922     /* Create an HEVCConfigurationBox */
1923     lsmash_bs_t *bs = lsmash_bs_create();
1924     if( !bs )
1925         return NULL;
1926     lsmash_bs_put_be32( bs, 0 );                           /* box size */
1927     lsmash_bs_put_be32( bs, ISOM_BOX_TYPE_HVCC.fourcc );   /* box type: 'hvcC' */
1928     lsmash_bs_put_byte( bs, HVCC_CONFIGURATION_VERSION );  /* configurationVersion */
1929     uint8_t temp8 = (param->general_profile_space << 6)
1930                   | (param->general_tier_flag     << 5)
1931                   |  param->general_profile_idc;
1932     lsmash_bs_put_byte( bs, temp8 );
1933     lsmash_bs_put_be32( bs, param->general_profile_compatibility_flags );
1934     lsmash_bs_put_be32( bs, param->general_constraint_indicator_flags >> 16 );
1935     lsmash_bs_put_be16( bs, param->general_constraint_indicator_flags );
1936     lsmash_bs_put_byte( bs, param->general_level_idc );
1937     lsmash_bs_put_be16( bs, param->min_spatial_segmentation_idc | 0xF000 );
1938     lsmash_bs_put_byte( bs, param->parallelismType              | 0xFC );
1939     lsmash_bs_put_byte( bs, param->chromaFormat                 | 0xFC );
1940     lsmash_bs_put_byte( bs, param->bitDepthLumaMinus8           | 0xF8 );
1941     lsmash_bs_put_byte( bs, param->bitDepthChromaMinus8         | 0xF8 );
1942     lsmash_bs_put_be16( bs, param->avgFrameRate );
1943     temp8 = (param->constantFrameRate << 6)
1944           | (param->numTemporalLayers << 3)
1945           | (param->temporalIdNested  << 2)
1946           |  param->lengthSizeMinusOne;
1947     lsmash_bs_put_byte( bs, temp8 );
1948     uint8_t numOfArrays = !!ps_count[0]
1949                         + !!ps_count[1]
1950                         + !!ps_count[2]
1951                         + !!ps_count[3]
1952                         + !!ps_count[4];
1953     lsmash_bs_put_byte( bs, numOfArrays );
1954     for( uint8_t i = 0; i < numOfArrays; i++ )
1955     {
1956         temp8 = (param_arrays[i]->array_completeness << 7) | param_arrays[i]->NAL_unit_type;
1957         lsmash_bs_put_byte( bs, temp8 );
1958         lsmash_bs_put_be16( bs, ps_count[i] );
1959         hevc_bs_put_parameter_sets( bs, dcr_ps_list[i], ps_count[i] );
1960     }
1961     uint8_t *data = lsmash_bs_export_data( bs, data_length );
1962     lsmash_bs_cleanup( bs );
1963     /* Update box size. */
1964     LSMASH_SET_BE32( data, *data_length );
1965     return data;
1966 }
1967 
hevc_validate_dcr_nalu_type(lsmash_hevc_dcr_nalu_type ps_type,void * ps_data,uint32_t ps_length)1968 static inline int hevc_validate_dcr_nalu_type
1969 (
1970     lsmash_hevc_dcr_nalu_type ps_type,
1971     void                     *ps_data,
1972     uint32_t                  ps_length
1973 )
1974 {
1975     if( !ps_data || ps_length < 3 )
1976         return LSMASH_ERR_INVALID_DATA;
1977     if( ps_type != HEVC_DCR_NALU_TYPE_VPS
1978      && ps_type != HEVC_DCR_NALU_TYPE_SPS
1979      && ps_type != HEVC_DCR_NALU_TYPE_PPS
1980      && ps_type != HEVC_DCR_NALU_TYPE_PREFIX_SEI
1981      && ps_type != HEVC_DCR_NALU_TYPE_SUFFIX_SEI )
1982         return LSMASH_ERR_INVALID_DATA;
1983     uint8_t nalu_type = (*((uint8_t *)ps_data) >> 1) & 0x3f;
1984     if( nalu_type != HEVC_NALU_TYPE_VPS
1985      && nalu_type != HEVC_NALU_TYPE_SPS
1986      && nalu_type != HEVC_NALU_TYPE_PPS
1987      && nalu_type != HEVC_NALU_TYPE_PREFIX_SEI
1988      && nalu_type != HEVC_NALU_TYPE_SUFFIX_SEI )
1989         return LSMASH_ERR_INVALID_DATA;
1990     if( (ps_type == HEVC_DCR_NALU_TYPE_VPS        && nalu_type != HEVC_NALU_TYPE_VPS)
1991      || (ps_type == HEVC_DCR_NALU_TYPE_SPS        && nalu_type != HEVC_NALU_TYPE_SPS)
1992      || (ps_type == HEVC_DCR_NALU_TYPE_PPS        && nalu_type != HEVC_NALU_TYPE_PPS)
1993      || (ps_type == HEVC_DCR_NALU_TYPE_PREFIX_SEI && nalu_type != HEVC_NALU_TYPE_PREFIX_SEI)
1994      || (ps_type == HEVC_DCR_NALU_TYPE_SUFFIX_SEI && nalu_type != HEVC_NALU_TYPE_SUFFIX_SEI) )
1995         return LSMASH_ERR_INVALID_DATA;
1996     return 0;
1997 }
1998 
hevc_check_vps_appendable(lsmash_bits_t * bits,uint8_t * rbsp_buffer,lsmash_hevc_specific_parameters_t * param,uint8_t * ps_data,uint32_t ps_length,lsmash_entry_list_t * ps_list)1999 static lsmash_dcr_nalu_appendable hevc_check_vps_appendable
2000 (
2001     lsmash_bits_t                     *bits,
2002     uint8_t                           *rbsp_buffer,
2003     lsmash_hevc_specific_parameters_t *param,
2004     uint8_t                           *ps_data,
2005     uint32_t                           ps_length,
2006     lsmash_entry_list_t               *ps_list
2007 )
2008 {
2009     hevc_vps_t vps;
2010     if( hevc_parse_vps_minimally( bits, &vps, rbsp_buffer,
2011                                   ps_data   + HEVC_MIN_NALU_HEADER_LENGTH,
2012                                   ps_length - HEVC_MIN_NALU_HEADER_LENGTH ) < 0 )
2013         return DCR_NALU_APPEND_ERROR;
2014     /* The value of profile_space must be identical in all the parameter sets in a single HEVC Decoder Configuration Record. */
2015     if( vps.ptl.general.profile_space != param->general_profile_space )
2016         return DCR_NALU_APPEND_NEW_DCR_REQUIRED;
2017     /* FIXME */
2018     if( vps.ptl.general.profile_idc != param->general_profile_idc )
2019         return DCR_NALU_APPEND_NEW_DCR_REQUIRED;
2020     for( lsmash_entry_t *entry = ps_list->head; entry; entry = entry->next )
2021     {
2022         isom_dcr_ps_entry_t *ps = (isom_dcr_ps_entry_t *)entry->data;
2023         if( !ps )
2024             return DCR_NALU_APPEND_ERROR;
2025         if( ps->unused )
2026             continue;
2027         uint8_t param_vps_id;
2028         if( hevc_get_vps_id( ps->nalUnit       + HEVC_MIN_NALU_HEADER_LENGTH,
2029                              ps->nalUnitLength - HEVC_MIN_NALU_HEADER_LENGTH, &param_vps_id ) < 0 )
2030             return DCR_NALU_APPEND_ERROR;
2031         if( param_vps_id == vps.video_parameter_set_id )
2032             /* VPS that has the same video_parameter_set_id already exists with different form. */
2033             return DCR_NALU_APPEND_NEW_DCR_REQUIRED;
2034     }
2035     return DCR_NALU_APPEND_POSSIBLE;
2036 }
2037 
hevc_check_sps_appendable(lsmash_bits_t * bits,uint8_t * rbsp_buffer,lsmash_hevc_specific_parameters_t * param,uint8_t * ps_data,uint32_t ps_length,lsmash_entry_list_t * ps_list)2038 static lsmash_dcr_nalu_appendable hevc_check_sps_appendable
2039 (
2040     lsmash_bits_t                     *bits,
2041     uint8_t                           *rbsp_buffer,
2042     lsmash_hevc_specific_parameters_t *param,
2043     uint8_t                           *ps_data,
2044     uint32_t                           ps_length,
2045     lsmash_entry_list_t               *ps_list
2046 )
2047 {
2048     hevc_sps_t sps;
2049     if( hevc_parse_sps_minimally( bits, &sps, rbsp_buffer,
2050                                   ps_data   + HEVC_MIN_NALU_HEADER_LENGTH,
2051                                   ps_length - HEVC_MIN_NALU_HEADER_LENGTH ) < 0 )
2052         return DCR_NALU_APPEND_ERROR;
2053     lsmash_bits_empty( bits );
2054     /* The values of profile_space, chromaFormat, bitDepthLumaMinus8 and bitDepthChromaMinus8
2055      * must be identical in all the parameter sets in a single HEVC Decoder Configuration Record. */
2056     if( sps.ptl.general.profile_space != param->general_profile_space
2057      || sps.chroma_format_idc         != param->chromaFormat
2058      || sps.bit_depth_luma_minus8     != param->bitDepthLumaMinus8
2059      || sps.bit_depth_chroma_minus8   != param->bitDepthChromaMinus8 )
2060         return DCR_NALU_APPEND_NEW_DCR_REQUIRED;
2061     /* FIXME; If the sequence parameter sets are marked with different profiles,
2062      * and the relevant profile compatibility flags are all zero,
2063      * then the stream may need examination to determine which profile, if any, the stream conforms to.
2064      * If the stream is not examined, or the examination reveals that there is no profile to which the stream conforms,
2065      * then the stream must be split into two or more sub-streams with separate configuration records in which these rules can be met. */
2066 #if 0
2067     if( sps.ptl.general.profile_idc != param->general_profile_idc
2068      && (sps.ptl.general.profile_compatibility_flags & param->general_profile_compatibility_flags) )
2069 #else
2070     if( sps.ptl.general.profile_idc != param->general_profile_idc )
2071 #endif
2072         return DCR_NALU_APPEND_NEW_DCR_REQUIRED;
2073     /* Forbidden to duplicate SPS that has the same seq_parameter_set_id with different form within the same configuration record. */
2074     for( lsmash_entry_t *entry = ps_list->head; entry; entry = entry->next )
2075     {
2076         isom_dcr_ps_entry_t *ps = (isom_dcr_ps_entry_t *)entry->data;
2077         if( !ps )
2078             return DCR_NALU_APPEND_ERROR;
2079         if( ps->unused )
2080             continue;
2081         uint8_t param_sps_id;
2082         if( hevc_get_sps_id( ps->nalUnit       + HEVC_MIN_NALU_HEADER_LENGTH,
2083                              ps->nalUnitLength - HEVC_MIN_NALU_HEADER_LENGTH, &param_sps_id ) < 0 )
2084             return DCR_NALU_APPEND_ERROR;
2085         if( param_sps_id == sps.seq_parameter_set_id )
2086             /* SPS that has the same seq_parameter_set_id already exists with different form. */
2087             return DCR_NALU_APPEND_NEW_DCR_REQUIRED;
2088         if( entry == ps_list->head )
2089         {
2090             /* Check if the cropped visual presentation sizes, the sample aspect ratios, the colour descriptions and
2091              * the default display windows are different. */
2092             hevc_sps_t first_sps;
2093             if( hevc_parse_sps_minimally( bits, &first_sps, rbsp_buffer,
2094                                           ps->nalUnit       + HEVC_MIN_NALU_HEADER_LENGTH,
2095                                           ps->nalUnitLength - HEVC_MIN_NALU_HEADER_LENGTH ) < 0 )
2096                 return DCR_NALU_APPEND_ERROR;
2097             if( sps.cropped_width                    != first_sps.cropped_width
2098              || sps.cropped_height                   != first_sps.cropped_height
2099              || sps.vui.sar_width                    != first_sps.vui.sar_width
2100              || sps.vui.sar_height                   != first_sps.vui.sar_height
2101              || sps.vui.colour_primaries             != first_sps.vui.colour_primaries
2102              || sps.vui.transfer_characteristics     != first_sps.vui.transfer_characteristics
2103              || sps.vui.matrix_coeffs                != first_sps.vui.matrix_coeffs
2104              || sps.vui.video_full_range_flag        != first_sps.vui.video_full_range_flag
2105              || sps.vui.def_disp_win_offset.left  .n != first_sps.vui.def_disp_win_offset.left  .n
2106              || sps.vui.def_disp_win_offset.right .n != first_sps.vui.def_disp_win_offset.right .n
2107              || sps.vui.def_disp_win_offset.top   .n != first_sps.vui.def_disp_win_offset.top   .n
2108              || sps.vui.def_disp_win_offset.bottom.n != first_sps.vui.def_disp_win_offset.bottom.n )
2109                 return DCR_NALU_APPEND_NEW_SAMPLE_ENTRY_REQUIRED;
2110         }
2111     }
2112     return DCR_NALU_APPEND_POSSIBLE;
2113 }
2114 
hevc_check_pps_appendable(uint8_t * ps_data,uint32_t ps_length,lsmash_entry_list_t * ps_list)2115 static lsmash_dcr_nalu_appendable hevc_check_pps_appendable
2116 (
2117     uint8_t             *ps_data,
2118     uint32_t             ps_length,
2119     lsmash_entry_list_t *ps_list
2120 )
2121 {
2122     uint8_t pps_id;
2123     if( hevc_get_pps_id( ps_data   + HEVC_MIN_NALU_HEADER_LENGTH,
2124                          ps_length - HEVC_MIN_NALU_HEADER_LENGTH, &pps_id ) < 0 )
2125         return DCR_NALU_APPEND_ERROR;
2126     for( lsmash_entry_t *entry = ps_list->head; entry; entry = entry->next )
2127     {
2128         isom_dcr_ps_entry_t *ps = (isom_dcr_ps_entry_t *)entry->data;
2129         if( !ps )
2130             return DCR_NALU_APPEND_ERROR;
2131         if( ps->unused )
2132             continue;
2133         uint8_t param_pps_id;
2134         if( hevc_get_pps_id( ps->nalUnit       + HEVC_MIN_NALU_HEADER_LENGTH,
2135                              ps->nalUnitLength - HEVC_MIN_NALU_HEADER_LENGTH, &param_pps_id ) < 0 )
2136             return DCR_NALU_APPEND_ERROR;
2137         if( pps_id == param_pps_id )
2138             /* PPS that has the same pic_parameter_set_id already exists with different form. */
2139             return DCR_NALU_APPEND_NEW_DCR_REQUIRED;
2140     }
2141     return DCR_NALU_APPEND_POSSIBLE;
2142 }
2143 
lsmash_check_hevc_dcr_nalu_appendable(lsmash_hevc_specific_parameters_t * param,lsmash_hevc_dcr_nalu_type ps_type,void * _ps_data,uint32_t ps_length)2144 lsmash_dcr_nalu_appendable lsmash_check_hevc_dcr_nalu_appendable
2145 (
2146     lsmash_hevc_specific_parameters_t *param,
2147     lsmash_hevc_dcr_nalu_type          ps_type,
2148     void                              *_ps_data,
2149     uint32_t                           ps_length
2150 )
2151 {
2152     uint8_t *ps_data = _ps_data;
2153     if( !param )
2154         return DCR_NALU_APPEND_ERROR;
2155     if( hevc_validate_dcr_nalu_type( ps_type, ps_data, ps_length ) < 0 )
2156         return DCR_NALU_APPEND_ERROR;
2157     /* Check whether the same parameter set already exsits or not. */
2158     lsmash_entry_list_t *ps_list = hevc_get_parameter_set_list( param, ps_type );
2159     if( !ps_list || !ps_list->head )
2160         return DCR_NALU_APPEND_POSSIBLE;    /* No parameter set */
2161     switch( nalu_check_same_ps_existence( ps_list, ps_data, ps_length ) )
2162     {
2163         case 0  : break;
2164         case 1  : return DCR_NALU_APPEND_DUPLICATED;    /* The same parameter set already exists. */
2165         default : return DCR_NALU_APPEND_ERROR;         /* An error occured. */
2166     }
2167     /* Check the number of parameter sets in HEVC Decoder Configuration Record. */
2168     uint32_t ps_count;
2169     if( nalu_get_ps_count( ps_list, &ps_count ) < 0 )
2170         return DCR_NALU_APPEND_ERROR;
2171     if( (ps_type == HEVC_DCR_NALU_TYPE_VPS        && ps_count >= HEVC_MAX_VPS_ID)
2172      || (ps_type == HEVC_DCR_NALU_TYPE_SPS        && ps_count >= HEVC_MAX_SPS_ID)
2173      || (ps_type == HEVC_DCR_NALU_TYPE_PPS        && ps_count >= HEVC_MAX_PPS_ID)
2174      || (ps_type == HEVC_DCR_NALU_TYPE_PREFIX_SEI && ps_count >= UINT16_MAX)
2175      || (ps_type == HEVC_DCR_NALU_TYPE_SUFFIX_SEI && ps_count >= UINT16_MAX) )
2176         return DCR_NALU_APPEND_NEW_DCR_REQUIRED;    /* No more appendable parameter sets. */
2177     if( ps_type == HEVC_DCR_NALU_TYPE_PREFIX_SEI
2178      || ps_type == HEVC_DCR_NALU_TYPE_SUFFIX_SEI )
2179         return DCR_NALU_APPEND_POSSIBLE;
2180     /* Check whether a new specific info is needed or not. */
2181     if( ps_type == HEVC_DCR_NALU_TYPE_PPS )
2182         /* PPS */
2183         return hevc_check_pps_appendable( ps_data, ps_length, ps_list );
2184     else
2185     {
2186         /* VPS or SPS
2187          * Set up bitstream handler for parse parameter sets. */
2188         lsmash_bits_t *bits = lsmash_bits_adhoc_create();
2189         if( !bits )
2190             return DCR_NALU_APPEND_ERROR;
2191         uint32_t max_ps_length;
2192         uint8_t *rbsp_buffer;
2193         if( nalu_get_max_ps_length( ps_list, &max_ps_length ) < 0
2194          || (rbsp_buffer = lsmash_malloc( LSMASH_MAX( max_ps_length, ps_length ) )) == NULL )
2195         {
2196             lsmash_bits_adhoc_cleanup( bits );
2197             return DCR_NALU_APPEND_ERROR;
2198         }
2199         lsmash_dcr_nalu_appendable appendable;
2200         if( ps_type == HEVC_DCR_NALU_TYPE_VPS )
2201             appendable = hevc_check_vps_appendable( bits, rbsp_buffer, param, ps_data, ps_length, ps_list );
2202         else
2203             appendable = hevc_check_sps_appendable( bits, rbsp_buffer, param, ps_data, ps_length, ps_list );
2204         lsmash_bits_adhoc_cleanup( bits );
2205         lsmash_free( rbsp_buffer );
2206         return appendable;
2207     }
2208 }
2209 
hevc_specific_parameters_ready(lsmash_hevc_specific_parameters_t * param)2210 static inline void hevc_specific_parameters_ready
2211 (
2212     lsmash_hevc_specific_parameters_t *param
2213 )
2214 {
2215     param->general_profile_compatibility_flags = ~UINT32_C(0);
2216     param->general_constraint_indicator_flags  = 0x0000FFFFFFFFFFFF;
2217     param->min_spatial_segmentation_idc        = 0x0FFF;
2218     param->avgFrameRate                        = 0;     /* unspecified average frame rate */
2219     param->constantFrameRate                   = 2;
2220     param->numTemporalLayers                   = 0;
2221     param->temporalIdNested                    = 1;
2222 }
2223 
hevc_specific_parameters_update_ptl(lsmash_hevc_specific_parameters_t * param,hevc_ptl_t * ptl)2224 static inline void hevc_specific_parameters_update_ptl
2225 (
2226     lsmash_hevc_specific_parameters_t *param,
2227     hevc_ptl_t                        *ptl
2228 )
2229 {
2230     param->general_profile_space                = ptl->general.profile_space;
2231     param->general_tier_flag                    = LSMASH_MAX( param->general_tier_flag, ptl->general.tier_flag );
2232     param->general_profile_idc                  = ptl->general.profile_idc;
2233     param->general_profile_compatibility_flags &= ptl->general.profile_compatibility_flags;
2234     param->general_constraint_indicator_flags  &= ((uint64_t)ptl->general.progressive_source_flag    << 47)
2235                                                 | ((uint64_t)ptl->general.interlaced_source_flag     << 46)
2236                                                 | ((uint64_t)ptl->general.non_packed_constraint_flag << 45)
2237                                                 | ((uint64_t)ptl->general.frame_only_constraint_flag << 44)
2238                                                 |            ptl->general.reserved_zero_44bits;
2239     param->general_level_idc                    = LSMASH_MAX( param->general_level_idc, ptl->general.level_idc );
2240 }
2241 
hevc_reorder_parameter_set_ascending_id(lsmash_hevc_specific_parameters_t * param,lsmash_hevc_dcr_nalu_type ps_type,lsmash_entry_list_t * ps_list,uint8_t ps_id)2242 static inline void hevc_reorder_parameter_set_ascending_id
2243 (
2244     lsmash_hevc_specific_parameters_t *param,
2245     lsmash_hevc_dcr_nalu_type          ps_type,
2246     lsmash_entry_list_t               *ps_list,
2247     uint8_t                            ps_id
2248 )
2249 {
2250     lsmash_entry_t *entry = NULL;
2251     if( ps_id )
2252         for( int i = ps_id - 1; i; i-- )
2253         {
2254             entry = hevc_get_ps_entry_from_param( param, ps_type, i );
2255             if( entry )
2256                 break;
2257         }
2258     int append_head = 0;
2259     if( !entry )
2260     {
2261         /* Couldn't find any parameter set with lower identifier.
2262          * Next, find parameter set with upper identifier. */
2263         int max_ps_id = ps_type == HEVC_DCR_NALU_TYPE_VPS ? HEVC_MAX_VPS_ID
2264                       : ps_type == HEVC_DCR_NALU_TYPE_SPS ? HEVC_MAX_SPS_ID
2265                       :                                     HEVC_MAX_PPS_ID;
2266         for( int i = ps_id + 1; i <= max_ps_id; i++ )
2267         {
2268             entry = hevc_get_ps_entry_from_param( param, ps_type, i );
2269             if( entry )
2270                 break;
2271         }
2272         if( entry )
2273             append_head = 1;
2274     }
2275     if( !entry )
2276         return;     /* The new entry was appended to the tail. */
2277     lsmash_entry_t *new_entry = ps_list->tail;
2278     if( append_head )
2279     {
2280         /* before: entry[i > ps_id] ... -> prev_entry -> new_entry[ps_id]
2281          * after:  new_entry[ps_id] -> entry[i > ps_id] -> ... -> prev_entry */
2282         if( new_entry->prev )
2283             new_entry->prev->next = NULL;
2284         new_entry->prev = NULL;
2285         entry->prev = new_entry;
2286         new_entry->next = entry;
2287         return;
2288     }
2289     /* before: entry[i < ps_id] -> next_entry -> ... -> prev_entry -> new_entry[ps_id]
2290      * after:  entry[i < ps_id] -> new_entry[ps_id] -> next_entry -> ... -> prev_entry */
2291     if( new_entry->prev )
2292         new_entry->prev->next = NULL;
2293     new_entry->prev = entry;
2294     new_entry->next = entry->next;
2295     if( entry->next )
2296         entry->next->prev = new_entry;
2297     entry->next = new_entry;
2298 }
2299 
lsmash_append_hevc_dcr_nalu(lsmash_hevc_specific_parameters_t * param,lsmash_hevc_dcr_nalu_type ps_type,void * _ps_data,uint32_t ps_length)2300 int lsmash_append_hevc_dcr_nalu
2301 (
2302     lsmash_hevc_specific_parameters_t *param,
2303     lsmash_hevc_dcr_nalu_type          ps_type,
2304     void                              *_ps_data,
2305     uint32_t                           ps_length
2306 )
2307 {
2308     uint8_t *ps_data = _ps_data;
2309     if( !param || !ps_data || ps_length < 2 )
2310         return LSMASH_ERR_FUNCTION_PARAM;
2311     int err = hevc_alloc_parameter_arrays_if_needed( param );
2312     if( err < 0 )
2313         return err;
2314     hevc_parameter_array_t *ps_array = hevc_get_parameter_set_array( param, ps_type );
2315     if( !ps_array )
2316         return LSMASH_ERR_FUNCTION_PARAM;
2317     lsmash_entry_list_t *ps_list = ps_array->list;
2318     if( ps_type == HEVC_DCR_NALU_TYPE_PREFIX_SEI
2319      || ps_type == HEVC_DCR_NALU_TYPE_SUFFIX_SEI )
2320     {
2321         /* Append a SEI anyway. */
2322         isom_dcr_ps_entry_t *ps = isom_create_ps_entry( ps_data, ps_length );
2323         if( !ps )
2324             return LSMASH_ERR_MEMORY_ALLOC;
2325         if( lsmash_list_add_entry( ps_list, ps ) < 0 )
2326         {
2327             isom_remove_dcr_ps( ps );
2328             return LSMASH_ERR_MEMORY_ALLOC;
2329         }
2330         return 0;
2331     }
2332     if( ps_type != HEVC_DCR_NALU_TYPE_VPS
2333      && ps_type != HEVC_DCR_NALU_TYPE_SPS
2334      && ps_type != HEVC_DCR_NALU_TYPE_PPS )
2335         return LSMASH_ERR_FUNCTION_PARAM;
2336     /* Check if the same parameter set identifier already exists. */
2337     uint8_t ps_id;
2338     if( (err = hevc_get_ps_id( ps_data   + HEVC_MIN_NALU_HEADER_LENGTH,
2339                                ps_length - HEVC_MIN_NALU_HEADER_LENGTH, &ps_id, ps_type )) < 0 )
2340         return err;
2341     lsmash_entry_t *entry = hevc_get_ps_entry_from_param( param, ps_type, ps_id );
2342     isom_dcr_ps_entry_t *ps = entry ? (isom_dcr_ps_entry_t *)entry->data : NULL;
2343     if( ps && !ps->unused )
2344         /* The same parameter set identifier already exists. */
2345         return LSMASH_ERR_FUNCTION_PARAM;
2346     int invoke_reorder;
2347     if( ps )
2348     {
2349         /* Reuse an already existed parameter set in the list. */
2350         ps->unused = 0;
2351         if( ps->nalUnit != ps_data )
2352         {
2353             /* The same address could be given when called by hevc_update_picture_info_for_slice(). */
2354             lsmash_free( ps->nalUnit );
2355             ps->nalUnit = ps_data;
2356         }
2357         ps->nalUnitLength = ps_length;
2358         invoke_reorder = 0;
2359     }
2360     else
2361     {
2362         /* Create a new parameter set and append it into the list. */
2363         ps = isom_create_ps_entry( ps_data, ps_length );
2364         if( !ps )
2365             return LSMASH_ERR_MEMORY_ALLOC;
2366         if( lsmash_list_add_entry( ps_list, ps ) < 0 )
2367         {
2368             isom_remove_dcr_ps( ps );
2369             return LSMASH_ERR_MEMORY_ALLOC;
2370         }
2371         invoke_reorder = 1;
2372     }
2373     lsmash_bits_t *bits        = NULL;
2374     uint8_t       *rbsp_buffer = NULL;
2375     uint32_t       ps_count;
2376     if( (err = nalu_get_ps_count( ps_list, &ps_count )) < 0 )
2377         goto fail;
2378     if( (bits = lsmash_bits_adhoc_create()) == NULL
2379      || (rbsp_buffer = lsmash_malloc( ps_length )) == NULL )
2380     {
2381         err = LSMASH_ERR_MEMORY_ALLOC;
2382         goto fail;
2383     }
2384     /* Update specific info with VPS, SPS or PPS. */
2385     {
2386         if( ps_type == HEVC_DCR_NALU_TYPE_VPS )
2387         {
2388             hevc_vps_t vps;
2389             if( (err = hevc_parse_vps_minimally( bits, &vps, rbsp_buffer,
2390                                                  ps_data   + HEVC_MIN_NALU_HEADER_LENGTH,
2391                                                  ps_length - HEVC_MIN_NALU_HEADER_LENGTH )) < 0 )
2392                 goto fail;
2393             if( ps_count == 1 )
2394             {
2395                 /* Initialize if not initialized yet. */
2396                 lsmash_entry_list_t *sps_list = hevc_get_parameter_set_list( param, HEVC_DCR_NALU_TYPE_SPS );
2397                 uint32_t sps_count;
2398                 if( (err = nalu_get_ps_count( sps_list, &sps_count )) < 0 )
2399                     goto fail;
2400                 if( sps_count == 0 )
2401                     hevc_specific_parameters_ready( param );
2402             }
2403             hevc_specific_parameters_update_ptl( param, &vps.ptl );
2404             param->numTemporalLayers  = LSMASH_MAX( param->numTemporalLayers, vps.max_sub_layers_minus1 + 1 );
2405             //param->temporalIdNested  &= vps.temporal_id_nesting_flag;
2406         }
2407         else if( ps_type == HEVC_DCR_NALU_TYPE_SPS )
2408         {
2409             hevc_sps_t sps;
2410             if( (err = hevc_parse_sps_minimally( bits, &sps, rbsp_buffer,
2411                                                  ps_data   + HEVC_MIN_NALU_HEADER_LENGTH,
2412                                                  ps_length - HEVC_MIN_NALU_HEADER_LENGTH )) < 0 )
2413                 goto fail;
2414             if( ps_count == 1 )
2415             {
2416                 /* Initialize if not initialized yet. */
2417                 lsmash_entry_list_t *vps_list = hevc_get_parameter_set_list( param, HEVC_DCR_NALU_TYPE_VPS );
2418                 uint32_t vps_count;
2419                 if( (err = nalu_get_ps_count( vps_list, &vps_count )) < 0 )
2420                     goto fail;
2421                 if( vps_count == 0 )
2422                     hevc_specific_parameters_ready( param );
2423             }
2424             hevc_specific_parameters_update_ptl( param, &sps.ptl );
2425             param->min_spatial_segmentation_idc = LSMASH_MIN( param->min_spatial_segmentation_idc, sps.vui.min_spatial_segmentation_idc );
2426             param->chromaFormat                 = sps.chroma_format_idc;
2427             param->bitDepthLumaMinus8           = sps.bit_depth_luma_minus8;
2428             param->bitDepthChromaMinus8         = sps.bit_depth_chroma_minus8;
2429             param->numTemporalLayers            = LSMASH_MAX( param->numTemporalLayers, sps.max_sub_layers_minus1 + 1 );
2430             param->temporalIdNested            &= sps.temporal_id_nesting_flag;
2431             /* Check type of constant frame rate. */
2432             if( param->constantFrameRate )
2433             {
2434                 int cfr;
2435                 if( param->constantFrameRate == 2 )
2436                 {
2437                     cfr = 1;
2438                     for( uint8_t i = 0; i <= sps.max_sub_layers_minus1; i++ )
2439                         cfr &= sps.vui.hrd.fixed_pic_rate_general_flag[i];
2440                 }
2441                 else
2442                     cfr = 0;
2443                 if( cfr )
2444                     param->constantFrameRate = 2;
2445                 else
2446                 {
2447                     for( uint8_t i = 0; i <= sps.max_sub_layers_minus1; i++ )
2448                         cfr |= sps.vui.hrd.fixed_pic_rate_general_flag[i];
2449                     param->constantFrameRate = cfr;
2450                 }
2451             }
2452 #if 0
2453             /* FIXME: probably, we can get average frame rate according to C.3.3 Picture output. */
2454             if( param->constantFrameRate )
2455             {
2456                 uint64_t interval = 0;
2457                 for( uint8_t i = 0; i <= sps.max_sub_layers_minus1; i++ )
2458                     interval += sps.vui.num_units_in_tick * sps.vui.hrd.elemental_duration_in_tc_minus1[i];
2459                 uint64_t frame_rate;
2460                 if( interval )
2461                     frame_rate = ((256 * (2 - sps.vui.field_seq_flag) * (uint64_t)sps.vui.time_scale)
2462                                *  (sps.max_sub_layers_minus1 + 1)) / interval;
2463                 else
2464                     frame_rate = 0;
2465                 if( frame_rate != param->avgFrameRate && param->avgFrameRate )
2466                     param->constantFrameRate = 0;
2467                 param->avgFrameRate = frame_rate;
2468             }
2469 #endif
2470         }
2471         else
2472         {
2473             hevc_pps_t pps;
2474             if( (err = hevc_parse_pps_minimally( bits, &pps, rbsp_buffer,
2475                                                  ps_data   + HEVC_MIN_NALU_HEADER_LENGTH,
2476                                                  ps_length - HEVC_MIN_NALU_HEADER_LENGTH )) < 0 )
2477                 goto fail;
2478             uint8_t parallelismType = 0;
2479 #if 1   /* Replace 1 with 0 if parallelismType shall be set to 0 when min_spatial_segmentation_idc equal to 0. */
2480 
2481             if( pps.entropy_coding_sync_enabled_flag )
2482                 parallelismType = pps.tiles_enabled_flag ? 0 : 3;
2483             else if( pps.tiles_enabled_flag )
2484                 parallelismType = 2;
2485             else
2486                 parallelismType = 1;
2487 #else
2488             /* Parse SPS and check the value of min_spatial_segmentation_idc is equal to zero or not.
2489              * If the value is not equal to zero, update parallelismType appropriately.
2490              * If corresponding SPS is not found, set 0 to parallelismType. */
2491             entry = hevc_get_ps_entry_from_param( param, HEVC_DCR_NALU_TYPE_SPS, pps.seq_parameter_set_id );
2492             if( entry && entry->data )
2493             {
2494                 ps = (isom_dcr_ps_entry_t *)entry->data;
2495                 lsmash_bits_t *sps_bits = lsmash_bits_adhoc_create();
2496                 if( !sps_bits )
2497                 {
2498                     err = LSMASH_ERR_MEMORY_ALLOC;
2499                     goto fail;
2500                 }
2501                 uint8_t *sps_rbsp_buffer = lsmash_malloc( ps->nalUnitLength );
2502                 if( !sps_rbsp_buffer )
2503                 {
2504                     lsmash_bits_adhoc_cleanup( sps_bits );
2505                     err = LSMASH_ERR_MEMORY_ALLOC;
2506                     goto fail;
2507                 }
2508                 hevc_sps_t sps;
2509                 if( hevc_parse_sps_minimally( sps_bits, &sps, sps_rbsp_buffer,
2510                                               ps->nalUnit       + HEVC_MIN_NALU_HEADER_LENGTH,
2511                                               ps->nalUnitLength - HEVC_MIN_NALU_HEADER_LENGTH ) == 0 )
2512                 {
2513                     if( sps.vui.min_spatial_segmentation_idc )
2514                     {
2515                         if( pps.entropy_coding_sync_enabled_flag )
2516                             parallelismType = pps.tiles_enabled_flag ? 0 : 3;
2517                         else if( pps.tiles_enabled_flag )
2518                             parallelismType = 2;
2519                         else
2520                             parallelismType = 1;
2521                     }
2522                     else
2523                         parallelismType = 0;
2524                 }
2525                 lsmash_bits_adhoc_cleanup( sps_bits );
2526                 lsmash_free( sps_rbsp_buffer );
2527             }
2528 #endif
2529             if( ps_count == 1 )
2530                 param->parallelismType = parallelismType;
2531             else if( param->parallelismType != parallelismType )
2532                 param->parallelismType = 0;
2533         }
2534     }
2535     if( invoke_reorder )
2536         /* Add a new parameter set in order of ascending parameter set identifier. */
2537         hevc_reorder_parameter_set_ascending_id( param, ps_type, ps_list, ps_id );
2538     err = 0;
2539     goto clean;
2540 fail:
2541     ps = (isom_dcr_ps_entry_t *)lsmash_list_get_entry_data( ps_list, ps_list->entry_count );
2542     if( ps )
2543         ps->unused = 1;
2544 clean:
2545     lsmash_bits_adhoc_cleanup( bits );
2546     lsmash_free( rbsp_buffer );
2547     return err;
2548 }
2549 
hevc_try_to_append_dcr_nalu(hevc_info_t * info,lsmash_hevc_dcr_nalu_type ps_type,void * _ps_data,uint32_t ps_length)2550 int hevc_try_to_append_dcr_nalu
2551 (
2552     hevc_info_t              *info,
2553     lsmash_hevc_dcr_nalu_type ps_type,
2554     void                     *_ps_data,
2555     uint32_t                  ps_length
2556 )
2557 {
2558     uint8_t *ps_data = _ps_data;
2559     lsmash_dcr_nalu_appendable ret = lsmash_check_hevc_dcr_nalu_appendable( &info->hvcC_param, ps_type, ps_data, ps_length );
2560     lsmash_hevc_specific_parameters_t *param;
2561     switch( ret )
2562     {
2563         case DCR_NALU_APPEND_ERROR                     :    /* Error */
2564             return LSMASH_ERR_NAMELESS;
2565         case DCR_NALU_APPEND_NEW_DCR_REQUIRED          :    /* Mulitiple sample description is needed. */
2566         case DCR_NALU_APPEND_NEW_SAMPLE_ENTRY_REQUIRED :    /* Mulitiple sample description is needed. */
2567             param = &info->hvcC_param_next;
2568             info->hvcC_pending = 1;
2569             break;
2570         case DCR_NALU_APPEND_POSSIBLE :                     /* Appendable */
2571             param = info->hvcC_pending ? &info->hvcC_param_next : &info->hvcC_param;
2572             break;
2573         default :   /* No need to append */
2574             return DCR_NALU_APPEND_DUPLICATED;
2575     }
2576     int err;
2577     switch( ps_type )
2578     {
2579         case HEVC_DCR_NALU_TYPE_VPS :
2580             if( (err = hevc_parse_vps( info, info->buffer.rbsp,
2581                                        ps_data   + HEVC_MIN_NALU_HEADER_LENGTH,
2582                                        ps_length - HEVC_MIN_NALU_HEADER_LENGTH )) < 0 )
2583                 return err;
2584             break;
2585         case HEVC_DCR_NALU_TYPE_SPS :
2586             if( (err = hevc_parse_sps( info, info->buffer.rbsp,
2587                                        ps_data   + HEVC_MIN_NALU_HEADER_LENGTH,
2588                                        ps_length - HEVC_MIN_NALU_HEADER_LENGTH )) < 0 )
2589                 return err;
2590             break;
2591         case HEVC_DCR_NALU_TYPE_PPS :
2592             if( (err = hevc_parse_pps( info, info->buffer.rbsp,
2593                                        ps_data   + HEVC_MIN_NALU_HEADER_LENGTH,
2594                                        ps_length - HEVC_MIN_NALU_HEADER_LENGTH )) < 0 )
2595                 return err;
2596             break;
2597         default :
2598             break;
2599     }
2600     return lsmash_append_hevc_dcr_nalu( param, ps_type, ps_data, ps_length );
2601 }
2602 
hevc_move_dcr_nalu_entry(lsmash_hevc_specific_parameters_t * dst_data,lsmash_hevc_specific_parameters_t * src_data,lsmash_hevc_dcr_nalu_type ps_type)2603 static int hevc_move_dcr_nalu_entry
2604 (
2605     lsmash_hevc_specific_parameters_t *dst_data,
2606     lsmash_hevc_specific_parameters_t *src_data,
2607     lsmash_hevc_dcr_nalu_type          ps_type
2608 )
2609 {
2610     lsmash_entry_list_t *src_ps_list = hevc_get_parameter_set_list( src_data, ps_type );
2611     lsmash_entry_list_t *dst_ps_list = hevc_get_parameter_set_list( dst_data, ps_type );
2612     assert( src_ps_list && dst_ps_list );
2613     for( lsmash_entry_t *src_entry = src_ps_list->head; src_entry; src_entry = src_entry->next )
2614     {
2615         isom_dcr_ps_entry_t *src_ps = (isom_dcr_ps_entry_t *)src_entry->data;
2616         if( !src_ps )
2617             continue;
2618         uint8_t src_ps_id;
2619         int err;
2620         if( (err = hevc_get_ps_id( src_ps->nalUnit       + HEVC_MIN_NALU_HEADER_LENGTH,
2621                                    src_ps->nalUnitLength - HEVC_MIN_NALU_HEADER_LENGTH,
2622                                    &src_ps_id, ps_type )) < 0 )
2623             return err;
2624         lsmash_entry_t *dst_entry;
2625         for( dst_entry = dst_ps_list->head; dst_entry; dst_entry = dst_entry->next )
2626         {
2627             isom_dcr_ps_entry_t *dst_ps = (isom_dcr_ps_entry_t *)dst_entry->data;
2628             if( !dst_ps )
2629                 continue;
2630             uint8_t dst_ps_id;
2631             if( (err = hevc_get_ps_id( dst_ps->nalUnit       + HEVC_MIN_NALU_HEADER_LENGTH,
2632                                        dst_ps->nalUnitLength - HEVC_MIN_NALU_HEADER_LENGTH,
2633                                        &dst_ps_id, ps_type )) < 0 )
2634                 return err;
2635             if( dst_ps_id == src_ps_id )
2636             {
2637                 /* Replace the old parameter set with the new one. */
2638                 assert( dst_entry->data != src_entry->data );
2639                 isom_remove_dcr_ps( dst_ps );
2640                 dst_entry->data = src_entry->data;
2641                 src_entry->data = NULL;
2642                 break;
2643             }
2644         }
2645         if( !dst_entry )
2646         {
2647             /* Move the parameter set. */
2648             if( lsmash_list_add_entry( dst_ps_list, src_ps ) < 0 )
2649                 return LSMASH_ERR_MEMORY_ALLOC;
2650             src_entry->data = NULL;
2651         }
2652     }
2653     return 0;
2654 }
2655 
hevc_move_pending_hvcC_param(hevc_info_t * info)2656 int hevc_move_pending_hvcC_param
2657 (
2658     hevc_info_t *info
2659 )
2660 {
2661     assert( info );
2662     if( !info->hvcC_pending )
2663         return 0;
2664     /* Mark 'unused' on parameter sets within the decoder configuration record. */
2665     for( int i = 0; i < HEVC_DCR_NALU_TYPE_NUM; i++ )
2666     {
2667         lsmash_entry_list_t *ps_list = hevc_get_parameter_set_list( &info->hvcC_param, i );
2668         assert( ps_list );
2669         for( lsmash_entry_t *entry = ps_list->head; entry; entry = entry->next )
2670         {
2671             isom_dcr_ps_entry_t *ps = (isom_dcr_ps_entry_t *)entry->data;
2672             if( !ps )
2673                 continue;
2674             ps->unused = 1;
2675         }
2676     }
2677     /* Move the new parameter sets. */
2678     int err;
2679     if( (err = hevc_move_dcr_nalu_entry( &info->hvcC_param, &info->hvcC_param_next, HEVC_DCR_NALU_TYPE_VPS        )) < 0
2680      || (err = hevc_move_dcr_nalu_entry( &info->hvcC_param, &info->hvcC_param_next, HEVC_DCR_NALU_TYPE_SPS        )) < 0
2681      || (err = hevc_move_dcr_nalu_entry( &info->hvcC_param, &info->hvcC_param_next, HEVC_DCR_NALU_TYPE_PPS        )) < 0
2682      || (err = hevc_move_dcr_nalu_entry( &info->hvcC_param, &info->hvcC_param_next, HEVC_DCR_NALU_TYPE_PREFIX_SEI )) < 0
2683      || (err = hevc_move_dcr_nalu_entry( &info->hvcC_param, &info->hvcC_param_next, HEVC_DCR_NALU_TYPE_SUFFIX_SEI )) < 0 )
2684         return err;
2685     /* Move to the pending. */
2686     lsmash_hevc_parameter_arrays_t *parameter_arrays = info->hvcC_param.parameter_arrays; /* Back up parameter arrays. */
2687     info->hvcC_param                  = info->hvcC_param_next;
2688     info->hvcC_param.parameter_arrays = parameter_arrays;
2689     /* No pending hvcC. */
2690     hevc_deallocate_parameter_arrays( &info->hvcC_param_next );
2691     uint8_t lengthSizeMinusOne = info->hvcC_param_next.lengthSizeMinusOne;
2692     memset( &info->hvcC_param_next, 0, sizeof(lsmash_hevc_specific_parameters_t) );
2693     info->hvcC_param_next.lengthSizeMinusOne = lengthSizeMinusOne;
2694     info->hvcC_pending = 0;
2695     return 0;
2696 }
2697 
lsmash_set_hevc_array_completeness(lsmash_hevc_specific_parameters_t * param,lsmash_hevc_dcr_nalu_type ps_type,int array_completeness)2698 int lsmash_set_hevc_array_completeness
2699 (
2700     lsmash_hevc_specific_parameters_t *param,
2701     lsmash_hevc_dcr_nalu_type          ps_type,
2702     int                                array_completeness
2703 )
2704 {
2705     if( hevc_alloc_parameter_arrays_if_needed( param ) < 0 )
2706         return LSMASH_ERR_MEMORY_ALLOC;
2707     hevc_parameter_array_t *ps_array = hevc_get_parameter_set_array( param, ps_type );
2708     if( !ps_array )
2709         return LSMASH_ERR_FUNCTION_PARAM;
2710     ps_array->array_completeness = array_completeness;
2711     return 0;
2712 }
2713 
lsmash_get_hevc_array_completeness(lsmash_hevc_specific_parameters_t * param,lsmash_hevc_dcr_nalu_type ps_type,int * array_completeness)2714 int lsmash_get_hevc_array_completeness
2715 (
2716     lsmash_hevc_specific_parameters_t *param,
2717     lsmash_hevc_dcr_nalu_type          ps_type,
2718     int                               *array_completeness
2719 )
2720 {
2721     if( hevc_alloc_parameter_arrays_if_needed( param ) < 0 )
2722         return LSMASH_ERR_MEMORY_ALLOC;
2723     hevc_parameter_array_t *ps_array = hevc_get_parameter_set_array( param, ps_type );
2724     if( !ps_array )
2725         return LSMASH_ERR_FUNCTION_PARAM;
2726     *array_completeness = ps_array->array_completeness;
2727     return 0;
2728 }
2729 
hevc_parse_succeeded(hevc_info_t * info,lsmash_hevc_specific_parameters_t * param)2730 static int hevc_parse_succeeded
2731 (
2732     hevc_info_t                       *info,
2733     lsmash_hevc_specific_parameters_t *param
2734 )
2735 {
2736     int ret;
2737     if( info->vps.present
2738      && info->sps.present
2739      && info->pps.present )
2740     {
2741         *param = info->hvcC_param;
2742         /* Avoid freeing parameter sets. */
2743         info->hvcC_param.parameter_arrays = NULL;
2744         ret = 0;
2745     }
2746     else
2747         ret = LSMASH_ERR_INVALID_DATA;
2748     hevc_cleanup_parser( info );
2749     return ret;
2750 }
2751 
hevc_parse_failed(hevc_info_t * info,int ret)2752 static inline int hevc_parse_failed
2753 (
2754     hevc_info_t *info,
2755     int          ret
2756 )
2757 {
2758     hevc_cleanup_parser( info );
2759     return ret;
2760 }
2761 
lsmash_setup_hevc_specific_parameters_from_access_unit(lsmash_hevc_specific_parameters_t * param,uint8_t * data,uint32_t data_length)2762 int lsmash_setup_hevc_specific_parameters_from_access_unit
2763 (
2764     lsmash_hevc_specific_parameters_t *param,
2765     uint8_t                           *data,
2766     uint32_t                           data_length
2767 )
2768 {
2769     if( !param || !data || data_length == 0 )
2770         return LSMASH_ERR_FUNCTION_PARAM;
2771     hevc_info_t *info = &(hevc_info_t){ { 0 } };
2772     lsmash_bs_t *bs   = &(lsmash_bs_t){ 0 };
2773     int err = lsmash_bs_set_empty_stream( bs, data, data_length );
2774     if( err < 0 )
2775         return err;
2776     uint64_t sc_head_pos = nalu_find_first_start_code( bs );
2777     if( sc_head_pos == NALU_NO_START_CODE_FOUND )
2778         return LSMASH_ERR_INVALID_DATA;
2779     else if( sc_head_pos == NALU_IO_ERROR )
2780         return LSMASH_ERR_IO;
2781     if( (err = hevc_setup_parser( info, 1 )) < 0 )
2782         return hevc_parse_failed( info, err );
2783     hevc_stream_buffer_t *sb    = &info->buffer;
2784     hevc_slice_info_t    *slice = &info->slice;
2785     while( 1 )
2786     {
2787         hevc_nalu_header_t nuh;
2788         uint64_t start_code_length;
2789         uint64_t trailing_zero_bytes;
2790         uint64_t nalu_length = hevc_find_next_start_code( bs, &nuh, &start_code_length, &trailing_zero_bytes );
2791         if( nalu_length == NALU_NO_START_CODE_FOUND )
2792             /* For the last NALU. This NALU already has been parsed. */
2793             return hevc_parse_succeeded( info, param );
2794         uint8_t  nalu_type        = nuh.nal_unit_type;
2795         uint64_t next_sc_head_pos = sc_head_pos
2796                                   + start_code_length
2797                                   + nalu_length
2798                                   + trailing_zero_bytes;
2799         if( nalu_type == HEVC_NALU_TYPE_FD )
2800         {
2801             /* We don't support streams with both filler and HRD yet. Otherwise, just skip filler. */
2802             if( info->sps.vui.hrd.present )
2803                 return hevc_parse_failed( info, LSMASH_ERR_PATCH_WELCOME );
2804         }
2805         else if( nalu_type <= HEVC_NALU_TYPE_RASL_R
2806              || (nalu_type >= HEVC_NALU_TYPE_BLA_W_LP && nalu_type <= HEVC_NALU_TYPE_CRA)
2807              || (nalu_type >= HEVC_NALU_TYPE_VPS      && nalu_type <= HEVC_NALU_TYPE_SUFFIX_SEI) )
2808         {
2809             /* Increase the buffer if needed. */
2810             uint64_t possible_au_length = NALU_DEFAULT_NALU_LENGTH_SIZE + nalu_length;
2811             if( sb->bank->buffer_size < possible_au_length
2812              && (err = hevc_supplement_buffer( sb, NULL, 2 * possible_au_length )) < 0 )
2813                 return hevc_parse_failed( info, err );
2814             /* Get the EBSP of the current NALU here. */
2815             uint8_t *nalu = lsmash_bs_get_buffer_data( bs ) + start_code_length;
2816             if( nalu_type <= HEVC_NALU_TYPE_RSV_VCL31 )
2817             {
2818                 /* VCL NALU (slice) */
2819                 hevc_slice_info_t prev_slice = *slice;
2820                 if( (err = hevc_parse_slice_segment_header( info, &nuh, sb->rbsp, nalu + nuh.length, nalu_length - nuh.length )) < 0 )
2821                     return hevc_parse_failed( info, err );
2822                 if( prev_slice.present )
2823                 {
2824                     /* Check whether the AU that contains the previous VCL NALU completed or not. */
2825                     if( hevc_find_au_delimit_by_slice_info( info, slice, &prev_slice ) )
2826                         /* The current NALU is the first VCL NALU of the primary coded picture of a new AU.
2827                          * Therefore, the previous slice belongs to that new AU. */
2828                         return hevc_parse_succeeded( info, param );
2829                 }
2830                 slice->present = 1;
2831             }
2832             else
2833             {
2834                 if( hevc_find_au_delimit_by_nalu_type( nalu_type, info->prev_nalu_type ) )
2835                     /* The last slice belongs to the AU you want at this time. */
2836                     return hevc_parse_succeeded( info, param );
2837                 switch( nalu_type )
2838                 {
2839                     case HEVC_NALU_TYPE_VPS :
2840                         if( (err = hevc_try_to_append_dcr_nalu( info, HEVC_DCR_NALU_TYPE_VPS, nalu, nalu_length )) < 0 )
2841                             return hevc_parse_failed( info, err );
2842                         break;
2843                     case HEVC_NALU_TYPE_SPS :
2844                         if( (err = hevc_try_to_append_dcr_nalu( info, HEVC_DCR_NALU_TYPE_SPS, nalu, nalu_length )) < 0 )
2845                             return hevc_parse_failed( info, err );
2846                         break;
2847                     case HEVC_NALU_TYPE_PPS :
2848                         if( (err = hevc_try_to_append_dcr_nalu( info, HEVC_DCR_NALU_TYPE_PPS, nalu, nalu_length )) < 0 )
2849                             return hevc_parse_failed( info, err );
2850                         break;
2851                     default :
2852                         break;
2853                 }
2854             }
2855         }
2856         /* Move to the first byte of the next start code. */
2857         info->prev_nalu_type = nalu_type;
2858         if( lsmash_bs_read_seek( bs, next_sc_head_pos, SEEK_SET ) != next_sc_head_pos )
2859             return hevc_parse_failed( info, LSMASH_ERR_NAMELESS );
2860         /* Check if no more data to read from the stream. */
2861         if( !lsmash_bs_is_end( bs, NALU_SHORT_START_CODE_LENGTH ) )
2862             sc_head_pos = next_sc_head_pos;
2863         else
2864             return hevc_parse_succeeded( info, param );
2865     }
2866 }
2867 
hevc_construct_specific_parameters(lsmash_codec_specific_t * dst,lsmash_codec_specific_t * src)2868 int hevc_construct_specific_parameters
2869 (
2870     lsmash_codec_specific_t *dst,
2871     lsmash_codec_specific_t *src
2872 )
2873 {
2874     assert( dst && dst->data.structured && src && src->data.unstructured );
2875     if( src->size < ISOM_BASEBOX_COMMON_SIZE + 7 )
2876         return LSMASH_ERR_INVALID_DATA;
2877     lsmash_hevc_specific_parameters_t *param = (lsmash_hevc_specific_parameters_t *)dst->data.structured;
2878     uint8_t *data = src->data.unstructured;
2879     uint64_t size = LSMASH_GET_BE32( data );
2880     data += ISOM_BASEBOX_COMMON_SIZE;
2881     if( size == 1 )
2882     {
2883         size = LSMASH_GET_BE64( data );
2884         data += 8;
2885     }
2886     if( size != src->size )
2887         return LSMASH_ERR_INVALID_DATA;
2888     if( hevc_alloc_parameter_arrays_if_needed( param ) < 0 )
2889         return LSMASH_ERR_MEMORY_ALLOC;
2890     lsmash_bs_t *bs = lsmash_bs_create();
2891     if( !bs )
2892         return LSMASH_ERR_MEMORY_ALLOC;
2893     int err = lsmash_bs_import_data( bs, data, src->size - (data - src->data.unstructured) );
2894     if( err < 0 )
2895         goto fail;
2896     if( lsmash_bs_get_byte( bs ) != HVCC_CONFIGURATION_VERSION )
2897     {
2898         err = LSMASH_ERR_INVALID_DATA;
2899         goto fail;  /* We don't support configurationVersion other than HVCC_CONFIGURATION_VERSION. */
2900     }
2901     uint8_t temp8 = lsmash_bs_get_byte( bs );
2902     param->general_profile_space               = (temp8 >> 6) & 0x03;
2903     param->general_tier_flag                   = (temp8 >> 5) & 0x01;
2904     param->general_profile_idc                 =  temp8       & 0x1F;
2905     param->general_profile_compatibility_flags = lsmash_bs_get_be32( bs );
2906     uint32_t temp32 = lsmash_bs_get_be32( bs );
2907     uint16_t temp16 = lsmash_bs_get_be16( bs );
2908     param->general_constraint_indicator_flags  = ((uint64_t)temp32 << 16) | temp16;
2909     param->general_level_idc                   = lsmash_bs_get_byte( bs );
2910     param->min_spatial_segmentation_idc        = lsmash_bs_get_be16( bs ) & 0x0FFF;
2911     param->parallelismType                     = lsmash_bs_get_byte( bs ) & 0x03;
2912     param->chromaFormat                        = lsmash_bs_get_byte( bs ) & 0x03;
2913     param->bitDepthLumaMinus8                  = lsmash_bs_get_byte( bs ) & 0x07;
2914     param->bitDepthChromaMinus8                = lsmash_bs_get_byte( bs ) & 0x07;
2915     param->avgFrameRate                        = lsmash_bs_get_be16( bs );
2916     temp8 = lsmash_bs_get_byte( bs );
2917     param->constantFrameRate                   = (temp8 >> 6) & 0x03;
2918     param->numTemporalLayers                   = (temp8 >> 3) & 0x07;
2919     param->temporalIdNested                    = (temp8 >> 2) & 0x01;
2920     param->lengthSizeMinusOne                  =  temp8       & 0x03;
2921     uint8_t numOfArrays                        = lsmash_bs_get_byte( bs );
2922     for( uint8_t i = 0; i < numOfArrays; i++ )
2923     {
2924         hevc_parameter_array_t param_array;
2925         memset( &param_array, 0, sizeof(hevc_parameter_array_t) );
2926         temp8 = lsmash_bs_get_byte( bs );
2927         param_array.array_completeness = (temp8 >> 7) & 0x01;
2928         param_array.NAL_unit_type      =  temp8       & 0x3F;
2929         param_array.list->entry_count  = lsmash_bs_get_be16( bs );
2930         if( param_array.NAL_unit_type == HEVC_NALU_TYPE_VPS
2931          || param_array.NAL_unit_type == HEVC_NALU_TYPE_SPS
2932          || param_array.NAL_unit_type == HEVC_NALU_TYPE_PPS
2933          || param_array.NAL_unit_type == HEVC_NALU_TYPE_PREFIX_SEI
2934          || param_array.NAL_unit_type == HEVC_NALU_TYPE_SUFFIX_SEI )
2935         {
2936             if( (err = nalu_get_dcr_ps( bs, param_array.list, param_array.list->entry_count )) < 0 )
2937                 goto fail;
2938         }
2939         else
2940             for( uint16_t j = 0; j < param_array.list->entry_count; j++ )
2941             {
2942                 uint16_t nalUnitLength = lsmash_bs_get_be16( bs );
2943                 lsmash_bs_skip_bytes( bs, nalUnitLength );  /* nalUnit */
2944             }
2945         switch( param_array.NAL_unit_type )
2946         {
2947             case HEVC_NALU_TYPE_VPS :
2948                 param->parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_VPS] = param_array;
2949                 break;
2950             case HEVC_NALU_TYPE_SPS :
2951                 param->parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_SPS] = param_array;
2952                 break;
2953             case HEVC_NALU_TYPE_PPS :
2954                 param->parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_PPS] = param_array;
2955                 break;
2956             case HEVC_NALU_TYPE_PREFIX_SEI :
2957                 param->parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_PREFIX_SEI] = param_array;
2958                 break;
2959             case HEVC_NALU_TYPE_SUFFIX_SEI :
2960                 param->parameter_arrays->ps_array[HEVC_DCR_NALU_TYPE_SUFFIX_SEI] = param_array;
2961                 break;
2962             default :
2963                 /* Discard unknown NALUs. */
2964                 break;
2965         }
2966     }
2967     lsmash_bs_cleanup( bs );
2968     return 0;
2969 fail:
2970     lsmash_bs_cleanup( bs );
2971     return err;
2972 }
2973 
hevc_print_codec_specific(FILE * fp,lsmash_file_t * file,isom_box_t * box,int level)2974 int hevc_print_codec_specific
2975 (
2976     FILE          *fp,
2977     lsmash_file_t *file,
2978     isom_box_t    *box,
2979     int            level
2980 )
2981 {
2982     assert( box->manager & LSMASH_BINARY_CODED_BOX );
2983     int indent = level;
2984     lsmash_ifprintf( fp, indent++, "[%s: HEVC Configuration Box]\n", isom_4cc2str( box->type.fourcc ) );
2985     lsmash_ifprintf( fp, indent, "position = %"PRIu64"\n", box->pos );
2986     lsmash_ifprintf( fp, indent, "size = %"PRIu64"\n", box->size );
2987     uint8_t     *data   = box->binary;
2988     uint32_t     offset = isom_skip_box_common( &data );
2989     lsmash_bs_t *bs     = lsmash_bs_create();
2990     if( !bs )
2991         return LSMASH_ERR_MEMORY_ALLOC;
2992     int err = lsmash_bs_import_data( bs, data, box->size - offset );
2993     if( err < 0 )
2994     {
2995         lsmash_bs_cleanup( bs );
2996         return err;
2997     }
2998     uint8_t configurationVersion = lsmash_bs_get_byte( bs );
2999     lsmash_ifprintf( fp, indent, "configurationVersion = %"PRIu8"\n",                     configurationVersion );
3000     if( configurationVersion != HVCC_CONFIGURATION_VERSION )
3001     {
3002         lsmash_bs_cleanup( bs );
3003         return 0;
3004     }
3005     uint8_t temp8 = lsmash_bs_get_byte( bs );
3006     lsmash_ifprintf( fp, indent, "general_profile_space = %"PRIu8"\n",                    (temp8 >> 6) & 0x03 );
3007     lsmash_ifprintf( fp, indent, "general_tier_flag = %"PRIu8"\n",                        (temp8 >> 5) & 0x01 );
3008     lsmash_ifprintf( fp, indent, "general_profile_idc = %"PRIu8"\n",                       temp8       & 0x1F );
3009     lsmash_ifprintf( fp, indent, "general_profile_compatibility_flags = 0x%08"PRIx32"\n", lsmash_bs_get_be32( bs ) );
3010     uint32_t temp32 = lsmash_bs_get_be32( bs );
3011     uint16_t temp16 = lsmash_bs_get_be16( bs );
3012     lsmash_ifprintf( fp, indent, "general_constraint_indicator_flags = 0x%012"PRIx64"\n", ((uint64_t)temp32 << 16) | temp16 );
3013     uint8_t general_level_idc = lsmash_bs_get_byte( bs );
3014     lsmash_ifprintf( fp, indent, "general_level_idc = %"PRIu8" (Level %g)\n",             general_level_idc, general_level_idc / 30.0 );
3015     temp16 = lsmash_bs_get_be16( bs );
3016     lsmash_ifprintf( fp, indent, "reserved = 0x%02"PRIx8"\n",                             (temp16 >> 12) & 0x0F );
3017     lsmash_ifprintf( fp, indent, "min_spatial_segmentation_idc = %"PRIu16"\n",             temp16        & 0x0FFF );
3018     temp8 = lsmash_bs_get_byte( bs );
3019     uint8_t parallelismType = temp8 & 0x03;
3020     static const char *parallelism_table[4] =
3021         {
3022             "Mixed types or Unknown",
3023             "Slice based",
3024             "Tile based",
3025             "Entropy coding synchronization based / WPP: Wavefront Parallel Processing"
3026         };
3027     lsmash_ifprintf( fp, indent, "reserved = 0x%02"PRIx8"\n",                             (temp8 >> 2) & 0x3F );
3028     lsmash_ifprintf( fp, indent, "parallelismType = %"PRIu8" (%s)\n",                     parallelismType,
3029                                                                                           parallelism_table[parallelismType] );
3030     temp8 = lsmash_bs_get_byte( bs );
3031     lsmash_ifprintf( fp, indent, "reserved = 0x%02"PRIx8"\n",                             (temp8 >> 2) & 0x3F );
3032     lsmash_ifprintf( fp, indent, "chromaFormat = %"PRIu8"\n",                              temp8       & 0x03 );
3033     temp8 = lsmash_bs_get_byte( bs );
3034     lsmash_ifprintf( fp, indent, "reserved = 0x%02"PRIx8"\n",                             (temp8 >> 3) & 0x1F );
3035     lsmash_ifprintf( fp, indent, "bitDepthLumaMinus8 = %"PRIu8"\n",                        temp8       & 0x07 );
3036     temp8 = lsmash_bs_get_byte( bs );
3037     lsmash_ifprintf( fp, indent, "reserved = 0x%02"PRIx8"\n",                             (temp8 >> 3) & 0x1F );
3038     lsmash_ifprintf( fp, indent, "bitDepthChromaMinus8 = %"PRIu8"\n",                      temp8       & 0x07 );
3039     lsmash_ifprintf( fp, indent, "avgFrameRate = %"PRIu16"\n",                            lsmash_bs_get_be16( bs ) );
3040     temp8 = lsmash_bs_get_byte( bs );
3041     lsmash_ifprintf( fp, indent, "constantFrameRate = %"PRIu8"\n",                        (temp8 >> 6) & 0x03 );
3042     lsmash_ifprintf( fp, indent, "numTemporalLayers = %"PRIu8"\n",                        (temp8 >> 3) & 0x07 );
3043     lsmash_ifprintf( fp, indent, "temporalIdNested = %"PRIu8"\n",                         (temp8 >> 2) & 0x01 );
3044     lsmash_ifprintf( fp, indent, "lengthSizeMinusOne = %"PRIu8"\n",                        temp8       & 0x03 );
3045     uint8_t numOfArrays = lsmash_bs_get_byte( bs );
3046     lsmash_ifprintf( fp, indent, "numOfArrays = %"PRIu8"\n", numOfArrays );
3047     for( uint8_t i = 0; i < numOfArrays; i++ )
3048     {
3049         int array_indent = indent + 1;
3050         lsmash_ifprintf( fp, array_indent++, "array[%"PRIu8"]\n", i );
3051         temp8 = lsmash_bs_get_byte( bs );
3052         lsmash_ifprintf( fp, array_indent, "array_completeness = %"PRIu8"\n", (temp8 >> 7) & 0x01 );
3053         lsmash_ifprintf( fp, array_indent, "reserved = %"PRIu8"\n",           (temp8 >> 6) & 0x01 );
3054         lsmash_ifprintf( fp, array_indent, "NAL_unit_type = %"PRIu8"\n",       temp8       & 0x3F );
3055         uint16_t numNalus = lsmash_bs_get_be16( bs );
3056         lsmash_ifprintf( fp, array_indent, "numNalus = %"PRIu16"\n", numNalus );
3057         for( uint16_t j = 0; j < numNalus; j++ )
3058         {
3059             uint16_t nalUnitLength = lsmash_bs_get_be16( bs );
3060             lsmash_bs_skip_bytes( bs, nalUnitLength );
3061             lsmash_ifprintf( fp, array_indent, "nalUnit[%"PRIu16"]\n", j );
3062             lsmash_ifprintf( fp, array_indent + 1, "nalUnitLength = %"PRIu16"\n", nalUnitLength );
3063         }
3064     }
3065     lsmash_bs_cleanup( bs );
3066     return 0;
3067 }
3068 
hevc_copy_dcr_nalu_array(lsmash_hevc_specific_parameters_t * dst_data,lsmash_hevc_specific_parameters_t * src_data,lsmash_hevc_dcr_nalu_type ps_type)3069 static inline int hevc_copy_dcr_nalu_array
3070 (
3071     lsmash_hevc_specific_parameters_t *dst_data,
3072     lsmash_hevc_specific_parameters_t *src_data,
3073     lsmash_hevc_dcr_nalu_type          ps_type
3074 )
3075 {
3076     hevc_parameter_array_t *src_ps_array = hevc_get_parameter_set_array( src_data, ps_type );
3077     hevc_parameter_array_t *dst_ps_array = hevc_get_parameter_set_array( dst_data, ps_type );
3078     assert( src_ps_array && dst_ps_array );
3079     dst_ps_array->array_completeness = src_ps_array->array_completeness;
3080     dst_ps_array->NAL_unit_type      = src_ps_array->NAL_unit_type;
3081     lsmash_entry_list_t *src_ps_list = src_ps_array->list;
3082     lsmash_entry_list_t *dst_ps_list = dst_ps_array->list;
3083     for( lsmash_entry_t *entry = src_ps_list->head; entry; entry = entry->next )
3084     {
3085         isom_dcr_ps_entry_t *src_ps = (isom_dcr_ps_entry_t *)entry->data;
3086         if( !src_ps || src_ps->unused )
3087             continue;
3088         isom_dcr_ps_entry_t *dst_ps = isom_create_ps_entry( src_ps->nalUnit, src_ps->nalUnitLength );
3089         if( !dst_ps )
3090         {
3091             hevc_deallocate_parameter_arrays( dst_data );
3092             return LSMASH_ERR_MEMORY_ALLOC;
3093         }
3094         if( lsmash_list_add_entry( dst_ps_list, dst_ps ) < 0 )
3095         {
3096             hevc_deallocate_parameter_arrays( dst_data );
3097             isom_remove_dcr_ps( dst_ps );
3098             return LSMASH_ERR_MEMORY_ALLOC;
3099         }
3100     }
3101     return 0;
3102 }
3103 
hevc_copy_codec_specific(lsmash_codec_specific_t * dst,lsmash_codec_specific_t * src)3104 int hevc_copy_codec_specific
3105 (
3106     lsmash_codec_specific_t *dst,
3107     lsmash_codec_specific_t *src
3108 )
3109 {
3110     assert( src && src->format == LSMASH_CODEC_SPECIFIC_FORMAT_STRUCTURED && src->data.structured );
3111     assert( dst && dst->format == LSMASH_CODEC_SPECIFIC_FORMAT_STRUCTURED && dst->data.structured );
3112     lsmash_hevc_specific_parameters_t *src_data = (lsmash_hevc_specific_parameters_t *)src->data.structured;
3113     lsmash_hevc_specific_parameters_t *dst_data = (lsmash_hevc_specific_parameters_t *)dst->data.structured;
3114     hevc_deallocate_parameter_arrays( dst_data );
3115     *dst_data = *src_data;
3116     if( !src_data->parameter_arrays )
3117         return 0;
3118     dst_data->parameter_arrays = hevc_alloc_parameter_arrays();
3119     if( !dst_data->parameter_arrays )
3120         return LSMASH_ERR_MEMORY_ALLOC;
3121     for( int i = 0; i < HEVC_DCR_NALU_TYPE_NUM; i++ )
3122     {
3123         int err = hevc_copy_dcr_nalu_array( dst_data, src_data, (lsmash_hevc_dcr_nalu_type)i );
3124         if( err < 0 )
3125             return err;
3126     }
3127     return 0;
3128 }
3129