]> git.sesse.net Git - vlc/blob - modules/packetizer/h264.c
h264: refactor Exp-Golomb reading functions with existing mpeg demuxing code
[vlc] / 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 "packetizer_helper.h"
45 #include "../demux/mpeg/mpeg_parser_helpers.h"
46
47 /*****************************************************************************
48  * Module descriptor
49  *****************************************************************************/
50 static int  Open ( vlc_object_t * );
51 static void Close( vlc_object_t * );
52
53 vlc_module_begin ()
54     set_category( CAT_SOUT )
55     set_subcategory( SUBCAT_SOUT_PACKETIZER )
56     set_description( N_("H.264 video packetizer") )
57     set_capability( "packetizer", 50 )
58     set_callbacks( Open, Close )
59 vlc_module_end ()
60
61
62 /****************************************************************************
63  * Local prototypes
64  ****************************************************************************/
65 typedef struct
66 {
67     int i_nal_type;
68     int i_nal_ref_idc;
69
70     int i_frame_type;
71     int i_pic_parameter_set_id;
72     int i_frame_num;
73
74     int i_field_pic_flag;
75     int i_bottom_field_flag;
76
77     int i_idr_pic_id;
78
79     int i_pic_order_cnt_lsb;
80     int i_delta_pic_order_cnt_bottom;
81
82     int i_delta_pic_order_cnt0;
83     int i_delta_pic_order_cnt1;
84 } slice_t;
85
86 #define SPS_MAX (32)
87 #define PPS_MAX (256)
88 struct decoder_sys_t
89 {
90     /* */
91     packetizer_t packetizer;
92
93     /* */
94     bool    b_slice;
95     block_t *p_frame;
96     bool    b_frame_sps;
97     bool    b_frame_pps;
98
99     bool   b_header;
100     bool   b_sps;
101     bool   b_pps;
102     block_t *pp_sps[SPS_MAX];
103     block_t *pp_pps[PPS_MAX];
104     int    i_recovery_frames;  /* -1 = no recovery */
105
106     /* avcC data */
107     int i_avcC_length_size;
108
109     /* Useful values of the Sequence Parameter Set */
110     int i_log2_max_frame_num;
111     int b_frame_mbs_only;
112     int i_pic_order_cnt_type;
113     int i_delta_pic_order_always_zero_flag;
114     int i_log2_max_pic_order_cnt_lsb;
115
116     /* Value from Picture Parameter Set */
117     int i_pic_order_present_flag;
118
119     /* Useful values of the Slice Header */
120     slice_t slice;
121
122     /* */
123     mtime_t i_frame_pts;
124     mtime_t i_frame_dts;
125
126     /* */
127     uint32_t i_cc_flags;
128     mtime_t i_cc_pts;
129     mtime_t i_cc_dts;
130     cc_data_t cc;
131
132     cc_data_t cc_next;
133 };
134
135 enum nal_unit_type_e
136 {
137     NAL_UNKNOWN = 0,
138     NAL_SLICE   = 1,
139     NAL_SLICE_DPA   = 2,
140     NAL_SLICE_DPB   = 3,
141     NAL_SLICE_DPC   = 4,
142     NAL_SLICE_IDR   = 5,    /* ref_idc != 0 */
143     NAL_SEI         = 6,    /* ref_idc == 0 */
144     NAL_SPS         = 7,
145     NAL_PPS         = 8,
146     NAL_AU_DELIMITER= 9
147     /* ref_idc == 0 for 6,9,10,11,12 */
148 };
149
150 #define BLOCK_FLAG_PRIVATE_AUD (1 << BLOCK_FLAG_PRIVATE_SHIFT)
151
152 static block_t *Packetize( decoder_t *, block_t ** );
153 static block_t *PacketizeAVC1( decoder_t *, block_t ** );
154 static block_t *GetCc( decoder_t *p_dec, bool pb_present[4] );
155
156 static void PacketizeReset( void *p_private, bool b_broken );
157 static block_t *PacketizeParse( void *p_private, bool *pb_ts_used, block_t * );
158 static int PacketizeValidate( void *p_private, block_t * );
159
160 static block_t *ParseNALBlock( decoder_t *, bool *pb_ts_used, block_t * );
161 static block_t *CreateAnnexbNAL( decoder_t *, const uint8_t *p, int );
162
163 static block_t *OutputPicture( decoder_t *p_dec );
164 static void PutSPS( decoder_t *p_dec, block_t *p_frag );
165 static void PutPPS( decoder_t *p_dec, block_t *p_frag );
166 static void ParseSlice( decoder_t *p_dec, bool *pb_new_picture, slice_t *p_slice,
167                         int i_nal_ref_idc, int i_nal_type, const block_t *p_frag );
168 static void ParseSei( decoder_t *, block_t * );
169
170
171 static const uint8_t p_h264_startcode[3] = { 0x00, 0x00, 0x01 };
172
173 /*****************************************************************************
174  * Open: probe the packetizer and return score
175  * When opening after demux, the packetizer is only loaded AFTER the decoder
176  * That means that what you set in fmt_out is ignored by the decoder in this special case
177  *****************************************************************************/
178 static int Open( vlc_object_t *p_this )
179 {
180     decoder_t     *p_dec = (decoder_t*)p_this;
181     decoder_sys_t *p_sys;
182     int i;
183
184     if( p_dec->fmt_in.i_codec != VLC_CODEC_H264 )
185         return VLC_EGENERIC;
186     if( p_dec->fmt_in.i_original_fourcc == VLC_FOURCC( 'a', 'v', 'c', '1') &&
187         p_dec->fmt_in.i_extra < 7 )
188         return VLC_EGENERIC;
189
190     /* Allocate the memory needed to store the decoder's structure */
191     if( ( p_dec->p_sys = p_sys = malloc( sizeof(decoder_sys_t) ) ) == NULL )
192     {
193         return VLC_ENOMEM;
194     }
195
196     packetizer_Init( &p_sys->packetizer,
197                      p_h264_startcode, sizeof(p_h264_startcode),
198                      p_h264_startcode, 1, 5,
199                      PacketizeReset, PacketizeParse, PacketizeValidate, p_dec );
200
201     p_sys->b_slice = false;
202     p_sys->p_frame = NULL;
203     p_sys->b_frame_sps = false;
204     p_sys->b_frame_pps = false;
205
206     p_sys->b_header= false;
207     p_sys->b_sps   = false;
208     p_sys->b_pps   = false;
209     for( i = 0; i < SPS_MAX; i++ )
210         p_sys->pp_sps[i] = NULL;
211     for( i = 0; i < PPS_MAX; i++ )
212         p_sys->pp_pps[i] = NULL;
213     p_sys->i_recovery_frames = -1;
214
215     p_sys->slice.i_nal_type = -1;
216     p_sys->slice.i_nal_ref_idc = -1;
217     p_sys->slice.i_idr_pic_id = -1;
218     p_sys->slice.i_frame_num = -1;
219     p_sys->slice.i_frame_type = 0;
220     p_sys->slice.i_pic_parameter_set_id = -1;
221     p_sys->slice.i_field_pic_flag = 0;
222     p_sys->slice.i_bottom_field_flag = -1;
223     p_sys->slice.i_pic_order_cnt_lsb = -1;
224     p_sys->slice.i_delta_pic_order_cnt_bottom = -1;
225
226     p_sys->i_frame_dts = VLC_TS_INVALID;
227     p_sys->i_frame_pts = VLC_TS_INVALID;
228
229     /* Setup properties */
230     es_format_Copy( &p_dec->fmt_out, &p_dec->fmt_in );
231     p_dec->fmt_out.i_codec = VLC_CODEC_H264;
232
233     if( p_dec->fmt_in.i_original_fourcc == VLC_FOURCC( 'a', 'v', 'c', '1' ) )
234     {
235         /* This type of stream is produced by mp4 and matroska
236          * when we want to store it in another streamformat, you need to convert
237          * The fmt_in.p_extra should ALWAYS contain the avcC
238          * The fmt_out.p_extra should contain all the SPS and PPS with 4 byte startcodes */
239         uint8_t *p = &((uint8_t*)p_dec->fmt_in.p_extra)[4];
240         int i_sps, i_pps;
241         bool b_dummy;
242         int i;
243
244         /* Parse avcC */
245         p_sys->i_avcC_length_size = 1 + ((*p++)&0x03);
246
247         /* Read SPS */
248         i_sps = (*p++)&0x1f;
249         for( i = 0; i < i_sps; i++ )
250         {
251             uint16_t i_length = GetWBE( p ); p += 2;
252             if( i_length >
253                 (uint8_t*)p_dec->fmt_in.p_extra + p_dec->fmt_in.i_extra - p )
254             {
255                 return VLC_EGENERIC;
256             }
257             block_t *p_sps = CreateAnnexbNAL( p_dec, p, i_length );
258             if( !p_sps )
259                 return VLC_EGENERIC;
260             ParseNALBlock( p_dec, &b_dummy, p_sps );
261             p += i_length;
262         }
263         /* Read PPS */
264         i_pps = *p++;
265         for( i = 0; i < i_pps; i++ )
266         {
267             uint16_t i_length = GetWBE( p ); p += 2;
268             if( i_length >
269                 (uint8_t*)p_dec->fmt_in.p_extra + p_dec->fmt_in.i_extra - p )
270             {
271                 return VLC_EGENERIC;
272             }
273             block_t *p_pps = CreateAnnexbNAL( p_dec, p, i_length );
274             if( !p_pps )
275                 return VLC_EGENERIC;
276             ParseNALBlock( p_dec, &b_dummy, p_pps );
277             p += i_length;
278         }
279         msg_Dbg( p_dec, "avcC length size=%d, sps=%d, pps=%d",
280                  p_sys->i_avcC_length_size, i_sps, i_pps );
281
282         if( !p_sys->b_sps || !p_sys->b_pps )
283             return VLC_EGENERIC;
284
285         /* FIXME: FFMPEG isn't happy at all if you leave this */
286         if( p_dec->fmt_out.i_extra > 0 )
287             free( p_dec->fmt_out.p_extra );
288         p_dec->fmt_out.i_extra = 0;
289         p_dec->fmt_out.p_extra = NULL;
290
291         /* Set the new extradata */
292         for( i = 0; i < SPS_MAX; i++ )
293         {
294             if( p_sys->pp_sps[i] )
295                 p_dec->fmt_out.i_extra += p_sys->pp_sps[i]->i_buffer;
296         }
297         for( i = 0; i < PPS_MAX; i++ )
298         {
299             if( p_sys->pp_pps[i] )
300                 p_dec->fmt_out.i_extra += p_sys->pp_pps[i]->i_buffer;
301         }
302         p_dec->fmt_out.p_extra = malloc( p_dec->fmt_out.i_extra );
303         if( p_dec->fmt_out.p_extra )
304         {
305             uint8_t *p_dst = p_dec->fmt_out.p_extra;
306
307             for( i = 0; i < SPS_MAX; i++ )
308             {
309                 if( p_sys->pp_sps[i] )
310                 {
311                     memcpy( p_dst, p_sys->pp_sps[i]->p_buffer, p_sys->pp_sps[i]->i_buffer );
312                     p_dst += p_sys->pp_sps[i]->i_buffer;
313                 }
314             }
315             for( i = 0; i < PPS_MAX; i++ )
316             {
317                 if( p_sys->pp_pps[i] )
318                 {
319                     memcpy( p_dst, p_sys->pp_pps[i]->p_buffer, p_sys->pp_pps[i]->i_buffer );
320                     p_dst += p_sys->pp_pps[i]->i_buffer;
321                 }
322             }
323             p_sys->b_header = true;
324         }
325         else
326         {
327             p_dec->fmt_out.i_extra = 0;
328         }
329
330         /* Set callback */
331         p_dec->pf_packetize = PacketizeAVC1;
332         /* TODO CC ? */
333     }
334     else
335     {
336         /* This type of stream contains data with 3 of 4 byte startcodes
337          * The fmt_in.p_extra MAY contain SPS/PPS with 4 byte startcodes
338          * The fmt_out.p_extra should be the same */
339
340         /* Set callback */
341         p_dec->pf_packetize = Packetize;
342         p_dec->pf_get_cc = GetCc;
343
344         /* */
345         p_sys->i_cc_pts = VLC_TS_INVALID;
346         p_sys->i_cc_dts = VLC_TS_INVALID;
347         p_sys->i_cc_flags = 0;
348         cc_Init( &p_sys->cc );
349         cc_Init( &p_sys->cc_next );
350
351         /* */
352         if( p_dec->fmt_in.i_extra > 0 )
353             packetizer_Header( &p_sys->packetizer,
354                                p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra );
355     }
356
357     return VLC_SUCCESS;
358 }
359
360 /*****************************************************************************
361  * Close: clean up the packetizer
362  *****************************************************************************/
363 static void Close( vlc_object_t *p_this )
364 {
365     decoder_t *p_dec = (decoder_t*)p_this;
366     decoder_sys_t *p_sys = p_dec->p_sys;
367     int i;
368
369     if( p_sys->p_frame )
370         block_ChainRelease( p_sys->p_frame );
371     for( i = 0; i < SPS_MAX; i++ )
372     {
373         if( p_sys->pp_sps[i] )
374             block_Release( p_sys->pp_sps[i] );
375     }
376     for( i = 0; i < PPS_MAX; i++ )
377     {
378         if( p_sys->pp_pps[i] )
379             block_Release( p_sys->pp_pps[i] );
380     }
381     packetizer_Clean( &p_sys->packetizer );
382
383     if( p_dec->pf_get_cc )
384     {
385          cc_Exit( &p_sys->cc_next );
386          cc_Exit( &p_sys->cc );
387     }
388
389     free( p_sys );
390 }
391
392 /****************************************************************************
393  * Packetize: the whole thing
394  * Search for the startcodes 3 or more bytes
395  * Feed ParseNALBlock ALWAYS with 4 byte startcode prepended NALs
396  ****************************************************************************/
397 static block_t *Packetize( decoder_t *p_dec, block_t **pp_block )
398 {
399     decoder_sys_t *p_sys = p_dec->p_sys;
400
401     return packetizer_Packetize( &p_sys->packetizer, pp_block );
402 }
403
404 /****************************************************************************
405  * PacketizeAVC1: Takes VCL blocks of data and creates annexe B type NAL stream
406  * Will always use 4 byte 0 0 0 1 startcodes
407  * Will prepend a SPS and PPS before each keyframe
408  ****************************************************************************/
409 static block_t *PacketizeAVC1( decoder_t *p_dec, block_t **pp_block )
410 {
411     decoder_sys_t *p_sys = p_dec->p_sys;
412     block_t       *p_block;
413     block_t       *p_ret = NULL;
414     uint8_t       *p;
415
416     if( !pp_block || !*pp_block )
417         return NULL;
418     if( (*pp_block)->i_flags&(BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
419     {
420         block_Release( *pp_block );
421         return NULL;
422     }
423
424     p_block = *pp_block;
425     *pp_block = NULL;
426
427     for( p = p_block->p_buffer; p < &p_block->p_buffer[p_block->i_buffer]; )
428     {
429         block_t *p_pic;
430         bool b_dummy;
431         int i_size = 0;
432         int i;
433
434         for( i = 0; i < p_sys->i_avcC_length_size; i++ )
435         {
436             i_size = (i_size << 8) | (*p++);
437         }
438
439         if( i_size <= 0 ||
440             i_size > ( p_block->p_buffer + p_block->i_buffer - p ) )
441         {
442             msg_Err( p_dec, "Broken frame : size %d is too big", i_size );
443             break;
444         }
445
446         block_t *p_part = CreateAnnexbNAL( p_dec, p, i_size );
447         if( !p_part )
448             break;
449
450         p_part->i_dts = p_block->i_dts;
451         p_part->i_pts = p_block->i_pts;
452
453         /* Parse the NAL */
454         if( ( p_pic = ParseNALBlock( p_dec, &b_dummy, p_part ) ) )
455         {
456             block_ChainAppend( &p_ret, p_pic );
457         }
458         p += i_size;
459     }
460     block_Release( p_block );
461
462     return p_ret;
463 }
464
465 /*****************************************************************************
466  * GetCc:
467  *****************************************************************************/
468 static block_t *GetCc( decoder_t *p_dec, bool pb_present[4] )
469 {
470     decoder_sys_t *p_sys = p_dec->p_sys;
471     block_t *p_cc;
472
473     for( int i = 0; i < 4; i++ )
474         pb_present[i] = p_sys->cc.pb_present[i];
475
476     if( p_sys->cc.i_data <= 0 )
477         return NULL;
478
479     p_cc = block_Alloc( p_sys->cc.i_data);
480     if( p_cc )
481     {
482         memcpy( p_cc->p_buffer, p_sys->cc.p_data, p_sys->cc.i_data );
483         p_cc->i_dts =
484         p_cc->i_pts = p_sys->cc.b_reorder ? p_sys->i_cc_pts : p_sys->i_cc_dts;
485         p_cc->i_flags = ( p_sys->cc.b_reorder  ? p_sys->i_cc_flags : BLOCK_FLAG_TYPE_P ) & BLOCK_FLAG_TYPE_MASK;
486     }
487     cc_Flush( &p_sys->cc );
488     return p_cc;
489 }
490
491 /****************************************************************************
492  * Helpers
493  ****************************************************************************/
494 static void PacketizeReset( void *p_private, bool b_broken )
495 {
496     decoder_t *p_dec = p_private;
497     decoder_sys_t *p_sys = p_dec->p_sys;
498
499     if( b_broken )
500     {
501         if( p_sys->p_frame )
502             block_ChainRelease( p_sys->p_frame );
503         p_sys->p_frame = NULL;
504         p_sys->b_frame_sps = false;
505         p_sys->b_frame_pps = false;
506         p_sys->slice.i_frame_type = 0;
507         p_sys->b_slice = false;
508     }
509     p_sys->i_frame_pts = VLC_TS_INVALID;
510     p_sys->i_frame_dts = VLC_TS_INVALID;
511 }
512 static block_t *PacketizeParse( void *p_private, bool *pb_ts_used, block_t *p_block )
513 {
514     decoder_t *p_dec = p_private;
515
516     /* Remove trailing 0 bytes */
517     while( p_block->i_buffer > 5 && p_block->p_buffer[p_block->i_buffer-1] == 0x00 )
518         p_block->i_buffer--;
519
520     return ParseNALBlock( p_dec, pb_ts_used, p_block );
521 }
522 static int PacketizeValidate( void *p_private, block_t *p_au )
523 {
524     VLC_UNUSED(p_private);
525     VLC_UNUSED(p_au);
526     return VLC_SUCCESS;
527 }
528
529 static block_t *CreateAnnexbNAL( decoder_t *p_dec, const uint8_t *p, int i_size )
530 {
531     block_t *p_nal;
532
533     p_nal = block_Alloc( 4 + i_size );
534     if( !p_nal ) return NULL;
535
536     /* Add start code */
537     p_nal->p_buffer[0] = 0x00;
538     p_nal->p_buffer[1] = 0x00;
539     p_nal->p_buffer[2] = 0x00;
540     p_nal->p_buffer[3] = 0x01;
541
542     /* Copy nalu */
543     memcpy( &p_nal->p_buffer[4], p, i_size );
544
545     VLC_UNUSED(p_dec);
546     return p_nal;
547 }
548
549 static void CreateDecodedNAL( uint8_t **pp_ret, int *pi_ret,
550                               const uint8_t *src, int i_src )
551 {
552     const uint8_t *end = &src[i_src];
553     uint8_t *dst = malloc( i_src );
554
555     *pp_ret = dst;
556
557     if( dst )
558     {
559         while( src < end )
560         {
561             if( src < end - 3 && src[0] == 0x00 && src[1] == 0x00 &&
562                 src[2] == 0x03 )
563             {
564                 *dst++ = 0x00;
565                 *dst++ = 0x00;
566
567                 src += 3;
568                 continue;
569             }
570             *dst++ = *src++;
571         }
572     }
573     *pi_ret = dst - *pp_ret;
574 }
575
576 /*****************************************************************************
577  * ParseNALBlock: parses annexB type NALs
578  * All p_frag blocks are required to start with 0 0 0 1 4-byte startcode
579  *****************************************************************************/
580 static block_t *ParseNALBlock( decoder_t *p_dec, bool *pb_ts_used, block_t *p_frag )
581 {
582     decoder_sys_t *p_sys = p_dec->p_sys;
583     block_t *p_pic = NULL;
584
585     const int i_nal_ref_idc = (p_frag->p_buffer[4] >> 5)&0x03;
586     const int i_nal_type = p_frag->p_buffer[4]&0x1f;
587     const mtime_t i_frag_dts = p_frag->i_dts;
588     const mtime_t i_frag_pts = p_frag->i_pts;
589
590     if( p_sys->b_slice && ( !p_sys->b_sps || !p_sys->b_pps ) )
591     {
592         block_ChainRelease( p_sys->p_frame );
593         msg_Warn( p_dec, "waiting for SPS/PPS" );
594
595         /* Reset context */
596         p_sys->slice.i_frame_type = 0;
597         p_sys->p_frame = NULL;
598         p_sys->b_frame_sps = false;
599         p_sys->b_frame_pps = false;
600         p_sys->b_slice = false;
601         cc_Flush( &p_sys->cc_next );
602     }
603
604     if( ( !p_sys->b_sps || !p_sys->b_pps ) &&
605         i_nal_type >= NAL_SLICE && i_nal_type <= NAL_SLICE_IDR )
606     {
607         p_sys->b_slice = true;
608         /* Fragment will be discarded later on */
609     }
610     else if( i_nal_type >= NAL_SLICE && i_nal_type <= NAL_SLICE_IDR )
611     {
612         slice_t slice;
613         bool  b_new_picture;
614
615         ParseSlice( p_dec, &b_new_picture, &slice, i_nal_ref_idc, i_nal_type, p_frag );
616
617         /* */
618         if( b_new_picture && p_sys->b_slice )
619             p_pic = OutputPicture( p_dec );
620
621         /* */
622         p_sys->slice = slice;
623         p_sys->b_slice = true;
624     }
625     else if( i_nal_type == NAL_SPS )
626     {
627         if( p_sys->b_slice )
628             p_pic = OutputPicture( p_dec );
629         p_sys->b_frame_sps = true;
630
631         PutSPS( p_dec, p_frag );
632
633         /* Do not append the SPS because we will insert it on keyframes */
634         p_frag = NULL;
635     }
636     else if( i_nal_type == NAL_PPS )
637     {
638         if( p_sys->b_slice )
639             p_pic = OutputPicture( p_dec );
640         p_sys->b_frame_pps = true;
641
642         PutPPS( p_dec, p_frag );
643
644         /* Do not append the PPS because we will insert it on keyframes */
645         p_frag = NULL;
646     }
647     else if( i_nal_type == NAL_AU_DELIMITER ||
648              i_nal_type == NAL_SEI ||
649              ( i_nal_type >= 13 && i_nal_type <= 18 ) )
650     {
651         if( p_sys->b_slice )
652             p_pic = OutputPicture( p_dec );
653
654         /* Parse SEI for CC support */
655         if( i_nal_type == NAL_SEI )
656         {
657             ParseSei( p_dec, p_frag );
658         }
659         else if( i_nal_type == NAL_AU_DELIMITER )
660         {
661             if( p_sys->p_frame && (p_sys->p_frame->i_flags & BLOCK_FLAG_PRIVATE_AUD) )
662             {
663                 block_Release( p_frag );
664                 p_frag = NULL;
665             }
666             else
667             {
668                 p_frag->i_flags |= BLOCK_FLAG_PRIVATE_AUD;
669             }
670         }
671     }
672
673     /* Append the block */
674     if( p_frag )
675         block_ChainAppend( &p_sys->p_frame, p_frag );
676
677     *pb_ts_used = false;
678     if( p_sys->i_frame_dts <= VLC_TS_INVALID &&
679         p_sys->i_frame_pts <= VLC_TS_INVALID )
680     {
681         p_sys->i_frame_dts = i_frag_dts;
682         p_sys->i_frame_pts = i_frag_pts;
683         *pb_ts_used = true;
684     }
685     return p_pic;
686 }
687
688 static block_t *OutputPicture( decoder_t *p_dec )
689 {
690     decoder_sys_t *p_sys = p_dec->p_sys;
691     block_t *p_pic;
692
693     if ( !p_sys->b_header && p_sys->i_recovery_frames != -1 )
694     {
695         if( p_sys->i_recovery_frames == 0 )
696         {
697             msg_Dbg( p_dec, "Recovery from SEI recovery point complete" );
698             p_sys->b_header = true;
699         }
700         --p_sys->i_recovery_frames;
701     }
702
703     if( !p_sys->b_header && p_sys->i_recovery_frames == -1 &&
704          p_sys->slice.i_frame_type != BLOCK_FLAG_TYPE_I)
705         return NULL;
706
707     const bool b_sps_pps_i = p_sys->slice.i_frame_type == BLOCK_FLAG_TYPE_I &&
708                              p_sys->b_sps &&
709                              p_sys->b_pps;
710     if( b_sps_pps_i || p_sys->b_frame_sps || p_sys->b_frame_pps )
711     {
712         block_t *p_head = NULL;
713         if( p_sys->p_frame->i_flags & BLOCK_FLAG_PRIVATE_AUD )
714         {
715             p_head = p_sys->p_frame;
716             p_sys->p_frame = p_sys->p_frame->p_next;
717         }
718
719         block_t *p_list = NULL;
720         for( int i = 0; i < SPS_MAX && (b_sps_pps_i || p_sys->b_frame_sps); i++ )
721         {
722             if( p_sys->pp_sps[i] )
723                 block_ChainAppend( &p_list, block_Duplicate( p_sys->pp_sps[i] ) );
724         }
725         for( int i = 0; i < PPS_MAX && (b_sps_pps_i || p_sys->b_frame_pps); i++ )
726         {
727             if( p_sys->pp_pps[i] )
728                 block_ChainAppend( &p_list, block_Duplicate( p_sys->pp_pps[i] ) );
729         }
730         if( b_sps_pps_i && p_list )
731             p_sys->b_header = true;
732
733         if( p_head )
734             p_head->p_next = p_list;
735         else
736             p_head = p_list;
737         block_ChainAppend( &p_head, p_sys->p_frame );
738
739         p_pic = block_ChainGather( p_head );
740     }
741     else
742     {
743         p_pic = block_ChainGather( p_sys->p_frame );
744     }
745     p_pic->i_dts = p_sys->i_frame_dts;
746     p_pic->i_pts = p_sys->i_frame_pts;
747     p_pic->i_length = 0;    /* FIXME */
748     p_pic->i_flags |= p_sys->slice.i_frame_type;
749     p_pic->i_flags &= ~BLOCK_FLAG_PRIVATE_AUD;
750     if( !p_sys->b_header )
751         p_pic->i_flags |= BLOCK_FLAG_PREROLL;
752
753     p_sys->slice.i_frame_type = 0;
754     p_sys->p_frame = NULL;
755     p_sys->i_frame_dts = VLC_TS_INVALID;
756     p_sys->i_frame_pts = VLC_TS_INVALID;
757     p_sys->b_frame_sps = false;
758     p_sys->b_frame_pps = false;
759     p_sys->b_slice = false;
760
761     /* CC */
762     p_sys->i_cc_pts = p_pic->i_pts;
763     p_sys->i_cc_dts = p_pic->i_dts;
764     p_sys->i_cc_flags = p_pic->i_flags;
765
766     p_sys->cc = p_sys->cc_next;
767     cc_Flush( &p_sys->cc_next );
768
769     return p_pic;
770 }
771
772 static void PutSPS( decoder_t *p_dec, block_t *p_frag )
773 {
774     decoder_sys_t *p_sys = p_dec->p_sys;
775
776     uint8_t *pb_dec = NULL;
777     int     i_dec = 0;
778     bs_t s;
779     int i_tmp;
780     int i_sps_id;
781
782     CreateDecodedNAL( &pb_dec, &i_dec, &p_frag->p_buffer[5],
783                      p_frag->i_buffer - 5 );
784
785     bs_init( &s, pb_dec, i_dec );
786     int i_profile_idc = bs_read( &s, 8 );
787     p_dec->fmt_out.i_profile = i_profile_idc;
788     /* Skip constraint_set0123, reserved(4) */
789     bs_skip( &s, 1+1+1+1 + 4 );
790     p_dec->fmt_out.i_level = bs_read( &s, 8 );
791     /* sps id */
792     i_sps_id = bs_read_ue( &s );
793     if( i_sps_id >= SPS_MAX || i_sps_id < 0 )
794     {
795         msg_Warn( p_dec, "invalid SPS (sps_id=%d)", i_sps_id );
796         free( pb_dec );
797         block_Release( p_frag );
798         return;
799     }
800
801     if( i_profile_idc == 100 || i_profile_idc == 110 ||
802         i_profile_idc == 122 || i_profile_idc == 244 ||
803         i_profile_idc ==  44 || i_profile_idc ==  83 ||
804         i_profile_idc ==  86 )
805     {
806         /* chroma_format_idc */
807         const int i_chroma_format_idc = bs_read_ue( &s );
808         if( i_chroma_format_idc == 3 )
809             bs_skip( &s, 1 ); /* separate_colour_plane_flag */
810         /* bit_depth_luma_minus8 */
811         bs_read_ue( &s );
812         /* bit_depth_chroma_minus8 */
813         bs_read_ue( &s );
814         /* qpprime_y_zero_transform_bypass_flag */
815         bs_skip( &s, 1 );
816         /* seq_scaling_matrix_present_flag */
817         i_tmp = bs_read( &s, 1 );
818         if( i_tmp )
819         {
820             for( int i = 0; i < ((3 != i_chroma_format_idc) ? 8 : 12); i++ )
821             {
822                 /* seq_scaling_list_present_flag[i] */
823                 i_tmp = bs_read( &s, 1 );
824                 if( !i_tmp )
825                     continue;
826                 const int i_size_of_scaling_list = (i < 6 ) ? 16 : 64;
827                 /* scaling_list (...) */
828                 int i_lastscale = 8;
829                 int i_nextscale = 8;
830                 for( int j = 0; j < i_size_of_scaling_list; j++ )
831                 {
832                     if( i_nextscale != 0 )
833                     {
834                         /* delta_scale */
835                         i_tmp = bs_read_se( &s );
836                         i_nextscale = ( i_lastscale + i_tmp + 256 ) % 256;
837                         /* useDefaultScalingMatrixFlag = ... */
838                     }
839                     /* scalinglist[j] */
840                     i_lastscale = ( i_nextscale == 0 ) ? i_lastscale : i_nextscale;
841                 }
842             }
843         }
844     }
845
846     /* Skip i_log2_max_frame_num */
847     p_sys->i_log2_max_frame_num = bs_read_ue( &s );
848     if( p_sys->i_log2_max_frame_num > 12)
849         p_sys->i_log2_max_frame_num = 12;
850     /* Read poc_type */
851     p_sys->i_pic_order_cnt_type = bs_read_ue( &s );
852     if( p_sys->i_pic_order_cnt_type == 0 )
853     {
854         /* skip i_log2_max_poc_lsb */
855         p_sys->i_log2_max_pic_order_cnt_lsb = bs_read_ue( &s );
856         if( p_sys->i_log2_max_pic_order_cnt_lsb > 12 )
857             p_sys->i_log2_max_pic_order_cnt_lsb = 12;
858     }
859     else if( p_sys->i_pic_order_cnt_type == 1 )
860     {
861         int i_cycle;
862         /* skip b_delta_pic_order_always_zero */
863         p_sys->i_delta_pic_order_always_zero_flag = bs_read( &s, 1 );
864         /* skip i_offset_for_non_ref_pic */
865         bs_read_se( &s );
866         /* skip i_offset_for_top_to_bottom_field */
867         bs_read_se( &s );
868         /* read i_num_ref_frames_in_poc_cycle */
869         i_cycle = bs_read_ue( &s );
870         if( i_cycle > 256 ) i_cycle = 256;
871         while( i_cycle > 0 )
872         {
873             /* skip i_offset_for_ref_frame */
874             bs_read_se(&s );
875             i_cycle--;
876         }
877     }
878     /* i_num_ref_frames */
879     bs_read_ue( &s );
880     /* b_gaps_in_frame_num_value_allowed */
881     bs_skip( &s, 1 );
882
883     /* Read size */
884     p_dec->fmt_out.video.i_width  = 16 * ( bs_read_ue( &s ) + 1 );
885     p_dec->fmt_out.video.i_height = 16 * ( bs_read_ue( &s ) + 1 );
886
887     /* b_frame_mbs_only */
888     p_sys->b_frame_mbs_only = bs_read( &s, 1 );
889     p_dec->fmt_out.video.i_height *=  ( 2 - p_sys->b_frame_mbs_only );
890     if( p_sys->b_frame_mbs_only == 0 )
891     {
892         bs_skip( &s, 1 );
893     }
894     /* b_direct8x8_inference */
895     bs_skip( &s, 1 );
896
897     /* crop */
898     i_tmp = bs_read( &s, 1 );
899     if( i_tmp )
900     {
901         /* left */
902         bs_read_ue( &s );
903         /* right */
904         bs_read_ue( &s );
905         /* top */
906         bs_read_ue( &s );
907         /* bottom */
908         bs_read_ue( &s );
909     }
910
911     /* vui */
912     i_tmp = bs_read( &s, 1 );
913     if( i_tmp )
914     {
915         /* read the aspect ratio part if any */
916         i_tmp = bs_read( &s, 1 );
917         if( i_tmp )
918         {
919             static const struct { int w, h; } sar[17] =
920             {
921                 { 0,   0 }, { 1,   1 }, { 12, 11 }, { 10, 11 },
922                 { 16, 11 }, { 40, 33 }, { 24, 11 }, { 20, 11 },
923                 { 32, 11 }, { 80, 33 }, { 18, 11 }, { 15, 11 },
924                 { 64, 33 }, { 160,99 }, {  4,  3 }, {  3,  2 },
925                 {  2,  1 },
926             };
927             int i_sar = bs_read( &s, 8 );
928             int w, h;
929
930             if( i_sar < 17 )
931             {
932                 w = sar[i_sar].w;
933                 h = sar[i_sar].h;
934             }
935             else if( i_sar == 255 )
936             {
937                 w = bs_read( &s, 16 );
938                 h = bs_read( &s, 16 );
939             }
940             else
941             {
942                 w = 0;
943                 h = 0;
944             }
945
946             if( w != 0 && h != 0 )
947             {
948                 p_dec->fmt_out.video.i_sar_num = w;
949                 p_dec->fmt_out.video.i_sar_den = h;
950             }
951             else
952             {
953                 p_dec->fmt_out.video.i_sar_num = 1;
954                 p_dec->fmt_out.video.i_sar_den = 1;
955             }
956         }
957     }
958
959     free( pb_dec );
960
961     /* We have a new SPS */
962     if( !p_sys->b_sps )
963         msg_Dbg( p_dec, "found NAL_SPS (sps_id=%d)", i_sps_id );
964     p_sys->b_sps = true;
965
966     if( p_sys->pp_sps[i_sps_id] )
967         block_Release( p_sys->pp_sps[i_sps_id] );
968     p_sys->pp_sps[i_sps_id] = p_frag;
969 }
970
971 static void PutPPS( decoder_t *p_dec, block_t *p_frag )
972 {
973     decoder_sys_t *p_sys = p_dec->p_sys;
974     bs_t s;
975     int i_pps_id;
976     int i_sps_id;
977
978     bs_init( &s, &p_frag->p_buffer[5], p_frag->i_buffer - 5 );
979     i_pps_id = bs_read_ue( &s ); // pps id
980     i_sps_id = bs_read_ue( &s ); // sps id
981     if( i_pps_id >= PPS_MAX || i_sps_id >= SPS_MAX )
982     {
983         msg_Warn( p_dec, "invalid PPS (pps_id=%d sps_id=%d)", i_pps_id, i_sps_id );
984         block_Release( p_frag );
985         return;
986     }
987     bs_skip( &s, 1 ); // entropy coding mode flag
988     p_sys->i_pic_order_present_flag = bs_read( &s, 1 );
989     /* TODO */
990
991     /* We have a new PPS */
992     if( !p_sys->b_pps )
993         msg_Dbg( p_dec, "found NAL_PPS (pps_id=%d sps_id=%d)", i_pps_id, i_sps_id );
994     p_sys->b_pps = true;
995
996     if( p_sys->pp_pps[i_pps_id] )
997         block_Release( p_sys->pp_pps[i_pps_id] );
998     p_sys->pp_pps[i_pps_id] = p_frag;
999 }
1000
1001 static void ParseSlice( decoder_t *p_dec, bool *pb_new_picture, slice_t *p_slice,
1002                         int i_nal_ref_idc, int i_nal_type, const block_t *p_frag )
1003 {
1004     decoder_sys_t *p_sys = p_dec->p_sys;
1005     uint8_t *pb_dec;
1006     int i_dec;
1007     int i_slice_type;
1008     slice_t slice;
1009     bs_t s;
1010
1011     /* do not convert the whole frame */
1012     CreateDecodedNAL( &pb_dec, &i_dec, &p_frag->p_buffer[5],
1013                      __MIN( p_frag->i_buffer - 5, 60 ) );
1014     bs_init( &s, pb_dec, i_dec );
1015
1016     /* first_mb_in_slice */
1017     /* int i_first_mb = */ bs_read_ue( &s );
1018
1019     /* slice_type */
1020     switch( (i_slice_type = bs_read_ue( &s )) )
1021     {
1022     case 0: case 5:
1023         slice.i_frame_type = BLOCK_FLAG_TYPE_P;
1024         break;
1025     case 1: case 6:
1026         slice.i_frame_type = BLOCK_FLAG_TYPE_B;
1027         break;
1028     case 2: case 7:
1029         slice.i_frame_type = BLOCK_FLAG_TYPE_I;
1030         break;
1031     case 3: case 8: /* SP */
1032         slice.i_frame_type = BLOCK_FLAG_TYPE_P;
1033         break;
1034     case 4: case 9:
1035         slice.i_frame_type = BLOCK_FLAG_TYPE_I;
1036         break;
1037     default:
1038         slice.i_frame_type = 0;
1039         break;
1040     }
1041
1042     /* */
1043     slice.i_nal_type = i_nal_type;
1044     slice.i_nal_ref_idc = i_nal_ref_idc;
1045
1046     slice.i_pic_parameter_set_id = bs_read_ue( &s );
1047     slice.i_frame_num = bs_read( &s, p_sys->i_log2_max_frame_num + 4 );
1048
1049     slice.i_field_pic_flag = 0;
1050     slice.i_bottom_field_flag = -1;
1051     if( !p_sys->b_frame_mbs_only )
1052     {
1053         /* field_pic_flag */
1054         slice.i_field_pic_flag = bs_read( &s, 1 );
1055         if( slice.i_field_pic_flag )
1056             slice.i_bottom_field_flag = bs_read( &s, 1 );
1057     }
1058
1059     slice.i_idr_pic_id = p_sys->slice.i_idr_pic_id;
1060     if( slice.i_nal_type == NAL_SLICE_IDR )
1061         slice.i_idr_pic_id = bs_read_ue( &s );
1062
1063     slice.i_pic_order_cnt_lsb = -1;
1064     slice.i_delta_pic_order_cnt_bottom = -1;
1065     slice.i_delta_pic_order_cnt0 = 0;
1066     slice.i_delta_pic_order_cnt1 = 0;
1067     if( p_sys->i_pic_order_cnt_type == 0 )
1068     {
1069         slice.i_pic_order_cnt_lsb = bs_read( &s, p_sys->i_log2_max_pic_order_cnt_lsb + 4 );
1070         if( p_sys->i_pic_order_present_flag && !slice.i_field_pic_flag )
1071             slice.i_delta_pic_order_cnt_bottom = bs_read_se( &s );
1072     }
1073     else if( (p_sys->i_pic_order_cnt_type == 1) &&
1074              (!p_sys->i_delta_pic_order_always_zero_flag) )
1075     {
1076         slice.i_delta_pic_order_cnt0 = bs_read_se( &s );
1077         if( p_sys->i_pic_order_present_flag && !slice.i_field_pic_flag )
1078             slice.i_delta_pic_order_cnt1 = bs_read_se( &s );
1079     }
1080     free( pb_dec );
1081
1082     /* Detection of the first VCL NAL unit of a primary coded picture
1083      * (cf. 7.4.1.2.4) */
1084     bool b_pic = false;
1085     if( slice.i_frame_num != p_sys->slice.i_frame_num ||
1086         slice.i_pic_parameter_set_id != p_sys->slice.i_pic_parameter_set_id ||
1087         slice.i_field_pic_flag != p_sys->slice.i_field_pic_flag ||
1088         slice.i_nal_ref_idc != p_sys->slice.i_nal_ref_idc )
1089         b_pic = true;
1090     if( (slice.i_bottom_field_flag != -1) &&
1091         (p_sys->slice.i_bottom_field_flag != -1) &&
1092         (slice.i_bottom_field_flag != p_sys->slice.i_bottom_field_flag) )
1093         b_pic = true;
1094     if( p_sys->i_pic_order_cnt_type == 0 &&
1095         ( slice.i_pic_order_cnt_lsb != p_sys->slice.i_pic_order_cnt_lsb ||
1096           slice.i_delta_pic_order_cnt_bottom != p_sys->slice.i_delta_pic_order_cnt_bottom ) )
1097         b_pic = true;
1098     else if( p_sys->i_pic_order_cnt_type == 1 &&
1099              ( slice.i_delta_pic_order_cnt0 != p_sys->slice.i_delta_pic_order_cnt0 ||
1100                slice.i_delta_pic_order_cnt1 != p_sys->slice.i_delta_pic_order_cnt1 ) )
1101         b_pic = true;
1102     if( ( slice.i_nal_type == NAL_SLICE_IDR || p_sys->slice.i_nal_type == NAL_SLICE_IDR ) &&
1103         ( slice.i_nal_type != p_sys->slice.i_nal_type || slice.i_idr_pic_id != p_sys->slice.i_idr_pic_id ) )
1104             b_pic = true;
1105
1106     /* */
1107     *pb_new_picture = b_pic;
1108     *p_slice = slice;
1109 }
1110
1111 static void ParseSei( decoder_t *p_dec, block_t *p_frag )
1112 {
1113     decoder_sys_t *p_sys = p_dec->p_sys;
1114     uint8_t *pb_dec;
1115     int i_dec;
1116
1117     /* */
1118     CreateDecodedNAL( &pb_dec, &i_dec, &p_frag->p_buffer[5], p_frag->i_buffer - 5 );
1119     if( !pb_dec )
1120         return;
1121
1122     /* The +1 is for rbsp trailing bits */
1123     for( int i_used = 0; i_used+1 < i_dec; )
1124     {
1125         /* Read type */
1126         int i_type = 0;
1127         while( i_used+1 < i_dec )
1128         {
1129             const int i_byte = pb_dec[i_used++];
1130             i_type += i_byte;
1131             if( i_byte != 0xff )
1132                 break;
1133         }
1134         /* Read size */
1135         int i_size = 0;
1136         while( i_used+1 < i_dec )
1137         {
1138             const int i_byte = pb_dec[i_used++];
1139             i_size += i_byte;
1140             if( i_byte != 0xff )
1141                 break;
1142         }
1143         /* Check room */
1144         if( i_used + i_size + 1 > i_dec )
1145             break;
1146
1147         /* Look for user_data_registered_itu_t_t35 */
1148         if( i_type == 4 )
1149         {
1150             static const uint8_t p_dvb1_data_start_code[] = {
1151                 0xb5,
1152                 0x00, 0x31,
1153                 0x47, 0x41, 0x39, 0x34
1154             };
1155             const int      i_t35 = i_size;
1156             const uint8_t *p_t35 = &pb_dec[i_used];
1157
1158             /* Check for we have DVB1_data() */
1159             if( i_t35 >= 5 &&
1160                 !memcmp( p_t35, p_dvb1_data_start_code, sizeof(p_dvb1_data_start_code) ) )
1161             {
1162                 cc_Extract( &p_sys->cc_next, true, &p_t35[3], i_t35 - 3 );
1163             }
1164         }
1165
1166         /* Look for SEI recovery point */
1167         if( i_type == 6 )
1168         {
1169             bs_t s;
1170             const int      i_rec = i_size;
1171             const uint8_t *p_rec = &pb_dec[i_used];
1172
1173             bs_init( &s, p_rec, i_rec );
1174             int i_recovery_frames = bs_read_ue( &s );
1175             //bool b_exact_match = bs_read( &s, 1 );
1176             //bool b_broken_link = bs_read( &s, 1 );
1177             //int i_changing_slice_group = bs_read( &s, 2 );
1178             if( !p_sys->b_header )
1179             {
1180                 msg_Dbg( p_dec, "Seen SEI recovery point, %d recovery frames", i_recovery_frames );
1181                 if ( p_sys->i_recovery_frames == -1 || i_recovery_frames < p_sys->i_recovery_frames )
1182                     p_sys->i_recovery_frames = i_recovery_frames;
1183             }
1184         }
1185
1186         i_used += i_size;
1187     }
1188
1189     free( pb_dec );
1190 }
1191