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