]> git.sesse.net Git - vlc/blob - modules/packetizer/mpegvideo.c
* modules/packetizer/mpegvideo.c: When a discontinuity is flagged, trash
[vlc] / modules / packetizer / mpegvideo.c
1 /*****************************************************************************
2  * mpegvideo.c: parse and packetize an MPEG1/2 video stream
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Eric Petit <titer@videolan.org>
9  *          Gildas Bazin <gbazin@netcourrier.com>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Problem with this implementation:
28  *
29  * Although we should time-stamp each picture with a PTS, this isn't possible
30  * with the current implementation.
31  * The problem comes from the fact that for non-low-delay streams we can't
32  * calculate the PTS of pictures used as backward reference. Even the temporal
33  * reference number doesn't help here because all the pictures don't
34  * necessarily have the same duration (eg. 3:2 pulldown).
35  *
36  * However this doesn't really matter as far as the MPEG muxers are concerned
37  * because they allow having empty PTS fields. --gibalou
38  *****************************************************************************/
39
40 /*****************************************************************************
41  * Preamble
42  *****************************************************************************/
43 #include <stdlib.h>                                      /* malloc(), free() */
44
45 #include <vlc/vlc.h>
46 #include <vlc/decoder.h>
47 #include <vlc/input.h>
48
49 #include "vlc_block_helper.h"
50
51 /*****************************************************************************
52  * Module descriptor
53  *****************************************************************************/
54 static int  Open ( vlc_object_t * );
55 static void Close( vlc_object_t * );
56
57 vlc_module_begin();
58     set_description( _("MPEG-I/II video packetizer") );
59     set_capability( "packetizer", 50 );
60     set_callbacks( Open, Close );
61 vlc_module_end();
62
63 /*****************************************************************************
64  * Local prototypes
65  *****************************************************************************/
66 static block_t *Packetize( decoder_t *, block_t ** );
67 static block_t *ParseMPEGBlock( decoder_t *, block_t * );
68
69 struct decoder_sys_t
70 {
71     /*
72      * Input properties
73      */
74     block_bytestream_t bytestream;
75     int i_state;
76     int i_offset;
77     uint8_t p_startcode[3];
78
79     /* Sequence header and extension */
80     block_t *p_seq;
81     block_t *p_ext;
82
83     /* Current frame being built */
84     block_t    *p_frame;
85     vlc_bool_t b_frame_slice;
86     mtime_t i_pts;
87     mtime_t i_dts;
88
89     /* Sequence properties */
90     int         i_frame_rate;
91     int         i_frame_rate_base;
92     vlc_bool_t  b_seq_progressive;
93     vlc_bool_t  b_low_delay;
94     int         i_aspect_ratio_info;
95     vlc_bool_t  b_inited;
96
97     /* Picture properties */
98     int i_temporal_ref;
99     int i_picture_type;
100     int i_picture_structure;
101     int i_top_field_first;
102     int i_repeat_first_field;
103     int i_progressive_frame;
104
105     mtime_t i_interpolated_dts;
106     mtime_t i_old_duration;
107     mtime_t i_last_ref_pts;
108
109     /* Number of pictures since last sequence header */
110     int i_seq_old;
111
112 };
113
114 enum {
115     STATE_NOSYNC,
116     STATE_NEXT_SYNC
117 };
118
119 /*****************************************************************************
120  * Open:
121  *****************************************************************************/
122 static int Open( vlc_object_t *p_this )
123 {
124     decoder_t *p_dec = (decoder_t*)p_this;
125     decoder_sys_t *p_sys;
126
127     if( p_dec->fmt_in.i_codec != VLC_FOURCC( 'm', 'p', 'g', '1' ) &&
128         p_dec->fmt_in.i_codec != VLC_FOURCC( 'm', 'p', 'g', '2' ) &&
129         p_dec->fmt_in.i_codec != VLC_FOURCC( 'm', 'p', 'g', 'v' ) )
130     {
131         return VLC_EGENERIC;
132     }
133
134     es_format_Init( &p_dec->fmt_out, VIDEO_ES, VLC_FOURCC('m','p','g','v') );
135     p_dec->pf_packetize = Packetize;
136
137     p_dec->p_sys = p_sys = malloc( sizeof( decoder_sys_t ) );
138
139     /* Misc init */
140     p_sys->i_state = STATE_NOSYNC;
141     p_sys->bytestream = block_BytestreamInit( p_dec );
142     p_sys->p_startcode[0] = 0;
143     p_sys->p_startcode[1] = 0;
144     p_sys->p_startcode[2] = 1;
145     p_sys->i_offset = 0;
146
147     p_sys->p_seq = NULL;
148     p_sys->p_ext = NULL;
149     p_sys->p_frame = NULL;
150     p_sys->b_frame_slice = VLC_FALSE;
151
152     p_sys->i_dts = p_sys->i_pts = 0;
153
154     p_sys->i_frame_rate = 1;
155     p_sys->i_frame_rate_base = 1;
156     p_sys->b_seq_progressive = VLC_TRUE;
157     p_sys->b_low_delay = VLC_TRUE;
158     p_sys->i_seq_old = 0;
159
160     p_sys->i_temporal_ref = 0;
161     p_sys->i_picture_type = 0;
162     p_sys->i_picture_structure = 0x03; /* frame */
163     p_sys->i_top_field_first = 0;
164     p_sys->i_repeat_first_field = 0;
165     p_sys->i_progressive_frame = 0;
166     p_sys->b_inited = 0;
167
168     p_sys->i_interpolated_dts = 0;
169     p_sys->i_old_duration = 0;
170     p_sys->i_last_ref_pts = 0;
171
172     return VLC_SUCCESS;
173 }
174
175 /*****************************************************************************
176  * Close:
177  *****************************************************************************/
178 static void Close( vlc_object_t *p_this )
179 {
180     decoder_t     *p_dec = (decoder_t*)p_this;
181     decoder_sys_t *p_sys = p_dec->p_sys;
182
183     block_BytestreamRelease( &p_sys->bytestream );
184
185     if( p_sys->p_seq )
186     {
187         block_Release( p_sys->p_seq );
188     }
189     if( p_sys->p_ext )
190     {
191         block_Release( p_sys->p_ext );
192     }
193     if( p_sys->p_frame )
194     {
195         block_ChainRelease( p_sys->p_frame );
196     }
197
198     free( p_sys );
199 }
200
201 /*****************************************************************************
202  * Packetize:
203  *****************************************************************************/
204 static block_t *Packetize( decoder_t *p_dec, block_t **pp_block )
205 {
206     decoder_sys_t *p_sys = p_dec->p_sys;
207     block_t       *p_pic;
208
209     if( pp_block == NULL || *pp_block == NULL )
210     {
211         return NULL;
212     }
213
214     if( (*pp_block)->i_flags & BLOCK_FLAG_DISCONTINUITY )
215     {
216         p_sys->i_state = STATE_NOSYNC;
217         if( p_sys->p_frame ) block_ChainRelease( p_sys->p_frame );
218         p_sys->p_frame = NULL;
219         p_sys->b_frame_slice = VLC_FALSE;
220         block_Release( *pp_block );
221         return NULL;
222     }
223
224     block_BytestreamPush( &p_sys->bytestream, *pp_block );
225
226     while( 1 )
227     {
228         switch( p_sys->i_state )
229         {
230
231         case STATE_NOSYNC:
232             if( block_FindStartcodeFromOffset( &p_sys->bytestream,
233                     &p_sys->i_offset, p_sys->p_startcode, 3 ) == VLC_SUCCESS )
234             {
235                 p_sys->i_state = STATE_NEXT_SYNC;
236             }
237
238             if( p_sys->i_offset )
239             {
240                 block_SkipBytes( &p_sys->bytestream, p_sys->i_offset );
241                 p_sys->i_offset = 0;
242                 block_BytestreamFlush( &p_sys->bytestream );
243             }
244
245             if( p_sys->i_state != STATE_NEXT_SYNC )
246             {
247                 /* Need more data */
248                 return NULL;
249             }
250
251             p_sys->i_offset = 1; /* To find next startcode */
252
253         case STATE_NEXT_SYNC:
254             /* TODO: If p_block == NULL, flush the buffer without checking the
255              * next sync word */
256
257             /* Find the next startcode */
258             if( block_FindStartcodeFromOffset( &p_sys->bytestream,
259                     &p_sys->i_offset, p_sys->p_startcode, 3 ) != VLC_SUCCESS )
260             {
261                 /* Need more data */
262                 return NULL;
263             }
264
265             /* Get the new fragment and set the pts/dts */
266             p_pic = block_New( p_dec, p_sys->i_offset );
267             p_pic->i_pts = p_sys->bytestream.p_block->i_pts;
268             p_pic->i_dts = p_sys->bytestream.p_block->i_dts;
269
270             block_GetBytes( &p_sys->bytestream, p_pic->p_buffer,
271                             p_pic->i_buffer );
272
273             /* don't reuse the same timestamps several times */
274             if( p_pic->i_buffer >= 4 && p_pic->p_buffer[3] == 0x00 )
275             {
276                 /* We have a picture start code */
277                 p_sys->bytestream.p_block->i_pts = 0;
278                 p_sys->bytestream.p_block->i_dts = 0;
279             }
280
281             p_sys->i_offset = 0;
282
283             /* Get picture if any */
284             if( !( p_pic = ParseMPEGBlock( p_dec, p_pic ) ) )
285             {
286                 p_sys->i_state = STATE_NOSYNC;
287                 break;
288             }
289
290             /* We've just started the stream, wait for the first PTS.
291              * We discard here so we can still get the sequence header. */
292             if( p_sys->i_dts <= 0 && p_sys->i_pts <= 0 &&
293                 p_sys->i_interpolated_dts <= 0 )
294             {
295                 msg_Dbg( p_dec, "need a starting pts/dts" );
296                 p_sys->i_state = STATE_NOSYNC;
297                 block_Release( p_pic );
298                 break;
299             }
300
301             /* When starting the stream we can have the first frame with
302              * a null DTS (i_interpolated_pts is initialized to 0) */
303             if( !p_pic->i_dts ) p_pic->i_dts = p_pic->i_pts;
304
305             /* So p_block doesn't get re-added several times */
306             *pp_block = block_BytestreamPop( &p_sys->bytestream );
307
308             p_sys->i_state = STATE_NOSYNC;
309
310             return p_pic;
311         }
312     }
313 }
314
315 /*****************************************************************************
316  * ParseMPEGBlock: Re-assemble fragments into a block containing a picture
317  *****************************************************************************/
318 static block_t *ParseMPEGBlock( decoder_t *p_dec, block_t *p_frag )
319 {
320     decoder_sys_t *p_sys = p_dec->p_sys;
321     block_t *p_pic = NULL;
322
323     /*
324      * Check if previous picture is finished
325      */
326     if( ( p_sys->b_frame_slice &&
327           (p_frag->p_buffer[3] == 0x00 || p_frag->p_buffer[3] > 0xaf) ) &&
328           p_sys->p_seq == NULL )
329     {
330         /* We have a picture but without a sequence header we can't
331          * do anything */
332         msg_Dbg( p_dec, "waiting for sequence start" );
333         if( p_sys->p_frame ) block_ChainRelease( p_sys->p_frame );
334         p_sys->p_frame = NULL;
335         p_sys->b_frame_slice = VLC_FALSE;
336
337     }
338     else if( p_sys->b_frame_slice &&
339              (p_frag->p_buffer[3] == 0x00 || p_frag->p_buffer[3] > 0xaf) )
340     {
341         mtime_t i_duration;
342
343         p_pic = block_ChainGather( p_sys->p_frame );
344
345         i_duration = (mtime_t)( 1000000 * p_sys->i_frame_rate_base /
346                                 p_sys->i_frame_rate );
347
348         if( !p_sys->b_seq_progressive && p_sys->i_picture_structure != 0x03 )
349         {
350             i_duration /= 2;
351         }
352
353         if( p_sys->b_seq_progressive )
354         {
355             if( p_sys->i_top_field_first == 0 &&
356                 p_sys->i_repeat_first_field == 1 )
357             {
358                 i_duration *= 2;
359             }
360             else if( p_sys->i_top_field_first == 1 &&
361                      p_sys->i_repeat_first_field == 1 )
362             {
363                 i_duration *= 3;
364             }
365         }
366         else
367         {
368             if( p_sys->i_picture_structure == 0x03 )
369             {
370                 if( p_sys->i_progressive_frame && p_sys->i_repeat_first_field )
371                 {
372                     i_duration += i_duration / 2;
373                 }
374             }
375         }
376
377         if( p_sys->b_low_delay || p_sys->i_picture_type == 0x03 )
378         {
379             /* Trivial case (DTS == PTS) */
380             /* Correct interpolated dts when we receive a new pts/dts */
381             if( p_sys->i_pts > 0 ) p_sys->i_interpolated_dts = p_sys->i_pts;
382             if( p_sys->i_dts > 0 ) p_sys->i_interpolated_dts = p_sys->i_dts;
383         }
384         else
385         {
386             /* Correct interpolated dts when we receive a new pts/dts */
387             if( p_sys->i_last_ref_pts > 0 )
388                 p_sys->i_interpolated_dts = p_sys->i_last_ref_pts;
389             if( p_sys->i_dts > 0 ) p_sys->i_interpolated_dts = p_sys->i_dts;
390
391             p_sys->i_last_ref_pts = p_sys->i_pts;
392         }
393
394         p_pic->i_dts = p_sys->i_interpolated_dts;
395
396         /* Set PTS only if we have a B frame or if it comes from the stream */
397         if( p_sys->i_pts > 0 )
398         {
399             p_pic->i_pts = p_sys->i_pts;
400         }
401         else if( p_sys->i_picture_type == 0x03 )
402         {
403             p_pic->i_pts = p_pic->i_dts;
404         }
405         else
406         {
407             p_pic->i_pts = 0;
408         }
409
410         if( p_sys->b_low_delay || p_sys->i_picture_type == 0x03 )
411         {
412             /* Trivial case (DTS == PTS) */
413             p_sys->i_interpolated_dts += i_duration;
414         }
415         else
416         {
417             p_sys->i_interpolated_dts += p_sys->i_old_duration;
418             p_sys->i_old_duration = i_duration;
419         }
420
421         switch ( p_sys->i_picture_type )
422         {
423         case 0x01:
424             p_pic->i_flags |= BLOCK_FLAG_TYPE_I;
425             break;
426         case 0x02:
427             p_pic->i_flags |= BLOCK_FLAG_TYPE_P;
428             break;
429         case 0x03:
430             p_pic->i_flags |= BLOCK_FLAG_TYPE_B;
431             break;
432         }
433
434         p_pic->i_length = p_sys->i_interpolated_dts - p_pic->i_dts;
435
436 #if 0
437         msg_Dbg( p_dec, "pic: type=%d dts="I64Fd" pts-dts="I64Fd,
438         p_sys->i_picture_type, p_pic->i_dts, p_pic->i_pts - p_pic->i_dts);
439 #endif
440
441         /* Reset context */
442         p_sys->p_frame = NULL;
443         p_sys->b_frame_slice = VLC_FALSE;
444     }
445
446     /*
447      * Check info of current fragment
448      */
449     if( p_frag->p_buffer[3] == 0xb8 )
450     {
451         /* Group start code */
452         if( p_sys->p_seq &&
453             p_sys->i_seq_old > p_sys->i_frame_rate/p_sys->i_frame_rate_base )
454         {
455             /* Usefull for mpeg1: repeat sequence header every second */
456             block_ChainAppend( &p_sys->p_frame,
457                                block_Duplicate( p_sys->p_seq ) );
458             if( p_sys->p_ext )
459             {
460                 block_ChainAppend( &p_sys->p_frame,
461                                    block_Duplicate( p_sys->p_ext ) );
462             }
463
464             p_sys->i_seq_old = 0;
465         }
466     }
467     else if( p_frag->p_buffer[3] == 0xb3 && p_frag->i_buffer >= 8 )
468     {
469         /* Sequence header code */
470         static const int code_to_frame_rate[16][2] =
471         {
472             { 1, 1 },  /* invalid */
473             { 24000, 1001 }, { 24, 1 }, { 25, 1 },       { 30000, 1001 },
474             { 30, 1 },       { 50, 1 }, { 60000, 1001 }, { 60, 1 },
475             /* Unofficial 15fps from Xing*/
476             { 15, 1001 },
477             /* Unofficial economy rates from libmpeg3 */
478             { 5, 1001 }, { 10, 1001 }, { 12, 1001 }, { 15, 1001 },
479             { 1, 1 },  { 1, 1 }  /* invalid */
480         };
481
482         if( p_sys->p_seq ) block_Release( p_sys->p_seq );
483         if( p_sys->p_ext ) block_Release( p_sys->p_ext );
484
485         p_sys->p_seq = block_Duplicate( p_frag );
486         p_sys->i_seq_old = 0;
487         p_sys->p_ext = NULL;
488
489         p_dec->fmt_out.video.i_width =
490             ( p_frag->p_buffer[4] << 4)|(p_frag->p_buffer[5] >> 4 );
491         p_dec->fmt_out.video.i_height =
492             ( (p_frag->p_buffer[5]&0x0f) << 8 )|p_frag->p_buffer[6];
493         p_sys->i_aspect_ratio_info = p_frag->p_buffer[7] >> 4;
494
495         /* TODO: MPEG1 aspect ratio */
496
497         p_sys->i_frame_rate = code_to_frame_rate[p_frag->p_buffer[7]&0x0f][0];
498         p_sys->i_frame_rate_base =
499             code_to_frame_rate[p_frag->p_buffer[7]&0x0f][1];
500
501         p_sys->b_seq_progressive = VLC_TRUE;
502         p_sys->b_low_delay = VLC_TRUE;
503
504         if ( !p_sys->b_inited )
505         {
506             msg_Dbg( p_dec, "Size %dx%d fps=%.3f",
507                  p_dec->fmt_out.video.i_width, p_dec->fmt_out.video.i_height,
508                  p_sys->i_frame_rate / (float)p_sys->i_frame_rate_base );
509             p_sys->b_inited = 1;
510         }
511     }
512     else if( p_frag->p_buffer[3] == 0xb5 )
513     {
514         int i_type = p_frag->p_buffer[4] >> 4;
515
516         /* Extention start code */
517         if( i_type == 0x01 )
518         {
519             static const int mpeg2_aspect[16][2] =
520             {
521                 {0,1}, {1,1}, {4,3}, {16,9}, {221,100},
522                 {0,1}, {0,1}, {0,1}, {0,1}, {0,1}, {0,1}, {0,1}, {0,1}, {0,1},
523                 {0,1}, {0,1}
524             };
525
526             /* sequence extention */
527             if( p_sys->p_ext) block_Release( p_sys->p_ext );
528             p_sys->p_ext = block_Duplicate( p_frag );
529
530             if( p_frag->i_buffer >= 10 )
531             {
532                 p_sys->b_seq_progressive =
533                     p_frag->p_buffer[5]&0x08 ? VLC_TRUE : VLC_FALSE;
534                 p_sys->b_low_delay =
535                     p_frag->p_buffer[9]&0x80 ? VLC_TRUE : VLC_FALSE;
536             }
537
538             p_dec->fmt_out.video.i_aspect =
539                 mpeg2_aspect[p_sys->i_aspect_ratio_info][0] *
540                 VOUT_ASPECT_FACTOR /
541                 mpeg2_aspect[p_sys->i_aspect_ratio_info][1];
542
543         }
544         else if( i_type == 0x08 )
545         {
546             /* picture extention */
547             p_sys->i_picture_structure = p_frag->p_buffer[6]&0x03;
548             p_sys->i_top_field_first   = p_frag->p_buffer[7] >> 7;
549             p_sys->i_repeat_first_field= (p_frag->p_buffer[7]>>1)&0x01;
550             p_sys->i_progressive_frame = p_frag->p_buffer[8] >> 7;
551         }
552     }
553     else if( p_frag->p_buffer[3] == 0x00 )
554     {
555         /* Picture start code */
556         p_sys->i_seq_old++;
557
558         if( p_frag->i_buffer >= 6 )
559         {
560             p_sys->i_temporal_ref =
561                 ( p_frag->p_buffer[4] << 2 )|(p_frag->p_buffer[5] >> 6);
562             p_sys->i_picture_type = ( p_frag->p_buffer[5] >> 3 ) & 0x03;
563         }
564
565         p_sys->i_dts = p_frag->i_dts;
566         p_sys->i_pts = p_frag->i_pts;
567     }
568     else if( p_frag->p_buffer[3] >= 0x01 && p_frag->p_buffer[3] <= 0xaf )
569     {
570         /* Slice start code */
571         p_sys->b_frame_slice = VLC_TRUE;
572     }
573
574     /* Append the block */
575     block_ChainAppend( &p_sys->p_frame, p_frag );
576
577     return p_pic;
578 }