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