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