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