]> git.sesse.net Git - vlc/blob - modules/mux/mpeg/ps.c
Merge branch 'master' of git@git.videolan.org:vlc
[vlc] / modules / mux / mpeg / ps.c
1 /*****************************************************************************
2  * ps.c: MPEG PS (ISO/IEC 13818-1) / MPEG SYSTEM (ISO/IEC 1172-1)
3  *       multiplexer module for vlc
4  *****************************************************************************
5  * Copyright (C) 2001, 2002 the VideoLAN team
6  * $Id$
7  *
8  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
9  *          Eric Petit <titer@videolan.org>
10  *          Gildas Bazin <gbazin@videolan.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/vlc.h>
36 #include <vlc_sout.h>
37 #include <vlc_codecs.h>
38 #include <vlc_block.h>
39
40 #include "bits.h"
41 #include "pes.h"
42
43 #include "iso_lang.h"
44
45 /*****************************************************************************
46  * Module descriptor
47  *****************************************************************************/
48 #define DTS_TEXT N_("DTS delay (ms)")
49 #define DTS_LONGTEXT N_("Delay the DTS (decoding time " \
50   "stamps) and PTS (presentation timestamps) of the data in the " \
51   "stream, compared to the SCRs. This allows for some buffering inside " \
52   "the client decoder.")
53
54 #define PES_SIZE_TEXT N_("PES maximum size")
55 #define PES_SIZE_LONGTEXT N_("Set the maximum allowed PES "\
56   "size when producing the MPEG PS streams.")
57
58 static int     Open   ( vlc_object_t * );
59 static void    Close  ( vlc_object_t * );
60
61 #define SOUT_CFG_PREFIX "sout-ps-"
62
63 vlc_module_begin();
64     set_description( _("PS muxer") );
65     set_shortname( "MPEG-PS" );
66     set_category( CAT_SOUT );
67     set_subcategory( SUBCAT_SOUT_MUX );
68     set_capability( "sout mux", 50 );
69     add_shortcut( "ps" );
70     add_shortcut( "mpeg1" );
71     add_shortcut( "dvd" );
72     set_callbacks( Open, Close );
73
74     add_integer( SOUT_CFG_PREFIX "dts-delay", 200, NULL, DTS_TEXT,
75                  DTS_LONGTEXT, true );
76     add_integer( SOUT_CFG_PREFIX "pes-max-size", PES_PAYLOAD_SIZE_MAX, NULL,
77                  PES_SIZE_TEXT, PES_SIZE_LONGTEXT, true );
78 vlc_module_end();
79
80 /*****************************************************************************
81  * Exported prototypes
82  *****************************************************************************/
83 static int Control  ( sout_mux_t *, int, va_list );
84 static int AddStream( sout_mux_t *, sout_input_t * );
85 static int DelStream( sout_mux_t *, sout_input_t * );
86 static int Mux      ( sout_mux_t * );
87
88 /*****************************************************************************
89  * Local prototypes
90  *****************************************************************************/
91 static int  MuxGetStream        ( sout_mux_t *, int *, mtime_t * );
92
93 static void MuxWritePackHeader  ( sout_mux_t *, block_t **, mtime_t );
94 static void MuxWriteSystemHeader( sout_mux_t *, block_t **, mtime_t );
95 static void MuxWritePSM         ( sout_mux_t *, block_t **, mtime_t );
96
97 static void StreamIdInit        ( bool *id, int i_range );
98 static int  StreamIdGet         ( bool *id, int i_id_min, int i_id_max );
99 static void StreamIdRelease     ( bool *id, int i_id_min, int i_id );
100
101 typedef struct ps_stream_s
102 {
103     int i_stream_id;
104     int i_stream_type;
105     int i_max_buff_size; /* used in system header */
106
107     /* Language is iso639-2T */
108     uint8_t lang[3];
109
110 } ps_stream_t;
111
112 struct sout_mux_sys_t
113 {
114     /* Which id are unused */
115     bool  stream_id_mpga[16]; /* 0xc0 -> 0xcf */
116     bool  stream_id_mpgv[16]; /* 0xe0 -> 0xef */
117     bool  stream_id_a52[8];   /* 0x80 -> 0x87 <- FIXME I'm not sure */
118     bool  stream_id_spu[32];  /* 0x20 -> 0x3f */
119     bool  stream_id_dts[8];   /* 0x88 -> 0x8f */
120     bool  stream_id_lpcm[16]; /* 0xa0 -> 0xaf */
121
122     int i_audio_bound;
123     int i_video_bound;
124     int i_pes_count;
125     int i_system_header;
126     int i_dts_delay;
127     int i_rate_bound; /* units of 50 bytes/second */
128  
129     int64_t i_instant_bitrate;
130     int64_t i_instant_size;
131     int64_t i_instant_dts;
132
133     bool b_mpeg2;
134
135     int i_pes_max_size;
136
137     int i_psm_version;
138     uint32_t crc32_table[256];
139 };
140
141 static const char *ppsz_sout_options[] = {
142     "dts-delay", "pes-max-size", NULL
143 };
144
145 /*****************************************************************************
146  * Open:
147  *****************************************************************************/
148 static int Open( vlc_object_t *p_this )
149 {
150     sout_mux_t *p_mux = (sout_mux_t*)p_this;
151     sout_mux_sys_t *p_sys;
152     vlc_value_t val;
153
154     msg_Info( p_mux, "Open" );
155     config_ChainParse( p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg );
156
157     p_mux->pf_control   = Control;
158     p_mux->pf_addstream = AddStream;
159     p_mux->pf_delstream = DelStream;
160     p_mux->pf_mux       = Mux;
161     p_mux->p_sys        = p_sys = malloc( sizeof( sout_mux_sys_t ) );
162
163     /* Init free stream id */
164     StreamIdInit( p_sys->stream_id_a52,  8  );
165     StreamIdInit( p_sys->stream_id_dts,  8  );
166     StreamIdInit( p_sys->stream_id_mpga, 16 );
167     StreamIdInit( p_sys->stream_id_mpgv, 16 );
168     StreamIdInit( p_sys->stream_id_lpcm, 16 );
169     StreamIdInit( p_sys->stream_id_spu,  32 );
170
171     p_sys->i_audio_bound   = 0;
172     p_sys->i_video_bound   = 0;
173     p_sys->i_system_header = 0;
174     p_sys->i_pes_count     = 0;
175
176     p_sys->i_psm_version   = 0;
177
178     p_sys->i_instant_bitrate  = 0;
179     p_sys->i_instant_size     = 0;
180     p_sys->i_instant_dts      = 0;
181     p_sys->i_rate_bound      = 0;
182     p_sys->b_mpeg2 = !(p_mux->psz_mux && !strcmp( p_mux->psz_mux, "mpeg1" ));
183
184     var_Get( p_mux, SOUT_CFG_PREFIX "dts-delay", &val );
185     p_sys->i_dts_delay = (int64_t)val.i_int * 1000;
186
187     var_Get( p_mux, SOUT_CFG_PREFIX "pes-max-size", &val );
188     p_sys->i_pes_max_size = (int64_t)val.i_int;
189
190     /* Initialise CRC32 table */
191     if( p_sys->b_mpeg2 )
192     {
193         uint32_t i, j, k;
194
195         for( i = 0; i < 256; i++ )
196         {
197             k = 0;
198             for( j = (i << 24) | 0x800000; j != 0x80000000; j <<= 1 )
199                 k = (k << 1) ^ (((k ^ j) & 0x80000000) ? 0x04c11db7 : 0);
200
201             p_sys->crc32_table[i] = k;
202         }
203     }
204
205     return VLC_SUCCESS;
206 }
207
208 /*****************************************************************************
209  * Close:
210  *****************************************************************************/
211 static void Close( vlc_object_t * p_this )
212 {
213     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
214     sout_mux_sys_t  *p_sys = p_mux->p_sys;
215
216     block_t   *p_end;
217
218     msg_Info( p_mux, "Close" );
219
220     p_end = block_New( p_mux, 4 );
221     p_end->p_buffer[0] = 0x00; p_end->p_buffer[1] = 0x00;
222     p_end->p_buffer[2] = 0x01; p_end->p_buffer[3] = 0xb9;
223
224     sout_AccessOutWrite( p_mux->p_access, p_end );
225
226     free( p_sys );
227 }
228
229 /*****************************************************************************
230  * Control:
231  *****************************************************************************/
232 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
233 {
234     VLC_UNUSED(p_mux);
235     bool *pb_bool;
236     char **ppsz;
237
238     switch( i_query )
239     {
240         case MUX_CAN_ADD_STREAM_WHILE_MUXING:
241             pb_bool = (bool*)va_arg( args, bool * );
242             *pb_bool = true;
243             return VLC_SUCCESS;
244
245         case MUX_GET_ADD_STREAM_WAIT:
246             pb_bool = (bool*)va_arg( args, bool * );
247             *pb_bool = false;
248             return VLC_SUCCESS;
249
250         case MUX_GET_MIME:
251             ppsz = (char**)va_arg( args, char ** );
252             *ppsz = strdup( "video/mpeg" );
253             return VLC_SUCCESS;
254
255         default:
256             return VLC_EGENERIC;
257     }
258 }
259
260 /*****************************************************************************
261  * AddStream:
262  *****************************************************************************/
263 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
264 {
265     sout_mux_sys_t  *p_sys = p_mux->p_sys;
266     ps_stream_t *p_stream;
267  
268
269     msg_Dbg( p_mux, "adding input codec=%4.4s",
270              (char*)&p_input->p_fmt->i_codec );
271
272     p_input->p_sys = p_stream = malloc( sizeof( ps_stream_t ) );
273     p_stream->i_stream_type = 0x81;
274
275     /* Init this new stream */
276     switch( p_input->p_fmt->i_codec )
277     {
278         case VLC_FOURCC( 'm', 'p', '1', 'v' ):
279             p_stream->i_stream_id =
280                 StreamIdGet( p_sys->stream_id_mpgv, 0xe0, 0xef );
281             p_stream->i_stream_type = 0x01; /* ISO/IEC 11172 Video */
282             break;
283         case VLC_FOURCC( 'm', 'p', '2', 'v' ):
284         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
285             p_stream->i_stream_id =
286                 StreamIdGet( p_sys->stream_id_mpgv, 0xe0, 0xef );
287             p_stream->i_stream_type = 0x02; /* ISO/IEC 13818 Video */
288             break;
289         case VLC_FOURCC( 'm', 'p', '4', 'v' ):
290             p_stream->i_stream_id =
291                 StreamIdGet( p_sys->stream_id_mpgv, 0xe0, 0xef );
292             p_stream->i_stream_type = 0x10;
293             break;
294         case VLC_FOURCC( 'h', '2', '6', '4' ):
295             p_stream->i_stream_id =
296                 StreamIdGet( p_sys->stream_id_mpgv, 0xe0, 0xef );
297             p_stream->i_stream_type = 0x1b;
298             break;
299         case VLC_FOURCC( 'l', 'p', 'c', 'm' ):
300             p_stream->i_stream_id =
301                 0xbd00 | StreamIdGet( p_sys->stream_id_lpcm, 0xa0, 0xaf );
302             break;
303         case VLC_FOURCC( 'd', 't', 's', ' ' ):
304             p_stream->i_stream_id =
305                 0xbd00 | StreamIdGet( p_sys->stream_id_dts, 0x88, 0x8f );
306             break;
307         case VLC_FOURCC( 'a', '5', '2', ' ' ):
308             p_stream->i_stream_id =
309                 0xbd00 | StreamIdGet( p_sys->stream_id_a52, 0x80, 0x87 );
310             break;
311         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
312             p_stream->i_stream_id =
313                 StreamIdGet( p_sys->stream_id_mpga, 0xc0, 0xcf );
314             p_stream->i_stream_type = 0x03; /* ISO/IEC 11172 Audio */
315             break;
316         case VLC_FOURCC( 'm', 'p', '4', 'a' ):
317             p_stream->i_stream_id =
318                 StreamIdGet( p_sys->stream_id_mpga, 0xc0, 0xcf );
319             p_stream->i_stream_type = 0x0f;
320             break;
321         case VLC_FOURCC( 's', 'p', 'u', ' ' ):
322             p_stream->i_stream_id =
323                 0xbd00 | StreamIdGet( p_sys->stream_id_spu, 0x20, 0x3f );
324             break;
325         default:
326             goto error;
327     }
328
329     if( p_stream->i_stream_id < 0 ) goto error;
330
331     if( p_input->p_fmt->i_cat == AUDIO_ES )
332     {
333         p_sys->i_audio_bound++;
334         p_stream->i_max_buff_size = 4 * 1024;
335     }
336     else if( p_input->p_fmt->i_cat == VIDEO_ES )
337     {
338         p_sys->i_video_bound++;
339         p_stream->i_max_buff_size = 400 * 1024; /* FIXME -- VCD uses 46, SVCD
340                         uses 230, ffmpeg has 230 with a note that it is small */
341     }
342     else
343     {   /* FIXME -- what's valid for not audio or video? */
344         p_stream->i_max_buff_size = 4 * 1024;
345     }
346
347     /* Try to set a sensible default value for the instant bitrate */
348     p_sys->i_instant_bitrate += p_input->p_fmt->i_bitrate + 1000/* overhead */;
349
350     /* FIXME -- spec requires  an upper limit rate boundary in the system header;
351        our codecs are VBR; using 2x nominal rate, convert to 50 bytes/sec */
352     p_sys->i_rate_bound += p_input->p_fmt->i_bitrate * 2 / (8 * 50);
353     p_sys->i_psm_version++;
354
355     p_stream->lang[0] = p_stream->lang[1] = p_stream->lang[2] = 0;
356     if( p_input->p_fmt->psz_language )
357     {
358         char *psz = p_input->p_fmt->psz_language;
359         const iso639_lang_t *pl = NULL;
360
361         if( strlen( psz ) == 2 )
362         {
363             pl = GetLang_1( psz );
364         }
365         else if( strlen( psz ) == 3 )
366         {
367             pl = GetLang_2B( psz );
368             if( !strcmp( pl->psz_iso639_1, "??" ) )
369             {
370                 pl = GetLang_2T( psz );
371             }
372         }
373         if( pl && strcmp( pl->psz_iso639_1, "??" ) )
374         {
375             p_stream->lang[0] = pl->psz_iso639_2T[0];
376             p_stream->lang[1] = pl->psz_iso639_2T[1];
377             p_stream->lang[2] = pl->psz_iso639_2T[2];
378
379             msg_Dbg( p_mux, "    - lang=%c%c%c",
380                      p_stream->lang[0], p_stream->lang[1], p_stream->lang[2] );
381         }
382     }
383     return VLC_SUCCESS;
384
385 error:
386     free( p_stream );
387     return VLC_EGENERIC;
388 }
389
390 /*****************************************************************************
391  * DelStream:
392  *****************************************************************************/
393 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
394 {
395     sout_mux_sys_t *p_sys = p_mux->p_sys;
396     ps_stream_t *p_stream =(ps_stream_t*)p_input->p_sys;
397
398     msg_Dbg( p_mux, "removing input" );
399     switch( p_input->p_fmt->i_codec )
400     {
401         case VLC_FOURCC( 'm', 'p', 'g', 'v' ):
402             StreamIdRelease( p_sys->stream_id_mpgv, 0xe0,
403                              p_stream->i_stream_id );
404             break;
405         case VLC_FOURCC( 'l', 'p', 'c', 'm' ):
406             StreamIdRelease( p_sys->stream_id_lpcm, 0xa0,
407                              p_stream->i_stream_id&0xff );
408             break;
409         case VLC_FOURCC( 'd', 't', 's', ' ' ):
410             StreamIdRelease( p_sys->stream_id_dts, 0x88,
411                              p_stream->i_stream_id&0xff );
412             break;
413         case VLC_FOURCC( 'a', '5', '2', ' ' ):
414             StreamIdRelease( p_sys->stream_id_a52, 0x80,
415                              p_stream->i_stream_id&0xff );
416             break;
417         case VLC_FOURCC( 'm', 'p', 'g', 'a' ):
418             StreamIdRelease( p_sys->stream_id_mpga, 0xc0,
419                              p_stream->i_stream_id  );
420             break;
421         case VLC_FOURCC( 's', 'p', 'u', ' ' ):
422             StreamIdRelease( p_sys->stream_id_spu, 0x20,
423                              p_stream->i_stream_id&0xff );
424             break;
425         default:
426             /* Never reached */
427             break;
428     }
429
430     if( p_input->p_fmt->i_cat == AUDIO_ES )
431     {
432         p_sys->i_audio_bound--;
433     }
434     else if( p_input->p_fmt->i_cat == VIDEO_ES )
435     {
436         p_sys->i_video_bound--;
437     }
438
439     /* Try to set a sensible default value for the instant bitrate */
440     p_sys->i_instant_bitrate -= (p_input->p_fmt->i_bitrate + 1000);
441     /* rate_bound is in units of 50 bytes/second */
442     p_sys->i_rate_bound -= (p_input->p_fmt->i_bitrate * 2)/(8 * 50);
443
444     p_sys->i_psm_version++;
445
446     free( p_stream );
447     return VLC_SUCCESS;
448 }
449
450 /*****************************************************************************
451  * Mux: Call each time there is new data for at least one stream
452  *****************************************************************************/
453 static int Mux( sout_mux_t *p_mux )
454 {
455     sout_mux_sys_t *p_sys = p_mux->p_sys;
456
457     for( ;; )
458     {
459         sout_input_t *p_input;
460         ps_stream_t *p_stream;
461
462         block_t *p_ps, *p_data;
463
464         mtime_t        i_dts;
465         int            i_stream;
466
467         /* Choose which stream to mux */
468         if( MuxGetStream( p_mux, &i_stream, &i_dts ) )
469         {
470             return VLC_SUCCESS;
471         }
472
473         p_input  = p_mux->pp_inputs[i_stream];
474         p_stream = (ps_stream_t*)p_input->p_sys;
475         p_ps     = NULL;
476
477         /* Write regulary PackHeader */
478         if( p_sys->i_pes_count % 30 == 0)
479         {
480             /* Update the instant bitrate every second or so */
481             if( p_sys->i_instant_size &&
482                 i_dts - p_sys->i_instant_dts > 1000000 )
483             {
484                 int64_t i_instant_bitrate = p_sys->i_instant_size * 8000000 /
485                     ( i_dts - p_sys->i_instant_dts );
486
487                 p_sys->i_instant_bitrate += i_instant_bitrate;
488                 p_sys->i_instant_bitrate /= 2;
489
490                 p_sys->i_instant_size = 0;
491                 p_sys->i_instant_dts = i_dts;
492             }
493             else if( !p_sys->i_instant_size )
494             {
495                 p_sys->i_instant_dts = i_dts;
496             }
497
498             MuxWritePackHeader( p_mux, &p_ps, i_dts );
499         }
500
501         /* Write regulary SystemHeader */
502         if( p_sys->i_pes_count % 300 == 0 )
503         {
504             block_t *p_pk;
505
506             MuxWriteSystemHeader( p_mux, &p_ps, i_dts );
507
508             /* For MPEG1 streaming, set HEADER flag */
509             for( p_pk = p_ps; p_pk != NULL; p_pk = p_pk->p_next )
510             {
511                 p_pk->i_flags |= BLOCK_FLAG_HEADER;
512             }
513         }
514
515         /* Write regulary ProgramStreamMap */
516         if( p_sys->b_mpeg2 && p_sys->i_pes_count % 300 == 0 )
517         {
518             MuxWritePSM( p_mux, &p_ps, i_dts );
519         }
520
521         /* Get and mux a packet */
522         p_data = block_FifoGet( p_input->p_fifo );
523         E_( EStoPES )( p_mux->p_sout, &p_data, p_data,
524                        p_input->p_fmt, p_stream->i_stream_id,
525                        p_sys->b_mpeg2, 0, 0, p_sys->i_pes_max_size );
526
527         block_ChainAppend( &p_ps, p_data );
528
529         /* Get size of output data so we can calculate the instant bitrate */
530         for( p_data = p_ps; p_data; p_data = p_data->p_next )
531         {
532             p_sys->i_instant_size += p_data->i_buffer;
533         }
534
535         sout_AccessOutWrite( p_mux->p_access, p_ps );
536
537         /* Increase counter */
538         p_sys->i_pes_count++;
539     }
540
541     return VLC_SUCCESS;
542 }
543
544 /*****************************************************************************
545  *
546  *****************************************************************************/
547 static void StreamIdInit( bool *id, int i_range )
548 {
549     int i;
550
551     for( i = 0; i < i_range; i++ )
552     {
553         id[i] = true;
554     }
555 }
556 static int StreamIdGet( bool *id, int i_id_min, int i_id_max )
557 {
558     int i;
559
560     for( i = 0; i <= i_id_max - i_id_min; i++ )
561     {
562         if( id[i] )
563         {
564             id[i] = false;
565
566             return i_id_min + i;
567         }
568     }
569     return -1;
570 }
571 static void StreamIdRelease( bool *id, int i_id_min, int i_id )
572 {
573     id[i_id - i_id_min] = true;
574 }
575
576 static void MuxWritePackHeader( sout_mux_t *p_mux, block_t **p_buf,
577                                 mtime_t i_dts )
578 {
579     sout_mux_sys_t *p_sys = p_mux->p_sys;
580     bits_buffer_t bits;
581     block_t *p_hdr;
582     mtime_t i_scr;
583     int i_mux_rate;
584
585     i_scr = (i_dts - p_sys->i_dts_delay) * 9 / 100;
586
587     p_hdr = block_New( p_mux, 18 );
588     p_hdr->i_pts = p_hdr->i_dts = i_dts;
589     bits_initwrite( &bits, 14, p_hdr->p_buffer );
590     bits_write( &bits, 32, 0x01ba );
591
592     /* The spec specifies that the mux rate must be rounded upwards */
593     i_mux_rate = (p_sys->i_instant_bitrate + 8 * 50 - 1 ) / (8 * 50);
594
595     if( p_sys->b_mpeg2 )
596     {
597         bits_write( &bits, 2, 0x01 );
598     }
599     else
600     {
601         bits_write( &bits, 4, 0x02 );
602     }
603
604     bits_write( &bits, 3, ( i_scr >> 30 )&0x07 );
605     bits_write( &bits, 1,  1 ); // marker
606     bits_write( &bits, 15, ( i_scr >> 15 )&0x7fff );
607     bits_write( &bits, 1,  1 ); // marker
608     bits_write( &bits, 15, i_scr&0x7fff );
609     bits_write( &bits, 1,  1 ); // marker
610
611     if( p_sys->b_mpeg2 )
612     {
613         bits_write( &bits, 9,  0 ); // src extension
614     }
615     bits_write( &bits, 1,  1 );     // marker
616
617     bits_write( &bits, 22, i_mux_rate);
618     bits_write( &bits, 1,  1 );     // marker
619
620     if( p_sys->b_mpeg2 )
621     {
622         bits_write( &bits, 1,  1 );     // marker
623         bits_write( &bits, 5,  0x1f );  // reserved
624         bits_write( &bits, 3,  0 );     // stuffing bytes
625     }
626
627     p_hdr->i_buffer = p_sys->b_mpeg2 ? 14: 12;
628
629     block_ChainAppend( p_buf, p_hdr );
630 }
631
632 static void MuxWriteSystemHeader( sout_mux_t *p_mux, block_t **p_buf,
633                                   mtime_t i_dts )
634 {
635     sout_mux_sys_t  *p_sys = p_mux->p_sys;
636     block_t   *p_hdr;
637     bits_buffer_t   bits;
638     bool      b_private;
639     int i_rate_bound;
640
641     int             i_nb_private, i_nb_stream;
642     int i;
643
644     /* Count the number of private stream */
645     for( i = 0, i_nb_private = 0; i < p_mux->i_nb_inputs; i++ )
646     {
647         ps_stream_t *p_stream;
648
649         p_stream = (ps_stream_t*)p_mux->pp_inputs[i]->p_sys;
650
651         if( ( p_stream->i_stream_id&0xff00 ) == 0xbd00 )
652         {
653             i_nb_private++;
654         }
655     }
656
657     /* Private stream are declared only one time */
658     i_nb_stream = p_mux->i_nb_inputs -
659         ( i_nb_private > 0 ? i_nb_private - 1 : 0 );
660
661     p_hdr = block_New( p_mux, 12 + i_nb_stream * 3 );
662     p_hdr->i_dts = p_hdr->i_pts = i_dts;
663
664     /* The spec specifies that the reported rate_bound must be upper limit */
665     i_rate_bound = (p_sys->i_rate_bound);
666
667     bits_initwrite( &bits, 12 + i_nb_stream * 3, p_hdr->p_buffer );
668     bits_write( &bits, 32, 0x01bb );
669     bits_write( &bits, 16, 12 - 6 + i_nb_stream * 3 );
670     bits_write( &bits, 1,  1 ); // marker bit
671     bits_write( &bits, 22, i_rate_bound);
672     bits_write( &bits, 1,  1 ); // marker bit
673
674     bits_write( &bits, 6,  p_sys->i_audio_bound );
675     bits_write( &bits, 1,  0 ); // fixed flag
676     bits_write( &bits, 1,  0 ); // CSPS flag
677     bits_write( &bits, 1,  0 ); // system audio lock flag
678     bits_write( &bits, 1,  0 ); // system video lock flag
679
680     bits_write( &bits, 1,  1 ); // marker bit
681
682     bits_write( &bits, 5,  p_sys->i_video_bound );
683     bits_write( &bits, 1,  1 ); // packet rate restriction flag (1 for mpeg1)
684     bits_write( &bits, 7,  0xff ); // reserved bits
685
686     /* stream_id table */
687     for( i = 0, b_private = false; i < p_mux->i_nb_inputs; i++ )
688     {
689         sout_input_t *p_input;
690         ps_stream_t *p_stream;
691
692         p_input = p_mux->pp_inputs[i];
693         p_stream = (ps_stream_t *)p_input->p_sys;
694
695         if( ( p_stream->i_stream_id&0xff00 ) == 0xbd00 )
696         {
697             if( b_private )
698             {
699                 continue;
700             }
701             b_private = true;
702             /* Write stream id */
703             bits_write( &bits, 8, 0xbd );
704         }
705         else
706         {
707             /* Write stream id */
708             bits_write( &bits, 8, p_stream->i_stream_id&0xff );
709         }
710
711         bits_write( &bits, 2, 0x03 ); /* reserved */
712         if( p_input->p_fmt->i_cat == AUDIO_ES )
713         {
714             bits_write( &bits, 1, 0 );
715             bits_write( &bits, 13, p_stream->i_max_buff_size / 128 );
716         }
717         else if( p_input->p_fmt->i_cat == VIDEO_ES )
718         {
719             bits_write( &bits, 1, 1 );
720             bits_write( &bits, 13, p_stream->i_max_buff_size / 1024);
721         }
722         else
723         {
724             /* FIXME -- the scale of 0 means do a /128 */
725             bits_write( &bits, 1, 0 );
726             bits_write( &bits, 13, p_stream->i_max_buff_size / 128 );
727         }
728     }
729
730     block_ChainAppend( p_buf, p_hdr );
731 }
732
733 static void MuxWritePSM( sout_mux_t *p_mux, block_t **p_buf, mtime_t i_dts )
734 {
735     sout_mux_sys_t *p_sys = p_mux->p_sys;
736     block_t *p_hdr;
737     bits_buffer_t bits;
738     int i, i_psm_size = 16, i_es_map_size = 0;
739
740     for( i = 0; i < p_mux->i_nb_inputs; i++ )
741     {
742         sout_input_t *p_input = p_mux->pp_inputs[i];
743         ps_stream_t *p_stream = p_input->p_sys;
744
745         i_es_map_size += 4;
746         if( p_stream->lang[0] != 0 ) i_es_map_size += 6;
747     }
748
749     i_psm_size += i_es_map_size;
750
751     p_hdr = block_New( p_mux, i_psm_size );
752     p_hdr->i_dts = p_hdr->i_pts = i_dts;
753
754     memset( p_hdr->p_buffer, 0, p_hdr->i_buffer );
755     bits_initwrite( &bits, i_psm_size, p_hdr->p_buffer );
756     bits_write( &bits, 32, 0x01bc );
757     bits_write( &bits, 16, i_psm_size - 6 );
758     bits_write( &bits, 1, 1 ); /* current_next_indicator */
759     bits_write( &bits, 2, 0xF ); /* reserved */
760     bits_write( &bits, 5, p_sys->i_psm_version );
761     bits_write( &bits, 7, 0xFF ); /* reserved */
762     bits_write( &bits, 1, 1 ); /* marker */
763
764     bits_write( &bits, 16, 0 ); /* program_stream_info_length */
765     /* empty */
766
767     bits_write( &bits, 16, i_es_map_size ); /* elementary_stream_map_length */
768     for( i = 0; i < p_mux->i_nb_inputs; i++ )
769     {
770         sout_input_t *p_input = p_mux->pp_inputs[i];
771         ps_stream_t *p_stream = p_input->p_sys;
772
773         bits_write( &bits, 8, p_stream->i_stream_type ); /* stream_type */
774         bits_write( &bits, 8, p_stream->i_stream_id ); /* elementary_stream_id */
775
776         /* ISO639 language descriptor */
777         if( p_stream->lang[0] != 0 )
778         {
779             bits_write( &bits, 16, 6 ); /* elementary_stream_info_length */
780
781             bits_write( &bits, 8, 0x0a ); /* descriptor_tag */
782             bits_write( &bits, 8, 4 ); /* descriptor_length */
783
784             bits_write( &bits, 8, p_stream->lang[0] );
785             bits_write( &bits, 8, p_stream->lang[1] );
786             bits_write( &bits, 8, p_stream->lang[2] );
787             bits_write( &bits, 8, 0 ); /* audio type: 0x00 undefined */
788         }
789         else
790         {
791             bits_write( &bits, 16, 0 ); /* elementary_stream_info_length */
792         }
793     }
794
795     /* CRC32 */
796     {
797         uint32_t i_crc = 0xffffffff;
798         for( i = 0; (size_t)i < p_hdr->i_buffer; i++ )
799         i_crc = (i_crc << 8) ^
800             p_sys->crc32_table[((i_crc >> 24) ^ p_hdr->p_buffer[i]) & 0xff];
801
802         bits_write( &bits, 32, i_crc );
803     }
804
805     block_ChainAppend( p_buf, p_hdr );
806 }
807
808 /*
809  * Find stream to be muxed.
810  */
811 static int MuxGetStream( sout_mux_t *p_mux, int *pi_stream, mtime_t *pi_dts )
812 {
813     mtime_t i_dts;
814     int     i_stream, i;
815
816     for( i = 0, i_dts = 0, i_stream = -1; i < p_mux->i_nb_inputs; i++ )
817     {
818         sout_input_t *p_input = p_mux->pp_inputs[i];
819         block_t *p_data;
820
821         if( block_FifoCount( p_input->p_fifo ) <= 0 )
822         {
823             if( p_input->p_fmt->i_cat == AUDIO_ES ||
824                 p_input->p_fmt->i_cat == VIDEO_ES )
825             {
826                 /* We need that audio+video fifo contain at least 1 packet */
827                 return VLC_EGENERIC;
828             }
829
830             /* SPU */
831             continue;
832         }
833
834         p_data = block_FifoShow( p_input->p_fifo );
835         if( i_stream == -1 || p_data->i_dts < i_dts )
836         {
837             i_stream = i;
838             i_dts    = p_data->i_dts;
839         }
840     }
841
842     *pi_stream = i_stream;
843     *pi_dts = i_dts;
844
845     return VLC_SUCCESS;
846 }