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