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