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