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