* all: new sout scheme. Now a chain of module are created that can
[vlc.git] / modules / packetizer / mpegvideo.c
1 /*****************************************************************************
2  * mpegvideo.c
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 VideoLAN
5  * $Id: mpegvideo.c,v 1.12 2003/04/13 20:00:21 fenrir 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_packetizer_input_t *p_sout_input;
48     sout_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     p_pack->output_format.i_width  = 0;
161     p_pack->output_format.i_height = 0;
162     p_pack->output_format.i_bitrate= 0;
163     p_pack->output_format.i_extra_data = 0;
164     p_pack->output_format.p_extra_data = NULL;
165
166     p_pack->p_sout_input = NULL;
167
168     if( InitBitstream( &p_pack->bit_stream, p_pack->p_fifo,
169                        NULL, NULL ) != VLC_SUCCESS )
170     {
171         msg_Err( p_pack->p_fifo, "cannot initialize bitstream" );
172         return -1;
173     }
174
175     p_pack->i_last_picture_structure = 0x03; /* frame picture */
176     return( 0 );
177 }
178
179 /* from ISO 13818-2 */
180 /* converting frame_rate_code to frame_rate */
181 static const double pd_frame_rates[16] =
182 {
183     0, 24000/1001, 24, 25, 30000/1001, 30, 50, 60000/1001, 60,
184     0, 0, 0, 0, 0, 0, 0
185 };
186
187 static int CopyUntilNextStartCode( packetizer_t   *p_pack,
188                                    sout_buffer_t  *p_sout_buffer,
189                                    unsigned int   *pi_pos )
190 {
191     int i_copy = 0;
192
193     do
194     {
195         p_sout_buffer->p_buffer[(*pi_pos)++] =
196                 GetBits( &p_pack->bit_stream, 8 );
197         i_copy++;
198
199         if( *pi_pos + 2048 > p_sout_buffer->i_buffer_size )
200         {
201             sout_BufferRealloc( p_pack->p_sout_input->p_sout,
202                                 p_sout_buffer,
203                                 p_sout_buffer->i_buffer_size + 50 * 1024);
204         }
205
206     } while( ShowBits( &p_pack->bit_stream, 24 ) != 0x01 &&
207              !p_pack->p_fifo->b_die && !p_pack->p_fifo->b_error );
208
209     return( i_copy );
210 }
211
212 /*****************************************************************************
213  * PacketizeThread: packetize an unit (here copy a complete pes)
214  *****************************************************************************/
215 static void PacketizeThread( packetizer_t *p_pack )
216 {
217     sout_buffer_t *p_sout_buffer = NULL;
218     int32_t       i_pos;
219     int           i_skipped;
220     mtime_t       i_duration; /* of the parsed picture */
221
222     mtime_t       i_pts;
223     mtime_t       i_dts;
224
225     /* needed to calculate pts/dts */
226     int i_temporal_ref = 0;
227     int i_picture_structure = 0x03; /* frame picture */
228     int i_top_field_first = 0;
229     int i_repeat_first_field = 0;
230
231     if( !p_pack->p_sout_input )
232     {
233         byte_t p_temp[512];/* 150 bytes is the maximal size
234                                of a sequence_header + sequence_extension */
235         int i_frame_rate_code;
236
237
238         /* skip data until we find a sequence_header_code */
239         /* TODO: store skipped somewhere so can send it to the mux
240          * after the input is created */
241         i_skipped = 0;
242         while( ShowBits( &p_pack->bit_stream, 32 ) != 0x1B3 &&
243                !p_pack->p_fifo->b_die && !p_pack->p_fifo->b_error )
244         {
245             RemoveBits( &p_pack->bit_stream, 8 );
246             i_skipped++;
247         }
248         msg_Warn( p_pack->p_fifo, "sequence_header_code found (%d skipped)",
249                  i_skipped );
250
251         /* copy the start_code */
252         i_pos = 0;
253         GetChunk( &p_pack->bit_stream, p_temp, 4 ); i_pos += 4;
254
255         /* horizontal_size_value */
256         p_pack->output_format.i_width = ShowBits( &p_pack->bit_stream, 12 );
257         /* vertical_size_value */
258         p_pack->output_format.i_height= ShowBits( &p_pack->bit_stream, 24 ) & 0xFFF;
259         /* frame_rate_code */
260         i_frame_rate_code = ShowBits( &p_pack->bit_stream, 32 ) & 0xF;
261
262         /* copy headers */
263         GetChunk( &p_pack->bit_stream, p_temp + i_pos, 7 ); i_pos += 7;
264
265         /* intra_quantiser_matrix [non_intra_quantiser_matrix] */
266         if( ShowBits( &p_pack->bit_stream, 7 ) & 0x1 )
267         {
268
269             GetChunk( &p_pack->bit_stream, p_temp + i_pos, 64 ); i_pos += 64;
270
271             if( ShowBits( &p_pack->bit_stream, 8 ) & 0x1 )
272             {
273                 GetChunk( &p_pack->bit_stream, p_temp + i_pos, 65); i_pos += 65;
274             }
275         }
276         /* non_intra_quantiser_matrix */
277         else if( ShowBits( &p_pack->bit_stream, 8 ) & 0x1 )
278         {
279             GetChunk( &p_pack->bit_stream, p_temp + i_pos, 65); i_pos += 65;
280         }
281         /* nothing */
282         else
283         {
284             GetChunk( &p_pack->bit_stream, p_temp + i_pos, 1 ); i_pos += 1;
285         }
286
287         /* sequence_extension (10 bytes) */
288         if( ShowBits( &p_pack->bit_stream, 32 ) != 0x1B5 )
289         {
290             msg_Dbg( p_pack->p_fifo, "ARRGG no extension_start_code" );
291             p_pack->i_progressive_sequence = 1;
292         }
293         else
294         {
295             GetChunk( &p_pack->bit_stream, p_temp + i_pos, 10 );
296             p_pack->i_progressive_sequence = ( p_temp[i_pos+5]&0x08 ) ? 1 : 0;
297
298             i_pos += 10;
299         }
300
301         /* remember sequence_header and sequence_extention */
302         memcpy( p_pack->p_sequence_header, p_temp, i_pos );
303         p_pack->i_sequence_header_length = i_pos;
304
305         p_pack->d_frame_rate =  pd_frame_rates[i_frame_rate_code];
306
307         msg_Warn( p_pack->p_fifo,
308                   "creating input (image size %dx%d, frame rate %.2f)",
309                   p_pack->output_format.i_width,
310                   p_pack->output_format.i_height,
311                   p_pack->d_frame_rate );
312
313         /* now we have informations to create the input */
314         p_pack->p_sout_input = sout_InputNew( p_pack->p_fifo,
315                                               &p_pack->output_format );
316
317         if( !p_pack->p_sout_input )
318         {
319             msg_Err( p_pack->p_fifo, "cannot add a new stream" );
320             p_pack->p_fifo->b_error = VLC_TRUE;
321             return;
322         }
323
324         p_sout_buffer = sout_BufferNew( p_pack->p_sout_input->p_sout,
325                                         100 * 1024 );
326         p_sout_buffer->i_size = i_pos;
327         memcpy( p_sout_buffer->p_buffer, p_temp, i_pos );
328
329     }
330     else
331     {
332         p_sout_buffer =
333                 sout_BufferNew( p_pack->p_sout_input->p_sout, 100 * 1024 );
334         i_pos = 0;
335     }
336
337     p_pack->i_last_sequence_header++;
338
339     for( ;; )
340     {
341         uint32_t i_code;
342         if( p_pack->p_fifo->b_die || p_pack->p_fifo->b_error )
343         {
344             break;
345         }
346
347         i_code = ShowBits( &p_pack->bit_stream, 32 );
348
349         if( i_code == 0x1B8 ) /* GOP */
350         {
351             /* usefull for bad MPEG-1 : repeat the sequence_header
352                every second */
353             if( p_pack->i_last_sequence_header > (int) p_pack->d_frame_rate )
354             {
355                memcpy( p_sout_buffer->p_buffer + i_pos,
356                        p_pack->p_sequence_header,
357                        p_pack->i_sequence_header_length );
358                i_pos += p_pack->i_sequence_header_length;
359                p_pack->i_last_sequence_header = 0;
360             }
361
362             p_pack->i_last_ref_pts =
363                    p_pack->i_last_dts +
364                         (mtime_t)( 1000000 / p_pack->d_frame_rate); /* 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
373             NextPTS( &p_pack->bit_stream, &i_pts, &i_dts );
374             i_temporal_ref = ShowBits( &p_pack->bit_stream, 10 );
375
376             CopyUntilNextStartCode( p_pack, p_sout_buffer, &i_pos );
377             break;
378         }
379         else if( i_code == 0x1b5 )
380         {
381             /* extention start code                   32 */
382             GetChunk( &p_pack->bit_stream,
383                       p_sout_buffer->p_buffer + i_pos, 4 ); i_pos += 4;
384
385             if( ShowBits( &p_pack->bit_stream, 4 ) == 0x08 )
386             {
387                 /* picture coding extention */
388
389                 /* extention start code identifier(b1000)  4 */
390                 /* f_code[2][2]                           16 */
391                 /* intra_dc_precision                      2 */
392                 /* picture_structure                       2 */
393                 /* top_field_first                         1 */
394                 i_picture_structure =
395                     ShowBits( &p_pack->bit_stream, 24 ) & 0x03;
396                 i_top_field_first =
397                     ShowBits( &p_pack->bit_stream, 25 ) & 0x01;
398                 i_repeat_first_field =
399                     ShowBits( &p_pack->bit_stream, 31 ) & 0x01;
400             }
401             CopyUntilNextStartCode( p_pack, p_sout_buffer, &i_pos );
402         }
403         else
404         {
405             if( i_code == 0x1B3 )
406             {
407                 p_pack->i_last_sequence_header = 0;
408             }
409             CopyUntilNextStartCode( p_pack, p_sout_buffer, &i_pos );
410         }
411     }
412
413     sout_BufferRealloc( p_pack->p_sout_input->p_sout,
414                         p_sout_buffer, i_pos );
415     p_sout_buffer->i_size = i_pos;
416
417     /* calculate dts/pts */
418     if( p_pack->i_progressive_sequence || i_picture_structure == 0x03)
419     {
420         i_duration = (mtime_t)( 1000000 / p_pack->d_frame_rate );
421     }
422     else
423     {
424         i_duration = (mtime_t)( 1000000 / p_pack->d_frame_rate / 2);
425     }
426
427     /* fix i_last_dts and i_last_ref_pts with i_dts and i_pts from stream */
428     if( i_dts <= 0 && p_pack->i_last_dts <= 0 )
429     {
430         msg_Dbg( p_pack->p_fifo, "need a starting pts" );
431         sout_BufferDelete( p_pack->p_sout_input->p_sout,
432                            p_sout_buffer );
433         return;
434     }
435
436 #if 1
437     if( i_dts > 0 )
438     {
439         //if( i_dts - p_pack->i_last_dts > 200000 ||
440         //    i_dts - p_pack->i_last_dts < 200000 )
441         {
442             p_pack->i_last_dts = i_dts;
443             if( i_pts > 0 )
444             {
445                 p_pack->i_last_ref_pts = i_pts -
446                     i_temporal_ref * (mtime_t)( 1000000 / p_pack->d_frame_rate );
447             }
448         }
449     }
450 #endif
451
452     p_sout_buffer->i_dts = p_pack->i_last_dts;
453     p_sout_buffer->i_pts = p_pack->i_last_ref_pts + 
454         i_temporal_ref * (mtime_t)( 1000000 / p_pack->d_frame_rate );
455     p_sout_buffer->i_length = i_duration;
456     p_sout_buffer->i_bitrate = (int)( 8 * i_pos * p_pack->d_frame_rate );
457     sout_InputSendBuffer( p_pack->p_sout_input, p_sout_buffer );
458
459     if( p_pack->i_progressive_sequence )
460     {
461         if( i_top_field_first == 0 && i_repeat_first_field == 0 )
462         {
463             p_pack->i_last_dts += i_duration;
464         }
465         else if( i_top_field_first == 0 && i_repeat_first_field == 1 )
466         {
467             p_pack->i_last_dts += 2 * i_duration;
468         }
469         else if( i_top_field_first == 1 && i_repeat_first_field == 1 )
470         {
471             p_pack->i_last_dts += 3 * i_duration;
472         }
473     }
474     else
475     {
476         if( i_picture_structure == 0x03 )
477         {
478             p_pack->i_last_dts += i_duration;
479         }
480         else if( i_picture_structure == p_pack->i_last_picture_structure )
481         {
482             p_pack->i_last_dts += 2 * i_duration;
483         }
484         else if( ( !i_top_field_first && i_picture_structure == 0x01 ) ||
485                  (  i_top_field_first && i_picture_structure == 0x02 ) )
486         {
487             p_pack->i_last_dts += 2 * i_duration;
488         }
489     }
490     p_pack->i_last_picture_structure = i_picture_structure;
491 }
492
493
494 /*****************************************************************************
495  * EndThread : packetizer thread destruction
496  *****************************************************************************/
497 static void EndThread ( packetizer_t *p_pack)
498 {
499     if( p_pack->p_sout_input )
500     {
501         sout_InputDelete( p_pack->p_sout_input );
502     }
503 }