]> git.sesse.net Git - vlc/blob - modules/packetizer/mpegvideo.c
* src/input/input_ext-dec.c: added a few sanity checks that avoid crashing
[vlc] / modules / packetizer / mpegvideo.c
1 /*****************************************************************************
2  * mpegvideo.c
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 VideoLAN
5  * $Id: mpegvideo.c,v 1.9 2003/02/26 13:51:36 gbazin Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Eric Petit <titer@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <vlc/vlc.h>
29 #include <vlc/decoder.h>
30 #include <vlc/input.h>
31 #include <vlc/sout.h>
32 #include "codecs.h"                         /* WAVEFORMATEX BITMAPINFOHEADER */
33
34 #include <stdlib.h>                                      /* malloc(), free() */
35 #include <string.h>                                              /* strdup() */
36
37 /*****************************************************************************
38  * Local prototypes
39  *****************************************************************************/
40 typedef struct packetizer_s
41 {
42     /* Input properties */
43     decoder_fifo_t          *p_fifo;
44     bit_stream_t            bit_stream;
45
46     /* Output properties */
47     sout_input_t            *p_sout_input;
48     sout_packet_format_t    output_format;
49
50     mtime_t                 i_last_dts;
51     mtime_t                 i_last_ref_pts;
52     double                  d_frame_rate;
53     int                     i_progressive_sequence;
54     uint8_t                 p_sequence_header[150];
55     int                     i_sequence_header_length;
56     int                     i_last_sequence_header;
57
58     int                     i_last_picture_structure;
59 } packetizer_t;
60
61 static int  Open    ( vlc_object_t * );
62 static int  Run     ( decoder_fifo_t * );
63
64 static int  InitThread     ( packetizer_t * );
65 static void PacketizeThread   ( packetizer_t * );
66 static void EndThread      ( packetizer_t * );
67
68 /*****************************************************************************
69  * Module descriptor
70  *****************************************************************************/
71
72 vlc_module_begin();
73     set_description( _("MPEG-I/II video packetizer") );
74     set_capability( "packetizer", 50 );
75     set_callbacks( Open, NULL );
76 vlc_module_end();
77
78 /*****************************************************************************
79  * OpenDecoder: probe the packetizer and return score
80  *****************************************************************************
81  * Tries to launch a decoder and return score so that the interface is able
82  * to choose.
83  *****************************************************************************/
84 static int Open( vlc_object_t *p_this )
85 {
86     decoder_fifo_t *p_fifo = (decoder_fifo_t*) p_this;
87
88     if( p_fifo->i_fourcc != VLC_FOURCC( 'm', 'p', 'g', 'v') &&
89         p_fifo->i_fourcc != VLC_FOURCC( 'm', 'p', 'g', '1') &&
90         p_fifo->i_fourcc != VLC_FOURCC( 'm', 'p', 'g', '2') )
91     {
92         return VLC_EGENERIC;
93     }
94
95     p_fifo->pf_run = Run;
96     return VLC_SUCCESS;
97 }
98
99 /*****************************************************************************
100  * RunDecoder: this function is called just after the thread is created
101  *****************************************************************************/
102 static int Run( decoder_fifo_t *p_fifo )
103 {
104     packetizer_t *p_pack;
105     int b_error;
106
107     msg_Info( p_fifo, "Running mpegvideo packetizer" );
108     if( !( p_pack = malloc( sizeof( packetizer_t ) ) ) )
109     {
110         msg_Err( p_fifo, "out of memory" );
111         DecoderError( p_fifo );
112         return( -1 );
113     }
114     memset( p_pack, 0, sizeof( packetizer_t ) );
115
116     p_pack->p_fifo = p_fifo;
117
118     if( InitThread( p_pack ) != 0 )
119     {
120         DecoderError( p_fifo );
121         return( -1 );
122     }
123
124     while( ( !p_pack->p_fifo->b_die )&&( !p_pack->p_fifo->b_error ) )
125     {
126         PacketizeThread( p_pack );
127     }
128
129
130     if( ( b_error = p_pack->p_fifo->b_error ) )
131     {
132         DecoderError( p_pack->p_fifo );
133     }
134
135     EndThread( p_pack );
136
137     if( p_pack )
138     {
139         free( p_pack );
140     }
141
142     if( b_error )
143     {
144         return( -1 );
145     }
146
147     return( 0 );
148 }
149
150
151 /*****************************************************************************
152  * InitThread: initialize data before entering main loop
153  *****************************************************************************/
154
155 static int InitThread( packetizer_t *p_pack )
156 {
157
158     p_pack->output_format.i_cat = VIDEO_ES;
159     p_pack->output_format.i_fourcc = VLC_FOURCC( 'm', 'p', 'g', 'v');
160
161     p_pack->p_sout_input = NULL;
162
163     if( InitBitstream( &p_pack->bit_stream, p_pack->p_fifo,
164                        NULL, NULL ) != VLC_SUCCESS )
165     {
166         msg_Err( p_pack->p_fifo, "cannot initialize bitstream" );
167         return -1;
168     }
169
170     p_pack->i_last_picture_structure = 0x03; /* frame picture */
171     return( 0 );
172 }
173
174 /* from ISO 13818-2 */
175 /* converting frame_rate_code to frame_rate */
176 static const double pd_frame_rates[16] =
177 {
178     0, 24000/1001, 24, 25, 30000/1001, 30, 50, 60000/1001, 60,
179     0, 0, 0, 0, 0, 0, 0
180 };
181
182 static int CopyUntilNextStartCode( packetizer_t   *p_pack,
183                                    sout_buffer_t  *p_sout_buffer,
184                                    unsigned int   *pi_pos )
185 {
186     int i_copy = 0;
187
188     do
189     {
190         p_sout_buffer->p_buffer[(*pi_pos)++] =
191                 GetBits( &p_pack->bit_stream, 8 );
192         i_copy++;
193
194         if( *pi_pos + 2048 > p_sout_buffer->i_buffer_size )
195         {
196             sout_BufferRealloc( p_pack->p_sout_input->p_sout,
197                                 p_sout_buffer,
198                                 p_sout_buffer->i_buffer_size + 50 * 1024);
199         }
200
201     } while( ShowBits( &p_pack->bit_stream, 24 ) != 0x01 &&
202              !p_pack->p_fifo->b_die && !p_pack->p_fifo->b_error );
203
204     return( i_copy );
205 }
206
207 /*****************************************************************************
208  * PacketizeThread: packetize an unit (here copy a complete pes)
209  *****************************************************************************/
210 static void PacketizeThread( packetizer_t *p_pack )
211 {
212     sout_buffer_t *p_sout_buffer = NULL;
213     int32_t i_pos;
214     int i_skipped;
215     mtime_t i_duration; /* of the parsed picture */
216
217     /* needed to calculate pts/dts */
218     int i_temporal_ref = 0;
219     int i_picture_structure = 0x03; /* frame picture */
220     int i_top_field_first = 0;
221     int i_repeat_first_field = 0;
222
223     if( !p_pack->p_sout_input )
224     {
225         byte_t p_temp[512];/* 150 bytes is the maximal size
226                                of a sequence_header + sequence_extension */
227         int i_frame_rate_code;
228         BITMAPINFOHEADER *p_bih;
229
230         p_bih = malloc( sizeof( BITMAPINFOHEADER ) );
231         p_pack->output_format.p_format = (void*)p_bih;
232
233         /* skip data until we find a sequence_header_code */
234         /* TODO: store skipped somewhere so can send it to the mux
235          * after the input is created */
236         i_skipped = 0;
237         while( ShowBits( &p_pack->bit_stream, 32 ) != 0x1B3 &&
238                !p_pack->p_fifo->b_die && !p_pack->p_fifo->b_error )
239         {
240             RemoveBits( &p_pack->bit_stream, 8 );
241             i_skipped++;
242         }
243         msg_Warn( p_pack->p_fifo, "sequence_header_code found (%d skipped)",
244                  i_skipped );
245
246         /* copy the start_code */
247         i_pos = 0;
248         GetChunk( &p_pack->bit_stream, p_temp, 4 ); i_pos += 4;
249
250         p_bih->biSize = sizeof( BITMAPINFOHEADER );
251         /* horizontal_size_value */
252         p_bih->biWidth = ShowBits( &p_pack->bit_stream, 12 );
253         /* vertical_size_value */
254         p_bih->biHeight = ShowBits( &p_pack->bit_stream, 24 ) & 0xFFF;
255         /* frame_rate_code */
256         i_frame_rate_code = ShowBits( &p_pack->bit_stream, 32 ) & 0xF;
257         p_bih->biPlanes = 1;
258         p_bih->biBitCount = 0;
259         p_bih->biCompression = VLC_FOURCC( 'm', 'p', 'g', '2' );
260         p_bih->biSizeImage = 0;
261         p_bih->biXPelsPerMeter = 0;
262         p_bih->biYPelsPerMeter = 0;
263         p_bih->biClrUsed = 0;
264         p_bih->biClrImportant = 0;
265
266         /* copy headers */
267         GetChunk( &p_pack->bit_stream, p_temp + i_pos, 7 ); i_pos += 7;
268
269         /* intra_quantiser_matrix [non_intra_quantiser_matrix] */
270         if( ShowBits( &p_pack->bit_stream, 7 ) & 0x1 )
271         {
272
273             GetChunk( &p_pack->bit_stream, p_temp + i_pos, 64 ); i_pos += 64;
274
275             if( ShowBits( &p_pack->bit_stream, 8 ) & 0x1 )
276             {
277                 GetChunk( &p_pack->bit_stream, p_temp + i_pos, 65); i_pos += 65;
278             }
279         }
280         /* non_intra_quantiser_matrix */
281         else if( ShowBits( &p_pack->bit_stream, 8 ) & 0x1 )
282         {
283             GetChunk( &p_pack->bit_stream, p_temp + i_pos, 65); i_pos += 65;
284         }
285         /* nothing */
286         else
287         {
288             GetChunk( &p_pack->bit_stream, p_temp + i_pos, 1 ); i_pos += 1;
289         }
290
291         /* sequence_extension (10 bytes) */
292         if( ShowBits( &p_pack->bit_stream, 32 ) != 0x1B5 )
293         {
294             msg_Dbg( p_pack->p_fifo, "ARRGG no extension_start_code" );
295             p_pack->i_progressive_sequence = 1;
296         }
297         else
298         {
299             GetChunk( &p_pack->bit_stream, p_temp + i_pos, 10 );
300             p_pack->i_progressive_sequence = ( p_temp[i_pos+5]&0x08 ) ? 1 : 0;
301
302             i_pos += 10;
303         }
304
305         /* remember sequence_header and sequence_extention */
306         memcpy( p_pack->p_sequence_header, p_temp, i_pos );
307         p_pack->i_sequence_header_length = i_pos;
308
309         p_pack->d_frame_rate =  pd_frame_rates[i_frame_rate_code];
310
311         msg_Warn( p_pack->p_fifo,
312                   "creating input (image size %dx%d, frame rate %.2f)",
313                   p_bih->biWidth, p_bih->biHeight, p_pack->d_frame_rate );
314
315         /* now we have informations to create the input */
316         p_pack->p_sout_input = sout_InputNew( p_pack->p_fifo,
317                                               &p_pack->output_format );
318
319         if( !p_pack->p_sout_input )
320         {
321             msg_Err( p_pack->p_fifo, "cannot add a new stream" );
322             return;
323         }
324
325         p_sout_buffer = sout_BufferNew( p_pack->p_sout_input->p_sout,
326                                         100 * 1024 );
327         p_sout_buffer->i_size = i_pos;
328         memcpy( p_sout_buffer->p_buffer, p_temp, i_pos );
329
330     }
331     else
332     {
333         p_sout_buffer =
334                 sout_BufferNew( p_pack->p_sout_input->p_sout, 100 * 1024 );
335         i_pos = 0;
336     }
337
338     p_pack->i_last_sequence_header++;
339
340     for( ;; )
341     {
342         uint32_t i_code;
343         if( p_pack->p_fifo->b_die || p_pack->p_fifo->b_error )
344         {
345             break;
346         }
347
348         i_code = ShowBits( &p_pack->bit_stream, 32 );
349
350         if( i_code == 0x1B8 ) /* GOP */
351         {
352             /* usefull for bad MPEG-1 : repeat the sequence_header
353                every second */
354             if( p_pack->i_last_sequence_header > (int) p_pack->d_frame_rate )
355             {
356                memcpy( p_sout_buffer->p_buffer + i_pos,
357                        p_pack->p_sequence_header,
358                        p_pack->i_sequence_header_length );
359                i_pos += p_pack->i_sequence_header_length;
360                p_pack->i_last_sequence_header = 0;
361             }
362
363             p_pack->i_last_ref_pts =
364                    p_pack->i_last_dts + 40000; /* FIXME */
365             CopyUntilNextStartCode( p_pack, p_sout_buffer, &i_pos );
366         }
367         else if( i_code == 0x100 ) /* Picture */
368         {
369             /* picture_start_code */
370             GetChunk( &p_pack->bit_stream,
371                       p_sout_buffer->p_buffer + i_pos, 4 ); i_pos += 4;
372             i_temporal_ref = ShowBits( &p_pack->bit_stream, 10 );
373
374             CopyUntilNextStartCode( p_pack, p_sout_buffer, &i_pos );
375             break;
376         }
377         else if( i_code == 0x1b5 )
378         {
379             /* extention start code                   32 */
380             GetChunk( &p_pack->bit_stream,
381                       p_sout_buffer->p_buffer + i_pos, 4 ); i_pos += 4;
382
383             if( ShowBits( &p_pack->bit_stream, 4 ) == 0x08 )
384             {
385                 /* picture coding extention */
386
387                 /* extention start code identifier(b1000)  4 */
388                 /* f_code[2][2]                           16 */
389                 /* intra_dc_precision                      2 */
390                 /* picture_structure                       2 */
391                 /* top_field_first                         1 */
392                 i_picture_structure =
393                     ShowBits( &p_pack->bit_stream, 24 ) & 0x03;
394                 i_top_field_first =
395                     ShowBits( &p_pack->bit_stream, 25 ) & 0x01;
396                 i_repeat_first_field =
397                     ShowBits( &p_pack->bit_stream, 31 ) & 0x01;
398             }
399             CopyUntilNextStartCode( p_pack, p_sout_buffer, &i_pos );
400         }
401         else
402         {
403             if( i_code == 0x1B3 )
404             {
405                 p_pack->i_last_sequence_header = 0;
406             }
407             CopyUntilNextStartCode( p_pack, p_sout_buffer, &i_pos );
408         }
409     }
410
411     sout_BufferRealloc( p_pack->p_sout_input->p_sout,
412                         p_sout_buffer, i_pos );
413     p_sout_buffer->i_size = i_pos;
414
415     /* calculate dts/pts */
416     if( p_pack->i_progressive_sequence || i_picture_structure == 0x03)
417     {
418         i_duration = (mtime_t)( 1000000 / p_pack->d_frame_rate );
419     }
420     else
421     {
422         i_duration = (mtime_t)( 1000000 / p_pack->d_frame_rate / 2);
423     }
424
425     p_sout_buffer->i_dts = p_pack->i_last_dts;
426     p_sout_buffer->i_pts = p_pack->i_last_ref_pts + 
427         i_temporal_ref * (mtime_t)( 1000000 / p_pack->d_frame_rate );
428     p_sout_buffer->i_length = i_duration;
429     p_sout_buffer->i_bitrate = (int)( 8 * i_pos * p_pack->d_frame_rate );
430     sout_InputSendBuffer( p_pack->p_sout_input, p_sout_buffer );
431
432     if( p_pack->i_progressive_sequence )
433     {
434         if( i_top_field_first == 0 && i_repeat_first_field == 0 )
435         {
436             p_pack->i_last_dts += i_duration;
437         }
438         else if( i_top_field_first == 0 && i_repeat_first_field == 1 )
439         {
440             p_pack->i_last_dts += 2 * i_duration;
441         }
442         else if( i_top_field_first == 1 && i_repeat_first_field == 1 )
443         {
444             p_pack->i_last_dts += 3 * i_duration;
445         }
446     }
447     else
448     {
449         if( i_picture_structure == 0x03 )
450         {
451             p_pack->i_last_dts += i_duration;
452         }
453         else if( i_picture_structure == p_pack->i_last_picture_structure )
454         {
455             p_pack->i_last_dts += 2 * i_duration;
456         }
457         else if( ( !i_top_field_first && i_picture_structure == 0x01 ) ||
458                  (  i_top_field_first && i_picture_structure == 0x02 ) )
459         {
460             p_pack->i_last_dts += 2 * i_duration;
461         }
462     }
463     p_pack->i_last_picture_structure = i_picture_structure;
464 }
465
466
467 /*****************************************************************************
468  * EndThread : packetizer thread destruction
469  *****************************************************************************/
470 static void EndThread ( packetizer_t *p_pack)
471 {
472     if( p_pack->p_sout_input )
473     {
474         sout_InputDelete( p_pack->p_sout_input );
475     }
476 }