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