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