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