]> git.sesse.net Git - vlc/blob - modules/mux/mpeg/ts.c
* modules/mux/mpeg/ts.c, modules/demux/ts.c: Fixed IOD descriptor
[vlc] / modules / mux / mpeg / ts.c
1 /*****************************************************************************
2  * ts.c: MPEG-II TS Muxer
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  *
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 <stdlib.h>
29
30 #include <vlc/vlc.h>
31 #include <vlc/input.h>
32 #include <vlc/sout.h>
33
34 #include "iso_lang.h"
35
36 #include "bits.h"
37 #include "pes.h"
38 #include "csa.h"
39
40 #ifdef HAVE_DVBPSI_DR_H
41 #   include <dvbpsi/dvbpsi.h>
42 #   include <dvbpsi/descriptor.h>
43 #   include <dvbpsi/pat.h>
44 #   include <dvbpsi/pmt.h>
45 #   include <dvbpsi/dr.h>
46 #   include <dvbpsi/psi.h>
47 #else
48 #   include "dvbpsi.h"
49 #   include "descriptor.h"
50 #   include "tables/pat.h"
51 #   include "tables/pmt.h"
52 #   include "descriptors/dr.h"
53 #   include "psi.h"
54 #endif
55
56 /*
57  * TODO:
58  *  - check PCR frequency requirement
59  *  - check PAT/PMT  "        "
60  *  - check PCR/PCR "soft"
61  *  - check if "registration" descriptor : "AC-3" should be a program
62  *    descriptor or an es one. (xine want an es one)
63  *
64  *  - remove creation of PAT/PMT without dvbpsi
65  *  - ?
66  * FIXME:
67  *  - subtitle support is far from perfect. I expect some subtitles drop
68  *    if they arrive a bit late
69  *    (We cannot rely on the fact that the fifo should be full)
70  */
71 /*****************************************************************************
72  * Module descriptor
73  *****************************************************************************/
74 static int     Open   ( vlc_object_t * );
75 static void    Close  ( vlc_object_t * );
76
77 #define VPID_TEXT N_("Video PID")
78 #define VPID_LONGTEXT N_("Assigns a fixed PID to the video stream. The PCR " \
79   "PID will automatically be the video.")
80 #define APID_TEXT N_("Audio PID")
81 #define APID_LONGTEXT N_("Assigns a fixed PID to the audio stream.")
82 #define SPUPID_TEXT N_("SPU PID")
83 #define SPUPID_LONGTEXT N_("Assigns a fixed PID to the SPU.")
84 #define PMTPID_TEXT N_("PMT PID")
85 #define PMTPID_LONGTEXT N_("Assings a fixed PID to the PMT")
86 #define TSID_TEXT N_("TS ID")
87 #define TSID_LONGTEXT N_("Assigns a fixed Transport Stream ID.")
88
89 #define SHAPING_TEXT N_("Shaping delay (ms)")
90 #define SHAPING_LONGTEXT N_("If enabled, the TS muxer will cut the " \
91   "stream in slices of the given duration, and ensure a constant bitrate " \
92   "between the two boundaries. This avoids having huge bitrate peaks for " \
93   "reference frames, in particular.")
94 #define KEYF_TEXT N_("Use keyframes")
95 #define KEYF_LONGTEXT N_("If enabled, and shaping is specified, " \
96   "the TS muxer will place the boundaries at the end of I pictures. In " \
97   "that case, the shaping duration given by the user is a worse case " \
98   "used when no reference frame is available. This enhances the efficiency " \
99   "of the shaping algorithm, since I frames are usually the biggest " \
100   "frames in the stream.")
101
102 #define PCR_TEXT N_("PCR delay (ms)")
103 #define PCR_LONGTEXT N_("This option allows you to set at which interval " \
104   "PCRs (Program Clock Reference) will be sent. " \
105   "This value should be below 100ms. (default is 30)")
106
107 #define BMIN_TEXT N_( "Minimum B (deprecated)")
108 #define BMIN_LONGTEXT N_( "This setting is deprecated and not used anymore" )
109
110 #define BMAX_TEXT N_( "Maximum B (deprecated)")
111 #define BMAX_LONGTEXT N_( "This setting is deprecated and not used anymore")
112
113 #define DTS_TEXT N_("DTS delay (ms)")
114 #define DTS_LONGTEXT N_("This option will delay the DTS (decoding time " \
115   "stamps) and PTS (presentation timestamps) of the data in the " \
116   "stream, compared to the PCRs. This allows for some buffering inside " \
117   "the client decoder.")
118
119 #define ACRYPT_TEXT N_("Crypt audio")
120 #define ACRYPT_LONGTEXT N_("Crypt audio using CSA")
121
122 #define CK_TEXT N_("CSA Key")
123 #define CK_LONGTEXT N_("Defines the CSA encryption key. This must be a " \
124   "16 char string (8 hexadecimal bytes).")
125
126 #define SOUT_CFG_PREFIX "sout-ts-"
127
128 vlc_module_begin();
129     set_description( _("TS muxer (libdvbpsi)") );
130     set_shortname( "MPEG-TS");
131     set_category( CAT_SOUT );
132     set_subcategory( SUBCAT_SOUT_MUX );
133     set_capability( "sout mux", 120 );
134     add_shortcut( "ts" );
135
136     add_integer( SOUT_CFG_PREFIX "pid-video", 0, NULL,VPID_TEXT, VPID_LONGTEXT,
137                                   VLC_TRUE );
138     add_integer( SOUT_CFG_PREFIX "pid-audio", 0, NULL, APID_TEXT,
139                  APID_LONGTEXT, VLC_TRUE );
140     add_integer( SOUT_CFG_PREFIX "pid-spu", 0, NULL, SPUPID_TEXT,
141                  SPUPID_LONGTEXT, VLC_TRUE );
142     add_integer( SOUT_CFG_PREFIX "pid-pmt", 0, NULL, PMTPID_TEXT,
143                  PMTPID_LONGTEXT, VLC_TRUE );
144     add_integer( SOUT_CFG_PREFIX "tsid", 0, NULL, TSID_TEXT,
145                  TSID_LONGTEXT, VLC_TRUE );
146
147     add_integer( SOUT_CFG_PREFIX "shaping", 200, NULL,SHAPING_TEXT,
148                  SHAPING_LONGTEXT, VLC_TRUE );
149     add_bool( SOUT_CFG_PREFIX "use-key-frames", VLC_FALSE, NULL, KEYF_TEXT,
150               KEYF_LONGTEXT, VLC_TRUE );
151
152     add_integer( SOUT_CFG_PREFIX "pcr", 30, NULL, PCR_TEXT, PCR_LONGTEXT,
153                  VLC_TRUE );
154     add_integer( SOUT_CFG_PREFIX "bmin", 0, NULL, BMIN_TEXT, BMIN_LONGTEXT,
155                  VLC_TRUE );
156     add_integer( SOUT_CFG_PREFIX "bmax", 0, NULL, BMAX_TEXT, BMAX_LONGTEXT,
157                  VLC_TRUE );
158     add_integer( SOUT_CFG_PREFIX "dts-delay", 200, NULL, DTS_TEXT,
159                  DTS_LONGTEXT, VLC_TRUE );
160
161     add_bool( SOUT_CFG_PREFIX "crypt-audio", VLC_TRUE, NULL, ACRYPT_TEXT,
162               ACRYPT_LONGTEXT, VLC_TRUE );
163
164     add_string( SOUT_CFG_PREFIX "csa-ck", NULL, NULL, CK_TEXT, CK_LONGTEXT,
165                 VLC_TRUE );
166
167     set_callbacks( Open, Close );
168 vlc_module_end();
169
170 /*****************************************************************************
171  * Local data structures
172  *****************************************************************************/
173 static const char *ppsz_sout_options[] = {
174     "pid-video", "pid-audio", "pid-spu", "pid-pmt", "tsid", "shaping", "pcr",
175     "bmin", "bmax", "use-key-frames", "dts-delay", "csa-ck", "crypt-audio",
176     NULL
177 };
178
179 typedef struct
180 {
181     int     i_depth;
182     block_t *p_first;
183     block_t **pp_last;
184 } sout_buffer_chain_t;
185
186 static inline void BufferChainInit  ( sout_buffer_chain_t *c )
187 {
188     c->i_depth = 0;
189     c->p_first = NULL;
190     c->pp_last = &c->p_first;
191 }
192 static inline void BufferChainAppend( sout_buffer_chain_t *c, block_t *b )
193 {
194     *c->pp_last = b;
195     c->i_depth++;
196
197     while( b->p_next )
198     {
199         b = b->p_next;
200         c->i_depth++;
201     }
202     c->pp_last = &b->p_next;
203 }
204 static inline block_t *BufferChainGet( sout_buffer_chain_t *c )
205 {
206     block_t *b = c->p_first;
207
208     if( b )
209     {
210         c->i_depth--;
211         c->p_first = b->p_next;
212
213         if( c->p_first == NULL )
214         {
215             c->pp_last = &c->p_first;
216         }
217
218         b->p_next = NULL;
219     }
220     return b;
221 }
222 static inline block_t *BufferChainPeek( sout_buffer_chain_t *c )
223 {
224     block_t *b = c->p_first;
225
226     return b;
227 }
228 static inline void BufferChainClean( sout_instance_t *p_sout,
229                                      sout_buffer_chain_t *c )
230 {
231     block_t *b;
232
233     while( ( b = BufferChainGet( c ) ) )
234     {
235         block_Release( b );
236     }
237     BufferChainInit( c );
238 }
239
240 typedef struct ts_stream_t
241 {
242     int             i_pid;
243     vlc_fourcc_t    i_codec;
244
245     int             i_stream_type;
246     int             i_stream_id;
247     int             i_continuity_counter;
248
249     /* to be used for carriege of DIV3 */
250     vlc_fourcc_t    i_bih_codec;
251     int             i_bih_width, i_bih_height;
252
253     /* Specific to mpeg4 in mpeg2ts */
254     int             i_es_id;
255
256     int             i_decoder_specific_info;
257     uint8_t         *p_decoder_specific_info;
258
259     /* language is iso639-2T */
260     uint8_t         lang[3];
261
262     sout_buffer_chain_t chain_pes;
263     mtime_t             i_pes_dts;
264     mtime_t             i_pes_length;
265     int                 i_pes_used;
266     vlc_bool_t          b_key_frame;
267
268 } ts_stream_t;
269
270 struct sout_mux_sys_t
271 {
272     int             i_pcr_pid;
273     sout_input_t    *p_pcr_input;
274
275     int             i_audio_bound;
276     int             i_video_bound;
277
278     int             i_pid_video;
279     int             i_pid_audio;
280     int             i_pid_spu;
281     int             i_pid_free; // first usable pid
282
283     int             i_tsid;
284     int             i_pat_version_number;
285     ts_stream_t     pat;
286
287     int             i_pmt_version_number;
288     ts_stream_t     pmt;        // Up to now only one program
289
290     int             i_mpeg4_streams;
291
292     int             i_null_continuity_counter;  /* Needed ? */
293
294     /* for TS building */
295     int64_t             i_bitrate_min;
296     int64_t             i_bitrate_max;
297
298     int64_t             i_shaping_delay;
299     int64_t             i_pcr_delay;
300
301     int64_t             i_dts_delay;
302
303     vlc_bool_t          b_use_key_frames;
304
305     mtime_t             i_pcr;  /* last PCR emited */
306
307     csa_t               *csa;
308     vlc_bool_t          b_crypt_audio;
309 };
310
311
312 /* Reserve a pid and return it */
313 static int  AllocatePID( sout_mux_sys_t *p_sys, int i_cat )
314 {
315     int i_pid;
316     if ( i_cat == VIDEO_ES && p_sys->i_pid_video )
317     {
318         i_pid = p_sys->i_pid_video;
319         p_sys->i_pid_video = 0;
320     }
321     else if ( i_cat == AUDIO_ES && p_sys->i_pid_audio )
322     {
323         i_pid = p_sys->i_pid_audio;
324         p_sys->i_pid_audio = 0;
325     }
326     else if ( i_cat == SPU_ES && p_sys->i_pid_spu )
327     {
328         i_pid = p_sys->i_pid_spu;
329         p_sys->i_pid_spu = 0;
330     }
331     else
332     {
333         i_pid = ++p_sys->i_pid_free;
334     }
335     return i_pid;
336 }
337
338 /*****************************************************************************
339  * Local prototypes
340  *****************************************************************************/
341 static int Control  ( sout_mux_t *, int, va_list );
342 static int AddStream( sout_mux_t *, sout_input_t * );
343 static int DelStream( sout_mux_t *, sout_input_t * );
344 static int Mux      ( sout_mux_t * );
345
346 static void TSSchedule  ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
347                           mtime_t i_pcr_length, mtime_t i_pcr_dts );
348 static void TSDate      ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
349                           mtime_t i_pcr_length, mtime_t i_pcr_dts );
350 static void GetPAT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
351 static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
352
353 static block_t *TSNew( sout_mux_t *p_mux, ts_stream_t *p_stream, vlc_bool_t b_pcr );
354 static void TSSetPCR( block_t *p_ts, mtime_t i_dts );
355
356 static void PEStoTS  ( sout_instance_t *, sout_buffer_chain_t *, block_t *, ts_stream_t * );
357
358 /*****************************************************************************
359  * Open:
360  *****************************************************************************/
361 static int Open( vlc_object_t *p_this )
362 {
363     sout_mux_t          *p_mux =(sout_mux_t*)p_this;
364     sout_mux_sys_t      *p_sys;
365     vlc_value_t         val;
366
367     msg_Dbg( p_mux, "Open" );
368     sout_CfgParse( p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg );
369
370     p_sys = malloc( sizeof( sout_mux_sys_t ) );
371
372     p_mux->pf_control   = Control;
373     p_mux->pf_addstream = AddStream;
374     p_mux->pf_delstream = DelStream;
375     p_mux->pf_mux       = Mux;
376     p_mux->p_sys        = p_sys;
377
378     srand( (uint32_t)mdate() );
379
380     p_sys->i_audio_bound = 0;
381     p_sys->i_video_bound = 0;
382
383     p_sys->i_pat_version_number = rand() % 32;
384     p_sys->pat.i_pid = 0;
385     p_sys->pat.i_continuity_counter = 0;
386
387     var_Get( p_mux, SOUT_CFG_PREFIX "tsid", &val );
388     if ( val.i_int )
389         p_sys->i_tsid = val.i_int;
390     else
391         p_sys->i_tsid = rand() % 65536;
392     p_sys->i_pmt_version_number = rand() % 32;
393     p_sys->pmt.i_continuity_counter = 0;
394
395     var_Get( p_mux, SOUT_CFG_PREFIX "pid-pmt", &val );
396     if (val.i_int )
397     {
398         p_sys->pmt.i_pid = val.i_int;
399     }
400     else
401     {
402        p_sys->pmt.i_pid = 0x42;
403     }
404
405     p_sys->i_pid_free = p_sys->pmt.i_pid + 1;
406
407     var_Get( p_mux, SOUT_CFG_PREFIX "pid-video", &val );
408     p_sys->i_pid_video = val.i_int;
409     if ( p_sys->i_pid_video > p_sys->i_pid_free )
410     {
411         p_sys->i_pid_free = p_sys->i_pid_video + 1;
412     }
413
414     var_Get( p_mux, SOUT_CFG_PREFIX "pid-audio", &val );
415     p_sys->i_pid_audio = val.i_int;
416     if ( p_sys->i_pid_audio > p_sys->i_pid_free )
417     {
418         p_sys->i_pid_free = p_sys->i_pid_audio + 1;
419     }
420
421     var_Get( p_mux, SOUT_CFG_PREFIX "pid-spu", &val );
422     p_sys->i_pid_spu = val.i_int;
423     if ( p_sys->i_pid_spu > p_sys->i_pid_free )
424     {
425         p_sys->i_pid_free = p_sys->i_pid_spu + 1;
426     }
427
428     p_sys->i_pcr_pid = 0x1fff;
429     p_sys->p_pcr_input = NULL;
430
431     p_sys->i_mpeg4_streams = 0;
432
433     p_sys->i_null_continuity_counter = 0;
434
435     /* Allow to create constrained stream */
436     var_Get( p_mux, SOUT_CFG_PREFIX "bmin", &val );
437     p_sys->i_bitrate_min = val.i_int;
438
439     var_Get( p_mux, SOUT_CFG_PREFIX "bmax", &val );
440     p_sys->i_bitrate_max = val.i_int;
441
442     if( p_sys->i_bitrate_min > 0 && p_sys->i_bitrate_max > 0 &&
443         p_sys->i_bitrate_min > p_sys->i_bitrate_max )
444     {
445         msg_Err( p_mux, "incompatible minimum and maximum bitrate, "
446                  "disabling bitrate control" );
447         p_sys->i_bitrate_min = 0;
448         p_sys->i_bitrate_max = 0;
449     }
450     if( p_sys->i_bitrate_min > 0 || p_sys->i_bitrate_max > 0 )
451     {
452         msg_Err( p_mux, "bmin and bmax no more supported "
453                  "(if you need them report it)" );
454     }
455
456     var_Get( p_mux, SOUT_CFG_PREFIX "shaping", &val );
457     p_sys->i_shaping_delay = (int64_t)val.i_int * 1000;
458     if( p_sys->i_shaping_delay <= 0 )
459     {
460         msg_Err( p_mux,
461                  "invalid shaping ("I64Fd"ms) resetting to 200ms",
462                  p_sys->i_shaping_delay / 1000 );
463         p_sys->i_shaping_delay = 200000;
464     }
465
466     var_Get( p_mux, SOUT_CFG_PREFIX "pcr", &val );
467     p_sys->i_pcr_delay = (int64_t)val.i_int * 1000;
468     if( p_sys->i_pcr_delay <= 0 ||
469         p_sys->i_pcr_delay >= p_sys->i_shaping_delay )
470     {
471         msg_Err( p_mux,
472                  "invalid pcr delay ("I64Fd"ms) resetting to 30ms",
473                  p_sys->i_pcr_delay / 1000 );
474         p_sys->i_pcr_delay = 30000;
475     }
476
477     var_Get( p_mux, SOUT_CFG_PREFIX "dts-delay", &val );
478     p_sys->i_dts_delay = (int64_t)val.i_int * 1000;
479
480     msg_Dbg( p_mux, "shaping="I64Fd" pcr="I64Fd" dts_delay="I64Fd,
481              p_sys->i_shaping_delay, p_sys->i_pcr_delay, p_sys->i_dts_delay );
482
483     var_Get( p_mux, SOUT_CFG_PREFIX "use-key-frames", &val );
484     p_sys->b_use_key_frames = val.b_bool;
485
486     /* for TS generation */
487     p_sys->i_pcr    = 0;
488
489     p_sys->csa      = NULL;
490     var_Get( p_mux, SOUT_CFG_PREFIX "csa-ck", &val );
491     if( val.psz_string )
492     {
493         char *psz = val.psz_string;
494
495         /* skip 0x */
496         if( psz[0] == '0' && ( psz[1] == 'x' || psz[1] == 'X' ) )
497         {
498             psz += 2;
499         }
500         if( strlen( psz ) != 16 )
501         {
502             msg_Dbg( p_mux, "invalid csa ck (it must be 16 chars long)" );
503         }
504         else
505         {
506             uint64_t i_ck = strtoull( psz, NULL, 16 );
507             uint8_t  ck[8];
508             int      i;
509
510             for( i = 0; i < 8; i++ )
511             {
512                 ck[i] = ( i_ck >> ( 56 - 8*i) )&0xff;
513             }
514
515             msg_Dbg( p_mux, "using CSA scrambling with ck=%x:%x:%x:%x:%x:%x:%x:%x",
516                      ck[0], ck[1], ck[2], ck[3], ck[4], ck[5], ck[6], ck[7] );
517
518             p_sys->csa = csa_New();
519             csa_SetCW( p_sys->csa, ck, ck );
520         }
521     }
522     if( val.psz_string ) free( val.psz_string );
523
524     var_Get( p_mux, SOUT_CFG_PREFIX "crypt-audio", &val );
525     p_sys->b_crypt_audio = val.b_bool;
526
527     return VLC_SUCCESS;
528 }
529
530 /*****************************************************************************
531  * Close:
532  *****************************************************************************/
533 static void Close( vlc_object_t * p_this )
534 {
535     sout_mux_t          *p_mux = (sout_mux_t*)p_this;
536     sout_mux_sys_t      *p_sys = p_mux->p_sys;
537
538     msg_Dbg( p_mux, "Close" );
539     if( p_sys->csa )
540     {
541         csa_Delete( p_sys->csa );
542     }
543
544     free( p_sys );
545 }
546
547 /*****************************************************************************
548  * Control:
549  *****************************************************************************/
550 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
551 {
552     vlc_bool_t *pb_bool;
553     char **ppsz;
554
555    switch( i_query )
556    {
557        case MUX_CAN_ADD_STREAM_WHILE_MUXING:
558            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
559            *pb_bool = VLC_TRUE;
560            return VLC_SUCCESS;
561
562        case MUX_GET_ADD_STREAM_WAIT:
563            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
564            *pb_bool = VLC_FALSE;
565            return VLC_SUCCESS;
566
567        case MUX_GET_MIME:
568            ppsz = (char**)va_arg( args, char ** );
569            *ppsz = strdup( "video/mpeg" );  /* FIXME not sure */
570            return VLC_SUCCESS;
571
572         default:
573             return VLC_EGENERIC;
574    }
575 }
576
577 /*****************************************************************************
578  * AddStream: called for each stream addition
579  *****************************************************************************/
580 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
581 {
582     sout_mux_sys_t      *p_sys = p_mux->p_sys;
583     ts_stream_t         *p_stream;
584
585     p_input->p_sys = p_stream = malloc( sizeof( ts_stream_t ) );
586
587     /* Init this new stream */
588     p_stream->i_pid = AllocatePID( p_sys, p_input->p_fmt->i_cat );
589     p_stream->i_codec = p_input->p_fmt->i_codec;
590     p_stream->i_continuity_counter    = 0;
591     p_stream->i_decoder_specific_info = 0;
592     p_stream->p_decoder_specific_info = NULL;
593
594     msg_Dbg( p_mux, "adding input codec=%4.4s pid=%d",
595              (char*)&p_input->p_fmt->i_codec, p_stream->i_pid );
596
597     /* All others fields depand on codec */
598     switch( p_input->p_fmt->i_cat )
599     {
600         case VIDEO_ES:
601             switch( p_input->p_fmt->i_codec )
602             {
603                 case VLC_FOURCC( 'm', 'p','g', 'v' ):
604                     /* TODO: do we need to check MPEG-I/II ? */
605                     p_stream->i_stream_type = 0x02;
606                     p_stream->i_stream_id = 0xe0;
607                     break;
608                 case VLC_FOURCC( 'm', 'p','4', 'v' ):
609                     p_stream->i_stream_type = 0x10;
610                     p_stream->i_stream_id = 0xfa;
611                     p_sys->i_mpeg4_streams++;
612                     p_stream->i_es_id = p_stream->i_pid;
613                     break;
614                 case VLC_FOURCC( 'h', '2','6', '4' ):
615                     p_stream->i_stream_type = 0x1b;
616                     p_stream->i_stream_id = 0xe0;
617                     break;
618                 /* XXX dirty dirty but somebody want that:
619                  *     using crapy MS-codec XXX */
620                 /* I didn't want to do that :P */
621                 case VLC_FOURCC( 'H', '2', '6', '3' ):
622                 case VLC_FOURCC( 'I', '2', '6', '3' ):
623                 case VLC_FOURCC( 'W', 'M', 'V', '3' ):
624                 case VLC_FOURCC( 'W', 'M', 'V', '2' ):
625                 case VLC_FOURCC( 'W', 'M', 'V', '1' ):
626                 case VLC_FOURCC( 'D', 'I', 'V', '3' ):
627                 case VLC_FOURCC( 'D', 'I', 'V', '2' ):
628                 case VLC_FOURCC( 'D', 'I', 'V', '1' ):
629                 case VLC_FOURCC( 'M', 'J', 'P', 'G' ):
630                     p_stream->i_stream_type = 0xa0; // private
631                     p_stream->i_stream_id = 0xa0;   // beurk
632                     p_stream->i_bih_codec  = p_input->p_fmt->i_codec;
633                     p_stream->i_bih_width  = p_input->p_fmt->video.i_width;
634                     p_stream->i_bih_height = p_input->p_fmt->video.i_height;
635                     break;
636                 default:
637                     free( p_stream );
638                     return VLC_EGENERIC;
639             }
640             p_sys->i_video_bound++;
641             break;
642
643         case AUDIO_ES:
644             switch( p_input->p_fmt->i_codec )
645             {
646                 case VLC_FOURCC( 'm', 'p','g', 'a' ):
647                     p_stream->i_stream_type =
648                         p_input->p_fmt->audio.i_rate >= 32000 ? 0x03 : 0x04;
649                     p_stream->i_stream_id = 0xc0;
650                     break;
651                 case VLC_FOURCC( 'a', '5','2', ' ' ):
652                     p_stream->i_stream_type = 0x81;
653                     p_stream->i_stream_id = 0xbd;
654                     break;
655                 case VLC_FOURCC( 'l', 'p','c', 'm' ):
656                     p_stream->i_stream_type = 0x83;
657                     p_stream->i_stream_id = 0xbd;
658                     break;
659                 case VLC_FOURCC( 'd', 't','s', ' ' ):
660                     p_stream->i_stream_type = 0x06;
661                     p_stream->i_stream_id = 0xbd;
662                     break;
663
664                 case VLC_FOURCC( 'm', 'p','4', 'a' ):
665                     p_stream->i_stream_type = 0x11;
666                     p_stream->i_stream_id = 0xfa;
667                     p_sys->i_mpeg4_streams++;
668                     p_stream->i_es_id = p_stream->i_pid;
669                     break;
670                 default:
671                     free( p_stream );
672                     return VLC_EGENERIC;
673             }
674             p_sys->i_audio_bound++;
675             break;
676
677         case SPU_ES:
678             switch( p_input->p_fmt->i_codec )
679             {
680                 case VLC_FOURCC( 's', 'p','u', ' ' ):
681                     p_stream->i_stream_type = 0x82;
682                     p_stream->i_stream_id = 0xbd;
683                     break;
684                 case VLC_FOURCC( 's', 'u','b', 't' ):
685                     p_stream->i_stream_type = 0x12;
686                     p_stream->i_stream_id = 0xfa;
687                     p_sys->i_mpeg4_streams++;
688                     p_stream->i_es_id = p_stream->i_pid;
689                     break;
690                 case VLC_FOURCC('d','v','b','s'):
691                     p_stream->i_stream_type = 0x06;
692                     p_stream->i_es_id = p_input->p_fmt->subs.dvb.i_id;
693                     p_stream->i_stream_id = 0xbd;
694                     break;
695                 case VLC_FOURCC('t','e','l','x'):
696                     p_stream->i_stream_type = 0x06;
697                     p_stream->i_stream_id = 0xbd; /* FIXME */
698                     break;
699                 default:
700                     free( p_stream );
701                     return VLC_EGENERIC;
702             }
703             break;
704
705         default:
706             free( p_stream );
707             return VLC_EGENERIC;
708     }
709
710     p_stream->lang[0] =
711     p_stream->lang[1] =
712     p_stream->lang[2] = '\0';
713     if( p_input->p_fmt->psz_language )
714     {
715         char *psz = p_input->p_fmt->psz_language;
716         const iso639_lang_t *pl = NULL;
717
718         if( strlen( psz ) == 2 )
719         {
720             pl = GetLang_1( psz );
721         }
722         else if( strlen( psz ) == 3 )
723         {
724             pl = GetLang_2B( psz );
725             if( !strcmp( pl->psz_iso639_1, "??" ) )
726             {
727                 pl = GetLang_2T( psz );
728             }
729         }
730         if( pl && strcmp( pl->psz_iso639_1, "??" ) )
731         {
732             p_stream->lang[0] = pl->psz_iso639_2T[0];
733             p_stream->lang[1] = pl->psz_iso639_2T[1];
734             p_stream->lang[2] = pl->psz_iso639_2T[2];
735
736             msg_Dbg( p_mux, "    - lang=%c%c%c",
737                      p_stream->lang[0], p_stream->lang[1], p_stream->lang[2] );
738         }
739     }
740
741
742     /* Copy extra data (VOL for MPEG-4 and extra BitMapInfoHeader for VFW */
743     p_stream->i_decoder_specific_info = p_input->p_fmt->i_extra;
744     if( p_stream->i_decoder_specific_info > 0 )
745     {
746         p_stream->p_decoder_specific_info =
747             malloc( p_stream->i_decoder_specific_info );
748         memcpy( p_stream->p_decoder_specific_info,
749                 p_input->p_fmt->p_extra,
750                 p_input->p_fmt->i_extra );
751     }
752
753     /* Create decoder specific info for subt */
754     if( p_stream->i_codec == VLC_FOURCC( 's', 'u','b', 't' ) )
755     {
756         uint8_t *p;
757
758         p_stream->i_decoder_specific_info = 55;
759         p_stream->p_decoder_specific_info = p =
760             malloc( p_stream->i_decoder_specific_info );
761
762         p[0] = 0x10;    /* textFormat, 0x10 for 3GPP TS 26.245 */
763         p[1] = 0x00;    /* flags: 1b: associated video info flag
764                                   3b: reserved
765                                   1b: duration flag
766                                   3b: reserved */
767         p[2] = 52;      /* remaining size */
768
769         p += 3;
770
771         p[0] = p[1] = p[2] = p[3] = 0; p+=4;    /* display flags */
772         *p++ = 0;  /* horizontal justification (-1: left, 0 center, 1 right) */
773         *p++ = 1;  /* vertical   justification (-1: top, 0 center, 1 bottom) */
774
775         p[0] = p[1] = p[2] = 0x00; p+=3;/* background rgb */
776         *p++ = 0xff;                    /* background a */
777
778         p[0] = p[1] = 0; p += 2;        /* text box top */
779         p[0] = p[1] = 0; p += 2;        /* text box left */
780         p[0] = p[1] = 0; p += 2;        /* text box bottom */
781         p[0] = p[1] = 0; p += 2;        /* text box right */
782
783         p[0] = p[1] = 0; p += 2;        /* start char */
784         p[0] = p[1] = 0; p += 2;        /* end char */
785         p[0] = p[1] = 0; p += 2;        /* default font id */
786
787         *p++ = 0;                       /* font style flags */
788         *p++ = 12;                      /* font size */
789
790         p[0] = p[1] = p[2] = 0x00; p+=3;/* foreground rgb */
791         *p++ = 0x00;                    /* foreground a */
792
793         p[0] = p[1] = p[2] = 0; p[3] = 22; p += 4;
794         memcpy( p, "ftab", 4 ); p += 4;
795         *p++ = 0; *p++ = 1;             /* entry count */
796         p[0] = p[1] = 0; p += 2;        /* font id */
797         *p++ = 9;                       /* font name length */
798         memcpy( p, "Helvetica", 9 );    /* font name */
799     }
800
801     /* Init pes chain */
802     BufferChainInit( &p_stream->chain_pes );
803     p_stream->i_pes_dts    = 0;
804     p_stream->i_pes_length = 0;
805     p_stream->i_pes_used   = 0;
806     p_stream->b_key_frame  = 0;
807
808     /* We only change PMT version (PAT isn't changed) */
809     p_sys->i_pmt_version_number = ( p_sys->i_pmt_version_number + 1 )%32;
810
811     /* Update pcr_pid */
812     if( p_input->p_fmt->i_cat != SPU_ES &&
813         ( p_sys->i_pcr_pid == 0x1fff || p_input->p_fmt->i_cat == VIDEO_ES ) )
814     {
815         if( p_sys->p_pcr_input )
816         {
817             /* There was already a PCR stream, so clean context */
818             /* FIXME */
819         }
820         p_sys->i_pcr_pid   = p_stream->i_pid;
821         p_sys->p_pcr_input = p_input;
822
823         msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
824     }
825
826     return VLC_SUCCESS;
827 }
828
829 /*****************************************************************************
830  * DelStream: called before a stream deletion
831  *****************************************************************************/
832 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
833 {
834     sout_mux_sys_t  *p_sys = p_mux->p_sys;
835     ts_stream_t     *p_stream;
836     vlc_value_t     val;
837
838     p_stream = (ts_stream_t*)p_input->p_sys;
839     msg_Dbg( p_mux, "removing input pid=%d", p_stream->i_pid );
840
841     if( p_sys->i_pcr_pid == p_stream->i_pid )
842     {
843         int i;
844
845         /* Find a new pcr stream (Prefer Video Stream) */
846         p_sys->i_pcr_pid = 0x1fff;
847         p_sys->p_pcr_input = NULL;
848         for( i = 0; i < p_mux->i_nb_inputs; i++ )
849         {
850             if( p_mux->pp_inputs[i] == p_input )
851             {
852                 continue;
853             }
854
855             if( p_mux->pp_inputs[i]->p_fmt->i_cat == VIDEO_ES )
856             {
857                 p_sys->i_pcr_pid  =
858                     ((ts_stream_t*)p_mux->pp_inputs[i]->p_sys)->i_pid;
859                 p_sys->p_pcr_input= p_mux->pp_inputs[i];
860                 break;
861             }
862             else if( p_mux->pp_inputs[i]->p_fmt->i_cat != SPU_ES &&
863                      p_sys->i_pcr_pid == 0x1fff )
864             {
865                 p_sys->i_pcr_pid  =
866                     ((ts_stream_t*)p_mux->pp_inputs[i]->p_sys)->i_pid;
867                 p_sys->p_pcr_input= p_mux->pp_inputs[i];
868             }
869         }
870         if( p_sys->p_pcr_input )
871         {
872             /* Empty TS buffer */
873             /* FIXME */
874         }
875         msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
876     }
877
878     /* Empty all data in chain_pes */
879     BufferChainClean( p_mux->p_sout, &p_stream->chain_pes );
880
881     if( p_stream->p_decoder_specific_info )
882     {
883         free( p_stream->p_decoder_specific_info );
884     }
885     if( p_stream->i_stream_id == 0xfa ||
886         p_stream->i_stream_id == 0xfb ||
887         p_stream->i_stream_id == 0xfe )
888     {
889         p_sys->i_mpeg4_streams--;
890     }
891
892     var_Get( p_mux, SOUT_CFG_PREFIX "pid-video", &val );
893     if( val.i_int > 0 )
894     {
895         int i_pid_video = val.i_int;
896         if ( i_pid_video == p_stream->i_pid )
897         {
898             p_sys->i_pid_video = i_pid_video;
899             msg_Dbg( p_mux, "freeing video PID %d", i_pid_video );
900         }
901     }
902     var_Get( p_mux, SOUT_CFG_PREFIX "pid-audio", &val );
903     if( val.i_int > 0 )
904     {
905         int i_pid_audio = val.i_int;
906         if ( i_pid_audio == p_stream->i_pid )
907         {
908             p_sys->i_pid_audio = i_pid_audio;
909             msg_Dbg( p_mux, "freeing audio PID %d", i_pid_audio );
910         }
911     }
912     var_Get( p_mux, SOUT_CFG_PREFIX "pid-spu", &val );
913     if( val.i_int > 0 )
914     {
915         int i_pid_spu = val.i_int;
916         if ( i_pid_spu == p_stream->i_pid )
917         {
918             p_sys->i_pid_spu = i_pid_spu;
919             msg_Dbg( p_mux, "freeing spu PID %d", i_pid_spu );
920         }
921     }
922     free( p_stream );
923
924     /* We only change PMT version (PAT isn't changed) */
925     p_sys->i_pmt_version_number++; p_sys->i_pmt_version_number %= 32;
926
927     return VLC_SUCCESS;
928 }
929
930 /*****************************************************************************
931  * Mux: Call each time there is new data for at least one stream
932  *****************************************************************************
933  *
934  *****************************************************************************/
935 static int Mux( sout_mux_t *p_mux )
936 {
937     sout_mux_sys_t  *p_sys = p_mux->p_sys;
938     ts_stream_t     *p_pcr_stream;
939
940     if( p_sys->i_pcr_pid == 0x1fff )
941     {
942         msg_Dbg( p_mux, "waiting for PCR streams" );
943         msleep( 1000 );
944         return VLC_SUCCESS;
945     }
946     p_pcr_stream = (ts_stream_t*)p_sys->p_pcr_input->p_sys;
947
948     for( ;; )
949     {
950         sout_buffer_chain_t chain_ts;
951         int                 i_packet_count;
952         int                 i_packet_pos;
953         mtime_t             i_pcr_dts;
954         mtime_t             i_pcr_length;
955         mtime_t             i_shaping_delay;
956         int i;
957
958         if( p_pcr_stream->b_key_frame )
959         {
960             i_shaping_delay = p_pcr_stream->i_pes_length;
961         }
962         else
963         {
964             i_shaping_delay = p_sys->i_shaping_delay;
965         }
966
967         /* 1: get enough PES packet for all input */
968         for( ;; )
969         {
970             vlc_bool_t b_ok = VLC_TRUE;
971             block_t *p_data;
972
973             /* Accumulate enough data in the pcr stream (>i_shaping_delay) */
974             /* Accumulate enough data in all other stream ( >= length of pcr)*/
975             for( i = 0; i < p_mux->i_nb_inputs; i++ )
976             {
977                 sout_input_t *p_input = p_mux->pp_inputs[i];
978                 ts_stream_t *p_stream = (ts_stream_t*)p_input->p_sys;
979                 int64_t i_spu_delay = 0;
980
981                 if( ( p_stream == p_pcr_stream &&
982                       p_stream->i_pes_length < i_shaping_delay ) ||
983                     p_stream->i_pes_dts + p_stream->i_pes_length <
984                     p_pcr_stream->i_pes_dts + p_pcr_stream->i_pes_length )
985                 {
986                     /* Need more data */
987                     if( p_input->p_fifo->i_depth <= 1 )
988                     {
989                         if( p_input->p_fmt->i_cat == AUDIO_ES ||
990                             p_input->p_fmt->i_cat == VIDEO_ES )
991                         {
992                             /* We need more data */
993                             return VLC_SUCCESS;
994                         }
995                         else if( p_input->p_fifo->i_depth <= 0 )
996                         {
997                             /* spu, only one packet is needed */
998                             continue;
999                         }
1000                         else
1001                         {
1002                             /* Don't mux the SPU yet if it is too early */
1003                             block_t *p_spu = block_FifoShow( p_input->p_fifo );
1004
1005                             i_spu_delay =
1006                                 p_spu->i_dts - p_pcr_stream->i_pes_dts;
1007
1008                             if( i_spu_delay > i_shaping_delay &&
1009                                 i_spu_delay < I64C(100000000) )
1010                                 continue;
1011
1012                             if ( i_spu_delay >= I64C(100000000)
1013                                   || i_spu_delay < 10000 )
1014                             {
1015                                 BufferChainClean( p_mux->p_sout,
1016                                                   &p_stream->chain_pes );
1017                                 p_stream->i_pes_dts = 0;
1018                                 p_stream->i_pes_used = 0;
1019                                 p_stream->i_pes_length = 0;
1020                                 continue;
1021                             }
1022                         }
1023                     }
1024                     b_ok = VLC_FALSE;
1025
1026                     p_data = block_FifoGet( p_input->p_fifo );
1027                     if( p_input->p_fifo->i_depth > 0 &&
1028                         p_input->p_fmt->i_cat != SPU_ES )
1029                     {
1030                         block_t *p_next = block_FifoShow( p_input->p_fifo );
1031                         p_data->i_length = p_next->i_dts - p_data->i_dts;
1032                     }
1033                     else
1034                         p_data->i_length = 1000;
1035
1036                     if( ( p_pcr_stream->i_pes_dts > 0 &&
1037                           p_data->i_dts - 10000000 > p_pcr_stream->i_pes_dts +
1038                           p_pcr_stream->i_pes_length ) ||
1039                         p_data->i_dts < p_stream->i_pes_dts ||
1040                         ( p_stream->i_pes_dts > 0 &&
1041                           p_input->p_fmt->i_cat != SPU_ES &&
1042                           p_data->i_dts - 10000000 > p_stream->i_pes_dts +
1043                           p_stream->i_pes_length ) )
1044                     {
1045                         msg_Warn( p_mux, "packet with too strange dts "
1046                                   "(dts="I64Fd",old="I64Fd",pcr="I64Fd")",
1047                                   p_data->i_dts, p_stream->i_pes_dts,
1048                                   p_pcr_stream->i_pes_dts );
1049                         block_Release( p_data );
1050
1051                         BufferChainClean( p_mux->p_sout,
1052                                           &p_stream->chain_pes );
1053                         p_stream->i_pes_dts = 0;
1054                         p_stream->i_pes_used = 0;
1055                         p_stream->i_pes_length = 0;
1056
1057                         if( p_input->p_fmt->i_cat != SPU_ES )
1058                         {
1059                             BufferChainClean( p_mux->p_sout,
1060                                               &p_pcr_stream->chain_pes );
1061                             p_pcr_stream->i_pes_dts = 0;
1062                             p_pcr_stream->i_pes_used = 0;
1063                             p_pcr_stream->i_pes_length = 0;
1064                         }
1065                     }
1066                     else
1067                     {
1068                         int i_header_size = 0;
1069                         int b_data_alignment = 0;
1070                         if( p_input->p_fmt->i_cat == SPU_ES )
1071                         {
1072                             if( p_input->p_fmt->i_codec ==
1073                                 VLC_FOURCC('s','u','b','t') )
1074                             {
1075                                 /* Prepend header */
1076                                 p_data = block_Realloc( p_data, 2,
1077                                                         p_data->i_buffer );
1078                                 p_data->p_buffer[0] =
1079                                     ( (p_data->i_buffer - 2) >> 8) & 0xff;
1080                                 p_data->p_buffer[1] =
1081                                     ( (p_data->i_buffer - 2)     ) & 0xff;
1082
1083                                 /* remove trailling \0 if any */
1084                                 if( p_data->i_buffer > 2 &&
1085                                     p_data->p_buffer[p_data->i_buffer -1] ==
1086                                     '\0' )
1087                                     p_data->i_buffer--;
1088
1089                                 /* Append a empty sub (sub text only) */
1090                                 if( p_data->i_length > 0 &&
1091                                     !( p_data->i_buffer == 1 &&
1092                                        *p_data->p_buffer == ' ' ) )
1093                                 {
1094                                     block_t *p_spu = block_New( p_mux, 3 );
1095
1096                                     p_spu->i_dts = p_spu->i_pts =
1097                                         p_data->i_dts + p_data->i_length;
1098                                     p_spu->i_length = 1000;
1099
1100                                     p_spu->p_buffer[0] = 0;
1101                                     p_spu->p_buffer[1] = 1;
1102                                     p_spu->p_buffer[2] = ' ';
1103
1104                                     E_(EStoPES)( p_mux->p_sout, &p_spu, p_spu,
1105                                                  p_input->p_fmt,
1106                                                  p_stream->i_stream_id, 1,
1107                                                  0, 0 );
1108                                     p_data->p_next = p_spu;
1109                                 }
1110                             }
1111                             else if( p_input->p_fmt->i_codec ==
1112                                        VLC_FOURCC('t','e','l','x') )
1113                             {
1114                                 /* EN 300 472 */
1115                                 i_header_size = 0x24;
1116                                 b_data_alignment = 1;
1117                             }
1118                         }
1119                         else if( p_data->i_length < 0 ||
1120                                  p_data->i_length > 2000000 )
1121                         {
1122                             /* FIXME choose a better value, but anyway we
1123                              * should never have to do that */
1124                             p_data->i_length = 1000;
1125                         }
1126
1127                         p_stream->i_pes_length += p_data->i_length;
1128                         if( p_stream->i_pes_dts == 0 )
1129                         {
1130                             p_stream->i_pes_dts = p_data->i_dts;
1131                         }
1132
1133                         /* Convert to pes */
1134                         if( p_stream->i_stream_id == 0xa0 &&
1135                             p_data->i_pts <= 0 )
1136                         {
1137                             /* XXX yes I know, it's awfull, but it's needed,
1138                              * so don't remove it ... */
1139                             p_data->i_pts = p_data->i_dts;
1140                         }
1141                         E_( EStoPES )( p_mux->p_sout, &p_data, p_data,
1142                                        p_input->p_fmt, p_stream->i_stream_id,
1143                                        1, b_data_alignment, i_header_size );
1144
1145                         BufferChainAppend( &p_stream->chain_pes, p_data );
1146
1147                         if( p_sys->b_use_key_frames && p_stream == p_pcr_stream
1148                             && (p_data->i_flags & BLOCK_FLAG_TYPE_I)
1149                             && !(p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME)
1150                             && (p_stream->i_pes_length > 400000) )
1151                         {
1152                             i_shaping_delay = p_stream->i_pes_length;
1153                             p_stream->b_key_frame = 1;
1154                         }
1155                     }
1156                 }
1157             }
1158
1159             if( b_ok )
1160             {
1161                 break;
1162             }
1163         }
1164
1165         /* save */
1166         i_pcr_dts      = p_pcr_stream->i_pes_dts;
1167         i_pcr_length   = p_pcr_stream->i_pes_length;
1168         p_pcr_stream->b_key_frame = 0;
1169
1170         /* msg_Dbg( p_mux, "starting muxing %lldms", i_pcr_length / 1000 ); */
1171         /* 2: calculate non accurate total size of muxed ts */
1172         i_packet_count = 0;
1173         for( i = 0; i < p_mux->i_nb_inputs; i++ )
1174         {
1175             ts_stream_t *p_stream = (ts_stream_t*)p_mux->pp_inputs[i]->p_sys;
1176             block_t *p_pes;
1177
1178             /* False for pcr stream but it will be enough to do PCR algo */
1179             for( p_pes = p_stream->chain_pes.p_first; p_pes != NULL;
1180                  p_pes = p_pes->p_next )
1181             {
1182                 int i_size = p_pes->i_buffer;
1183                 if( p_pes->i_dts + p_pes->i_length >
1184                     p_pcr_stream->i_pes_dts + p_pcr_stream->i_pes_length )
1185                 {
1186                     mtime_t i_frag = p_pcr_stream->i_pes_dts +
1187                         p_pcr_stream->i_pes_length - p_pes->i_dts;
1188                     if( i_frag < 0 )
1189                     {
1190                         /* Next stream */
1191                         break;
1192                     }
1193                     i_size = p_pes->i_buffer * i_frag / p_pes->i_length;
1194                 }
1195                 i_packet_count += ( i_size + 183 ) / 184;
1196             }
1197         }
1198         /* add overhead for PCR (not really exact) */
1199         i_packet_count += (8 * i_pcr_length / p_sys->i_pcr_delay + 175) / 176;
1200
1201         /* 3: mux PES into TS */
1202         BufferChainInit( &chain_ts );
1203         /* append PAT/PMT  -> FIXME with big pcr delay it won't have enough pat/pmt */
1204         GetPAT( p_mux, &chain_ts);
1205         GetPMT( p_mux, &chain_ts );
1206         i_packet_pos = 0;
1207         i_packet_count += chain_ts.i_depth;
1208         /* msg_Dbg( p_mux, "estimated pck=%d", i_packet_count ); */
1209
1210         for( ;; )
1211         {
1212             int         i_stream;
1213             mtime_t     i_dts;
1214             ts_stream_t *p_stream;
1215             sout_input_t *p_input;
1216             block_t *p_ts;
1217             vlc_bool_t   b_pcr;
1218
1219             /* Select stream (lowest dts) */
1220             for( i = 0, i_stream = -1, i_dts = 0; i < p_mux->i_nb_inputs; i++ )
1221             {
1222                 p_input = p_mux->pp_inputs[i];
1223                 p_stream = (ts_stream_t*)p_mux->pp_inputs[i]->p_sys;
1224
1225                 if( p_stream->i_pes_dts == 0 )
1226                 {
1227                     continue;
1228                 }
1229
1230                 if( i_stream == -1 ||
1231                     p_stream->i_pes_dts < i_dts )
1232                 {
1233                     i_stream = i;
1234                     i_dts = p_stream->i_pes_dts;
1235                 }
1236             }
1237             if( i_stream == -1 || i_dts > i_pcr_dts + i_pcr_length )
1238             {
1239                 break;
1240             }
1241             p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
1242
1243             /* do we need to issue pcr */
1244             b_pcr = VLC_FALSE;
1245             if( p_stream == p_pcr_stream &&
1246                 i_pcr_dts + i_packet_pos * i_pcr_length / i_packet_count >=
1247                 p_sys->i_pcr + p_sys->i_pcr_delay )
1248             {
1249                 b_pcr = VLC_TRUE;
1250                 p_sys->i_pcr = i_pcr_dts + i_packet_pos *
1251                     i_pcr_length / i_packet_count;
1252             }
1253
1254             /* Build the TS packet */
1255             p_ts = TSNew( p_mux, p_stream, b_pcr );
1256             if( p_sys->csa != NULL &&
1257                  (p_input->p_fmt->i_cat != AUDIO_ES || p_sys->b_crypt_audio) )
1258             {
1259                 p_ts->i_flags |= BLOCK_FLAG_SCRAMBLED;
1260             }
1261             i_packet_pos++;
1262
1263             /* */
1264             BufferChainAppend( &chain_ts, p_ts );
1265         }
1266
1267         /* 4: date and send */
1268         TSSchedule( p_mux, &chain_ts, i_pcr_length, i_pcr_dts );
1269     }
1270 }
1271
1272 static void TSSchedule( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1273                         mtime_t i_pcr_length, mtime_t i_pcr_dts )
1274 {
1275     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1276     sout_buffer_chain_t new_chain;
1277     int i_packet_count = p_chain_ts->i_depth;
1278     int i;
1279
1280     BufferChainInit( &new_chain );
1281
1282     if ( i_pcr_length <= 0 )
1283     {
1284         i_pcr_length = i_packet_count;
1285     }
1286
1287     for( i = 0; i < i_packet_count; i++ )
1288     {
1289         block_t *p_ts = BufferChainGet( p_chain_ts );
1290         mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1291
1292         BufferChainAppend( &new_chain, p_ts );
1293
1294         if( p_ts->i_dts &&
1295             p_ts->i_dts + p_sys->i_dts_delay * 2/3 < i_new_dts )
1296         {
1297             mtime_t i_max_diff = i_new_dts - p_ts->i_dts;
1298             mtime_t i_cut_dts = p_ts->i_dts;
1299
1300             p_ts = BufferChainPeek( p_chain_ts );
1301             i++;
1302             i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1303             while ( p_ts != NULL && i_new_dts - p_ts->i_dts >= i_max_diff )
1304             {
1305                 p_ts = BufferChainGet( p_chain_ts );
1306                 i_max_diff = i_new_dts - p_ts->i_dts;
1307                 i_cut_dts = p_ts->i_dts;
1308                 BufferChainAppend( &new_chain, p_ts );
1309
1310                 p_ts = BufferChainPeek( p_chain_ts );
1311                 i++;
1312                 i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1313             }
1314             msg_Dbg( p_mux, "adjusting rate at "I64Fd"/"I64Fd" (%d/%d)",
1315                      i_cut_dts - i_pcr_dts, i_pcr_length, new_chain.i_depth,
1316                      p_chain_ts->i_depth );
1317             if ( new_chain.i_depth )
1318                 TSDate( p_mux, &new_chain,
1319                         i_cut_dts - i_pcr_dts,
1320                         i_pcr_dts );
1321             if ( p_chain_ts->i_depth )
1322                 TSSchedule( p_mux,
1323                             p_chain_ts, i_pcr_dts + i_pcr_length - i_cut_dts,
1324                             i_cut_dts );
1325             return;
1326         }
1327     }
1328
1329     if ( new_chain.i_depth )
1330         TSDate( p_mux, &new_chain, i_pcr_length, i_pcr_dts );
1331 }
1332
1333 static void TSDate( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1334                     mtime_t i_pcr_length, mtime_t i_pcr_dts )
1335 {
1336     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1337     int i_packet_count = p_chain_ts->i_depth;
1338     int i;
1339
1340     if ( i_pcr_length / 1000 > 0 )
1341     {
1342         int i_bitrate = ((uint64_t)i_packet_count * 188 * 8000)
1343                           / (uint64_t)(i_pcr_length / 1000);
1344         if ( p_sys->i_bitrate_max && p_sys->i_bitrate_max < i_bitrate )
1345         {
1346             msg_Warn( p_mux, "max bitrate exceeded at "I64Fd
1347                       " (%d bi/s for %d pkt in "I64Fd" us)",
1348                       i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
1349                       i_bitrate, i_packet_count, i_pcr_length);
1350         }
1351 #if 0
1352         else
1353         {
1354             msg_Dbg( p_mux, "starting at "I64Fd
1355                      " (%d bi/s for %d packets in "I64Fd" us)",
1356                      i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
1357                      i_bitrate, i_packet_count, i_pcr_length);
1358         }
1359 #endif
1360     }
1361     else
1362     {
1363         /* This shouldn't happen, but happens in some rare heavy load
1364          * and packet losses conditions. */
1365         i_pcr_length = i_packet_count;
1366     }
1367
1368     /* msg_Dbg( p_mux, "real pck=%d", i_packet_count ); */
1369     for( i = 0; i < i_packet_count; i++ )
1370     {
1371         block_t *p_ts = BufferChainGet( p_chain_ts );
1372         mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1373
1374         p_ts->i_dts    = i_new_dts;
1375         p_ts->i_length = i_pcr_length / i_packet_count;
1376
1377         if( p_ts->i_flags & BLOCK_FLAG_CLOCK )
1378         {
1379             /* msg_Dbg( p_mux, "pcr=%lld ms", p_ts->i_dts / 1000 ); */
1380             TSSetPCR( p_ts, p_ts->i_dts - p_sys->i_dts_delay );
1381         }
1382         if( p_ts->i_flags & BLOCK_FLAG_SCRAMBLED )
1383         {
1384             csa_Encrypt( p_sys->csa, p_ts->p_buffer, 0 );
1385         }
1386
1387         /* latency */
1388         p_ts->i_dts += p_sys->i_shaping_delay * 3 / 2;
1389
1390         sout_AccessOutWrite( p_mux->p_access, p_ts );
1391     }
1392 }
1393
1394 static block_t *TSNew( sout_mux_t *p_mux, ts_stream_t *p_stream,
1395                        vlc_bool_t b_pcr )
1396 {
1397     block_t *p_pes = p_stream->chain_pes.p_first;
1398     block_t *p_ts;
1399
1400     vlc_bool_t b_new_pes = VLC_FALSE;
1401     vlc_bool_t b_adaptation_field = VLC_FALSE;
1402
1403     int        i_payload_max = 184 - ( b_pcr ? 8 : 0 );
1404     int        i_payload;
1405
1406     if( p_stream->i_pes_used <= 0 )
1407     {
1408         b_new_pes = VLC_TRUE;
1409     }
1410     i_payload = __MIN( (int)p_pes->i_buffer - p_stream->i_pes_used,
1411                        i_payload_max );
1412
1413     if( b_pcr || i_payload < i_payload_max )
1414     {
1415         b_adaptation_field = VLC_TRUE;
1416     }
1417
1418     p_ts = block_New( p_mux, 188 );
1419     p_ts->i_dts = p_pes->i_dts;
1420
1421     p_ts->p_buffer[0] = 0x47;
1422     p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 ) |
1423         ( ( p_stream->i_pid >> 8 )&0x1f );
1424     p_ts->p_buffer[2] = p_stream->i_pid & 0xff;
1425     p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 ) |
1426         p_stream->i_continuity_counter;
1427
1428     p_stream->i_continuity_counter = (p_stream->i_continuity_counter+1)%16;
1429
1430     if( b_adaptation_field )
1431     {
1432         int i;
1433
1434         if( b_pcr )
1435         {
1436             int     i_stuffing = i_payload_max - i_payload;
1437
1438             p_ts->i_flags |= BLOCK_FLAG_CLOCK;
1439
1440             p_ts->p_buffer[4] = 7 + i_stuffing;
1441             p_ts->p_buffer[5] = 0x10;   /* flags */
1442             p_ts->p_buffer[6] = ( 0 )&0xff;
1443             p_ts->p_buffer[7] = ( 0 )&0xff;
1444             p_ts->p_buffer[8] = ( 0 )&0xff;
1445             p_ts->p_buffer[9] = ( 0 )&0xff;
1446             p_ts->p_buffer[10]= ( 0 )&0x80;
1447             p_ts->p_buffer[11]= 0;
1448
1449             for( i = 12; i < 12 + i_stuffing; i++ )
1450             {
1451                 p_ts->p_buffer[i] = 0xff;
1452             }
1453         }
1454         else
1455         {
1456             int i_stuffing = i_payload_max - i_payload;
1457
1458             p_ts->p_buffer[4] = i_stuffing - 1;
1459             if( i_stuffing > 1 )
1460             {
1461                 p_ts->p_buffer[5] = 0x00;
1462                 for( i = 6; i < 6 + i_stuffing - 2; i++ )
1463                 {
1464                     p_ts->p_buffer[i] = 0xff;
1465                 }
1466             }
1467         }
1468     }
1469
1470     /* copy payload */
1471     memcpy( &p_ts->p_buffer[188 - i_payload],
1472             &p_pes->p_buffer[p_stream->i_pes_used], i_payload );
1473
1474     p_stream->i_pes_used += i_payload;
1475     p_stream->i_pes_dts = p_pes->i_dts + p_pes->i_length *
1476         p_stream->i_pes_used / p_pes->i_buffer;
1477     p_stream->i_pes_length -= p_pes->i_length * i_payload / p_pes->i_buffer;
1478
1479     if( p_stream->i_pes_used >= (int)p_pes->i_buffer )
1480     {
1481         p_pes = BufferChainGet( &p_stream->chain_pes );
1482         block_Release( p_pes );
1483
1484         p_pes = p_stream->chain_pes.p_first;
1485         if( p_pes )
1486         {
1487             p_stream->i_pes_dts    = p_pes->i_dts;
1488             p_stream->i_pes_length = 0;
1489             while( p_pes )
1490             {
1491                 p_stream->i_pes_length += p_pes->i_length;
1492
1493                 p_pes = p_pes->p_next;
1494             }
1495         }
1496         else
1497         {
1498             p_stream->i_pes_dts = 0;
1499             p_stream->i_pes_length = 0;
1500         }
1501         p_stream->i_pes_used = 0;
1502     }
1503
1504     return p_ts;
1505 }
1506
1507
1508 static void TSSetPCR( block_t *p_ts, mtime_t i_dts )
1509 {
1510     mtime_t i_pcr = 9 * i_dts / 100;
1511
1512     p_ts->p_buffer[6]  = ( i_pcr >> 25 )&0xff;
1513     p_ts->p_buffer[7]  = ( i_pcr >> 17 )&0xff;
1514     p_ts->p_buffer[8]  = ( i_pcr >> 9  )&0xff;
1515     p_ts->p_buffer[9]  = ( i_pcr >> 1  )&0xff;
1516     p_ts->p_buffer[10]|= ( i_pcr << 7  )&0x80;
1517 }
1518
1519 #if 0
1520 static void TSSetConstraints( sout_mux_t *p_mux, sout_buffer_chain_t *c,
1521                               mtime_t i_length, int i_bitrate_min,
1522                               int i_bitrate_max )
1523 {
1524     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1525     sout_buffer_chain_t s = *c;
1526
1527     int i_packets = 0;
1528     int i_packets_min = 0;
1529     int i_packets_max = 0;
1530
1531     if( i_length <= 0 )
1532     {
1533         return;
1534     }
1535
1536     i_packets     = c->i_depth;
1537     i_packets_min = ( (int64_t)i_bitrate_min * i_length / 8 / 1000000  + 187 ) / 188;
1538     i_packets_max = ( (int64_t)i_bitrate_max * i_length / 8 / 1000000  + 187 ) / 188;
1539
1540     if( i_packets < i_packets_min && i_packets_min > 0 )
1541     {
1542         block_t *p_pk;
1543         int i_div = ( i_packets_min - i_packets ) / i_packets;
1544         int i_mod = ( i_packets_min - i_packets ) % i_packets;
1545         int i_rest = 0;
1546
1547         /* We need to pad with null packets (pid=0x1fff)
1548          * We try to melt null packets with true packets */
1549         msg_Dbg( p_mux,
1550                  "packets=%d but min=%d -> adding %d packets of padding",
1551                  i_packets, i_packets_min, i_packets_min - i_packets );
1552
1553         BufferChainInit( c );
1554         while( ( p_pk = BufferChainGet( &s ) ) )
1555         {
1556             int i, i_null;
1557
1558             BufferChainAppend( c, p_pk );
1559
1560             i_null = i_div + ( i_rest + i_mod ) / i_packets;
1561
1562             for( i = 0; i < i_null; i++ )
1563             {
1564                 block_t *p_null;
1565
1566                 p_null = sout_BufferNew( p_mux->p_sout, 188 );
1567                 p_null->p_buffer[0] = 0x47;
1568                 p_null->p_buffer[1] = 0x1f;
1569                 p_null->p_buffer[2] = 0xff;
1570                 p_null->p_buffer[3] = 0x10 | p_sys->i_null_continuity_counter;
1571                 memset( &p_null->p_buffer[4], 0, 184 );
1572                 p_sys->i_null_continuity_counter =
1573                     ( p_sys->i_null_continuity_counter + 1 ) % 16;
1574
1575                 BufferChainAppend( c, p_null );
1576             }
1577
1578             i_rest = ( i_rest + i_mod ) % i_packets;
1579         }
1580     }
1581     else if( i_packets > i_packets_max && i_packets_max > 0 )
1582     {
1583         block_t *p_pk;
1584         int           i;
1585
1586         /* Arg, we need to drop packets, I don't do something clever (like
1587          * dropping complete pid, b frames, ... ), I just get the right amount
1588          * of packets and discard the others */
1589         msg_Warn( p_mux,
1590                   "packets=%d but max=%d -> removing %d packets -> stream broken",
1591                   i_packets, i_packets_max, i_packets - i_packets_max );
1592
1593         BufferChainInit( c );
1594         for( i = 0; i < i_packets_max; i++ )
1595         {
1596             BufferChainAppend( c, BufferChainGet( &s ) );
1597         }
1598
1599         while( ( p_pk = BufferChainGet( &s ) ) )
1600         {
1601             sout_BufferDelete( p_mux->p_sout, p_pk );
1602         }
1603     }
1604 }
1605 #endif
1606
1607 static void PEStoTS( sout_instance_t *p_sout,
1608                      sout_buffer_chain_t *c, block_t *p_pes,
1609                      ts_stream_t *p_stream )
1610 {
1611     uint8_t *p_data;
1612     int     i_size;
1613     int     b_new_pes;
1614
1615     /* get PES total size */
1616     i_size = p_pes->i_buffer;
1617     p_data = p_pes->p_buffer;
1618
1619     b_new_pes = VLC_TRUE;
1620
1621     for( ;; )
1622     {
1623         int           b_adaptation_field;
1624         int           i_copy;
1625         block_t *p_ts;
1626
1627         p_ts = block_New( p_sout, 188 );
1628         /* write header
1629          * 8b   0x47    sync byte
1630          * 1b           transport_error_indicator
1631          * 1b           payload_unit_start
1632          * 1b           transport_priority
1633          * 13b          pid
1634          * 2b           transport_scrambling_control
1635          * 2b           if adaptation_field 0x03 else 0x01
1636          * 4b           continuity_counter
1637          */
1638
1639         i_copy    = __MIN( i_size, 184 );
1640         b_adaptation_field = i_size < 184 ? VLC_TRUE : VLC_FALSE;
1641
1642         p_ts->p_buffer[0] = 0x47;
1643         p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 )|
1644                             ( ( p_stream->i_pid >> 8 )&0x1f );
1645         p_ts->p_buffer[2] = p_stream->i_pid & 0xff;
1646         p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 )|
1647                             p_stream->i_continuity_counter;
1648
1649         b_new_pes = VLC_FALSE;
1650         p_stream->i_continuity_counter = (p_stream->i_continuity_counter+1)%16;
1651
1652         if( b_adaptation_field )
1653         {
1654             int i_stuffing = 184 - i_copy;
1655             int i;
1656
1657             p_ts->p_buffer[4] = i_stuffing - 1;
1658             if( i_stuffing > 1 )
1659             {
1660                 p_ts->p_buffer[5] = 0x00;
1661                 for( i = 6; i < 6 + i_stuffing - 2; i++ )
1662                 {
1663                     p_ts->p_buffer[i] = 0xff;
1664                 }
1665             }
1666         }
1667         /* copy payload */
1668         memcpy( &p_ts->p_buffer[188 - i_copy], p_data, i_copy );
1669         p_data += i_copy;
1670         i_size -= i_copy;
1671
1672         BufferChainAppend( c, p_ts );
1673
1674         if( i_size <= 0 )
1675         {
1676             block_t *p_next = p_pes->p_next;
1677
1678             p_pes->p_next = NULL;
1679             block_Release( p_pes );
1680             if( p_next == NULL )
1681             {
1682                 break;
1683             }
1684             b_new_pes = VLC_TRUE;
1685             p_pes = p_next;
1686             i_size = p_pes->i_buffer;
1687             p_data = p_pes->p_buffer;
1688         }
1689     }
1690
1691     return;
1692 }
1693
1694 static block_t *WritePSISection( sout_instance_t *p_sout,
1695                                        dvbpsi_psi_section_t* p_section )
1696 {
1697     block_t   *p_psi, *p_first = NULL;
1698
1699
1700     while( p_section )
1701     {
1702         int             i_size;
1703
1704         i_size =  (uint32_t)( p_section->p_payload_end - p_section->p_data )+
1705                   ( p_section->b_syntax_indicator ? 4 : 0 );
1706
1707         p_psi = block_New( p_sout, i_size + 1 );
1708         p_psi->i_pts = 0;
1709         p_psi->i_dts = 0;
1710         p_psi->i_length = 0;
1711         p_psi->i_buffer = i_size + 1;
1712
1713         p_psi->p_buffer[0] = 0; // pointer
1714         memcpy( p_psi->p_buffer + 1,
1715                 p_section->p_data,
1716                 i_size );
1717
1718         block_ChainAppend( &p_first, p_psi );
1719
1720         p_section = p_section->p_next;
1721     }
1722
1723     return( p_first );
1724 }
1725
1726 static void GetPAT( sout_mux_t *p_mux,
1727                     sout_buffer_chain_t *c )
1728 {
1729     sout_mux_sys_t       *p_sys = p_mux->p_sys;
1730     block_t        *p_pat;
1731     dvbpsi_pat_t         pat;
1732     dvbpsi_psi_section_t *p_section;
1733
1734     dvbpsi_InitPAT( &pat, p_sys->i_tsid, p_sys->i_pat_version_number,
1735                     1 );      // b_current_next
1736     /* add all program (only one) */
1737     dvbpsi_PATAddProgram( &pat,
1738                           1,                    // i_number
1739                           p_sys->pmt.i_pid );   // i_pid
1740
1741     p_section = dvbpsi_GenPATSections( &pat,
1742                                        0 );     // max program per section
1743
1744     p_pat = WritePSISection( p_mux->p_sout, p_section );
1745
1746     PEStoTS( p_mux->p_sout, c, p_pat, &p_sys->pat );
1747
1748     dvbpsi_DeletePSISections( p_section );
1749     dvbpsi_EmptyPAT( &pat );
1750 }
1751
1752 static uint32_t GetDescriptorLength24b( int i_length )
1753 {
1754     uint32_t i_l1, i_l2, i_l3;
1755
1756     i_l1 = i_length&0x7f;
1757     i_l2 = ( i_length >> 7 )&0x7f;
1758     i_l3 = ( i_length >> 14 )&0x7f;
1759
1760     return( 0x808000 | ( i_l3 << 16 ) | ( i_l2 << 8 ) | i_l1 );
1761 }
1762
1763 static void GetPMT( sout_mux_t *p_mux,
1764                     sout_buffer_chain_t *c )
1765 {
1766     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1767     block_t   *p_pmt;
1768
1769     dvbpsi_pmt_t        pmt;
1770     dvbpsi_pmt_es_t     *p_es;
1771     dvbpsi_psi_section_t *p_section;
1772
1773     int                 i_stream;
1774
1775     dvbpsi_InitPMT( &pmt,
1776                     0x01,   // program number
1777                     p_sys->i_pmt_version_number,
1778                     1,      // b_current_next
1779                     p_sys->i_pcr_pid );
1780
1781     if( p_sys->i_mpeg4_streams > 0 )
1782     {
1783         uint8_t iod[4096];
1784         bits_buffer_t bits;
1785         bits_buffer_t bits_fix_IOD;
1786
1787         /* Make valgrind happy : it works at byte level not bit one so
1788          * bit_write confuse it (but DON'T CHANGE the way that bit_write is
1789          * working (needed when fixing some bits) */
1790         memset( iod, 0, 4096 );
1791
1792         bits_initwrite( &bits, 4096, iod );
1793         // IOD_label_scope
1794         bits_write( &bits, 8,   0x11 );
1795         // IOD_label
1796         bits_write( &bits, 8,   0x01 );
1797         // InitialObjectDescriptor
1798         bits_align( &bits );
1799         bits_write( &bits, 8,   0x02 );     // tag
1800         bits_fix_IOD = bits;    // save states to fix length later
1801         bits_write( &bits, 24,
1802             GetDescriptorLength24b( 0 ) ); // variable length (fixed later)
1803         bits_write( &bits, 10,  0x01 );     // ObjectDescriptorID
1804         bits_write( &bits, 1,   0x00 );     // URL Flag
1805         bits_write( &bits, 1,   0x00 );     // includeInlineProfileLevelFlag
1806         bits_write( &bits, 4,   0x0f );     // reserved
1807         bits_write( &bits, 8,   0xff );     // ODProfile (no ODcapability )
1808         bits_write( &bits, 8,   0xff );     // sceneProfile
1809         bits_write( &bits, 8,   0xfe );     // audioProfile (unspecified)
1810         bits_write( &bits, 8,   0xfe );     // visualProfile( // )
1811         bits_write( &bits, 8,   0xff );     // graphicProfile (no )
1812         for( i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
1813         {
1814             ts_stream_t *p_stream;
1815             p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
1816
1817             if( p_stream->i_stream_id == 0xfa ||
1818                 p_stream->i_stream_id == 0xfb ||
1819                 p_stream->i_stream_id == 0xfe )
1820             {
1821                 bits_buffer_t bits_fix_ESDescr, bits_fix_Decoder;
1822                 /* ES descriptor */
1823                 bits_align( &bits );
1824                 bits_write( &bits, 8,   0x03 );     // ES_DescrTag
1825                 bits_fix_ESDescr = bits;
1826                 bits_write( &bits, 24,
1827                             GetDescriptorLength24b( 0 ) ); // variable size
1828                 bits_write( &bits, 16,  p_stream->i_es_id );
1829                 bits_write( &bits, 1,   0x00 );     // streamDependency
1830                 bits_write( &bits, 1,   0x00 );     // URL Flag
1831                 bits_write( &bits, 1,   0x00 );     // OCRStreamFlag
1832                 bits_write( &bits, 5,   0x1f );     // streamPriority
1833
1834                 // DecoderConfigDesciptor
1835                 bits_align( &bits );
1836                 bits_write( &bits, 8,   0x04 ); // DecoderConfigDescrTag
1837                 bits_fix_Decoder = bits;
1838                 bits_write( &bits, 24,  GetDescriptorLength24b( 0 ) );
1839                 if( p_stream->i_stream_type == 0x10 )
1840                 {
1841                     bits_write( &bits, 8, 0x20 );   // Visual 14496-2
1842                     bits_write( &bits, 6, 0x04 );   // VisualStream
1843                 }
1844                 else if( p_stream->i_stream_type == 0x1b )
1845                 {
1846                     bits_write( &bits, 8, 0x21 );   // Visual 14496-2
1847                     bits_write( &bits, 6, 0x04 );   // VisualStream
1848                 }
1849                 else if( p_stream->i_stream_type == 0x11  || p_stream->i_stream_type == 0x0f )
1850                 {
1851                     bits_write( &bits, 8, 0x40 );   // Audio 14496-3
1852                     bits_write( &bits, 6, 0x05 );   // AudioStream
1853                 }
1854                 else if( p_stream->i_stream_type == 0x12 &&
1855                          p_stream->i_codec == VLC_FOURCC('s','u','b','t') )
1856                 {
1857                     bits_write( &bits, 8, 0x0B );   // Text Stream
1858                     bits_write( &bits, 6, 0x04 );   // VisualStream
1859                 }
1860                 else
1861                 {
1862                     bits_write( &bits, 8, 0x00 );
1863                     bits_write( &bits, 6, 0x00 );
1864
1865                     msg_Err( p_mux->p_sout,"Unsupported stream_type => "
1866                              "broken IOD" );
1867                 }
1868                 bits_write( &bits, 1,   0x00 );     // UpStream
1869                 bits_write( &bits, 1,   0x01 );     // reserved
1870                 bits_write( &bits, 24,  1024 * 1024 );  // bufferSizeDB
1871                 bits_write( &bits, 32,  0x7fffffff );   // maxBitrate
1872                 bits_write( &bits, 32,  0 );            // avgBitrate
1873
1874                 if( p_stream->i_decoder_specific_info > 0 )
1875                 {
1876                     int i;
1877                     // DecoderSpecificInfo
1878                     bits_align( &bits );
1879                     bits_write( &bits, 8,   0x05 ); // tag
1880                     bits_write( &bits, 24, GetDescriptorLength24b(
1881                                 p_stream->i_decoder_specific_info ) );
1882                     for( i = 0; i < p_stream->i_decoder_specific_info; i++ )
1883                     {
1884                         bits_write( &bits, 8,
1885                             ((uint8_t*)p_stream->p_decoder_specific_info)[i] );
1886                     }
1887                 }
1888                 /* fix Decoder length */
1889                 bits_write( &bits_fix_Decoder, 24,
1890                             GetDescriptorLength24b( bits.i_data -
1891                             bits_fix_Decoder.i_data - 3 ) );
1892
1893                 /* SLConfigDescriptor : predifined (0x01) */
1894                 bits_align( &bits );
1895                 bits_write( &bits, 8,   0x06 ); // tag
1896                 bits_write( &bits, 24,  GetDescriptorLength24b( 8 ) );
1897                 bits_write( &bits, 8,   0x01 ); // predefined
1898                 bits_write( &bits, 1,   0 );   // durationFlag
1899                 bits_write( &bits, 32,  0 );   // OCRResolution
1900                 bits_write( &bits, 8,   0 );   // OCRLength
1901                 bits_write( &bits, 8,   0 );   // InstantBitrateLength
1902                 bits_align( &bits );
1903
1904                 /* fix ESDescr length */
1905                 bits_write( &bits_fix_ESDescr, 24,
1906                             GetDescriptorLength24b( bits.i_data -
1907                             bits_fix_ESDescr.i_data - 3 ) );
1908             }
1909         }
1910         bits_align( &bits );
1911         /* fix IOD length */
1912         bits_write( &bits_fix_IOD, 24,
1913                     GetDescriptorLength24b( bits.i_data -
1914                                             bits_fix_IOD.i_data - 3 ) );
1915         dvbpsi_PMTAddDescriptor( &pmt, 0x1d, bits.i_data, bits.p_data );
1916     }
1917
1918     for( i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
1919     {
1920         ts_stream_t *p_stream;
1921
1922         p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
1923
1924         p_es = dvbpsi_PMTAddES( &pmt, p_stream->i_stream_type,
1925                                 p_stream->i_pid );
1926         if( p_stream->i_stream_id == 0xfa || p_stream->i_stream_id == 0xfb )
1927         {
1928             uint8_t     es_id[2];
1929
1930             /* SL descriptor */
1931             es_id[0] = (p_stream->i_es_id >> 8)&0xff;
1932             es_id[1] = (p_stream->i_es_id)&0xff;
1933             dvbpsi_PMTESAddDescriptor( p_es, 0x1f, 2, es_id );
1934         }
1935         else if( p_stream->i_stream_type == 0xa0 )
1936         {
1937             uint8_t data[512];
1938             int i_extra = __MIN( p_stream->i_decoder_specific_info, 502 );
1939
1940             /* private DIV3 descripor */
1941             memcpy( &data[0], &p_stream->i_bih_codec, 4 );
1942             data[4] = ( p_stream->i_bih_width >> 8 )&0xff;
1943             data[5] = ( p_stream->i_bih_width      )&0xff;
1944             data[6] = ( p_stream->i_bih_height>> 8 )&0xff;
1945             data[7] = ( p_stream->i_bih_height     )&0xff;
1946             data[8] = ( i_extra >> 8 )&0xff;
1947             data[9] = ( i_extra      )&0xff;
1948             if( i_extra > 0 )
1949             {
1950                 memcpy( &data[10], p_stream->p_decoder_specific_info, i_extra );
1951             }
1952
1953             /* 0xa0 is private */
1954             dvbpsi_PMTESAddDescriptor( p_es, 0xa0, i_extra + 10, data );
1955         }
1956         else if( p_stream->i_stream_type == 0x81 )
1957         {
1958             uint8_t format[4] = { 0x41, 0x43, 0x2d, 0x33 };
1959
1960             /* "registration" descriptor : "AC-3" */
1961             dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, format );
1962         }
1963         else if( p_stream->i_codec == VLC_FOURCC('d','t','s',' ') )
1964         {
1965             /* DTS registration descriptor (ETSI TS 101 154 Annex F) */
1966
1967             /* DTS format identifier, frame size 1024 - FIXME */
1968             uint8_t data[4] = { 0x44, 0x54, 0x53, 0x32 };
1969             dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, data );
1970         }
1971         else if( p_stream->i_codec == VLC_FOURCC('t','e','l','x') )
1972         {
1973             dvbpsi_PMTESAddDescriptor( p_es, 0x56,
1974                                        p_stream->i_decoder_specific_info,
1975                                        p_stream->p_decoder_specific_info );
1976         }
1977 #ifdef _DVBPSI_DR_59_H_
1978         else if( p_stream->i_codec == VLC_FOURCC('d','v','b','s') )
1979         {
1980             /* DVB subtitles */
1981             dvbpsi_subtitling_dr_t descr;
1982             dvbpsi_subtitle_t sub;
1983             dvbpsi_descriptor_t *p_descr;
1984
1985             memcpy( sub.i_iso6392_language_code, p_stream->lang, 3 );
1986             sub.i_subtitling_type = 0x10; /* no aspect-ratio criticality */
1987             sub.i_composition_page_id = p_stream->i_es_id & 0xFF;
1988             sub.i_ancillary_page_id = p_stream->i_es_id >> 16;
1989
1990             descr.i_subtitles_number = 1;
1991             descr.p_subtitle[0] = sub;
1992
1993             p_descr = dvbpsi_GenSubtitlingDr( &descr, 0 );
1994             /* Work around bug in old libdvbpsi */ p_descr->i_length = 8;
1995             dvbpsi_PMTESAddDescriptor( p_es, p_descr->i_tag,
1996                                        p_descr->i_length, p_descr->p_data );
1997             continue;
1998         }
1999 #endif /* _DVBPSI_DR_59_H_ */
2000
2001         if( p_stream->lang[0] != 0 )
2002         {
2003             uint8_t data[4];
2004
2005             /* I construct the content myself, way faster than looking at
2006              * over complicated/mind broken libdvbpsi way */
2007             data[0] = p_stream->lang[0];
2008             data[1] = p_stream->lang[1];
2009             data[2] = p_stream->lang[2];
2010             data[3] = 0x00; /* audio type: 0x00 undefined */
2011
2012             dvbpsi_PMTESAddDescriptor( p_es, 0x0a, 4, data );
2013         }
2014     }
2015
2016     p_section = dvbpsi_GenPMTSections( &pmt );
2017
2018     p_pmt = WritePSISection( p_mux->p_sout, p_section );
2019
2020     PEStoTS( p_mux->p_sout, c, p_pmt, &p_sys->pmt );
2021
2022     dvbpsi_DeletePSISections( p_section );
2023     dvbpsi_EmptyPMT( &pmt );
2024 }