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