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