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