packetizer: h264: renamed hrd parameter flag
[vlc.git] / modules / packetizer / h264.c
1 /*****************************************************************************
2  * h264.c: h264/avc video packetizer
3  *****************************************************************************
4  * Copyright (C) 2001, 2002, 2006 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Eric Petit <titer@videolan.org>
9  *          Gildas Bazin <gbazin@videolan.org>
10  *          Derk-Jan Hartman <hartman at videolan dot org>
11  *
12  * This program is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU Lesser General Public License as published by
14  * the Free Software Foundation; either version 2.1 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20  * GNU Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
37 #include <vlc_sout.h>
38 #include <vlc_codec.h>
39 #include <vlc_block.h>
40
41 #include <vlc_block_helper.h>
42 #include <vlc_bits.h>
43 #include "../codec/cc.h"
44 #include "h264_nal.h"
45 #include "hxxx_nal.h"
46 #include "hxxx_common.h"
47 #include "packetizer_helper.h"
48 #include "startcode_helper.h"
49
50 /*****************************************************************************
51  * Module descriptor
52  *****************************************************************************/
53 static int  Open ( vlc_object_t * );
54 static void Close( vlc_object_t * );
55
56 vlc_module_begin ()
57     set_category( CAT_SOUT )
58     set_subcategory( SUBCAT_SOUT_PACKETIZER )
59     set_description( N_("H.264 video packetizer") )
60     set_capability( "packetizer", 50 )
61     set_callbacks( Open, Close )
62 vlc_module_end ()
63
64
65 /****************************************************************************
66  * Local prototypes
67  ****************************************************************************/
68 typedef struct
69 {
70     int i_nal_type;
71     int i_nal_ref_idc;
72
73     int i_frame_type;
74     int i_pic_parameter_set_id;
75     int i_frame_num;
76
77     int i_field_pic_flag;
78     int i_bottom_field_flag;
79
80     int i_idr_pic_id;
81
82     int i_pic_order_cnt_lsb;
83     int i_delta_pic_order_cnt_bottom;
84
85     int i_delta_pic_order_cnt0;
86     int i_delta_pic_order_cnt1;
87 } slice_t;
88
89 struct decoder_sys_t
90 {
91     /* */
92     packetizer_t packetizer;
93
94     /* */
95     bool    b_slice;
96     block_t *p_frame;
97     block_t **pp_frame_last;
98     bool    b_frame_sps;
99     bool    b_frame_pps;
100
101     bool   b_header;
102     bool   b_sps;
103     bool   b_pps;
104     block_t *pp_sps[H264_SPS_MAX];
105     block_t *pp_pps[H264_PPS_MAX];
106     int    i_recovery_frames;  /* -1 = no recovery */
107
108     /* avcC data */
109     uint8_t i_avcC_length_size;
110
111     /* Useful values of the Sequence Parameter Set */
112     int i_log2_max_frame_num;
113     int b_frame_mbs_only;
114     int i_pic_order_cnt_type;
115     int i_delta_pic_order_always_zero_flag;
116     int i_log2_max_pic_order_cnt_lsb;
117
118     /* Value from Picture Parameter Set */
119     int i_pic_order_present_flag;
120
121     /* VUI */
122     bool b_timing_info_present_flag;
123     uint32_t i_num_units_in_tick;
124     uint32_t i_time_scale;
125     bool b_fixed_frame_rate;
126     bool b_pic_struct_present_flag;
127     uint8_t i_pic_struct;
128     bool b_cpb_dpb_delays_present_flag;
129     uint8_t i_cpb_removal_delay_length_minus1;
130     uint8_t i_dpb_output_delay_length_minus1;
131
132     /* Useful values of the Slice Header */
133     slice_t slice;
134
135     /* */
136     bool b_even_frame;
137     mtime_t i_frame_pts;
138     mtime_t i_frame_dts;
139     mtime_t i_prev_pts;
140     mtime_t i_prev_dts;
141
142     /* */
143     uint32_t i_cc_flags;
144     mtime_t i_cc_pts;
145     mtime_t i_cc_dts;
146     cc_data_t cc;
147
148     cc_data_t cc_next;
149 };
150
151 #define BLOCK_FLAG_PRIVATE_AUD (1 << BLOCK_FLAG_PRIVATE_SHIFT)
152
153 static block_t *Packetize( decoder_t *, block_t ** );
154 static block_t *PacketizeAVC1( decoder_t *, block_t ** );
155 static block_t *GetCc( decoder_t *p_dec, bool pb_present[4] );
156 static void PacketizeFlush( decoder_t * );
157
158 static void PacketizeReset( void *p_private, bool b_broken );
159 static block_t *PacketizeParse( void *p_private, bool *pb_ts_used, block_t * );
160 static int PacketizeValidate( void *p_private, block_t * );
161
162 static block_t *ParseNALBlock( decoder_t *, bool *pb_ts_used, block_t * );
163
164 static block_t *OutputPicture( decoder_t *p_dec );
165 static void PutSPS( decoder_t *p_dec, block_t *p_frag );
166 static void PutPPS( decoder_t *p_dec, block_t *p_frag );
167 static bool ParseSlice( decoder_t *p_dec, bool *pb_new_picture, slice_t *p_slice,
168                         int i_nal_ref_idc, int i_nal_type, const block_t *p_frag );
169 static void ParseSei( decoder_t *, block_t * );
170
171
172 static const uint8_t p_h264_startcode[3] = { 0x00, 0x00, 0x01 };
173
174 /*****************************************************************************
175  * Open: probe the packetizer and return score
176  * When opening after demux, the packetizer is only loaded AFTER the decoder
177  * That means that what you set in fmt_out is ignored by the decoder in this special case
178  *****************************************************************************/
179 static int Open( vlc_object_t *p_this )
180 {
181     decoder_t     *p_dec = (decoder_t*)p_this;
182     decoder_sys_t *p_sys;
183     int i;
184
185     const bool b_avc = (p_dec->fmt_in.i_original_fourcc == VLC_FOURCC( 'a', 'v', 'c', '1' ));
186
187     if( p_dec->fmt_in.i_codec != VLC_CODEC_H264 )
188         return VLC_EGENERIC;
189     if( b_avc && p_dec->fmt_in.i_extra < 7 )
190         return VLC_EGENERIC;
191
192     /* Allocate the memory needed to store the decoder's structure */
193     if( ( p_dec->p_sys = p_sys = malloc( sizeof(decoder_sys_t) ) ) == NULL )
194     {
195         return VLC_ENOMEM;
196     }
197
198     packetizer_Init( &p_sys->packetizer,
199                      p_h264_startcode, sizeof(p_h264_startcode), startcode_FindAnnexB,
200                      p_h264_startcode, 1, 5,
201                      PacketizeReset, PacketizeParse, PacketizeValidate, p_dec );
202
203     p_sys->b_slice = false;
204     p_sys->p_frame = NULL;
205     p_sys->pp_frame_last = &p_sys->p_frame;
206     p_sys->b_frame_sps = false;
207     p_sys->b_frame_pps = false;
208
209     p_sys->b_header= false;
210     p_sys->b_sps   = false;
211     p_sys->b_pps   = false;
212     for( i = 0; i < H264_SPS_MAX; i++ )
213         p_sys->pp_sps[i] = NULL;
214     for( i = 0; i < H264_PPS_MAX; i++ )
215         p_sys->pp_pps[i] = NULL;
216     p_sys->i_recovery_frames = -1;
217
218     p_sys->slice.i_nal_type = -1;
219     p_sys->slice.i_nal_ref_idc = -1;
220     p_sys->slice.i_idr_pic_id = -1;
221     p_sys->slice.i_frame_num = -1;
222     p_sys->slice.i_frame_type = 0;
223     p_sys->slice.i_pic_parameter_set_id = -1;
224     p_sys->slice.i_field_pic_flag = 0;
225     p_sys->slice.i_bottom_field_flag = -1;
226     p_sys->slice.i_pic_order_cnt_lsb = -1;
227     p_sys->slice.i_delta_pic_order_cnt_bottom = -1;
228
229     p_sys->b_timing_info_present_flag = false;
230     p_sys->b_pic_struct_present_flag = false;
231     p_sys->b_cpb_dpb_delays_present_flag = false;
232     p_sys->i_cpb_removal_delay_length_minus1 = 0;
233     p_sys->i_dpb_output_delay_length_minus1 = 0;
234
235     p_sys->b_even_frame = false;
236     p_sys->i_frame_dts = VLC_TS_INVALID;
237     p_sys->i_frame_pts = VLC_TS_INVALID;
238     p_sys->i_prev_dts = VLC_TS_INVALID;
239     p_sys->i_prev_pts = VLC_TS_INVALID;
240
241     /* Setup properties */
242     es_format_Copy( &p_dec->fmt_out, &p_dec->fmt_in );
243     p_dec->fmt_out.i_codec = VLC_CODEC_H264;
244     p_dec->fmt_out.b_packetized = true;
245
246     if( b_avc )
247     {
248         /* This type of stream is produced by mp4 and matroska
249          * when we want to store it in another streamformat, you need to convert
250          * The fmt_in.p_extra should ALWAYS contain the avcC
251          * The fmt_out.p_extra should contain all the SPS and PPS with 4 byte startcodes */
252         if( h264_isavcC( p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra ) )
253         {
254             free( p_dec->fmt_out.p_extra );
255             size_t i_size;
256             p_dec->fmt_out.p_extra = h264_avcC_to_AnnexB_NAL( p_dec->fmt_in.p_extra,
257                                                               p_dec->fmt_in.i_extra,
258                                                              &i_size,
259                                                              &p_sys->i_avcC_length_size );
260             p_dec->fmt_out.i_extra = i_size;
261             p_sys->b_header = !!p_dec->fmt_out.i_extra;
262
263             if(!p_dec->fmt_out.p_extra)
264             {
265                 msg_Err( p_dec, "Invalid AVC extradata");
266                 return VLC_EGENERIC;
267             }
268         }
269         else
270         {
271             msg_Err( p_dec, "Invalid or missing AVC extradata");
272             return VLC_EGENERIC;
273         }
274
275         /* Set callback */
276         p_dec->pf_packetize = PacketizeAVC1;
277     }
278     else
279     {
280         /* This type of stream contains data with 3 of 4 byte startcodes
281          * The fmt_in.p_extra MAY contain SPS/PPS with 4 byte startcodes
282          * The fmt_out.p_extra should be the same */
283
284         /* Set callback */
285         p_dec->pf_packetize = Packetize;
286     }
287
288     /* */
289     if( p_dec->fmt_out.i_extra > 0 )
290     {
291         packetizer_Header( &p_sys->packetizer,
292                            p_dec->fmt_out.p_extra, p_dec->fmt_out.i_extra );
293     }
294
295     if( b_avc )
296     {
297         if( !p_sys->b_sps || !p_sys->b_pps )
298         {
299             msg_Err( p_dec, "Invalid or missing SPS %d or PPS %d in AVC extradata",
300                      p_sys->b_sps, p_sys->b_pps );
301             return VLC_EGENERIC;
302         }
303
304         msg_Dbg( p_dec, "Packetizer fed with AVC, nal length size=%d",
305                          p_sys->i_avcC_length_size );
306     }
307
308     /* CC are the same for H264/AVC in T35 sections (ETSI TS 101 154)  */
309     p_dec->pf_get_cc = GetCc;
310     p_dec->pf_flush = PacketizeFlush;
311
312     /* */
313     p_sys->i_cc_pts = VLC_TS_INVALID;
314     p_sys->i_cc_dts = VLC_TS_INVALID;
315     p_sys->i_cc_flags = 0;
316     cc_Init( &p_sys->cc );
317     cc_Init( &p_sys->cc_next );
318
319     return VLC_SUCCESS;
320 }
321
322 /*****************************************************************************
323  * Close: clean up the packetizer
324  *****************************************************************************/
325 static void Close( vlc_object_t *p_this )
326 {
327     decoder_t *p_dec = (decoder_t*)p_this;
328     decoder_sys_t *p_sys = p_dec->p_sys;
329     int i;
330
331     if( p_sys->p_frame )
332         block_ChainRelease( p_sys->p_frame );
333     for( i = 0; i < H264_SPS_MAX; i++ )
334     {
335         if( p_sys->pp_sps[i] )
336             block_Release( p_sys->pp_sps[i] );
337     }
338     for( i = 0; i < H264_PPS_MAX; i++ )
339     {
340         if( p_sys->pp_pps[i] )
341             block_Release( p_sys->pp_pps[i] );
342     }
343     packetizer_Clean( &p_sys->packetizer );
344
345     cc_Exit( &p_sys->cc_next );
346     cc_Exit( &p_sys->cc );
347
348     free( p_sys );
349 }
350
351 static void PacketizeFlush( decoder_t *p_dec )
352 {
353     decoder_sys_t *p_sys = p_dec->p_sys;
354
355     packetizer_Flush( &p_sys->packetizer );
356 }
357
358 /****************************************************************************
359  * Packetize: the whole thing
360  * Search for the startcodes 3 or more bytes
361  * Feed ParseNALBlock ALWAYS with 4 byte startcode prepended NALs
362  ****************************************************************************/
363 static block_t *Packetize( decoder_t *p_dec, block_t **pp_block )
364 {
365     decoder_sys_t *p_sys = p_dec->p_sys;
366
367     return packetizer_Packetize( &p_sys->packetizer, pp_block );
368 }
369
370 /****************************************************************************
371  * PacketizeAVC1: Takes VCL blocks of data and creates annexe B type NAL stream
372  * Will always use 4 byte 0 0 0 1 startcodes
373  * Will prepend a SPS and PPS before each keyframe
374  ****************************************************************************/
375 static block_t *PacketizeAVC1( decoder_t *p_dec, block_t **pp_block )
376 {
377     decoder_sys_t *p_sys = p_dec->p_sys;
378
379     return PacketizeXXC1( p_dec, p_sys->i_avcC_length_size,
380                           pp_block, ParseNALBlock );
381 }
382
383 /*****************************************************************************
384  * GetCc:
385  *****************************************************************************/
386 static block_t *GetCc( decoder_t *p_dec, bool pb_present[4] )
387 {
388     decoder_sys_t *p_sys = p_dec->p_sys;
389     block_t *p_cc;
390
391     for( int i = 0; i < 4; i++ )
392         pb_present[i] = p_sys->cc.pb_present[i];
393
394     if( p_sys->cc.i_data <= 0 )
395         return NULL;
396
397     p_cc = block_Alloc( p_sys->cc.i_data);
398     if( p_cc )
399     {
400         memcpy( p_cc->p_buffer, p_sys->cc.p_data, p_sys->cc.i_data );
401         p_cc->i_dts =
402         p_cc->i_pts = p_sys->cc.b_reorder ? p_sys->i_cc_pts : p_sys->i_cc_dts;
403         p_cc->i_flags = ( p_sys->cc.b_reorder  ? p_sys->i_cc_flags : BLOCK_FLAG_TYPE_P ) & BLOCK_FLAG_TYPE_MASK;
404     }
405     cc_Flush( &p_sys->cc );
406     return p_cc;
407 }
408
409 /****************************************************************************
410  * Helpers
411  ****************************************************************************/
412 static void PacketizeReset( void *p_private, bool b_broken )
413 {
414     decoder_t *p_dec = p_private;
415     decoder_sys_t *p_sys = p_dec->p_sys;
416
417     if( b_broken )
418     {
419         if( p_sys->p_frame )
420             block_ChainRelease( p_sys->p_frame );
421         p_sys->p_frame = NULL;
422         p_sys->pp_frame_last = &p_sys->p_frame;
423         p_sys->b_frame_sps = false;
424         p_sys->b_frame_pps = false;
425         p_sys->slice.i_frame_type = 0;
426         p_sys->b_slice = false;
427     }
428     p_sys->i_frame_pts = VLC_TS_INVALID;
429     p_sys->i_frame_dts = VLC_TS_INVALID;
430     p_sys->i_prev_dts = VLC_TS_INVALID;
431     p_sys->i_prev_pts = VLC_TS_INVALID;
432     p_sys->b_even_frame = false;
433 }
434 static block_t *PacketizeParse( void *p_private, bool *pb_ts_used, block_t *p_block )
435 {
436     decoder_t *p_dec = p_private;
437
438     /* Remove trailing 0 bytes */
439     while( p_block->i_buffer > 5 && p_block->p_buffer[p_block->i_buffer-1] == 0x00 )
440         p_block->i_buffer--;
441
442     return ParseNALBlock( p_dec, pb_ts_used, p_block );
443 }
444 static int PacketizeValidate( void *p_private, block_t *p_au )
445 {
446     VLC_UNUSED(p_private);
447     VLC_UNUSED(p_au);
448     return VLC_SUCCESS;
449 }
450
451 /*****************************************************************************
452  * ParseNALBlock: parses annexB type NALs
453  * All p_frag blocks are required to start with 0 0 0 1 4-byte startcode
454  *****************************************************************************/
455 static block_t *ParseNALBlock( decoder_t *p_dec, bool *pb_ts_used, block_t *p_frag )
456 {
457     decoder_sys_t *p_sys = p_dec->p_sys;
458     block_t *p_pic = NULL;
459
460     const int i_nal_ref_idc = (p_frag->p_buffer[4] >> 5)&0x03;
461     const int i_nal_type = p_frag->p_buffer[4]&0x1f;
462     const mtime_t i_frag_dts = p_frag->i_dts;
463     const mtime_t i_frag_pts = p_frag->i_pts;
464
465     if( p_sys->b_slice && ( !p_sys->b_sps || !p_sys->b_pps ) )
466     {
467         block_ChainRelease( p_sys->p_frame );
468         msg_Warn( p_dec, "waiting for SPS/PPS" );
469
470         /* Reset context */
471         p_sys->slice.i_frame_type = 0;
472         p_sys->p_frame = NULL;
473         p_sys->pp_frame_last = &p_sys->p_frame;
474         p_sys->b_frame_sps = false;
475         p_sys->b_frame_pps = false;
476         p_sys->b_slice = false;
477         cc_Flush( &p_sys->cc_next );
478     }
479
480     if( ( !p_sys->b_sps || !p_sys->b_pps ) &&
481         i_nal_type >= H264_NAL_SLICE && i_nal_type <= H264_NAL_SLICE_IDR )
482     {
483         p_sys->b_slice = true;
484         /* Fragment will be discarded later on */
485     }
486     else if( i_nal_type >= H264_NAL_SLICE && i_nal_type <= H264_NAL_SLICE_IDR )
487     {
488         slice_t slice;
489         bool  b_new_picture;
490
491         if(ParseSlice( p_dec, &b_new_picture, &slice, i_nal_ref_idc, i_nal_type, p_frag ))
492         {
493             /* */
494             if( b_new_picture && p_sys->b_slice )
495                 p_pic = OutputPicture( p_dec );
496
497             /* */
498             p_sys->slice = slice;
499             p_sys->b_slice = true;
500         }
501     }
502     else if( i_nal_type == H264_NAL_SPS )
503     {
504         if( p_sys->b_slice )
505             p_pic = OutputPicture( p_dec );
506         p_sys->b_frame_sps = true;
507
508         PutSPS( p_dec, p_frag );
509
510         /* Do not append the SPS because we will insert it on keyframes */
511         p_frag = NULL;
512     }
513     else if( i_nal_type == H264_NAL_PPS )
514     {
515         if( p_sys->b_slice )
516             p_pic = OutputPicture( p_dec );
517         p_sys->b_frame_pps = true;
518
519         PutPPS( p_dec, p_frag );
520
521         /* Do not append the PPS because we will insert it on keyframes */
522         p_frag = NULL;
523     }
524     else if( i_nal_type == H264_NAL_AU_DELIMITER ||
525              i_nal_type == H264_NAL_SEI ||
526              ( i_nal_type >= H264_NAL_PREFIX && i_nal_type <= H264_NAL_RESERVED_18 ) )
527     {
528         if( p_sys->b_slice )
529             p_pic = OutputPicture( p_dec );
530
531         /* Parse SEI for CC support */
532         if( i_nal_type == H264_NAL_SEI )
533         {
534             ParseSei( p_dec, p_frag );
535         }
536         else if( i_nal_type == H264_NAL_AU_DELIMITER )
537         {
538             if( p_sys->p_frame && (p_sys->p_frame->i_flags & BLOCK_FLAG_PRIVATE_AUD) )
539             {
540                 block_Release( p_frag );
541                 p_frag = NULL;
542             }
543             else
544             {
545                 p_frag->i_flags |= BLOCK_FLAG_PRIVATE_AUD;
546             }
547         }
548     }
549
550     /* Append the block */
551     if( p_frag )
552         block_ChainLastAppend( &p_sys->pp_frame_last, p_frag );
553
554     *pb_ts_used = false;
555     if( p_sys->i_frame_dts <= VLC_TS_INVALID &&
556         p_sys->i_frame_pts <= VLC_TS_INVALID )
557     {
558         p_sys->i_frame_dts = i_frag_dts;
559         p_sys->i_frame_pts = i_frag_pts;
560         *pb_ts_used = true;
561     }
562     return p_pic;
563 }
564
565 static block_t *OutputPicture( decoder_t *p_dec )
566 {
567     decoder_sys_t *p_sys = p_dec->p_sys;
568     block_t *p_pic;
569
570     if ( !p_sys->b_header && p_sys->i_recovery_frames != -1 )
571     {
572         if( p_sys->i_recovery_frames == 0 )
573         {
574             msg_Dbg( p_dec, "Recovery from SEI recovery point complete" );
575             p_sys->b_header = true;
576         }
577         --p_sys->i_recovery_frames;
578     }
579
580     if( !p_sys->b_header && p_sys->i_recovery_frames == -1 &&
581          p_sys->slice.i_frame_type != BLOCK_FLAG_TYPE_I)
582         return NULL;
583
584     const bool b_sps_pps_i = p_sys->slice.i_frame_type == BLOCK_FLAG_TYPE_I &&
585                              p_sys->b_sps &&
586                              p_sys->b_pps;
587     if( b_sps_pps_i || p_sys->b_frame_sps || p_sys->b_frame_pps )
588     {
589         block_t *p_head = NULL;
590         if( p_sys->p_frame->i_flags & BLOCK_FLAG_PRIVATE_AUD )
591         {
592             p_head = p_sys->p_frame;
593             p_sys->p_frame = p_sys->p_frame->p_next;
594             if( p_sys->p_frame == NULL )
595                 p_sys->pp_frame_last = &p_sys->p_frame;
596             p_head->p_next = NULL;
597         }
598
599         block_t *p_list = NULL;
600         block_t **pp_list_tail = &p_list;
601         for( int i = 0; i < H264_SPS_MAX && (b_sps_pps_i || p_sys->b_frame_sps); i++ )
602         {
603             if( p_sys->pp_sps[i] )
604                 block_ChainLastAppend( &pp_list_tail, block_Duplicate( p_sys->pp_sps[i] ) );
605         }
606         for( int i = 0; i < H264_PPS_MAX && (b_sps_pps_i || p_sys->b_frame_pps); i++ )
607         {
608             if( p_sys->pp_pps[i] )
609                 block_ChainLastAppend( &pp_list_tail, block_Duplicate( p_sys->pp_pps[i] ) );
610         }
611         if( b_sps_pps_i && p_list )
612             p_sys->b_header = true;
613
614         if( p_list )
615             block_ChainAppend( &p_head, p_list );
616
617         if( p_sys->p_frame )
618             block_ChainAppend( &p_head, p_sys->p_frame );
619
620         p_pic = block_ChainGather( p_head );
621     }
622     else
623     {
624         p_pic = block_ChainGather( p_sys->p_frame );
625     }
626
627     unsigned i_num_clock_ts = 1;
628     if( p_sys->b_frame_mbs_only == 0 && p_sys->b_pic_struct_present_flag )
629     {
630         if( p_sys->i_pic_struct < 9 )
631         {
632             const uint8_t rgi_numclock[9] = { 1, 1, 1, 2, 2, 3, 3, 2, 3 };
633             i_num_clock_ts = rgi_numclock[ p_sys->i_pic_struct ];
634         }
635     }
636
637     if( p_sys->i_time_scale )
638     {
639         p_pic->i_length = CLOCK_FREQ * i_num_clock_ts *
640                           p_sys->i_num_units_in_tick / p_sys->i_time_scale;
641     }
642
643     mtime_t i_field_pts = VLC_TS_INVALID;
644     if( p_sys->b_frame_mbs_only == 0 && p_sys->b_pic_struct_present_flag )
645     {
646         switch( p_sys->i_pic_struct )
647         {
648         /* Top and Bottom field slices */
649         case 1:
650         case 2:
651             if( !p_sys->b_even_frame )
652             {
653                 p_pic->i_flags |= (p_sys->i_pic_struct == 1) ? BLOCK_FLAG_TOP_FIELD_FIRST
654                                                              : BLOCK_FLAG_BOTTOM_FIELD_FIRST;
655             }
656             else if( p_pic->i_pts <= VLC_TS_INVALID && p_sys->i_prev_pts > VLC_TS_INVALID && p_pic->i_length )
657             {
658                 /* interpolate from even frame */
659                 i_field_pts = p_sys->i_prev_pts + p_pic->i_length;
660             }
661
662             p_sys->b_even_frame = !p_sys->b_even_frame;
663             break;
664         /* Each of the following slices contains multiple fields */
665         case 3:
666             p_pic->i_flags |= BLOCK_FLAG_TOP_FIELD_FIRST;
667             p_sys->b_even_frame = false;
668             break;
669         case 4:
670             p_pic->i_flags |= BLOCK_FLAG_BOTTOM_FIELD_FIRST;
671             p_sys->b_even_frame = false;
672             break;
673         case 5:
674             p_pic->i_flags |= BLOCK_FLAG_TOP_FIELD_FIRST;
675             break;
676         case 6:
677             p_pic->i_flags |= BLOCK_FLAG_BOTTOM_FIELD_FIRST;
678             break;
679         default:
680             p_sys->b_even_frame = false;
681             break;
682         }
683     }
684
685     /* set dts/pts to current block timestamps */
686     p_pic->i_dts = p_sys->i_frame_dts;
687     p_pic->i_pts = p_sys->i_frame_pts;
688
689     /* Fixup missing timestamps after split (multiple AU/block)*/
690     if( p_pic->i_dts <= VLC_TS_INVALID )
691         p_pic->i_dts = p_sys->i_prev_dts;
692
693     /* PTS Fixup, interlaced fields (multiple AU/block) */
694     if( p_pic->i_pts <= VLC_TS_INVALID && i_field_pts != VLC_TS_INVALID )
695         p_pic->i_pts = i_field_pts;
696
697     /* save for next pic fixups */
698     p_sys->i_prev_dts = p_pic->i_dts;
699     p_sys->i_prev_pts = p_pic->i_pts;
700
701     p_pic->i_flags |= p_sys->slice.i_frame_type;
702     p_pic->i_flags &= ~BLOCK_FLAG_PRIVATE_AUD;
703     if( !p_sys->b_header )
704         p_pic->i_flags |= BLOCK_FLAG_PREROLL;
705
706     /* reset after output */
707     p_sys->i_frame_dts = VLC_TS_INVALID;
708     p_sys->i_frame_pts = VLC_TS_INVALID;
709     p_sys->slice.i_frame_type = 0;
710     p_sys->p_frame = NULL;
711     p_sys->pp_frame_last = &p_sys->p_frame;
712     p_sys->b_frame_sps = false;
713     p_sys->b_frame_pps = false;
714     p_sys->b_slice = false;
715
716     /* CC */
717     p_sys->i_cc_pts = p_pic->i_pts;
718     p_sys->i_cc_dts = p_pic->i_dts;
719     p_sys->i_cc_flags = p_pic->i_flags;
720
721     p_sys->cc = p_sys->cc_next;
722     cc_Flush( &p_sys->cc_next );
723
724     return p_pic;
725 }
726
727 static void PutSPS( decoder_t *p_dec, block_t *p_frag )
728 {
729     decoder_sys_t *p_sys = p_dec->p_sys;
730
731     const uint8_t *p_buffer = p_frag->p_buffer;
732     size_t i_buffer = p_frag->i_buffer;
733
734     if( !hxxx_strip_AnnexB_startcode( &p_buffer, &i_buffer ) )
735         return;
736
737     h264_sequence_parameter_set_t *p_sps = h264_decode_sps( p_buffer, i_buffer, true );
738     if( !p_sps )
739     {
740         msg_Warn( p_dec, "invalid SPS" );
741         block_Release( p_frag );
742         return;
743     }
744
745     p_dec->fmt_out.i_profile = p_sps->i_profile;
746     p_dec->fmt_out.i_level = p_sps->i_level;
747
748     (void) h264_get_picture_size( p_sps, &p_dec->fmt_out.video.i_width,
749                                          &p_dec->fmt_out.video.i_height,
750                                          &p_dec->fmt_out.video.i_visible_width,
751                                          &p_dec->fmt_out.video.i_visible_height );
752
753     if( p_sps->vui.i_sar_num != 0 && p_sps->vui.i_sar_den != 0 )
754     {
755         p_dec->fmt_out.video.i_sar_num = p_sps->vui.i_sar_num;
756         p_dec->fmt_out.video.i_sar_den = p_sps->vui.i_sar_den;
757     }
758
759     p_sys->i_log2_max_frame_num = p_sps->i_log2_max_frame_num;
760     p_sys->b_frame_mbs_only = p_sps->frame_mbs_only_flag;
761     p_sys->i_pic_order_cnt_type = p_sps->i_pic_order_cnt_type;
762     p_sys->i_delta_pic_order_always_zero_flag = p_sps->i_delta_pic_order_always_zero_flag;
763     p_sys->i_log2_max_pic_order_cnt_lsb = p_sps->i_log2_max_pic_order_cnt_lsb;
764
765     if( p_sps->vui.b_valid )
766     {
767         p_sys->b_timing_info_present_flag = p_sps->vui.b_timing_info_present_flag;
768         p_sys->i_num_units_in_tick =  p_sps->vui.i_num_units_in_tick;
769         p_sys->i_time_scale = p_sps->vui.i_time_scale;
770         p_sys->b_fixed_frame_rate = p_sps->vui.b_fixed_frame_rate;
771         p_sys->b_pic_struct_present_flag = p_sps->vui.b_pic_struct_present_flag;
772         p_sys->b_cpb_dpb_delays_present_flag = p_sps->vui.b_hrd_parameters_present_flag;
773         p_sys->i_cpb_removal_delay_length_minus1 = p_sps->vui.i_cpb_removal_delay_length_minus1;
774         p_sys->i_dpb_output_delay_length_minus1 = p_sps->vui.i_dpb_output_delay_length_minus1;
775
776         if( p_sps->vui.b_fixed_frame_rate && !p_dec->fmt_out.video.i_frame_rate_base )
777         {
778             p_dec->fmt_out.video.i_frame_rate_base = p_sps->vui.i_num_units_in_tick;
779             p_dec->fmt_out.video.i_frame_rate = p_sps->vui.i_time_scale;
780         }
781         p_dec->fmt_out.video.primaries =
782             hxxx_colour_primaries_to_vlc( p_sps->vui.colour.i_colour_primaries );
783         p_dec->fmt_out.video.transfer =
784             hxxx_transfer_characteristics_to_vlc( p_sps->vui.colour.i_transfer_characteristics );
785         p_dec->fmt_out.video.space =
786             hxxx_matrix_coeffs_to_vlc( p_sps->vui.colour.i_matrix_coefficients );
787         p_dec->fmt_out.video.b_color_range_full = p_sps->vui.colour.b_full_range;
788     }
789     /* We have a new SPS */
790     if( !p_sys->b_sps )
791         msg_Dbg( p_dec, "found NAL_SPS (sps_id=%d)", p_sps->i_id );
792     p_sys->b_sps = true;
793
794     if( p_sys->pp_sps[p_sps->i_id] )
795         block_Release( p_sys->pp_sps[p_sps->i_id] );
796     p_sys->pp_sps[p_sps->i_id] = p_frag;
797
798     h264_release_sps( p_sps );
799 }
800
801 static void PutPPS( decoder_t *p_dec, block_t *p_frag )
802 {
803     decoder_sys_t *p_sys = p_dec->p_sys;
804     const uint8_t *p_buffer = p_frag->p_buffer;
805     size_t i_buffer = p_frag->i_buffer;
806
807     if( !hxxx_strip_AnnexB_startcode( &p_buffer, &i_buffer ) )
808         return;
809
810     h264_picture_parameter_set_t *p_pps = h264_decode_pps( p_buffer, i_buffer, true );
811     if( !p_pps )
812     {
813         msg_Warn( p_dec, "invalid PPS" );
814         block_Release( p_frag );
815         return;
816     }
817     p_sys->i_pic_order_present_flag = p_pps->i_pic_order_present_flag;
818
819     /* We have a new PPS */
820     if( !p_sys->b_pps )
821         msg_Dbg( p_dec, "found NAL_PPS (pps_id=%d sps_id=%d)", p_pps->i_id, p_pps->i_sps_id );
822     p_sys->b_pps = true;
823
824     if( p_sys->pp_pps[p_pps->i_id] )
825         block_Release( p_sys->pp_pps[p_pps->i_id] );
826     p_sys->pp_pps[p_pps->i_id] = p_frag;
827
828     h264_release_pps( p_pps );
829 }
830
831 static bool ParseSlice( decoder_t *p_dec, bool *pb_new_picture, slice_t *p_slice,
832                         int i_nal_ref_idc, int i_nal_type, const block_t *p_frag )
833 {
834     decoder_sys_t *p_sys = p_dec->p_sys;
835     int i_slice_type;
836     slice_t slice;
837     bs_t s;
838     unsigned i_bitflow = 0;
839
840     const uint8_t *p_stripped = p_frag->p_buffer;
841     size_t i_stripped = p_frag->i_buffer;
842
843     if( !hxxx_strip_AnnexB_startcode( &p_stripped, &i_stripped ) || i_stripped < 2 )
844         return false;
845
846     bs_init( &s, p_stripped, i_stripped );
847     s.p_fwpriv = &i_bitflow;
848     s.pf_forward = hxxx_bsfw_ep3b_to_rbsp;  /* Does the emulated 3bytes conversion to rbsp */
849     bs_skip( &s, 8 ); /* nal unit header */
850
851     /* first_mb_in_slice */
852     /* int i_first_mb = */ bs_read_ue( &s );
853
854     /* slice_type */
855     switch( (i_slice_type = bs_read_ue( &s )) )
856     {
857     case 0: case 5:
858         slice.i_frame_type = BLOCK_FLAG_TYPE_P;
859         break;
860     case 1: case 6:
861         slice.i_frame_type = BLOCK_FLAG_TYPE_B;
862         break;
863     case 2: case 7:
864         slice.i_frame_type = BLOCK_FLAG_TYPE_I;
865         break;
866     case 3: case 8: /* SP */
867         slice.i_frame_type = BLOCK_FLAG_TYPE_P;
868         break;
869     case 4: case 9:
870         slice.i_frame_type = BLOCK_FLAG_TYPE_I;
871         break;
872     default:
873         slice.i_frame_type = 0;
874         break;
875     }
876
877     /* */
878     slice.i_nal_type = i_nal_type;
879     slice.i_nal_ref_idc = i_nal_ref_idc;
880
881     slice.i_pic_parameter_set_id = bs_read_ue( &s );
882     slice.i_frame_num = bs_read( &s, p_sys->i_log2_max_frame_num + 4 );
883
884     slice.i_field_pic_flag = 0;
885     slice.i_bottom_field_flag = -1;
886     if( !p_sys->b_frame_mbs_only )
887     {
888         /* field_pic_flag */
889         slice.i_field_pic_flag = bs_read( &s, 1 );
890         if( slice.i_field_pic_flag )
891             slice.i_bottom_field_flag = bs_read( &s, 1 );
892     }
893
894     slice.i_idr_pic_id = p_sys->slice.i_idr_pic_id;
895     if( slice.i_nal_type == H264_NAL_SLICE_IDR )
896         slice.i_idr_pic_id = bs_read_ue( &s );
897
898     slice.i_pic_order_cnt_lsb = -1;
899     slice.i_delta_pic_order_cnt_bottom = -1;
900     slice.i_delta_pic_order_cnt0 = 0;
901     slice.i_delta_pic_order_cnt1 = 0;
902     if( p_sys->i_pic_order_cnt_type == 0 )
903     {
904         slice.i_pic_order_cnt_lsb = bs_read( &s, p_sys->i_log2_max_pic_order_cnt_lsb + 4 );
905         if( p_sys->i_pic_order_present_flag && !slice.i_field_pic_flag )
906             slice.i_delta_pic_order_cnt_bottom = bs_read_se( &s );
907     }
908     else if( (p_sys->i_pic_order_cnt_type == 1) &&
909              (!p_sys->i_delta_pic_order_always_zero_flag) )
910     {
911         slice.i_delta_pic_order_cnt0 = bs_read_se( &s );
912         if( p_sys->i_pic_order_present_flag && !slice.i_field_pic_flag )
913             slice.i_delta_pic_order_cnt1 = bs_read_se( &s );
914     }
915
916     /* Detection of the first VCL NAL unit of a primary coded picture
917      * (cf. 7.4.1.2.4) */
918     bool b_pic = false;
919     if( slice.i_frame_num != p_sys->slice.i_frame_num ||
920         slice.i_pic_parameter_set_id != p_sys->slice.i_pic_parameter_set_id ||
921         slice.i_field_pic_flag != p_sys->slice.i_field_pic_flag ||
922         !slice.i_nal_ref_idc != !p_sys->slice.i_nal_ref_idc )
923         b_pic = true;
924     if( (slice.i_bottom_field_flag != -1) &&
925         (p_sys->slice.i_bottom_field_flag != -1) &&
926         (slice.i_bottom_field_flag != p_sys->slice.i_bottom_field_flag) )
927         b_pic = true;
928     if( p_sys->i_pic_order_cnt_type == 0 &&
929         ( slice.i_pic_order_cnt_lsb != p_sys->slice.i_pic_order_cnt_lsb ||
930           slice.i_delta_pic_order_cnt_bottom != p_sys->slice.i_delta_pic_order_cnt_bottom ) )
931         b_pic = true;
932     else if( p_sys->i_pic_order_cnt_type == 1 &&
933              ( slice.i_delta_pic_order_cnt0 != p_sys->slice.i_delta_pic_order_cnt0 ||
934                slice.i_delta_pic_order_cnt1 != p_sys->slice.i_delta_pic_order_cnt1 ) )
935         b_pic = true;
936     if( ( slice.i_nal_type == H264_NAL_SLICE_IDR || p_sys->slice.i_nal_type == H264_NAL_SLICE_IDR ) &&
937         ( slice.i_nal_type != p_sys->slice.i_nal_type || slice.i_idr_pic_id != p_sys->slice.i_idr_pic_id ) )
938             b_pic = true;
939
940     /* */
941     *pb_new_picture = b_pic;
942     *p_slice = slice;
943
944     return true;
945 }
946
947 static void ParseSei( decoder_t *p_dec, block_t *p_frag )
948 {
949     decoder_sys_t *p_sys = p_dec->p_sys;
950     bs_t s;
951     unsigned i_bitflow = 0;
952
953     const uint8_t *p_stripped = p_frag->p_buffer;
954     size_t i_stripped = p_frag->i_buffer;
955
956     if( !hxxx_strip_AnnexB_startcode( &p_stripped, &i_stripped ) || i_stripped < 2 )
957         return;
958
959     bs_init( &s, p_stripped, i_stripped );
960     s.p_fwpriv = &i_bitflow;
961     s.pf_forward = hxxx_bsfw_ep3b_to_rbsp;  /* Does the emulated 3bytes conversion to rbsp */
962     bs_skip( &s, 8 ); /* nal unit header */
963
964     while( bs_remain( &s ) >= 8 && bs_aligned( &s ) )
965     {
966         /* Read type */
967         unsigned i_type = 0;
968         while( bs_remain( &s ) >= 8 )
969         {
970             const uint8_t i_byte = bs_read( &s, 8 );
971             i_type += i_byte;
972             if( i_byte != 0xff )
973                 break;
974         }
975
976         /* Read size */
977         unsigned i_size = 0;
978         while( bs_remain( &s ) >= 8 )
979         {
980             const uint8_t i_byte = bs_read( &s, 8 );
981             i_size += i_byte;
982             if( i_byte != 0xff )
983                 break;
984         }
985
986         /* Check room */
987         if( bs_remain( &s ) < 8 )
988             break;
989
990         /* Save start offset */
991         const unsigned i_start_bit_pos = bs_pos( &s );
992
993         switch( i_type )
994         {
995             /* Look for pic timing */
996             case H264_SEI_PIC_TIMING:
997             {
998                 if( p_sys->b_cpb_dpb_delays_present_flag )
999                 {
1000                     bs_read( &s, p_sys->i_cpb_removal_delay_length_minus1 + 1 );
1001                     bs_read( &s, p_sys->i_dpb_output_delay_length_minus1 + 1 );
1002                 }
1003
1004                 if( p_sys->b_pic_struct_present_flag )
1005                     p_sys->i_pic_struct = bs_read( &s, 4 );
1006                 /* + unparsed remains */
1007             } break;
1008
1009             /* Look for user_data_registered_itu_t_t35 */
1010             case H264_SEI_USER_DATA_REGISTERED_ITU_T_T35:
1011             {
1012                 /* TS 101 154 Auxiliary Data and H264/AVC video */
1013                 static const uint8_t p_DVB1_data_start_code[] = {
1014                     0xb5, /* United States */
1015                     0x00, 0x31, /* US provider code */
1016                     0x47, 0x41, 0x39, 0x34 /* user identifier */
1017                 };
1018
1019                 static const uint8_t p_DIRECTV_data_start_code[] = {
1020                     0xb5, /* United States */
1021                     0x00, 0x2f, /* US provider code */
1022                     0x03  /* Captions */
1023                 };
1024
1025                 const unsigned i_t35 = i_size;
1026                 uint8_t *p_t35 = malloc( i_t35 );
1027                 if( !p_t35 )
1028                     break;
1029                 for( unsigned i=0; i<i_t35; i++ )
1030                     p_t35[i] = bs_read( &s, 8 );
1031
1032                 /* Check for we have DVB1_data() */
1033                 if( i_t35 >= sizeof(p_DVB1_data_start_code) &&
1034                         !memcmp( p_t35, p_DVB1_data_start_code, sizeof(p_DVB1_data_start_code) ) )
1035                 {
1036                     cc_Extract( &p_sys->cc_next, true, &p_t35[3], i_t35 - 3 );
1037                 } else if( i_t35 >= sizeof(p_DIRECTV_data_start_code) &&
1038                            !memcmp( p_t35, p_DIRECTV_data_start_code, sizeof(p_DIRECTV_data_start_code) ) )
1039                 {
1040                     cc_Extract( &p_sys->cc_next, true, &p_t35[3], i_t35 - 3 );
1041                 }
1042
1043                 free( p_t35 );
1044             } break;
1045
1046             /* Look for SEI recovery point */
1047             case H264_SEI_RECOVERY_POINT:
1048             {
1049                 int i_recovery_frames = bs_read_ue( &s );
1050                 //bool b_exact_match = bs_read( &s, 1 );
1051                 //bool b_broken_link = bs_read( &s, 1 );
1052                 //int i_changing_slice_group = bs_read( &s, 2 );
1053                 if( !p_sys->b_header )
1054                 {
1055                     msg_Dbg( p_dec, "Seen SEI recovery point, %d recovery frames", i_recovery_frames );
1056                     if ( p_sys->i_recovery_frames == -1 || i_recovery_frames < p_sys->i_recovery_frames )
1057                         p_sys->i_recovery_frames = i_recovery_frames;
1058                 }
1059             } break;
1060
1061             default:
1062                 /* Will skip */
1063                 break;
1064         }
1065
1066         const unsigned i_end_bit_pos = bs_pos( &s );
1067         /* Skip unsparsed content */
1068         if( i_end_bit_pos - i_start_bit_pos > i_size * 8 ) /* Something went wrong with _ue reads */
1069             break;
1070         bs_skip( &s, i_size * 8 - ( i_end_bit_pos - i_start_bit_pos ) );
1071     }
1072
1073 }
1074