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