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