]> git.sesse.net Git - vlc/blob - modules/mux/mpeg/ts.c
Add yet another XDCAM fourCC
[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     free(p_stream->lang);
1106     free(p_stream);
1107     return VLC_ENOMEM;
1108 }
1109
1110 /*****************************************************************************
1111  * DelStream: called before a stream deletion
1112  *****************************************************************************/
1113 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
1114 {
1115     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1116     ts_stream_t     *p_stream = (ts_stream_t*)p_input->p_sys;
1117     int              pid;
1118
1119     msg_Dbg( p_mux, "removing input pid=%d", p_stream->i_pid );
1120
1121     if( p_sys->i_pcr_pid == p_stream->i_pid )
1122     {
1123         /* Find a new pcr stream (Prefer Video Stream) */
1124         p_sys->i_pcr_pid = 0x1fff;
1125         p_sys->p_pcr_input = NULL;
1126         for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1127         {
1128             if( p_mux->pp_inputs[i] == p_input )
1129             {
1130                 continue;
1131             }
1132
1133             if( p_mux->pp_inputs[i]->p_fmt->i_cat == VIDEO_ES )
1134             {
1135                 p_sys->i_pcr_pid  =
1136                     ((ts_stream_t*)p_mux->pp_inputs[i]->p_sys)->i_pid;
1137                 p_sys->p_pcr_input= p_mux->pp_inputs[i];
1138                 break;
1139             }
1140             else if( p_mux->pp_inputs[i]->p_fmt->i_cat != SPU_ES &&
1141                      p_sys->i_pcr_pid == 0x1fff )
1142             {
1143                 p_sys->i_pcr_pid  =
1144                     ((ts_stream_t*)p_mux->pp_inputs[i]->p_sys)->i_pid;
1145                 p_sys->p_pcr_input= p_mux->pp_inputs[i];
1146             }
1147         }
1148         if( p_sys->p_pcr_input )
1149         {
1150             /* Empty TS buffer */
1151             /* FIXME */
1152         }
1153         msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
1154     }
1155
1156     /* Empty all data in chain_pes */
1157     BufferChainClean( &p_stream->chain_pes );
1158
1159     free(p_stream->lang);
1160     free( p_stream->p_extra );
1161     if( p_stream->i_stream_id == 0xfa ||
1162         p_stream->i_stream_id == 0xfb ||
1163         p_stream->i_stream_id == 0xfe )
1164     {
1165         p_sys->i_mpeg4_streams--;
1166     }
1167
1168     pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-video" );
1169     if ( pid > 0 && pid == p_stream->i_pid )
1170     {
1171         p_sys->i_pid_video = pid;
1172         msg_Dbg( p_mux, "freeing video PID %d", pid);
1173     }
1174     pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-audio" );
1175     if ( pid > 0 && pid == p_stream->i_pid )
1176     {
1177         p_sys->i_pid_audio = pid;
1178         msg_Dbg( p_mux, "freeing audio PID %d", pid);
1179     }
1180     pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-spu" );
1181     if ( pid > 0 && pid == p_stream->i_pid )
1182     {
1183         p_sys->i_pid_spu = pid;
1184         msg_Dbg( p_mux, "freeing spu PID %d", pid);
1185     }
1186
1187     free( p_stream );
1188
1189     /* We only change PMT version (PAT isn't changed) */
1190     p_sys->i_pmt_version_number++;
1191     p_sys->i_pmt_version_number %= 32;
1192
1193     return VLC_SUCCESS;
1194 }
1195
1196 static void SetHeader( sout_buffer_chain_t *c,
1197                         int depth )
1198 {
1199     block_t *p_ts = BufferChainPeek( c );
1200     while( depth > 0 )
1201     {
1202         p_ts = p_ts->p_next;
1203         depth--;
1204     }
1205     p_ts->i_flags |= BLOCK_FLAG_HEADER;
1206 }
1207
1208 /* returns true if needs more data */
1209 static bool MuxStreams(sout_mux_t *p_mux )
1210 {
1211     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1212     ts_stream_t *p_pcr_stream = (ts_stream_t*)p_sys->p_pcr_input->p_sys;
1213
1214     sout_buffer_chain_t chain_ts;
1215     mtime_t i_shaping_delay = p_pcr_stream->b_key_frame
1216         ? p_pcr_stream->i_pes_length
1217         : p_sys->i_shaping_delay;
1218
1219     bool b_ok = true;
1220
1221     /* Accumulate enough data in the pcr stream (>i_shaping_delay) */
1222     /* Accumulate enough data in all other stream ( >= length of pcr)*/
1223     for (int i = -1; !b_ok || i < p_mux->i_nb_inputs; i++ )
1224     {
1225         if (i == p_mux->i_nb_inputs)
1226         {
1227             /* get enough PES packet for all input */
1228             b_ok = true;
1229             i = -1;
1230         }
1231         sout_input_t *p_input;
1232
1233         if( i == -1 )
1234             p_input = p_sys->p_pcr_input;
1235         else if( p_mux->pp_inputs[i]->p_sys == p_pcr_stream )
1236             continue;
1237         else
1238             p_input = p_mux->pp_inputs[i];
1239         ts_stream_t *p_stream = (ts_stream_t*)p_input->p_sys;
1240
1241         if( ( p_stream != p_pcr_stream ||
1242               p_stream->i_pes_length >= i_shaping_delay ) &&
1243             p_stream->i_pes_dts + p_stream->i_pes_length >=
1244             p_pcr_stream->i_pes_dts + p_pcr_stream->i_pes_length )
1245             continue;
1246
1247         /* Need more data */
1248         if( block_FifoCount( p_input->p_fifo ) <= 1 )
1249         {
1250             if( ( p_input->p_fmt->i_cat == AUDIO_ES ) ||
1251                 ( p_input->p_fmt->i_cat == VIDEO_ES ) )
1252             {
1253                 /* We need more data */
1254                 return true;
1255             }
1256             else if( block_FifoCount( p_input->p_fifo ) <= 0 )
1257             {
1258                 /* spu, only one packet is needed */
1259                 continue;
1260             }
1261             else if( p_input->p_fmt->i_cat == SPU_ES )
1262             {
1263                 /* Don't mux the SPU yet if it is too early */
1264                 block_t *p_spu = block_FifoShow( p_input->p_fifo );
1265
1266                 int64_t i_spu_delay = p_spu->i_dts - p_pcr_stream->i_pes_dts;
1267                 if( ( i_spu_delay > i_shaping_delay ) &&
1268                     ( i_spu_delay < INT64_C(100000000) ) )
1269                     continue;
1270
1271                 if ( ( i_spu_delay >= INT64_C(100000000) ) ||
1272                      ( i_spu_delay < INT64_C(10000) ) )
1273                 {
1274                     BufferChainClean( &p_stream->chain_pes );
1275                     p_stream->i_pes_dts = 0;
1276                     p_stream->i_pes_used = 0;
1277                     p_stream->i_pes_length = 0;
1278                     continue;
1279                 }
1280             }
1281         }
1282         b_ok = false;
1283
1284         block_t *p_data;
1285         if( p_stream == p_pcr_stream || p_sys->b_data_alignment
1286              || p_input->p_fmt->i_codec != VLC_CODEC_MPGA )
1287         {
1288             p_data = block_FifoGet( p_input->p_fifo );
1289             if (p_data->i_pts <= VLC_TS_INVALID)
1290                 p_data->i_pts = p_data->i_dts;
1291
1292             if( p_input->p_fmt->i_codec == VLC_CODEC_MP4A )
1293                 p_data = Add_ADTS( p_data, p_input->p_fmt );
1294         }
1295         else
1296             p_data = FixPES( p_mux, p_input->p_fifo );
1297
1298         if( block_FifoCount( p_input->p_fifo ) > 0 &&
1299             p_input->p_fmt->i_cat != SPU_ES )
1300         {
1301             block_t *p_next = block_FifoShow( p_input->p_fifo );
1302             p_data->i_length = p_next->i_dts - p_data->i_dts;
1303         }
1304         else if( p_input->p_fmt->i_codec !=
1305                    VLC_CODEC_SUBT )
1306             p_data->i_length = 1000;
1307
1308         if( ( p_pcr_stream->i_pes_dts > 0 &&
1309               p_data->i_dts - 10000000 > p_pcr_stream->i_pes_dts +
1310               p_pcr_stream->i_pes_length ) ||
1311             p_data->i_dts < p_stream->i_pes_dts ||
1312             ( p_stream->i_pes_dts > 0 &&
1313               p_input->p_fmt->i_cat != SPU_ES &&
1314               p_data->i_dts - 10000000 > p_stream->i_pes_dts +
1315               p_stream->i_pes_length ) )
1316         {
1317             msg_Warn( p_mux, "packet with too strange dts "
1318                       "(dts=%"PRId64",old=%"PRId64",pcr=%"PRId64")",
1319                       p_data->i_dts, p_stream->i_pes_dts,
1320                       p_pcr_stream->i_pes_dts );
1321             block_Release( p_data );
1322
1323             BufferChainClean( &p_stream->chain_pes );
1324             p_stream->i_pes_dts = 0;
1325             p_stream->i_pes_used = 0;
1326             p_stream->i_pes_length = 0;
1327
1328             if( p_input->p_fmt->i_cat != SPU_ES )
1329             {
1330                 BufferChainClean( &p_pcr_stream->chain_pes );
1331                 p_pcr_stream->i_pes_dts = 0;
1332                 p_pcr_stream->i_pes_used = 0;
1333                 p_pcr_stream->i_pes_length = 0;
1334             }
1335
1336             continue;
1337         }
1338
1339         int i_header_size = 0;
1340         int i_max_pes_size = 0;
1341         int b_data_alignment = 0;
1342         if( p_input->p_fmt->i_cat == SPU_ES ) switch (p_input->p_fmt->i_codec)
1343         {
1344         case VLC_CODEC_SUBT:
1345             /* Prepend header */
1346             p_data = block_Realloc( p_data, 2, p_data->i_buffer );
1347             p_data->p_buffer[0] = ( (p_data->i_buffer - 2) >> 8) & 0xff;
1348             p_data->p_buffer[1] = ( (p_data->i_buffer - 2)     ) & 0xff;
1349
1350             /* remove trailling \0 if any */
1351             if( p_data->i_buffer > 2 && !p_data->p_buffer[p_data->i_buffer-1] )
1352                 p_data->i_buffer--;
1353
1354             /* Append a empty sub (sub text only) */
1355             if( p_data->i_length > 0 &&
1356                 ( p_data->i_buffer != 1 || *p_data->p_buffer != ' ' ) )
1357             {
1358                 block_t *p_spu = block_Alloc( 3 );
1359
1360                 p_spu->i_dts = p_data->i_dts + p_data->i_length;
1361                 p_spu->i_pts = p_spu->i_dts;
1362                 p_spu->i_length = 1000;
1363
1364                 p_spu->p_buffer[0] = 0;
1365                 p_spu->p_buffer[1] = 1;
1366                 p_spu->p_buffer[2] = ' ';
1367
1368                 EStoPES( &p_spu, p_spu, p_input->p_fmt,
1369                              p_stream->i_stream_id, 1, 0, 0, 0 );
1370                 p_data->p_next = p_spu;
1371             }
1372             break;
1373
1374         case VLC_CODEC_TELETEXT:
1375             /* EN 300 472 */
1376             i_header_size = 0x24;
1377             b_data_alignment = 1;
1378             break;
1379
1380         case VLC_CODEC_DVBS:
1381             /* EN 300 743 */
1382             b_data_alignment = 1;
1383             break;
1384         }
1385         else if( p_data->i_length < 0 || p_data->i_length > 2000000 )
1386         {
1387             /* FIXME choose a better value, but anyway we
1388              * should never have to do that */
1389             p_data->i_length = 1000;
1390         }
1391
1392         p_stream->i_pes_length += p_data->i_length;
1393         if( p_stream->i_pes_dts == 0 )
1394         {
1395             p_stream->i_pes_dts = p_data->i_dts;
1396         }
1397
1398         /* Convert to pes */
1399         if( p_stream->i_stream_id == 0xa0 && p_data->i_pts <= 0 )
1400         {
1401             /* XXX yes I know, it's awful, but it's needed,
1402              * so don't remove it ... */
1403             p_data->i_pts = p_data->i_dts;
1404         }
1405
1406         if( p_input->p_fmt->i_codec == VLC_CODEC_DIRAC )
1407         {
1408             b_data_alignment = 1;
1409             /* dirac pes packets should be unbounded in
1410              * length, specify a suitibly large max size */
1411             i_max_pes_size = INT_MAX;
1412         }
1413
1414          EStoPES ( &p_data, p_data, p_input->p_fmt, p_stream->i_stream_id,
1415                        1, b_data_alignment, i_header_size,
1416                        i_max_pes_size );
1417
1418         BufferChainAppend( &p_stream->chain_pes, p_data );
1419
1420         if( p_sys->b_use_key_frames && p_stream == p_pcr_stream
1421             && (p_data->i_flags & BLOCK_FLAG_TYPE_I)
1422             && !(p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME)
1423             && (p_stream->i_pes_length > 400000) )
1424         {
1425             i_shaping_delay = p_stream->i_pes_length;
1426             p_stream->b_key_frame = 1;
1427         }
1428     }
1429
1430     /* save */
1431     const mtime_t i_pcr_length = p_pcr_stream->i_pes_length;
1432     p_pcr_stream->b_key_frame = 0;
1433
1434     /* msg_Dbg( p_mux, "starting muxing %lldms", i_pcr_length / 1000 ); */
1435     /* 2: calculate non accurate total size of muxed ts */
1436     int i_packet_count = 0;
1437     for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1438     {
1439         ts_stream_t *p_stream = (ts_stream_t*)p_mux->pp_inputs[i]->p_sys;
1440
1441         /* False for pcr stream but it will be enough to do PCR algo */
1442         for (block_t *p_pes = p_stream->chain_pes.p_first; p_pes != NULL;
1443              p_pes = p_pes->p_next )
1444         {
1445             int i_size = p_pes->i_buffer;
1446             if( p_pes->i_dts + p_pes->i_length >
1447                 p_pcr_stream->i_pes_dts + p_pcr_stream->i_pes_length )
1448             {
1449                 mtime_t i_frag = p_pcr_stream->i_pes_dts +
1450                     p_pcr_stream->i_pes_length - p_pes->i_dts;
1451                 if( i_frag < 0 )
1452                 {
1453                     /* Next stream */
1454                     break;
1455                 }
1456                 i_size = p_pes->i_buffer * i_frag / p_pes->i_length;
1457             }
1458             i_packet_count += ( i_size + 183 ) / 184;
1459         }
1460     }
1461     /* add overhead for PCR (not really exact) */
1462     i_packet_count += (8 * i_pcr_length / p_sys->i_pcr_delay + 175) / 176;
1463
1464     /* 3: mux PES into TS */
1465     BufferChainInit( &chain_ts );
1466     /* append PAT/PMT  -> FIXME with big pcr delay it won't have enough pat/pmt */
1467     bool pat_was_previous = true; //This is to prevent unnecessary double PAT/PMT insertions
1468     GetPAT( p_mux, &chain_ts );
1469     GetPMT( p_mux, &chain_ts );
1470     int i_packet_pos = 0;
1471     i_packet_count += chain_ts.i_depth;
1472     /* msg_Dbg( p_mux, "estimated pck=%d", i_packet_count ); */
1473
1474     const mtime_t i_pcr_dts = p_pcr_stream->i_pes_dts;
1475     for (;;)
1476     {
1477         int          i_stream = -1;
1478         mtime_t      i_dts = 0;
1479         ts_stream_t  *p_stream;
1480
1481         /* Select stream (lowest dts) */
1482         for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1483         {
1484             p_stream = (ts_stream_t*)p_mux->pp_inputs[i]->p_sys;
1485
1486             if( p_stream->i_pes_dts == 0 )
1487             {
1488                 continue;
1489             }
1490
1491             if( i_stream == -1 || p_stream->i_pes_dts < i_dts )
1492             {
1493                 i_stream = i;
1494                 i_dts = p_stream->i_pes_dts;
1495             }
1496         }
1497         if( i_stream == -1 || i_dts > i_pcr_dts + i_pcr_length )
1498         {
1499             break;
1500         }
1501         p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
1502         sout_input_t *p_input = p_mux->pp_inputs[i_stream];
1503
1504         /* do we need to issue pcr */
1505         bool b_pcr = false;
1506         if( p_stream == p_pcr_stream &&
1507             i_pcr_dts + i_packet_pos * i_pcr_length / i_packet_count >=
1508             p_sys->i_pcr + p_sys->i_pcr_delay )
1509         {
1510             b_pcr = true;
1511             p_sys->i_pcr = i_pcr_dts + i_packet_pos *
1512                 i_pcr_length / i_packet_count;
1513         }
1514
1515         /* Build the TS packet */
1516         block_t *p_ts = TSNew( p_mux, p_stream, b_pcr );
1517         if( p_sys->csa != NULL &&
1518              (p_input->p_fmt->i_cat != AUDIO_ES || p_sys->b_crypt_audio) &&
1519              (p_input->p_fmt->i_cat != VIDEO_ES || p_sys->b_crypt_video) )
1520         {
1521             p_ts->i_flags |= BLOCK_FLAG_SCRAMBLED;
1522         }
1523         i_packet_pos++;
1524
1525         /* Write PAT/PMT before every keyframe if use-key-frames is enabled,
1526          * this helps to do segmenting with livehttp-output so it can cut segment
1527          * and start new one with pat,pmt,keyframe*/
1528         if( ( p_sys->b_use_key_frames ) && ( p_ts->i_flags & BLOCK_FLAG_TYPE_I ) )
1529         {
1530             if( likely( !pat_was_previous ) )
1531             {
1532                 int startcount = chain_ts.i_depth;
1533                 GetPAT( p_mux, &chain_ts );
1534                 GetPMT( p_mux, &chain_ts );
1535                 SetHeader( &chain_ts, startcount );
1536                 i_packet_count += (chain_ts.i_depth - startcount );
1537             } else {
1538                 SetHeader( &chain_ts, 0); //We just inserted pat/pmt,so just flag it instead of adding new one
1539             }
1540         }
1541         pat_was_previous = false;
1542
1543         /* */
1544         BufferChainAppend( &chain_ts, p_ts );
1545     }
1546
1547     /* 4: date and send */
1548     TSSchedule( p_mux, &chain_ts, i_pcr_length, i_pcr_dts );
1549     return false;
1550 }
1551
1552 /*****************************************************************************
1553  * Mux: Call each time there is new data for at least one stream
1554  *****************************************************************************
1555  *
1556  *****************************************************************************/
1557 static int Mux( sout_mux_t *p_mux )
1558 {
1559     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1560
1561     if( p_sys->i_pcr_pid == 0x1fff )
1562     {
1563         for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1564         {
1565             block_FifoEmpty( p_mux->pp_inputs[i]->p_fifo );
1566         }
1567         msg_Dbg( p_mux, "waiting for PCR streams" );
1568         return VLC_SUCCESS;
1569     }
1570
1571     while (!MuxStreams(p_mux))
1572         ;
1573     return VLC_SUCCESS;
1574 }
1575
1576 #define STD_PES_PAYLOAD 170
1577 static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo )
1578 {
1579     VLC_UNUSED(p_mux);
1580     block_t *p_data;
1581     size_t i_size;
1582
1583     p_data = block_FifoShow( p_fifo );
1584     i_size = p_data->i_buffer;
1585
1586     if( i_size == STD_PES_PAYLOAD )
1587     {
1588         return block_FifoGet( p_fifo );
1589     }
1590     else if( i_size > STD_PES_PAYLOAD )
1591     {
1592         block_t *p_new = block_Alloc( STD_PES_PAYLOAD );
1593         memcpy( p_new->p_buffer, p_data->p_buffer, STD_PES_PAYLOAD );
1594         p_new->i_pts = p_data->i_pts;
1595         p_new->i_dts = p_data->i_dts;
1596         p_new->i_length = p_data->i_length * STD_PES_PAYLOAD
1597                             / p_data->i_buffer;
1598         p_data->i_buffer -= STD_PES_PAYLOAD;
1599         p_data->p_buffer += STD_PES_PAYLOAD;
1600         p_data->i_pts += p_new->i_length;
1601         p_data->i_dts += p_new->i_length;
1602         p_data->i_length -= p_new->i_length;
1603         p_data->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1604         return p_new;
1605     }
1606     else
1607     {
1608         block_t *p_next;
1609         int i_copy;
1610
1611         p_data = block_FifoGet( p_fifo );
1612         p_data = block_Realloc( p_data, 0, STD_PES_PAYLOAD );
1613         p_next = block_FifoShow( p_fifo );
1614         if ( p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME )
1615         {
1616             p_data->i_flags &= ~BLOCK_FLAG_NO_KEYFRAME;
1617             p_data->i_pts = p_next->i_pts;
1618             p_data->i_dts = p_next->i_dts;
1619         }
1620         i_copy = __MIN( STD_PES_PAYLOAD - i_size, p_next->i_buffer );
1621
1622         memcpy( &p_data->p_buffer[i_size], p_next->p_buffer, i_copy );
1623         p_next->i_pts += p_next->i_length * i_copy / p_next->i_buffer;
1624         p_next->i_dts += p_next->i_length * i_copy / p_next->i_buffer;
1625         p_next->i_length -= p_next->i_length * i_copy / p_next->i_buffer;
1626         p_next->i_buffer -= i_copy;
1627         p_next->p_buffer += i_copy;
1628         p_next->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1629
1630         if( !p_next->i_buffer )
1631         {
1632             p_next = block_FifoGet( p_fifo );
1633             block_Release( p_next );
1634         }
1635         return p_data;
1636     }
1637 }
1638
1639 static block_t *Add_ADTS( block_t *p_data, es_format_t *p_fmt )
1640 {
1641 #define ADTS_HEADER_SIZE 7 /* CRC needs 2 more bytes */
1642
1643     uint8_t *p_extra = p_fmt->p_extra;
1644
1645     if( !p_data || p_fmt->i_extra < 2 || !p_extra )
1646         return p_data; /* no data to construct the headers */
1647
1648     size_t frame_length = p_data->i_buffer + ADTS_HEADER_SIZE;
1649     int i_index = ( (p_extra[0] << 1) | (p_extra[1] >> 7) ) & 0x0f;
1650     int i_profile = (p_extra[0] >> 3) - 1; /* i_profile < 4 */
1651
1652     if( i_index == 0x0f && p_fmt->i_extra < 5 )
1653         return p_data; /* not enough data */
1654
1655     int i_channels = (p_extra[i_index == 0x0f ? 4 : 1] >> 3) & 0x0f;
1656
1657     /* keep a copy in case block_Realloc() fails */
1658     block_t *p_bak_block = block_Duplicate( p_data );
1659     if( !p_bak_block ) /* OOM, block_Realloc() is likely to lose our block */
1660         return p_data; /* the frame isn't correct but that's the best we have */
1661
1662     block_t *p_new_block = block_Realloc( p_data, ADTS_HEADER_SIZE,
1663                                             p_data->i_buffer );
1664     if( !p_new_block )
1665         return p_bak_block; /* OOM, send the (incorrect) original frame */
1666
1667     block_Release( p_bak_block ); /* we don't need the copy anymore */
1668
1669
1670     uint8_t *p_buffer = p_new_block->p_buffer;
1671
1672     /* fixed header */
1673     p_buffer[0] = 0xff;
1674     p_buffer[1] = 0xf1; /* 0xf0 | 0x00 | 0x00 | 0x01 */
1675     p_buffer[2] = (i_profile << 6) | ((i_index & 0x0f) << 2) | ((i_channels >> 2) & 0x01) ;
1676     p_buffer[3] = (i_channels << 6) | ((frame_length >> 11) & 0x03);
1677
1678     /* variable header (starts at last 2 bits of 4th byte) */
1679
1680     int i_fullness = 0x7ff; /* 0x7ff means VBR */
1681     /* XXX: We should check if it's CBR or VBR, but no known implementation
1682      * do that, and it's a pain to calculate this field */
1683
1684     p_buffer[4] = frame_length >> 3;
1685     p_buffer[5] = ((frame_length & 0x07) << 5) | ((i_fullness >> 6) & 0x1f);
1686     p_buffer[6] = ((i_fullness & 0x3f) << 2) /* | 0xfc */;
1687
1688     return p_new_block;
1689 }
1690
1691 static void TSSchedule( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1692                         mtime_t i_pcr_length, mtime_t i_pcr_dts )
1693 {
1694     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1695     sout_buffer_chain_t new_chain;
1696     int i_packet_count = p_chain_ts->i_depth;
1697
1698     BufferChainInit( &new_chain );
1699
1700     if ( i_pcr_length <= 0 )
1701     {
1702         i_pcr_length = i_packet_count;
1703     }
1704
1705     for (int i = 0; i < i_packet_count; i++ )
1706     {
1707         block_t *p_ts = BufferChainGet( p_chain_ts );
1708         mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1709
1710         BufferChainAppend( &new_chain, p_ts );
1711
1712         if (!p_ts->i_dts || p_ts->i_dts + p_sys->i_dts_delay * 2/3 >= i_new_dts)
1713             continue;
1714
1715         mtime_t i_max_diff = i_new_dts - p_ts->i_dts;
1716         mtime_t i_cut_dts = p_ts->i_dts;
1717
1718         p_ts = BufferChainPeek( p_chain_ts );
1719         i++;
1720         i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1721         while ( p_ts != NULL && i_new_dts - p_ts->i_dts >= i_max_diff )
1722         {
1723             p_ts = BufferChainGet( p_chain_ts );
1724             i_max_diff = i_new_dts - p_ts->i_dts;
1725             i_cut_dts = p_ts->i_dts;
1726             BufferChainAppend( &new_chain, p_ts );
1727
1728             p_ts = BufferChainPeek( p_chain_ts );
1729             i++;
1730             i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1731         }
1732         msg_Dbg( p_mux, "adjusting rate at %"PRId64"/%"PRId64" (%d/%d)",
1733                  i_cut_dts - i_pcr_dts, i_pcr_length, new_chain.i_depth,
1734                  p_chain_ts->i_depth );
1735         if ( new_chain.i_depth )
1736             TSDate( p_mux, &new_chain, i_cut_dts - i_pcr_dts, i_pcr_dts );
1737         if ( p_chain_ts->i_depth )
1738             TSSchedule( p_mux, p_chain_ts, i_pcr_dts + i_pcr_length - i_cut_dts,
1739                         i_cut_dts );
1740         return;
1741     }
1742
1743     if ( new_chain.i_depth )
1744         TSDate( p_mux, &new_chain, i_pcr_length, i_pcr_dts );
1745 }
1746
1747 static void TSDate( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1748                     mtime_t i_pcr_length, mtime_t i_pcr_dts )
1749 {
1750     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1751     int i_packet_count = p_chain_ts->i_depth;
1752
1753     if ( i_pcr_length / 1000 > 0 )
1754     {
1755         int i_bitrate = ((uint64_t)i_packet_count * 188 * 8000)
1756                           / (uint64_t)(i_pcr_length / 1000);
1757         if ( p_sys->i_bitrate_max && p_sys->i_bitrate_max < i_bitrate )
1758         {
1759             msg_Warn( p_mux, "max bitrate exceeded at %"PRId64
1760                       " (%d bi/s for %d pkt in %"PRId64" us)",
1761                       i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
1762                       i_bitrate, i_packet_count, i_pcr_length);
1763         }
1764     }
1765     else
1766     {
1767         /* This shouldn't happen, but happens in some rare heavy load
1768          * and packet losses conditions. */
1769         i_pcr_length = i_packet_count;
1770     }
1771
1772     /* msg_Dbg( p_mux, "real pck=%d", i_packet_count ); */
1773     for (int i = 0; i < i_packet_count; i++ )
1774     {
1775         block_t *p_ts = BufferChainGet( p_chain_ts );
1776         mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1777
1778         p_ts->i_dts    = i_new_dts;
1779         p_ts->i_length = i_pcr_length / i_packet_count;
1780
1781         if( p_ts->i_flags & BLOCK_FLAG_CLOCK )
1782         {
1783             /* msg_Dbg( p_mux, "pcr=%lld ms", p_ts->i_dts / 1000 ); */
1784             TSSetPCR( p_ts, p_ts->i_dts - p_sys->i_dts_delay );
1785         }
1786         if( p_ts->i_flags & BLOCK_FLAG_SCRAMBLED )
1787         {
1788             vlc_mutex_lock( &p_sys->csa_lock );
1789             csa_Encrypt( p_sys->csa, p_ts->p_buffer, p_sys->i_csa_pkt_size );
1790             vlc_mutex_unlock( &p_sys->csa_lock );
1791         }
1792
1793         /* latency */
1794         p_ts->i_dts += p_sys->i_shaping_delay * 3 / 2;
1795
1796         sout_AccessOutWrite( p_mux->p_access, p_ts );
1797     }
1798 }
1799
1800 static block_t *TSNew( sout_mux_t *p_mux, ts_stream_t *p_stream,
1801                        bool b_pcr )
1802 {
1803     VLC_UNUSED(p_mux);
1804     block_t *p_pes = p_stream->chain_pes.p_first;
1805
1806     bool b_new_pes = false;
1807     bool b_adaptation_field = false;
1808
1809     int i_payload_max = 184 - ( b_pcr ? 8 : 0 );
1810
1811     if( p_stream->i_pes_used <= 0 )
1812     {
1813         b_new_pes = true;
1814     }
1815     int i_payload = __MIN( (int)p_pes->i_buffer - p_stream->i_pes_used,
1816                        i_payload_max );
1817
1818     if( b_pcr || i_payload < i_payload_max )
1819     {
1820         b_adaptation_field = true;
1821     }
1822
1823     block_t *p_ts = block_Alloc( 188 );
1824
1825     if (b_new_pes && !(p_pes->i_flags & BLOCK_FLAG_NO_KEYFRAME) && p_pes->i_flags & BLOCK_FLAG_TYPE_I)
1826     {
1827         p_ts->i_flags |= BLOCK_FLAG_TYPE_I;
1828     }
1829
1830     p_ts->i_dts = p_pes->i_dts;
1831
1832     p_ts->p_buffer[0] = 0x47;
1833     p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 ) |
1834         ( ( p_stream->i_pid >> 8 )&0x1f );
1835     p_ts->p_buffer[2] = p_stream->i_pid & 0xff;
1836     p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 ) |
1837         p_stream->i_continuity_counter;
1838
1839     p_stream->i_continuity_counter = (p_stream->i_continuity_counter+1)%16;
1840     p_stream->b_discontinuity = p_pes->i_flags & BLOCK_FLAG_DISCONTINUITY;
1841
1842     if( b_adaptation_field )
1843     {
1844         int i_stuffing = i_payload_max - i_payload;
1845         if( b_pcr )
1846         {
1847             p_ts->i_flags |= BLOCK_FLAG_CLOCK;
1848
1849             p_ts->p_buffer[4] = 7 + i_stuffing;
1850             p_ts->p_buffer[5] = 0x10;   /* flags */
1851             if( p_stream->b_discontinuity )
1852             {
1853                 p_ts->p_buffer[5] |= 0x80; /* flag TS dicontinuity */
1854                 p_stream->b_discontinuity = false;
1855             }
1856             p_ts->p_buffer[6] = 0 &0xff;
1857             p_ts->p_buffer[7] = 0 &0xff;
1858             p_ts->p_buffer[8] = 0 &0xff;
1859             p_ts->p_buffer[9] = 0 &0xff;
1860             p_ts->p_buffer[10]= ( 0 &0x80 ) | 0x7e;
1861             p_ts->p_buffer[11]= 0;
1862
1863             for (int i = 12; i < 12 + i_stuffing; i++ )
1864             {
1865                 p_ts->p_buffer[i] = 0xff;
1866             }
1867         }
1868         else
1869         {
1870             p_ts->p_buffer[4] = i_stuffing - 1;
1871             if( i_stuffing > 1 )
1872             {
1873                 p_ts->p_buffer[5] = 0x00;
1874                 for (int i = 6; i < 6 + i_stuffing - 2; i++ )
1875                 {
1876                     p_ts->p_buffer[i] = 0xff;
1877                 }
1878             }
1879         }
1880     }
1881
1882     /* copy payload */
1883     memcpy( &p_ts->p_buffer[188 - i_payload],
1884             &p_pes->p_buffer[p_stream->i_pes_used], i_payload );
1885
1886     p_stream->i_pes_used += i_payload;
1887     p_stream->i_pes_dts = p_pes->i_dts + p_pes->i_length *
1888         p_stream->i_pes_used / p_pes->i_buffer;
1889     p_stream->i_pes_length -= p_pes->i_length * i_payload / p_pes->i_buffer;
1890
1891     if( p_stream->i_pes_used >= (int)p_pes->i_buffer )
1892     {
1893         block_Release(BufferChainGet( &p_stream->chain_pes ));
1894
1895         p_pes = p_stream->chain_pes.p_first;
1896         p_stream->i_pes_length = 0;
1897         if( p_pes )
1898         {
1899             p_stream->i_pes_dts = p_pes->i_dts;
1900             while( p_pes )
1901             {
1902                 p_stream->i_pes_length += p_pes->i_length;
1903                 p_pes = p_pes->p_next;
1904             }
1905         }
1906         else
1907         {
1908             p_stream->i_pes_dts = 0;
1909         }
1910         p_stream->i_pes_used = 0;
1911     }
1912
1913     return p_ts;
1914 }
1915
1916 static void TSSetPCR( block_t *p_ts, mtime_t i_dts )
1917 {
1918     mtime_t i_pcr = 9 * i_dts / 100;
1919
1920     p_ts->p_buffer[6]  = ( i_pcr >> 25 )&0xff;
1921     p_ts->p_buffer[7]  = ( i_pcr >> 17 )&0xff;
1922     p_ts->p_buffer[8]  = ( i_pcr >> 9  )&0xff;
1923     p_ts->p_buffer[9]  = ( i_pcr >> 1  )&0xff;
1924     p_ts->p_buffer[10]|= ( i_pcr << 7  )&0x80;
1925 }
1926
1927 static void PEStoTS( sout_buffer_chain_t *c, block_t *p_pes,
1928                      ts_stream_t *p_stream )
1929 {
1930     /* get PES total size */
1931     uint8_t *p_data = p_pes->p_buffer;
1932     int      i_size = p_pes->i_buffer;
1933
1934     bool    b_new_pes = true;
1935
1936     for (;;)
1937     {
1938         /* write header
1939          * 8b   0x47    sync byte
1940          * 1b           transport_error_indicator
1941          * 1b           payload_unit_start
1942          * 1b           transport_priority
1943          * 13b          pid
1944          * 2b           transport_scrambling_control
1945          * 2b           if adaptation_field 0x03 else 0x01
1946          * 4b           continuity_counter
1947          */
1948
1949         int i_copy = __MIN( i_size, 184 );
1950         bool b_adaptation_field = i_size < 184;
1951         block_t *p_ts = block_Alloc( 188 );
1952
1953         p_ts->p_buffer[0] = 0x47;
1954         p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 )|
1955                             ( ( p_stream->i_pid >> 8 )&0x1f );
1956         p_ts->p_buffer[2] = p_stream->i_pid & 0xff;
1957         p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 )|
1958                             p_stream->i_continuity_counter;
1959
1960         b_new_pes = false;
1961         p_stream->i_continuity_counter = (p_stream->i_continuity_counter+1)%16;
1962
1963         if( b_adaptation_field )
1964         {
1965             int i_stuffing = 184 - i_copy;
1966
1967             p_ts->p_buffer[4] = i_stuffing - 1;
1968             if( i_stuffing > 1 )
1969             {
1970                 p_ts->p_buffer[5] = 0x00;
1971                 if( p_stream->b_discontinuity )
1972                 {
1973                     p_ts->p_buffer[5] |= 0x80;
1974                     p_stream->b_discontinuity = false;
1975                 }
1976                 for (int i = 6; i < 6 + i_stuffing - 2; i++ )
1977                 {
1978                     p_ts->p_buffer[i] = 0xff;
1979                 }
1980             }
1981         }
1982         /* copy payload */
1983         memcpy( &p_ts->p_buffer[188 - i_copy], p_data, i_copy );
1984         p_data += i_copy;
1985         i_size -= i_copy;
1986
1987         BufferChainAppend( c, p_ts );
1988
1989         if( i_size <= 0 )
1990         {
1991             block_t *p_next = p_pes->p_next;
1992
1993             p_pes->p_next = NULL;
1994             block_Release( p_pes );
1995             if( p_next == NULL )
1996                 return;
1997
1998             b_new_pes = true;
1999             p_pes = p_next;
2000             i_size = p_pes->i_buffer;
2001             p_data = p_pes->p_buffer;
2002         }
2003     }
2004 }
2005
2006 static block_t *WritePSISection( dvbpsi_psi_section_t* p_section )
2007 {
2008     block_t   *p_psi, *p_first = NULL;
2009
2010     while( p_section )
2011     {
2012         int i_size = (uint32_t)(p_section->p_payload_end - p_section->p_data) +
2013                   (p_section->b_syntax_indicator ? 4 : 0);
2014
2015         p_psi = block_Alloc( i_size + 1 );
2016         if( !p_psi )
2017             goto error;
2018         p_psi->i_pts = 0;
2019         p_psi->i_dts = 0;
2020         p_psi->i_length = 0;
2021         p_psi->i_buffer = i_size + 1;
2022
2023         p_psi->p_buffer[0] = 0; /* pointer */
2024         memcpy( p_psi->p_buffer + 1,
2025                 p_section->p_data,
2026                 i_size );
2027
2028         block_ChainAppend( &p_first, p_psi );
2029
2030         p_section = p_section->p_next;
2031     }
2032
2033     return( p_first );
2034
2035 error:
2036     if( p_first )
2037         block_ChainRelease( p_first );
2038     return NULL;
2039 }
2040
2041 static void GetPAT( sout_mux_t *p_mux,
2042                     sout_buffer_chain_t *c )
2043 {
2044     sout_mux_sys_t       *p_sys = p_mux->p_sys;
2045     block_t              *p_pat;
2046     dvbpsi_pat_t         pat;
2047     dvbpsi_psi_section_t *p_section;
2048
2049     dvbpsi_InitPAT( &pat, p_sys->i_tsid, p_sys->i_pat_version_number,
2050                     1 );      /* b_current_next */
2051     /* add all programs */
2052     for (unsigned i = 0; i < p_sys->i_num_pmt; i++ )
2053         dvbpsi_PATAddProgram( &pat, p_sys->i_pmt_program_number[i],
2054                               p_sys->pmt[i].i_pid );
2055
2056 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
2057     p_section = dvbpsi_pat_sections_generate( p_sys->p_dvbpsi, &pat, 0 );
2058 #else
2059     p_section = dvbpsi_GenPATSections( &pat, 0 /* max program per section */ );
2060 #endif
2061     p_pat = WritePSISection( p_section );
2062
2063     PEStoTS( c, p_pat, &p_sys->pat );
2064
2065     dvbpsi_DeletePSISections( p_section );
2066     dvbpsi_EmptyPAT( &pat );
2067 }
2068
2069 static uint32_t GetDescriptorLength24b( int i_length )
2070 {
2071     uint32_t i_l1, i_l2, i_l3;
2072
2073     i_l1 = i_length&0x7f;
2074     i_l2 = ( i_length >> 7 )&0x7f;
2075     i_l3 = ( i_length >> 14 )&0x7f;
2076
2077     return( 0x808000 | ( i_l3 << 16 ) | ( i_l2 << 8 ) | i_l1 );
2078 }
2079
2080 static void GetPMTmpeg4(sout_mux_t *p_mux)
2081 {
2082     sout_mux_sys_t *p_sys = p_mux->p_sys;
2083     uint8_t iod[4096];
2084     bits_buffer_t bits, bits_fix_IOD;
2085
2086     /* Make valgrind happy : it works at byte level not bit one so
2087      * bit_write confuse it (but DON'T CHANGE the way that bit_write is
2088      * working (needed when fixing some bits) */
2089     memset( iod, 0, 4096 );
2090
2091     bits_initwrite( &bits, 4096, iod );
2092     /* IOD_label_scope */
2093     bits_write( &bits, 8,   0x11 );
2094     /* IOD_label */
2095     bits_write( &bits, 8,   0x01 );
2096     /* InitialObjectDescriptor */
2097     bits_align( &bits );
2098     bits_write( &bits, 8,   0x02 );     /* tag */
2099     bits_fix_IOD = bits;    /* save states to fix length later */
2100     bits_write( &bits, 24,
2101         GetDescriptorLength24b( 0 ) );  /* variable length (fixed later) */
2102     bits_write( &bits, 10,  0x01 );     /* ObjectDescriptorID */
2103     bits_write( &bits, 1,   0x00 );     /* URL Flag */
2104     bits_write( &bits, 1,   0x00 );     /* includeInlineProfileLevelFlag */
2105     bits_write( &bits, 4,   0x0f );     /* reserved */
2106     bits_write( &bits, 8,   0xff );     /* ODProfile (no ODcapability ) */
2107     bits_write( &bits, 8,   0xff );     /* sceneProfile */
2108     bits_write( &bits, 8,   0xfe );     /* audioProfile (unspecified) */
2109     bits_write( &bits, 8,   0xfe );     /* visualProfile( // ) */
2110     bits_write( &bits, 8,   0xff );     /* graphicProfile (no ) */
2111     for (int i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
2112     {
2113         ts_stream_t *p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
2114
2115         if( p_stream->i_stream_id != 0xfa && p_stream->i_stream_id != 0xfb &&
2116             p_stream->i_stream_id != 0xfe )
2117             continue;
2118
2119         bits_buffer_t bits_fix_ESDescr, bits_fix_Decoder;
2120         /* ES descriptor */
2121         bits_align( &bits );
2122         bits_write( &bits, 8,   0x03 );     /* ES_DescrTag */
2123         bits_fix_ESDescr = bits;
2124         bits_write( &bits, 24,
2125                     GetDescriptorLength24b( 0 ) ); /* variable size */
2126         bits_write( &bits, 16,  p_stream->i_es_id );
2127         bits_write( &bits, 1,   0x00 );     /* streamDependency */
2128         bits_write( &bits, 1,   0x00 );     /* URL Flag */
2129         bits_write( &bits, 1,   0x00 );     /* OCRStreamFlag */
2130         bits_write( &bits, 5,   0x1f );     /* streamPriority */
2131
2132         /* DecoderConfigDesciptor */
2133         bits_align( &bits );
2134         bits_write( &bits, 8,   0x04 ); /* DecoderConfigDescrTag */
2135         bits_fix_Decoder = bits;
2136         bits_write( &bits, 24,  GetDescriptorLength24b( 0 ) );
2137         if( p_stream->i_stream_type == 0x10 )
2138         {
2139             bits_write( &bits, 8, 0x20 );   /* Visual 14496-2 */
2140             bits_write( &bits, 6, 0x04 );   /* VisualStream */
2141         }
2142         else if( p_stream->i_stream_type == 0x1b )
2143         {
2144             bits_write( &bits, 8, 0x21 );   /* Visual 14496-2 */
2145             bits_write( &bits, 6, 0x04 );   /* VisualStream */
2146         }
2147         else if( p_stream->i_stream_type == 0x11 ||
2148                  p_stream->i_stream_type == 0x0f )
2149         {
2150             bits_write( &bits, 8, 0x40 );   /* Audio 14496-3 */
2151             bits_write( &bits, 6, 0x05 );   /* AudioStream */
2152         }
2153         else if( p_stream->i_stream_type == 0x12 &&
2154                  p_stream->i_codec == VLC_CODEC_SUBT )
2155         {
2156             bits_write( &bits, 8, 0x0B );   /* Text Stream */
2157             bits_write( &bits, 6, 0x04 );   /* VisualStream */
2158         }
2159         else
2160         {
2161             bits_write( &bits, 8, 0x00 );
2162             bits_write( &bits, 6, 0x00 );
2163
2164             msg_Err( p_mux, "Unsupported stream_type => broken IOD" );
2165         }
2166         bits_write( &bits, 1,   0x00 );         /* UpStream */
2167         bits_write( &bits, 1,   0x01 );         /* reserved */
2168         bits_write( &bits, 24,  1024 * 1024 );  /* bufferSizeDB */
2169         bits_write( &bits, 32,  0x7fffffff );   /* maxBitrate */
2170         bits_write( &bits, 32,  0 );            /* avgBitrate */
2171
2172         if( p_stream->i_extra > 0 )
2173         {
2174             /* DecoderSpecificInfo */
2175             bits_align( &bits );
2176             bits_write( &bits, 8,   0x05 ); /* tag */
2177             bits_write( &bits, 24, GetDescriptorLength24b(
2178                         p_stream->i_extra ) );
2179             for (int i = 0; i < p_stream->i_extra; i++ )
2180             {
2181                 bits_write( &bits, 8,
2182                     ((uint8_t*)p_stream->p_extra)[i] );
2183             }
2184         }
2185         /* fix Decoder length */
2186         bits_write( &bits_fix_Decoder, 24,
2187                     GetDescriptorLength24b( bits.i_data -
2188                     bits_fix_Decoder.i_data - 3 ) );
2189
2190         /* SLConfigDescriptor : predefined (0x01) */
2191         bits_align( &bits );
2192         bits_write( &bits, 8,   0x06 ); /* tag */
2193         bits_write( &bits, 24,  GetDescriptorLength24b( 8 ) );
2194         bits_write( &bits, 8,   0x01 );/* predefined */
2195         bits_write( &bits, 1,   0 );   /* durationFlag */
2196         bits_write( &bits, 32,  0 );   /* OCRResolution */
2197         bits_write( &bits, 8,   0 );   /* OCRLength */
2198         bits_write( &bits, 8,   0 );   /* InstantBitrateLength */
2199         bits_align( &bits );
2200
2201         /* fix ESDescr length */
2202         bits_write( &bits_fix_ESDescr, 24,
2203                     GetDescriptorLength24b( bits.i_data -
2204                     bits_fix_ESDescr.i_data - 3 ) );
2205     }
2206     bits_align( &bits );
2207     /* fix IOD length */
2208     bits_write( &bits_fix_IOD, 24,
2209                 GetDescriptorLength24b(bits.i_data - bits_fix_IOD.i_data - 3 ));
2210
2211     dvbpsi_PMTAddDescriptor(&p_sys->dvbpmt[0], 0x1d, bits.i_data, bits.p_data);
2212 }
2213
2214 static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c )
2215 {
2216     sout_mux_sys_t *p_sys = p_mux->p_sys;
2217
2218     if( p_sys->dvbpmt == NULL )
2219     {
2220         p_sys->dvbpmt = malloc( p_sys->i_num_pmt * sizeof(dvbpsi_pmt_t) );
2221         if( p_sys->dvbpmt == NULL )
2222             return;
2223     }
2224
2225     dvbpsi_sdt_t sdt;
2226     if( p_sys->b_sdt )
2227         dvbpsi_InitSDT( &sdt, p_sys->i_tsid, 1, 1, p_sys->i_netid );
2228
2229     for (unsigned i = 0; i < p_sys->i_num_pmt; i++ )
2230     {
2231         dvbpsi_InitPMT( &p_sys->dvbpmt[i],
2232                         p_sys->i_pmt_program_number[i],   /* program number */
2233                         p_sys->i_pmt_version_number,
2234                         1,      /* b_current_next */
2235                         p_sys->i_pcr_pid );
2236
2237         if( !p_sys->b_sdt )
2238             continue;
2239
2240         dvbpsi_sdt_service_t *p_service = dvbpsi_SDTAddService( &sdt,
2241             p_sys->i_pmt_program_number[i],  /* service id */
2242             0,         /* eit schedule */
2243             0,         /* eit present */
2244             4,         /* running status ("4=RUNNING") */
2245             0 );       /* free ca */
2246
2247         const char *psz_sdtprov = p_sys->sdt_descriptors[i].psz_provider;
2248         const char *psz_sdtserv = p_sys->sdt_descriptors[i].psz_service_name;
2249
2250         if( !psz_sdtprov || !psz_sdtserv )
2251             continue;
2252         size_t provlen = VLC_CLIP(strlen(psz_sdtprov), 0, 255);
2253         size_t servlen = VLC_CLIP(strlen(psz_sdtserv), 0, 255);
2254
2255         uint8_t psz_sdt_desc[3 + provlen + servlen];
2256
2257         psz_sdt_desc[0] = 0x01; /* digital television service */
2258
2259         /* service provider name length */
2260         psz_sdt_desc[1] = (char)provlen;
2261         memcpy( &psz_sdt_desc[2], psz_sdtprov, provlen );
2262
2263         /* service name length */
2264         psz_sdt_desc[ 2 + provlen ] = (char)servlen;
2265         memcpy( &psz_sdt_desc[3+provlen], psz_sdtserv, servlen );
2266
2267 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
2268         dvbpsi_sdt_service_descriptor_add( p_service, 0x48,
2269                                            (3 + provlen + servlen),
2270                                            psz_sdt_desc );
2271 #else
2272         dvbpsi_SDTServiceAddDescriptor( p_service, 0x48,
2273                 3 + provlen + servlen, psz_sdt_desc );
2274 #endif
2275     }
2276
2277     if( p_sys->i_mpeg4_streams > 0 )
2278         GetPMTmpeg4(p_mux);
2279
2280     for (int i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
2281     {
2282         ts_stream_t *p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
2283
2284         int i_pidinput = p_mux->pp_inputs[i_stream]->p_fmt->i_id;
2285         pmt_map_t *p_usepid = bsearch( &i_pidinput, p_sys->pmtmap,
2286                     p_sys->i_pmtslots, sizeof(pmt_map_t), intcompare );
2287
2288         /* If there's an error somewhere, dump it to the first pmt */
2289         unsigned prog = p_usepid ? p_usepid->i_prog : 0;
2290
2291         dvbpsi_pmt_es_t *p_es = dvbpsi_PMTAddES( &p_sys->dvbpmt[prog],
2292                     p_stream->i_stream_type, p_stream->i_pid );
2293
2294         if( p_stream->i_stream_id == 0xfa || p_stream->i_stream_id == 0xfb )
2295         {
2296             uint8_t     es_id[2];
2297
2298             /* SL descriptor */
2299             es_id[0] = (p_stream->i_es_id >> 8)&0xff;
2300             es_id[1] = (p_stream->i_es_id)&0xff;
2301             dvbpsi_PMTESAddDescriptor( p_es, 0x1f, 2, es_id );
2302         }
2303         else if( p_stream->i_stream_type == 0xa0 )
2304         {
2305             uint8_t data[512];
2306             int i_extra = __MIN( p_stream->i_extra, 502 );
2307
2308             /* private DIV3 descripor */
2309             memcpy( &data[0], &p_stream->i_bih_codec, 4 );
2310             data[4] = ( p_stream->i_bih_width >> 8 )&0xff;
2311             data[5] = ( p_stream->i_bih_width      )&0xff;
2312             data[6] = ( p_stream->i_bih_height>> 8 )&0xff;
2313             data[7] = ( p_stream->i_bih_height     )&0xff;
2314             data[8] = ( i_extra >> 8 )&0xff;
2315             data[9] = ( i_extra      )&0xff;
2316             if( i_extra > 0 )
2317             {
2318                 memcpy( &data[10], p_stream->p_extra, i_extra );
2319             }
2320
2321             /* 0xa0 is private */
2322             dvbpsi_PMTESAddDescriptor( p_es, 0xa0, i_extra + 10, data );
2323         }
2324         else if( p_stream->i_stream_type == 0x81 )
2325         {
2326             uint8_t format[4] = { 'A', 'C', '-', '3'};
2327
2328             /* "registration" descriptor : "AC-3" */
2329             dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, format );
2330         }
2331         else if( p_stream->i_codec == VLC_CODEC_DIRAC )
2332         {
2333             /* Dirac registration descriptor */
2334
2335             uint8_t data[4] = { 'd', 'r', 'a', 'c' };
2336             dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, data );
2337         }
2338         else if( p_stream->i_codec == VLC_CODEC_DTS )
2339         {
2340             /* DTS registration descriptor (ETSI TS 101 154 Annex F) */
2341
2342             /* DTS format identifier, frame size 1024 - FIXME */
2343             uint8_t data[4] = { 'D', 'T', 'S', '2' };
2344             dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, data );
2345         }
2346         else if( p_stream->i_codec == VLC_CODEC_EAC3 )
2347         {
2348             uint8_t data[1] = { 0x00 };
2349             dvbpsi_PMTESAddDescriptor( p_es, 0x7a, 1, data );
2350         }
2351         else if( p_stream->i_codec == VLC_CODEC_TELETEXT )
2352         {
2353             if( p_stream->i_extra )
2354             {
2355                 dvbpsi_PMTESAddDescriptor( p_es, 0x56,
2356                                            p_stream->i_extra,
2357                                            p_stream->p_extra );
2358             }
2359             continue;
2360         }
2361         else if( p_stream->i_codec == VLC_CODEC_DVBS )
2362         {
2363             /* DVB subtitles */
2364             if( p_stream->i_extra )
2365             {
2366                 /* pass-through from the TS demux */
2367                 dvbpsi_PMTESAddDescriptor( p_es, 0x59,
2368                                            p_stream->i_extra,
2369                                            p_stream->p_extra );
2370             }
2371             else
2372             {
2373                 /* from the dvbsub transcoder */
2374                 dvbpsi_subtitling_dr_t descr;
2375                 dvbpsi_subtitle_t sub;
2376                 dvbpsi_descriptor_t *p_descr;
2377
2378                 memcpy( sub.i_iso6392_language_code, p_stream->lang, 3 );
2379                 sub.i_subtitling_type = 0x10; /* no aspect-ratio criticality */
2380                 sub.i_composition_page_id = p_stream->i_es_id & 0xFF;
2381                 sub.i_ancillary_page_id = p_stream->i_es_id >> 16;
2382
2383                 descr.i_subtitles_number = 1;
2384                 descr.p_subtitle[0] = sub;
2385
2386                 p_descr = dvbpsi_GenSubtitlingDr( &descr, 0 );
2387                 /* Work around bug in old libdvbpsi */ p_descr->i_length = 8;
2388                 dvbpsi_PMTESAddDescriptor( p_es, p_descr->i_tag,
2389                                            p_descr->i_length, p_descr->p_data );
2390             }
2391             continue;
2392         }
2393
2394         if( p_stream->i_langs )
2395         {
2396             dvbpsi_PMTESAddDescriptor( p_es, 0x0a, 4*p_stream->i_langs,
2397                 p_stream->lang);
2398         }
2399     }
2400
2401     for (unsigned i = 0; i < p_sys->i_num_pmt; i++ )
2402     {
2403         dvbpsi_psi_section_t *sect;
2404 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
2405         sect = dvbpsi_pmt_sections_generate( p_sys->p_dvbpsi, &p_sys->dvbpmt[i] );
2406 #else
2407         sect = dvbpsi_GenPMTSections( &p_sys->dvbpmt[i] );
2408 #endif
2409         block_t *pmt = WritePSISection( sect );
2410         PEStoTS( c, pmt, &p_sys->pmt[i] );
2411         dvbpsi_DeletePSISections(sect);
2412         dvbpsi_EmptyPMT( &p_sys->dvbpmt[i] );
2413     }
2414
2415     if( p_sys->b_sdt )
2416     {
2417         dvbpsi_psi_section_t *sect;
2418 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
2419         sect = dvbpsi_sdt_sections_generate( p_sys->p_dvbpsi, &sdt );
2420 #else
2421         sect = dvbpsi_GenSDTSections( &sdt );
2422 #endif
2423         block_t *p_sdt = WritePSISection( sect );
2424         PEStoTS( c, p_sdt, &p_sys->sdt );
2425         dvbpsi_DeletePSISections( sect );
2426         dvbpsi_EmptySDT( &sdt );
2427     }
2428 }