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