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