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