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