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