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