]> git.sesse.net Git - vlc/blob - modules/mux/mpeg/ts.c
MPEG mux: fix compilation
[vlc] / modules / mux / mpeg / ts.c
1 /*****************************************************************************
2  * ts.c: MPEG-II TS Muxer
3  *****************************************************************************
4  * Copyright (C) 2001-2005 VLC authors and VideoLAN
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 it
13  * under the terms of the GNU Lesser General Public License as published by
14  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * 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 #include "tsutil.h"
49 #include "streams.h"
50
51 # include <dvbpsi/dvbpsi.h>
52 # include <dvbpsi/demux.h>
53 # include <dvbpsi/descriptor.h>
54 # include <dvbpsi/pat.h>
55 # include <dvbpsi/pmt.h>
56 # include <dvbpsi/sdt.h>
57 # include <dvbpsi/dr.h>
58 # include <dvbpsi/psi.h>
59
60 #include "dvbpsi_compat.h"
61
62 #include "tables.h"
63
64 /*
65  * TODO:
66  *  - check PCR frequency requirement
67  *  - check PAT/PMT  "        "
68  *  - check PCR/PCR "soft"
69  *  - check if "registration" descriptor : "AC-3" should be a program
70  *    descriptor or an es one. (xine want an es one)
71  *
72  *  - remove creation of PAT/PMT without dvbpsi
73  *  - ?
74  * FIXME:
75  *  - subtitle support is far from perfect. I expect some subtitles drop
76  *    if they arrive a bit late
77  *    (We cannot rely on the fact that the fifo should be full)
78  */
79
80 /*****************************************************************************
81  * Callback prototypes
82  *****************************************************************************/
83 static int ChangeKeyCallback    ( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
84 static int ActiveKeyCallback    ( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
85
86 /*****************************************************************************
87  * Module descriptor
88  *****************************************************************************/
89 static int     Open   ( vlc_object_t * );
90 static void    Close  ( vlc_object_t * );
91
92 #define VPID_TEXT N_("Video PID")
93 #define VPID_LONGTEXT N_("Assign a fixed PID to the video stream. The PCR " \
94   "PID will automatically be the video.")
95 #define APID_TEXT N_("Audio PID")
96 #define APID_LONGTEXT N_("Assign a fixed PID to the audio stream.")
97 #define SPUPID_TEXT N_("SPU PID")
98 #define SPUPID_LONGTEXT N_("Assign a fixed PID to the SPU.")
99 #define PMTPID_TEXT N_("PMT PID")
100 #define PMTPID_LONGTEXT N_("Assign a fixed PID to the PMT")
101 #define TSID_TEXT N_("TS ID")
102 #define TSID_LONGTEXT N_("Assign a fixed Transport Stream ID.")
103 #define NETID_TEXT N_("NET ID")
104 #define NETID_LONGTEXT N_("Assign a fixed Network ID (for SDT table)")
105
106 #define PMTPROG_TEXT N_("PMT Program numbers")
107 #define PMTPROG_LONGTEXT N_("Assign a program number to each PMT. This " \
108                             "requires \"Set PID to ID of ES\" to be enabled." )
109
110 #define MUXPMT_TEXT N_("Mux PMT (requires --sout-ts-es-id-pid)")
111 #define MUXPMT_LONGTEXT N_("Define the pids to add to each pmt. This " \
112                            "requires \"Set PID to ID of ES\" to be enabled." )
113
114 #define SDTDESC_TEXT N_("SDT Descriptors (requires --sout-ts-es-id-pid)")
115 #define SDTDESC_LONGTEXT N_("Defines the descriptors of each SDT. This" \
116                         "requires \"Set PID to ID of ES\" to be enabled." )
117
118 #define PID_TEXT N_("Set PID to ID of ES")
119 #define PID_LONGTEXT N_("Sets PID to the ID if the incoming ES. This is for " \
120   "use with --ts-es-id-pid, and allows having the same PIDs in the input " \
121   "and output streams.")
122
123 #define ALIGNMENT_TEXT N_("Data alignment")
124 #define ALIGNMENT_LONGTEXT N_("Enforces alignment of all access units on " \
125   "PES boundaries. Disabling this might save some bandwidth but introduce incompatibilities.")
126
127 #define SHAPING_TEXT N_("Shaping delay (ms)")
128 #define SHAPING_LONGTEXT N_("Cut the " \
129   "stream in slices of the given duration, and ensure a constant bitrate " \
130   "between the two boundaries. This avoids having huge bitrate peaks, " \
131   "especially for reference frames." )
132
133 #define KEYF_TEXT N_("Use keyframes")
134 #define KEYF_LONGTEXT N_("If enabled, and shaping is specified, " \
135   "the TS muxer will place the boundaries at the end of I pictures. In " \
136   "that case, the shaping duration given by the user is a worse case " \
137   "used when no reference frame is available. This enhances the efficiency " \
138   "of the shaping algorithm, since I frames are usually the biggest " \
139   "frames in the stream.")
140
141 #define PCR_TEXT N_("PCR interval (ms)")
142 #define PCR_LONGTEXT N_("Set at which interval " \
143   "PCRs (Program Clock Reference) will be sent (in milliseconds). " \
144   "This value should be below 100ms. (default is 70ms).")
145
146 #define BMIN_TEXT N_( "Minimum B (deprecated)")
147 #define BMIN_LONGTEXT N_( "This setting is deprecated and not used anymore" )
148
149 #define BMAX_TEXT N_( "Maximum B (deprecated)")
150 #define BMAX_LONGTEXT N_( "This setting is deprecated and not used anymore")
151
152 #define DTS_TEXT N_("DTS delay (ms)")
153 #define DTS_LONGTEXT N_("Delay the DTS (decoding time " \
154   "stamps) and PTS (presentation timestamps) of the data in the " \
155   "stream, compared to the PCRs. This allows for some buffering inside " \
156   "the client decoder.")
157
158 #define ACRYPT_TEXT N_("Crypt audio")
159 #define ACRYPT_LONGTEXT N_("Crypt audio using CSA")
160 #define VCRYPT_TEXT N_("Crypt video")
161 #define VCRYPT_LONGTEXT N_("Crypt video using CSA")
162
163 #define CK_TEXT N_("CSA Key")
164 #define CK_LONGTEXT N_("CSA encryption key. This must be a " \
165   "16 char string (8 hexadecimal bytes).")
166
167 #define CK2_TEXT N_("Second CSA Key")
168 #define CK2_LONGTEXT N_("The even CSA encryption key. This must be a " \
169   "16 char string (8 hexadecimal bytes).")
170
171 #define CU_TEXT N_("CSA Key in use")
172 #define CU_LONGTEXT N_("CSA encryption key used. It can be the odd/first/1 " \
173   "(default) or the even/second/2 one.")
174
175 #define CPKT_TEXT N_("Packet size in bytes to encrypt")
176 #define CPKT_LONGTEXT N_("Size of the TS packet to encrypt. " \
177     "The encryption routines subtract the TS-header from the value before " \
178     "encrypting." )
179
180 #define SOUT_CFG_PREFIX "sout-ts-"
181 #define MAX_PMT 64       /* Maximum number of programs. FIXME: I just chose an arbitrary number. Where is the maximum in the spec? */
182 #define MAX_PMT_PID 64       /* Maximum pids in each pmt.  FIXME: I just chose an arbitrary number. Where is the maximum in the spec? */
183 #if MAX_SDT_DESC < MAX_PMT
184   #error "MAX_SDT_DESC < MAX_PMT"
185 #endif
186
187 vlc_module_begin ()
188     set_description( N_("TS muxer (libdvbpsi)") )
189     set_shortname( "MPEG-TS")
190     set_category( CAT_SOUT )
191     set_subcategory( SUBCAT_SOUT_MUX )
192     set_capability( "sout mux", 120 )
193     add_shortcut( "ts" )
194
195     add_integer(SOUT_CFG_PREFIX "pid-video", 100, VPID_TEXT, VPID_LONGTEXT, true)
196         change_integer_range( 32, 8190 )
197     add_integer(SOUT_CFG_PREFIX "pid-audio", 200, APID_TEXT, APID_LONGTEXT, true)
198         change_integer_range( 32, 8190 )
199     add_integer(SOUT_CFG_PREFIX "pid-spu",   300, SPUPID_TEXT, SPUPID_LONGTEXT, true)
200         change_integer_range( 32, 8190 )
201     add_integer(SOUT_CFG_PREFIX "pid-pmt", 32, PMTPID_TEXT, PMTPID_LONGTEXT, true)
202         change_integer_range( 32, 8190 )
203     add_integer(SOUT_CFG_PREFIX "tsid",  0, TSID_TEXT, TSID_LONGTEXT, true)
204     add_integer(SOUT_CFG_PREFIX "netid", 0, NETID_TEXT, NETID_LONGTEXT, true)
205     add_string(SOUT_CFG_PREFIX "program-pmt", NULL, PMTPROG_TEXT, PMTPROG_LONGTEXT, true)
206     add_bool(SOUT_CFG_PREFIX "es-id-pid", false, PID_TEXT, PID_LONGTEXT, true)
207     add_string(SOUT_CFG_PREFIX "muxpmt",  NULL, MUXPMT_TEXT, MUXPMT_LONGTEXT, true)
208     add_string(SOUT_CFG_PREFIX "sdtdesc", NULL, SDTDESC_TEXT, SDTDESC_LONGTEXT, true)
209     add_bool(SOUT_CFG_PREFIX "alignment", true, ALIGNMENT_TEXT, ALIGNMENT_LONGTEXT, true)
210
211     add_integer(SOUT_CFG_PREFIX "shaping", 200, SHAPING_TEXT, SHAPING_LONGTEXT, true)
212     add_bool(SOUT_CFG_PREFIX "use-key-frames", false, KEYF_TEXT, KEYF_LONGTEXT, true)
213
214     add_integer( SOUT_CFG_PREFIX "pcr", 70, PCR_TEXT, PCR_LONGTEXT, true)
215     add_integer( SOUT_CFG_PREFIX "bmin", 0, BMIN_TEXT, BMIN_LONGTEXT, true)
216     add_integer( SOUT_CFG_PREFIX "bmax", 0, BMAX_TEXT, BMAX_LONGTEXT, true)
217     add_integer( SOUT_CFG_PREFIX "dts-delay", 400, DTS_TEXT, DTS_LONGTEXT, true)
218
219     add_bool( SOUT_CFG_PREFIX "crypt-audio", true, ACRYPT_TEXT, ACRYPT_LONGTEXT, true)
220     add_bool( SOUT_CFG_PREFIX "crypt-video", true, VCRYPT_TEXT, VCRYPT_LONGTEXT, true)
221     add_string( SOUT_CFG_PREFIX "csa-ck",  NULL, CK_TEXT,   CK_LONGTEXT,   true)
222     add_string( SOUT_CFG_PREFIX "csa2-ck", NULL, CK2_TEXT,  CK2_LONGTEXT,  true)
223     add_string( SOUT_CFG_PREFIX "csa-use", "1",  CU_TEXT,   CU_LONGTEXT,   true)
224     add_integer(SOUT_CFG_PREFIX "csa-pkt", 188,  CPKT_TEXT, CPKT_LONGTEXT, true)
225
226     set_callbacks( Open, Close )
227 vlc_module_end ()
228
229 /*****************************************************************************
230  * Local data structures
231  *****************************************************************************/
232 static const char *const ppsz_sout_options[] = {
233     "pid-video", "pid-audio", "pid-spu", "pid-pmt", "tsid",
234     "netid", "sdtdesc",
235     "es-id-pid", "shaping", "pcr", "bmin", "bmax", "use-key-frames",
236     "dts-delay", "csa-ck", "csa2-ck", "csa-use", "csa-pkt", "crypt-audio", "crypt-video",
237     "muxpmt", "program-pmt", "alignment",
238     NULL
239 };
240
241 typedef struct pmt_map_t   /* Holds the mapping between the pmt-pid/pmt table */
242 {
243     int i_pid;
244     unsigned i_prog;
245 } pmt_map_t;
246
247 typedef struct
248 {
249     int     i_depth;
250     block_t *p_first;
251     block_t **pp_last;
252 } sout_buffer_chain_t;
253
254 static inline void BufferChainInit  ( sout_buffer_chain_t *c )
255 {
256     c->i_depth = 0;
257     c->p_first = NULL;
258     c->pp_last = &c->p_first;
259 }
260
261 static inline void BufferChainAppend( sout_buffer_chain_t *c, block_t *b )
262 {
263     *c->pp_last = b;
264     c->i_depth++;
265
266     while( b->p_next )
267     {
268         b = b->p_next;
269         c->i_depth++;
270     }
271     c->pp_last = &b->p_next;
272 }
273
274 static inline block_t *BufferChainGet( sout_buffer_chain_t *c )
275 {
276     block_t *b = c->p_first;
277
278     if( b )
279     {
280         c->i_depth--;
281         c->p_first = b->p_next;
282
283         if( c->p_first == NULL )
284         {
285             c->pp_last = &c->p_first;
286         }
287
288         b->p_next = NULL;
289     }
290     return b;
291 }
292
293 static inline block_t *BufferChainPeek( sout_buffer_chain_t *c )
294 {
295     block_t *b = c->p_first;
296
297     return b;
298 }
299
300 static inline void BufferChainClean( sout_buffer_chain_t *c )
301 {
302     block_t *b;
303
304     while( ( b = BufferChainGet( c ) ) )
305     {
306         block_Release( b );
307     }
308     BufferChainInit( c );
309 }
310
311 typedef struct
312 {
313     sout_buffer_chain_t chain_pes;
314     mtime_t             i_pes_dts;
315     mtime_t             i_pes_length;
316     int                 i_pes_used;
317     bool                b_key_frame;
318
319 } pes_state_t;
320
321 typedef struct
322 {
323     ts_stream_t  ts;
324     pes_stream_t pes;
325     pes_state_t  state;
326 } sout_input_sys_t;
327
328 struct sout_mux_sys_t
329 {
330     int             i_pcr_pid;
331     sout_input_t    *p_pcr_input;
332
333     vlc_mutex_t     csa_lock;
334
335 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
336     dvbpsi_t        *p_dvbpsi;
337 #endif
338     bool            b_es_id_pid;
339     bool            b_sdt;
340     int             i_pid_video;
341     int             i_pid_audio;
342     int             i_pid_spu;
343
344     int             i_tsid;
345     unsigned        i_num_pmt;
346     int             i_pmtslots;
347     int             i_pat_version_number;
348     ts_stream_t     pat;
349
350     int             i_pmt_version_number;
351     ts_stream_t     pmt[MAX_PMT];
352     pmt_map_t       pmtmap[MAX_PMT_PID];
353     int             i_pmt_program_number[MAX_PMT];
354     bool            b_data_alignment;
355
356     sdt_psi_t       sdt;
357
358     /* for TS building */
359     int64_t         i_bitrate_min;
360     int64_t         i_bitrate_max;
361
362     int64_t         i_shaping_delay;
363     int64_t         i_pcr_delay;
364
365     int64_t         i_dts_delay;
366     mtime_t         first_dts;
367
368     bool            b_use_key_frames;
369
370     mtime_t         i_pcr;  /* last PCR emited */
371
372     csa_t           *csa;
373     int             i_csa_pkt_size;
374     bool            b_crypt_audio;
375     bool            b_crypt_video;
376 };
377
378
379 static int GetNextFreePID( sout_mux_t *p_mux, int i_pid_start )
380 {
381     sout_mux_sys_t *p_sys = p_mux->p_sys;
382
383     restart:
384     for(unsigned i=i_pid_start; i<p_sys->i_num_pmt; i++)
385     {
386         if(p_sys->pmt[i].i_pid == i_pid_start)
387         {
388             i_pid_start++;
389             goto restart;
390         }
391     }
392
393     for(int i=0; i<p_mux->i_nb_inputs; i++)
394     {
395         sout_input_sys_t *p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys;
396         if(p_stream->ts.i_pid == i_pid_start)
397         {
398             i_pid_start++;
399             goto restart;
400         }
401     }
402
403     if( i_pid_start > 8190 )
404     {
405         i_pid_start = 32;
406         goto restart;
407     }
408
409     return i_pid_start;
410 }
411
412 /* Reserve a pid and return it */
413 static int  AllocatePID( sout_mux_t *p_mux, int i_cat )
414 {
415     sout_mux_sys_t *p_sys = p_mux->p_sys;
416     int i_pid;
417     int *pi_candidate_pid = NULL;
418
419     switch( i_cat )
420     {
421     case VIDEO_ES:
422         pi_candidate_pid = &p_sys->i_pid_video;
423         break;
424
425     case AUDIO_ES:
426         pi_candidate_pid = &p_sys->i_pid_audio;
427         break;
428
429     case SPU_ES:
430     default:
431         pi_candidate_pid = &p_sys->i_pid_spu;
432         break;
433     }
434
435     *pi_candidate_pid = GetNextFreePID( p_mux, *pi_candidate_pid );
436     i_pid = (*pi_candidate_pid)++;
437
438     return i_pid;
439 }
440
441 static int pmtcompare( const void *pa, const void *pb )
442 {
443     int id1 = ((pmt_map_t *)pa)->i_pid;
444     int id2 = ((pmt_map_t *)pb)->i_pid;
445
446     return id1 - id2;
447 }
448
449 static int intcompare( const void *pa, const void *pb )
450 {
451     return *(int*)pa - *(int*)pb;
452 }
453
454 /*****************************************************************************
455  * Local prototypes
456  *****************************************************************************/
457 static int Control  ( sout_mux_t *, int, va_list );
458 static int AddStream( sout_mux_t *, sout_input_t * );
459 static int DelStream( sout_mux_t *, sout_input_t * );
460 static int Mux      ( sout_mux_t * );
461
462 static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo );
463 static block_t *Add_ADTS( block_t *, es_format_t * );
464 static void TSSchedule  ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
465                           mtime_t i_pcr_length, mtime_t i_pcr_dts );
466 static void TSDate      ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
467                           mtime_t i_pcr_length, mtime_t i_pcr_dts );
468 static void GetPAT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
469 static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
470
471 static block_t *TSNew( sout_mux_t *p_mux, sout_input_sys_t *p_stream, bool b_pcr );
472 static void TSSetPCR( block_t *p_ts, mtime_t i_dts );
473
474 static csa_t *csaSetup( vlc_object_t *p_this )
475 {
476     sout_mux_t *p_mux = (sout_mux_t*)p_this;
477     sout_mux_sys_t *p_sys = p_mux->p_sys;
478     char *csack = var_CreateGetNonEmptyStringCommand( p_mux, SOUT_CFG_PREFIX "csa-ck" );
479     if( !csack )
480         return NULL;
481
482     csa_t *csa = csa_New();
483
484     if( csa_SetCW( p_this, csa, csack, true ) )
485     {
486         free(csack);
487         csa_Delete( csa );
488         return NULL;
489     }
490
491     vlc_mutex_init( &p_sys->csa_lock );
492     p_sys->b_crypt_audio = var_GetBool( p_mux, SOUT_CFG_PREFIX "crypt-audio" );
493     p_sys->b_crypt_video = var_GetBool( p_mux, SOUT_CFG_PREFIX "crypt-video" );
494
495     char *csa2ck = var_CreateGetNonEmptyStringCommand( p_mux, SOUT_CFG_PREFIX "csa2-ck");
496     if (!csa2ck || csa_SetCW( p_this, csa, csa2ck, false ) )
497         csa_SetCW( p_this, csa, csack, false );
498     free(csa2ck);
499
500     var_Create( p_mux, SOUT_CFG_PREFIX "csa-use", VLC_VAR_STRING | VLC_VAR_DOINHERIT | VLC_VAR_ISCOMMAND );
501     var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa-use", ActiveKeyCallback, NULL );
502     var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa-ck", ChangeKeyCallback, (void *)1 );
503     var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa2-ck", ChangeKeyCallback, NULL );
504
505     vlc_value_t use_val;
506     var_Get( p_mux, SOUT_CFG_PREFIX "csa-use", &use_val );
507     if ( var_Set( p_mux, SOUT_CFG_PREFIX "csa-use", use_val ) )
508         var_SetString( p_mux, SOUT_CFG_PREFIX "csa-use", "odd" );
509     free( use_val.psz_string );
510
511     p_sys->i_csa_pkt_size = var_GetInteger( p_mux, SOUT_CFG_PREFIX "csa-pkt" );
512     if( p_sys->i_csa_pkt_size < 12 || p_sys->i_csa_pkt_size > 188 )
513     {
514         msg_Err( p_mux, "wrong packet size %d specified",
515             p_sys->i_csa_pkt_size );
516         p_sys->i_csa_pkt_size = 188;
517     }
518
519     msg_Dbg( p_mux, "encrypting %d bytes of packet", p_sys->i_csa_pkt_size );
520
521     free(csack);
522
523     return csa;
524 }
525
526 /*****************************************************************************
527  * Open:
528  *****************************************************************************/
529 static int Open( vlc_object_t *p_this )
530 {
531     sout_mux_t          *p_mux =(sout_mux_t*)p_this;
532     sout_mux_sys_t      *p_sys = NULL;
533
534     config_ChainParse( p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg );
535
536     p_sys = calloc( 1, sizeof( sout_mux_sys_t ) );
537     if( !p_sys )
538         return VLC_ENOMEM;
539     p_sys->i_num_pmt = 1;
540
541
542 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
543     p_sys->p_dvbpsi = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
544     if( !p_sys->p_dvbpsi )
545     {
546         free( p_sys );
547         return VLC_ENOMEM;
548     }
549     p_sys->p_dvbpsi->p_sys = (void *) p_mux;
550 #endif
551
552     p_sys->b_es_id_pid = var_GetBool( p_mux, SOUT_CFG_PREFIX "es-id-pid" );
553
554     /*
555        fetch string of pmts. Here's a sample: --sout-ts-muxpmt="0x451,0x200,0x28a,0x240,,0x450,0x201,0x28b,0x241,,0x452,0x202,0x28c,0x242"
556        This would mean 0x451, 0x200, 0x28a, 0x240 would fall under one pmt (program), 0x450,0x201,0x28b,0x241 would fall under another
557     */
558     char *muxpmt = var_GetNonEmptyString(p_mux, SOUT_CFG_PREFIX "muxpmt");
559     for (char *psz = muxpmt; psz; )
560     {
561         char *psz_next;
562         uint16_t i_pid = strtoul( psz, &psz_next, 0 );
563         psz = *psz_next ? &psz_next[1] : NULL;
564
565         if ( i_pid == 0 )
566         {
567             if ( ++p_sys->i_num_pmt > MAX_PMT )
568             {
569                 msg_Err( p_mux, "Number of PMTs > %d)", MAX_PMT );
570                 p_sys->i_num_pmt = MAX_PMT;
571             }
572         }
573         else
574         {
575             p_sys->pmtmap[p_sys->i_pmtslots].i_pid = i_pid;
576             p_sys->pmtmap[p_sys->i_pmtslots].i_prog = p_sys->i_num_pmt - 1;
577             if ( ++p_sys->i_pmtslots >= MAX_PMT_PID )
578             {
579                 msg_Err( p_mux, "Number of pids in PMT > %d", MAX_PMT_PID );
580                 p_sys->i_pmtslots = MAX_PMT_PID - 1;
581             }
582         }
583     }
584     /* Now sort according to pids for fast search later on */
585     qsort( (void *)p_sys->pmtmap, p_sys->i_pmtslots,
586             sizeof(pmt_map_t), pmtcompare );
587     free(muxpmt);
588
589     unsigned short subi[3];
590     vlc_rand_bytes(subi, sizeof(subi));
591     p_sys->i_pat_version_number = nrand48(subi) & 0x1f;
592
593     vlc_value_t val;
594     var_Get( p_mux, SOUT_CFG_PREFIX "tsid", &val );
595     if ( val.i_int )
596         p_sys->i_tsid = val.i_int;
597     else
598         p_sys->i_tsid = nrand48(subi) & 0xffff;
599
600     p_sys->sdt.i_netid = nrand48(subi) & 0xffff;
601
602     var_Get( p_mux, SOUT_CFG_PREFIX "netid", &val );
603     if ( val.i_int )
604         p_sys->sdt.i_netid = val.i_int;
605
606     p_sys->i_pmt_version_number = nrand48(subi) & 0x1f;
607     p_sys->sdt.ts.i_pid = 0x11;
608
609     char *sdtdesc = var_GetNonEmptyString( p_mux, SOUT_CFG_PREFIX "sdtdesc" );
610
611     /* Syntax is provider_sdt1,service_name_sdt1,provider_sdt2,service_name_sdt2... */
612     if( sdtdesc )
613     {
614         p_sys->b_sdt = true;
615
616         char *psz_sdttoken = sdtdesc;
617
618         for (int i = 0; i < MAX_SDT_DESC * 2 && psz_sdttoken; i++)
619         {
620             char *psz_end = strchr( psz_sdttoken, ',' );
621             if ( psz_end )
622                 *psz_end++ = '\0';
623
624             if (i % 2)
625                 p_sys->sdt.desc[i/2].psz_service_name = strdup(psz_sdttoken);
626             else
627                 p_sys->sdt.desc[i/2].psz_provider = strdup(psz_sdttoken);
628
629             psz_sdttoken = psz_end;
630         }
631         free(sdtdesc);
632     }
633
634     p_sys->b_data_alignment = var_GetBool( p_mux, SOUT_CFG_PREFIX "alignment" );
635
636     char *pgrpmt = var_GetNonEmptyString(p_mux, SOUT_CFG_PREFIX "program-pmt");
637     if( pgrpmt )
638     {
639         char *psz = pgrpmt;
640         char *psz_next = psz;
641
642         for (int i = 0; psz; )
643         {
644             uint16_t i_pid = strtoul( psz, &psz_next, 0 );
645             if( psz_next[0] != '\0' )
646                 psz = &psz_next[1];
647             else
648                 psz = NULL;
649
650             if( i_pid == 0 )
651             {
652                 if( i >= MAX_PMT )
653                     msg_Err( p_mux, "Number of PMTs > maximum (%d)", MAX_PMT );
654             }
655             else
656             {
657                 p_sys->i_pmt_program_number[i] = i_pid;
658                 i++;
659             }
660         }
661         free(pgrpmt);
662     }
663     else
664     {
665         /* Option not specified, use 1, 2, 3... */
666         for (unsigned i = 0; i < p_sys->i_num_pmt; i++ )
667             p_sys->i_pmt_program_number[i] = i + 1;
668     }
669
670     var_Get( p_mux, SOUT_CFG_PREFIX "pid-pmt", &val );
671     for (unsigned i = 0; i < p_sys->i_num_pmt; i++ )
672         p_sys->pmt[i].i_pid = val.i_int + i;
673
674     p_sys->i_pid_video = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-video" );
675     p_sys->i_pid_audio = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-audio" );
676     p_sys->i_pid_spu = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-spu" );
677
678     p_sys->i_pcr_pid = 0x1fff;
679
680     /* Allow to create constrained stream */
681     p_sys->i_bitrate_min = var_GetInteger( p_mux, SOUT_CFG_PREFIX "bmin" );
682
683     p_sys->i_bitrate_max = var_GetInteger( p_mux, SOUT_CFG_PREFIX "bmax" );
684
685     if( p_sys->i_bitrate_min > 0 && p_sys->i_bitrate_max > 0 &&
686         p_sys->i_bitrate_min > p_sys->i_bitrate_max )
687     {
688         msg_Err( p_mux, "incompatible minimum and maximum bitrate, "
689                  "disabling bitrate control" );
690         p_sys->i_bitrate_min = 0;
691         p_sys->i_bitrate_max = 0;
692     }
693     if( p_sys->i_bitrate_min > 0 || p_sys->i_bitrate_max > 0 )
694     {
695         msg_Err( p_mux, "bmin and bmax no more supported "
696                  "(if you need them report it)" );
697     }
698
699     var_Get( p_mux, SOUT_CFG_PREFIX "shaping", &val );
700     p_sys->i_shaping_delay = val.i_int * 1000;
701     if( p_sys->i_shaping_delay <= 0 )
702     {
703         msg_Err( p_mux,
704                  "invalid shaping (%"PRId64"ms) resetting to 200ms",
705                  p_sys->i_shaping_delay / 1000 );
706         p_sys->i_shaping_delay = 200000;
707     }
708
709     var_Get( p_mux, SOUT_CFG_PREFIX "pcr", &val );
710     p_sys->i_pcr_delay = val.i_int * 1000;
711     if( p_sys->i_pcr_delay <= 0 ||
712         p_sys->i_pcr_delay >= p_sys->i_shaping_delay )
713     {
714         msg_Err( p_mux,
715                  "invalid pcr delay (%"PRId64"ms) resetting to 70ms",
716                  p_sys->i_pcr_delay / 1000 );
717         p_sys->i_pcr_delay = 70000;
718     }
719
720     var_Get( p_mux, SOUT_CFG_PREFIX "dts-delay", &val );
721     p_sys->i_dts_delay = val.i_int * 1000;
722
723     msg_Dbg( p_mux, "shaping=%"PRId64" pcr=%"PRId64" dts_delay=%"PRId64,
724              p_sys->i_shaping_delay, p_sys->i_pcr_delay, p_sys->i_dts_delay );
725
726     p_sys->b_use_key_frames = var_GetBool( p_mux, SOUT_CFG_PREFIX "use-key-frames" );
727
728     p_mux->p_sys        = p_sys;
729
730     p_sys->csa = csaSetup(p_this);
731
732     p_mux->pf_control   = Control;
733     p_mux->pf_addstream = AddStream;
734     p_mux->pf_delstream = DelStream;
735     p_mux->pf_mux       = Mux;
736
737     return VLC_SUCCESS;
738 }
739
740 /*****************************************************************************
741  * Close:
742  *****************************************************************************/
743 static void Close( vlc_object_t * p_this )
744 {
745     sout_mux_t          *p_mux = (sout_mux_t*)p_this;
746     sout_mux_sys_t      *p_sys = p_mux->p_sys;
747
748 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
749     if( p_sys->p_dvbpsi )
750         dvbpsi_delete( p_sys->p_dvbpsi );
751 #endif
752
753     if( p_sys->csa )
754     {
755         var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa-ck", ChangeKeyCallback, NULL );
756         var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa2-ck", ChangeKeyCallback, NULL );
757         var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa-use", ActiveKeyCallback, NULL );
758         csa_Delete( p_sys->csa );
759         vlc_mutex_destroy( &p_sys->csa_lock );
760     }
761
762     for (int i = 0; i < MAX_SDT_DESC; i++ )
763     {
764         free( p_sys->sdt.desc[i].psz_service_name );
765         free( p_sys->sdt.desc[i].psz_provider );
766     }
767
768     free( p_sys );
769 }
770
771 /*****************************************************************************
772  * ChangeKeyCallback: called when changing the odd encryption key on the fly.
773  *****************************************************************************/
774 static int ChangeKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
775                            vlc_value_t oldval, vlc_value_t newval,
776                            void *p_data )
777 {
778     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
779     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
780     sout_mux_sys_t  *p_sys = p_mux->p_sys;
781     int ret;
782
783     vlc_mutex_lock(&p_sys->csa_lock);
784     ret = csa_SetCW(p_this, p_sys->csa, newval.psz_string, !!(intptr_t)p_data);
785     vlc_mutex_unlock(&p_sys->csa_lock);
786
787     return ret;
788 }
789
790 /*****************************************************************************
791  * ActiveKeyCallback: called when changing the active (in use) encryption key on the fly.
792  *****************************************************************************/
793 static int ActiveKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
794                            vlc_value_t oldval, vlc_value_t newval,
795                            void *p_data )
796 {
797     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval); VLC_UNUSED(p_data);
798     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
799     sout_mux_sys_t  *p_sys = p_mux->p_sys;
800     int             i_res, use_odd = -1;
801
802     if( !strcmp(newval.psz_string, "odd" ) ||
803         !strcmp(newval.psz_string, "first" ) ||
804         !strcmp(newval.psz_string, "1" ) )
805     {
806         use_odd = 1;
807     }
808     else if( !strcmp(newval.psz_string, "even" ) ||
809              !strcmp(newval.psz_string, "second" ) ||
810              !strcmp(newval.psz_string, "2" ) )
811     {
812         use_odd = 0;
813     }
814
815     if (use_odd < 0)
816         return VLC_EBADVAR;
817
818     vlc_mutex_lock( &p_sys->csa_lock );
819     i_res = csa_UseKey( p_this, p_sys->csa, use_odd );
820     vlc_mutex_unlock( &p_sys->csa_lock );
821
822     return i_res;
823 }
824
825 /*****************************************************************************
826  * Control:
827  *****************************************************************************/
828 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
829 {
830     VLC_UNUSED(p_mux);
831     bool *pb_bool;
832     char **ppsz;
833
834     switch( i_query )
835     {
836     case MUX_CAN_ADD_STREAM_WHILE_MUXING:
837         pb_bool = (bool*)va_arg( args, bool * );
838         *pb_bool = true;
839         return VLC_SUCCESS;
840
841     case MUX_GET_ADD_STREAM_WAIT:
842         pb_bool = (bool*)va_arg( args, bool * );
843         *pb_bool = false;
844         return VLC_SUCCESS;
845
846     case MUX_GET_MIME:
847         ppsz = (char**)va_arg( args, char ** );
848         *ppsz = strdup( "video/mp2t" );
849         return VLC_SUCCESS;
850
851     default:
852         return VLC_EGENERIC;
853     }
854 }
855
856 /* returns a pointer to a valid string, with length 0 or 3 */
857 static const char *GetIso639_2LangCode(const char *lang)
858 {
859     const iso639_lang_t *pl;
860
861     if (strlen(lang) == 2)
862     {
863         pl = GetLang_1(lang);
864     }
865     else
866     {
867         pl = GetLang_2B(lang);      /* try native code first */
868         if (!*pl->psz_iso639_2T)
869             pl = GetLang_2T(lang);  /* else fallback to english code */
870
871     }
872
873     return pl->psz_iso639_2T;   /* returns the english code */
874 }
875
876 /*****************************************************************************
877  * AddStream: called for each stream addition
878  *****************************************************************************/
879 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
880 {
881     sout_mux_sys_t      *p_sys = p_mux->p_sys;
882     sout_input_sys_t    *p_stream;
883
884     p_input->p_sys = p_stream = calloc( 1, sizeof( sout_input_sys_t ) );
885     if( !p_stream )
886         goto oom;
887
888     if ( p_sys->b_es_id_pid )
889         p_stream->ts.i_pid = p_input->p_fmt->i_id & 0x1fff;
890     else
891         p_stream->ts.i_pid = AllocatePID( p_mux, p_input->p_fmt->i_cat );
892
893     p_stream->pes.i_codec = p_input->p_fmt->i_codec;
894
895     p_stream->pes.i_stream_type = -1;
896     switch( p_input->p_fmt->i_codec )
897     {
898     /* VIDEO */
899
900     case VLC_CODEC_MPGV:
901     case VLC_CODEC_MP2V:
902     case VLC_CODEC_MP1V:
903         /* TODO: do we need to check MPEG-I/II ? */
904         p_stream->pes.i_stream_type = 0x02;
905         p_stream->pes.i_stream_id = 0xe0;
906         break;
907     case VLC_CODEC_MP4V:
908         p_stream->pes.i_stream_type = 0x10;
909         p_stream->pes.i_stream_id = 0xe0;
910         p_stream->pes.i_es_id = p_stream->ts.i_pid;
911         break;
912     case VLC_CODEC_HEVC:
913         p_stream->pes.i_stream_type = 0x24;
914         p_stream->pes.i_stream_id = 0xe0;
915         break;
916     case VLC_CODEC_H264:
917         p_stream->pes.i_stream_type = 0x1b;
918         p_stream->pes.i_stream_id = 0xe0;
919         break;
920     /* XXX dirty dirty but somebody want crapy MS-codec XXX */
921     case VLC_CODEC_H263I:
922     case VLC_CODEC_H263:
923     case VLC_CODEC_WMV3:
924     case VLC_CODEC_WMV2:
925     case VLC_CODEC_WMV1:
926     case VLC_CODEC_DIV3:
927     case VLC_CODEC_DIV2:
928     case VLC_CODEC_DIV1:
929     case VLC_CODEC_MJPG:
930         p_stream->pes.i_stream_type = 0xa0; /* private */
931         p_stream->pes.i_stream_id = 0xa0;   /* beurk */
932         p_stream->pes.i_bih_codec  = p_input->p_fmt->i_codec;
933         p_stream->pes.i_bih_width  = p_input->p_fmt->video.i_width;
934         p_stream->pes.i_bih_height = p_input->p_fmt->video.i_height;
935         break;
936     case VLC_CODEC_DIRAC:
937         /* stream_id makes use of stream_id_extension */
938         p_stream->pes.i_stream_id = (PES_EXTENDED_STREAM_ID << 8) | 0x60;
939         p_stream->pes.i_stream_type = 0xd1;
940         break;
941
942     /* AUDIO */
943
944     case VLC_CODEC_MPGA:
945     case VLC_CODEC_MP3:
946         p_stream->pes.i_stream_type =
947             p_input->p_fmt->audio.i_rate >= 32000 ? 0x03 : 0x04;
948         p_stream->pes.i_stream_id = 0xc0;
949         break;
950     case VLC_CODEC_A52:
951         p_stream->pes.i_stream_type = 0x81;
952         p_stream->pes.i_stream_id = 0xbd;
953         break;
954     case VLC_CODEC_DVD_LPCM:
955         p_stream->pes.i_stream_type = 0x83;
956         p_stream->pes.i_stream_id = 0xbd;
957         break;
958     case VLC_CODEC_OPUS:
959         if (p_input->p_fmt->audio.i_channels > 8) {
960             msg_Err(p_mux, "Too many opus channels (%d > 8)",
961                 p_input->p_fmt->audio.i_channels);
962             break;
963         }
964     case VLC_CODEC_EAC3:
965     case VLC_CODEC_DTS:
966         p_stream->pes.i_stream_type = 0x06;
967         p_stream->pes.i_stream_id = 0xbd;
968         break;
969     case VLC_CODEC_MP4A:
970         /* XXX: make that configurable in some way when LOAS
971          * is implemented for AAC in TS */
972         //p_stream->pes.i_stream_type = 0x11; /* LOAS/LATM */
973         p_stream->pes.i_stream_type = 0x0f; /* ADTS */
974         p_stream->pes.i_stream_id = 0xc0;
975         p_stream->pes.i_es_id = p_stream->ts.i_pid;
976         break;
977
978     /* TEXT */
979
980     case VLC_CODEC_SPU:
981         p_stream->pes.i_stream_type = 0x82;
982         p_stream->pes.i_stream_id = 0xbd;
983         break;
984     case VLC_CODEC_SUBT:
985         p_stream->pes.i_stream_type = 0x12;
986         p_stream->pes.i_stream_id = 0xfa;
987         p_stream->pes.i_es_id = p_stream->ts.i_pid;
988         break;
989     case VLC_CODEC_DVBS:
990         p_stream->pes.i_stream_type = 0x06;
991         p_stream->pes.i_es_id = p_input->p_fmt->subs.dvb.i_id;
992         p_stream->pes.i_stream_id = 0xbd;
993         break;
994     case VLC_CODEC_TELETEXT:
995         p_stream->pes.i_stream_type = 0x06;
996         p_stream->pes.i_stream_id = 0xbd; /* FIXME */
997         break;
998     }
999
1000     if (p_stream->pes.i_stream_type == -1)
1001     {
1002         msg_Warn( p_mux, "rejecting stream with unsupported codec %4.4s",
1003                   (char*)&p_stream->pes.i_codec );
1004         free( p_stream );
1005         return VLC_EGENERIC;
1006     }
1007
1008     p_stream->pes.i_langs = 1 + p_input->p_fmt->i_extra_languages;
1009     p_stream->pes.lang = calloc(1, p_stream->pes.i_langs * 4);
1010     if( !p_stream->pes.lang )
1011         goto oom;
1012
1013     msg_Dbg( p_mux, "adding input codec=%4.4s pid=%d",
1014              (char*)&p_stream->pes.i_codec, p_stream->ts.i_pid );
1015
1016     for (int i = 0; i < p_stream->pes.i_langs; i++) {
1017         char *lang = (i == 0)
1018             ? p_input->p_fmt->psz_language
1019             : p_input->p_fmt->p_extra_languages[i-1].psz_language;
1020
1021         if (!lang)
1022             continue;
1023
1024         const char *code = GetIso639_2LangCode(lang);
1025         if (*code)
1026         {
1027             memcpy(&p_stream->pes.lang[i*4], code, 3);
1028             p_stream->pes.lang[i*4+3] = 0x00; /* audio type: 0x00 undefined */
1029             msg_Dbg( p_mux, "    - lang=%3.3s", &p_stream->pes.lang[i*4] );
1030         }
1031     }
1032
1033     /* Create decoder specific info for subt */
1034     if( p_stream->pes.i_codec == VLC_CODEC_SUBT )
1035     {
1036         p_stream->pes.i_extra = 55;
1037         p_stream->pes.p_extra = malloc( p_stream->pes.i_extra );
1038         if (!p_stream->pes.p_extra)
1039             goto oom;
1040
1041         uint8_t *p = p_stream->pes.p_extra;
1042         p[0] = 0x10;    /* textFormat, 0x10 for 3GPP TS 26.245 */
1043         p[1] = 0x00;    /* flags: 1b: associated video info flag
1044                                 3b: reserved
1045                                 1b: duration flag
1046                                 3b: reserved */
1047         p[2] = 52;      /* remaining size */
1048
1049         p += 3;
1050
1051         p[0] = p[1] = p[2] = p[3] = 0; p+=4;    /* display flags */
1052         *p++ = 0;  /* horizontal justification (-1: left, 0 center, 1 right) */
1053         *p++ = 1;  /* vertical   justification (-1: top, 0 center, 1 bottom) */
1054
1055         p[0] = p[1] = p[2] = 0x00; p+=3;/* background rgb */
1056         *p++ = 0xff;                    /* background a */
1057
1058         p[0] = p[1] = 0; p += 2;        /* text box top */
1059         p[0] = p[1] = 0; p += 2;        /* text box left */
1060         p[0] = p[1] = 0; p += 2;        /* text box bottom */
1061         p[0] = p[1] = 0; p += 2;        /* text box right */
1062
1063         p[0] = p[1] = 0; p += 2;        /* start char */
1064         p[0] = p[1] = 0; p += 2;        /* end char */
1065         p[0] = p[1] = 0; p += 2;        /* default font id */
1066
1067         *p++ = 0;                       /* font style flags */
1068         *p++ = 12;                      /* font size */
1069
1070         p[0] = p[1] = p[2] = 0x00; p+=3;/* foreground rgb */
1071         *p++ = 0x00;                    /* foreground a */
1072
1073         p[0] = p[1] = p[2] = 0; p[3] = 22; p += 4;
1074         memcpy( p, "ftab", 4 ); p += 4;
1075         *p++ = 0; *p++ = 1;             /* entry count */
1076         p[0] = p[1] = 0; p += 2;        /* font id */
1077         *p++ = 9;                       /* font name length */
1078         memcpy( p, "Helvetica", 9 );    /* font name */
1079     }
1080     else
1081     {
1082         /* Copy extra data (VOL for MPEG-4 and extra BitMapInfoHeader for VFW */
1083         es_format_t *fmt = p_input->p_fmt;
1084         if( fmt->i_extra > 0 )
1085         {
1086             p_stream->pes.i_extra = fmt->i_extra;
1087             p_stream->pes.p_extra = malloc( fmt->i_extra );
1088             if( !p_stream->pes.p_extra )
1089                 goto oom;
1090
1091             memcpy( p_stream->pes.p_extra, fmt->p_extra, fmt->i_extra );
1092         }
1093     }
1094
1095     /* Init pes chain */
1096     BufferChainInit( &p_stream->state.chain_pes );
1097
1098     /* We only change PMT version (PAT isn't changed) */
1099     p_sys->i_pmt_version_number = ( p_sys->i_pmt_version_number + 1 )%32;
1100
1101     /* Update pcr_pid */
1102     if( p_input->p_fmt->i_cat != SPU_ES &&
1103         ( p_sys->i_pcr_pid == 0x1fff || p_input->p_fmt->i_cat == VIDEO_ES ) )
1104     {
1105         if( p_sys->p_pcr_input )
1106         {
1107             /* There was already a PCR stream, so clean context */
1108             /* FIXME */
1109         }
1110         p_sys->i_pcr_pid   = p_stream->ts.i_pid;
1111         p_sys->p_pcr_input = p_input;
1112
1113         msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
1114     }
1115
1116     return VLC_SUCCESS;
1117
1118 oom:
1119     if(p_stream)
1120     {
1121         free(p_stream->pes.lang);
1122         free(p_stream);
1123     }
1124     return VLC_ENOMEM;
1125 }
1126
1127 /*****************************************************************************
1128  * DelStream: called before a stream deletion
1129  *****************************************************************************/
1130 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
1131 {
1132     sout_mux_sys_t   *p_sys = p_mux->p_sys;
1133     sout_input_sys_t *p_stream = (sout_input_sys_t*)p_input->p_sys;
1134     int               pid;
1135
1136     msg_Dbg( p_mux, "removing input pid=%d", p_stream->ts.i_pid );
1137
1138     if( p_sys->i_pcr_pid == p_stream->ts.i_pid )
1139     {
1140         /* Find a new pcr stream (Prefer Video Stream) */
1141         p_sys->i_pcr_pid = 0x1fff;
1142         p_sys->p_pcr_input = NULL;
1143         for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1144         {
1145             if( p_mux->pp_inputs[i] == p_input )
1146             {
1147                 continue;
1148             }
1149
1150             if( p_mux->pp_inputs[i]->p_fmt->i_cat == VIDEO_ES )
1151             {
1152                 p_sys->i_pcr_pid  =
1153                     ((sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys)->ts.i_pid;
1154                 p_sys->p_pcr_input= p_mux->pp_inputs[i];
1155                 break;
1156             }
1157             else if( p_mux->pp_inputs[i]->p_fmt->i_cat != SPU_ES &&
1158                      p_sys->i_pcr_pid == 0x1fff )
1159             {
1160                 p_sys->i_pcr_pid  =
1161                     ((sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys)->ts.i_pid;
1162                 p_sys->p_pcr_input= p_mux->pp_inputs[i];
1163             }
1164         }
1165         if( p_sys->p_pcr_input )
1166         {
1167             /* Empty TS buffer */
1168             /* FIXME */
1169         }
1170         msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
1171     }
1172
1173     /* Empty all data in chain_pes */
1174     BufferChainClean( &p_stream->state.chain_pes );
1175
1176     free(p_stream->pes.lang);
1177     free( p_stream->pes.p_extra );
1178
1179     pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-video" );
1180     if ( pid > 0 && pid == p_stream->ts.i_pid )
1181     {
1182         p_sys->i_pid_video = pid;
1183         msg_Dbg( p_mux, "freeing video PID %d", pid);
1184     }
1185     pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-audio" );
1186     if ( pid > 0 && pid == p_stream->ts.i_pid )
1187     {
1188         p_sys->i_pid_audio = pid;
1189         msg_Dbg( p_mux, "freeing audio PID %d", pid);
1190     }
1191     pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-spu" );
1192     if ( pid > 0 && pid == p_stream->ts.i_pid )
1193     {
1194         p_sys->i_pid_spu = pid;
1195         msg_Dbg( p_mux, "freeing spu PID %d", pid);
1196     }
1197
1198     free( p_stream );
1199
1200     /* We only change PMT version (PAT isn't changed) */
1201     p_sys->i_pmt_version_number++;
1202     p_sys->i_pmt_version_number %= 32;
1203
1204     return VLC_SUCCESS;
1205 }
1206
1207 static void SetHeader( sout_buffer_chain_t *c,
1208                         int depth )
1209 {
1210     block_t *p_ts = BufferChainPeek( c );
1211     while( depth > 0 )
1212     {
1213         p_ts = p_ts->p_next;
1214         depth--;
1215     }
1216     p_ts->i_flags |= BLOCK_FLAG_HEADER;
1217 }
1218
1219 static block_t *Pack_Opus(block_t *p_data)
1220 {
1221     lldiv_t d = lldiv(p_data->i_buffer, 255);
1222     p_data = block_Realloc(p_data, 2 + d.quot + 1, p_data->i_buffer);
1223     if (p_data) { /* no flags */
1224         p_data->p_buffer[0] = 0x7f;
1225         p_data->p_buffer[1] = 0xe0;
1226         memset(&p_data->p_buffer[2], 0xff, d.quot);
1227         p_data->p_buffer[2+d.quot] = d.rem;
1228     }
1229
1230     return p_data;
1231 }
1232
1233 /* returns true if needs more data */
1234 static bool MuxStreams(sout_mux_t *p_mux )
1235 {
1236     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1237     sout_input_sys_t *p_pcr_stream = (sout_input_sys_t*)p_sys->p_pcr_input->p_sys;
1238
1239     sout_buffer_chain_t chain_ts;
1240     mtime_t i_shaping_delay = p_pcr_stream->state.b_key_frame
1241         ? p_pcr_stream->state.i_pes_length
1242         : p_sys->i_shaping_delay;
1243
1244     bool b_ok = true;
1245
1246     /* Accumulate enough data in the pcr stream (>i_shaping_delay) */
1247     /* Accumulate enough data in all other stream ( >= length of pcr)*/
1248     for (int i = -1; !b_ok || i < p_mux->i_nb_inputs; i++ )
1249     {
1250         if (i == p_mux->i_nb_inputs)
1251         {
1252             /* get enough PES packet for all input */
1253             b_ok = true;
1254             i = -1;
1255         }
1256         sout_input_t *p_input;
1257
1258         if( i == -1 )
1259             p_input = p_sys->p_pcr_input;
1260         else if( p_mux->pp_inputs[i]->p_sys == p_pcr_stream )
1261             continue;
1262         else
1263             p_input = p_mux->pp_inputs[i];
1264         sout_input_sys_t *p_stream = (sout_input_sys_t*)p_input->p_sys;
1265
1266         if( ( p_stream != p_pcr_stream ||
1267               p_stream->state.i_pes_length >= i_shaping_delay ) &&
1268             p_stream->state.i_pes_dts + p_stream->state.i_pes_length >=
1269             p_pcr_stream->state.i_pes_dts + p_pcr_stream->state.i_pes_length )
1270             continue;
1271
1272         /* Need more data */
1273         if( block_FifoCount( p_input->p_fifo ) <= 1 )
1274         {
1275             if( ( p_input->p_fmt->i_cat == AUDIO_ES ) ||
1276                 ( p_input->p_fmt->i_cat == VIDEO_ES ) )
1277             {
1278                 /* We need more data */
1279                 return true;
1280             }
1281             else if( block_FifoCount( p_input->p_fifo ) <= 0 )
1282             {
1283                 /* spu, only one packet is needed */
1284                 continue;
1285             }
1286             else if( p_input->p_fmt->i_cat == SPU_ES )
1287             {
1288                 /* Don't mux the SPU yet if it is too early */
1289                 block_t *p_spu = block_FifoShow( p_input->p_fifo );
1290
1291                 int64_t i_spu_delay = p_spu->i_dts - p_pcr_stream->state.i_pes_dts;
1292                 if( ( i_spu_delay > i_shaping_delay ) &&
1293                     ( i_spu_delay < 100 * CLOCK_FREQ ) )
1294                     continue;
1295
1296                 if ( ( i_spu_delay >= 100 * CLOCK_FREQ ) ||
1297                      ( i_spu_delay < CLOCK_FREQ / 100 ) )
1298                 {
1299                     BufferChainClean( &p_stream->state.chain_pes );
1300                     p_stream->state.i_pes_dts = 0;
1301                     p_stream->state.i_pes_used = 0;
1302                     p_stream->state.i_pes_length = 0;
1303                     continue;
1304                 }
1305             }
1306         }
1307         b_ok = false;
1308
1309         block_t *p_data;
1310         if( p_stream == p_pcr_stream || p_sys->b_data_alignment
1311              || ((p_input->p_fmt->i_codec != VLC_CODEC_MPGA ) &&
1312                  (p_input->p_fmt->i_codec != VLC_CODEC_MP3) ) )
1313         {
1314             p_data = block_FifoGet( p_input->p_fifo );
1315             if (p_data->i_pts <= VLC_TS_INVALID)
1316                 p_data->i_pts = p_data->i_dts;
1317
1318             if( p_input->p_fmt->i_codec == VLC_CODEC_MP4A )
1319                 p_data = Add_ADTS( p_data, p_input->p_fmt );
1320             else if( p_input->p_fmt->i_codec == VLC_CODEC_OPUS )
1321                 p_data = Pack_Opus( p_data );
1322         }
1323         else
1324             p_data = FixPES( p_mux, p_input->p_fifo );
1325
1326         if( block_FifoCount( p_input->p_fifo ) > 0 &&
1327             p_input->p_fmt->i_cat != SPU_ES )
1328         {
1329             block_t *p_next = block_FifoShow( p_input->p_fifo );
1330             p_data->i_length = p_next->i_dts - p_data->i_dts;
1331         }
1332         else if( p_input->p_fmt->i_codec !=
1333                    VLC_CODEC_SUBT )
1334             p_data->i_length = 1000;
1335
1336         if (p_sys->first_dts == 0)
1337             p_sys->first_dts = p_data->i_dts;
1338
1339         if( ( p_pcr_stream->state.i_pes_dts > 0 &&
1340               p_data->i_dts - 10 * CLOCK_FREQ > p_pcr_stream->state.i_pes_dts +
1341               p_pcr_stream->state.i_pes_length ) ||
1342             p_data->i_dts < p_stream->state.i_pes_dts ||
1343             ( p_stream->state.i_pes_dts > 0 &&
1344               p_input->p_fmt->i_cat != SPU_ES &&
1345               p_data->i_dts - 10 * CLOCK_FREQ > p_stream->state.i_pes_dts +
1346               p_stream->state.i_pes_length ) )
1347         {
1348             msg_Warn( p_mux, "packet with too strange dts "
1349                       "(dts=%"PRId64",old=%"PRId64",pcr=%"PRId64")",
1350                       p_data->i_dts, p_stream->state.i_pes_dts,
1351                       p_pcr_stream->state.i_pes_dts );
1352             block_Release( p_data );
1353
1354             BufferChainClean( &p_stream->state.chain_pes );
1355             p_stream->state.i_pes_dts = 0;
1356             p_stream->state.i_pes_used = 0;
1357             p_stream->state.i_pes_length = 0;
1358
1359             if( p_input->p_fmt->i_cat != SPU_ES )
1360             {
1361                 BufferChainClean( &p_pcr_stream->state.chain_pes );
1362                 p_pcr_stream->state.i_pes_dts = 0;
1363                 p_pcr_stream->state.i_pes_used = 0;
1364                 p_pcr_stream->state.i_pes_length = 0;
1365             }
1366
1367             continue;
1368         }
1369
1370         int i_header_size = 0;
1371         int i_max_pes_size = 0;
1372         int b_data_alignment = 0;
1373         if( p_input->p_fmt->i_cat == SPU_ES ) switch (p_input->p_fmt->i_codec)
1374         {
1375         case VLC_CODEC_SUBT:
1376             /* Prepend header */
1377             p_data = block_Realloc( p_data, 2, p_data->i_buffer );
1378             p_data->p_buffer[0] = ( (p_data->i_buffer - 2) >> 8) & 0xff;
1379             p_data->p_buffer[1] = ( (p_data->i_buffer - 2)     ) & 0xff;
1380
1381             /* remove trailling \0 if any */
1382             if( p_data->i_buffer > 2 && !p_data->p_buffer[p_data->i_buffer-1] )
1383                 p_data->i_buffer--;
1384
1385             /* Append a empty sub (sub text only) */
1386             if( p_data->i_length > 0 &&
1387                 ( p_data->i_buffer != 1 || *p_data->p_buffer != ' ' ) )
1388             {
1389                 block_t *p_spu = block_Alloc( 3 );
1390
1391                 p_spu->i_dts = p_data->i_dts + p_data->i_length;
1392                 p_spu->i_pts = p_spu->i_dts;
1393                 p_spu->i_length = 1000;
1394
1395                 p_spu->p_buffer[0] = 0;
1396                 p_spu->p_buffer[1] = 1;
1397                 p_spu->p_buffer[2] = ' ';
1398
1399                 EStoPES( &p_spu, p_input->p_fmt,
1400                              p_stream->pes.i_stream_id, 1, 0, 0, 0, p_sys->first_dts );
1401                 p_data->p_next = p_spu;
1402             }
1403             break;
1404
1405         case VLC_CODEC_TELETEXT:
1406             /* EN 300 472 */
1407             i_header_size = 0x24;
1408             b_data_alignment = 1;
1409             break;
1410
1411         case VLC_CODEC_DVBS:
1412             /* EN 300 743 */
1413             b_data_alignment = 1;
1414             break;
1415         }
1416         else if( p_data->i_length < 0 || p_data->i_length > 2000000 )
1417         {
1418             /* FIXME choose a better value, but anyway we
1419              * should never have to do that */
1420             p_data->i_length = 1000;
1421         }
1422
1423         p_stream->state.i_pes_length += p_data->i_length;
1424         if( p_stream->state.i_pes_dts == 0 )
1425         {
1426             p_stream->state.i_pes_dts = p_data->i_dts;
1427         }
1428
1429         /* Convert to pes */
1430         if( p_stream->pes.i_stream_id == 0xa0 && p_data->i_pts <= 0 )
1431         {
1432             /* XXX yes I know, it's awful, but it's needed,
1433              * so don't remove it ... */
1434             p_data->i_pts = p_data->i_dts;
1435         }
1436
1437         if( p_input->p_fmt->i_codec == VLC_CODEC_DIRAC )
1438         {
1439             b_data_alignment = 1;
1440             /* dirac pes packets should be unbounded in
1441              * length, specify a suitibly large max size */
1442             i_max_pes_size = INT_MAX;
1443         }
1444
1445         EStoPES ( &p_data, p_input->p_fmt, p_stream->pes.i_stream_id,
1446                        1, b_data_alignment, i_header_size,
1447                        i_max_pes_size, p_sys->first_dts );
1448
1449         BufferChainAppend( &p_stream->state.chain_pes, p_data );
1450
1451         if( p_sys->b_use_key_frames && p_stream == p_pcr_stream
1452             && (p_data->i_flags & BLOCK_FLAG_TYPE_I)
1453             && !(p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME)
1454             && (p_stream->state.i_pes_length > 400000) )
1455         {
1456             i_shaping_delay = p_stream->state.i_pes_length;
1457             p_stream->state.b_key_frame = 1;
1458         }
1459     }
1460
1461     /* save */
1462     const mtime_t i_pcr_length = p_pcr_stream->state.i_pes_length;
1463     p_pcr_stream->state.b_key_frame = 0;
1464
1465     /* msg_Dbg( p_mux, "starting muxing %lldms", i_pcr_length / 1000 ); */
1466     /* 2: calculate non accurate total size of muxed ts */
1467     int i_packet_count = 0;
1468     for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1469     {
1470         sout_input_sys_t *p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys;
1471
1472         /* False for pcr stream but it will be enough to do PCR algo */
1473         for (block_t *p_pes = p_stream->state.chain_pes.p_first; p_pes != NULL;
1474              p_pes = p_pes->p_next )
1475         {
1476             int i_size = p_pes->i_buffer;
1477             if( p_pes->i_dts + p_pes->i_length >
1478                 p_pcr_stream->state.i_pes_dts + p_pcr_stream->state.i_pes_length )
1479             {
1480                 mtime_t i_frag = p_pcr_stream->state.i_pes_dts +
1481                     p_pcr_stream->state.i_pes_length - p_pes->i_dts;
1482                 if( i_frag < 0 )
1483                 {
1484                     /* Next stream */
1485                     break;
1486                 }
1487                 i_size = p_pes->i_buffer * i_frag / p_pes->i_length;
1488             }
1489             i_packet_count += ( i_size + 183 ) / 184;
1490         }
1491     }
1492     /* add overhead for PCR (not really exact) */
1493     i_packet_count += (8 * i_pcr_length / p_sys->i_pcr_delay + 175) / 176;
1494
1495     /* 3: mux PES into TS */
1496     BufferChainInit( &chain_ts );
1497     /* append PAT/PMT  -> FIXME with big pcr delay it won't have enough pat/pmt */
1498     bool pat_was_previous = true; //This is to prevent unnecessary double PAT/PMT insertions
1499     GetPAT( p_mux, &chain_ts );
1500     GetPMT( p_mux, &chain_ts );
1501     int i_packet_pos = 0;
1502     i_packet_count += chain_ts.i_depth;
1503     /* msg_Dbg( p_mux, "estimated pck=%d", i_packet_count ); */
1504
1505     const mtime_t i_pcr_dts = p_pcr_stream->state.i_pes_dts;
1506     for (;;)
1507     {
1508         int          i_stream = -1;
1509         mtime_t      i_dts = 0;
1510         sout_input_sys_t *p_stream;
1511
1512         /* Select stream (lowest dts) */
1513         for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1514         {
1515             p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys;
1516
1517             if( p_stream->state.i_pes_dts == 0 )
1518             {
1519                 continue;
1520             }
1521
1522             if( i_stream == -1 || p_stream->state.i_pes_dts < i_dts )
1523             {
1524                 i_stream = i;
1525                 i_dts = p_stream->state.i_pes_dts;
1526             }
1527         }
1528         if( i_stream == -1 || i_dts > i_pcr_dts + i_pcr_length )
1529         {
1530             break;
1531         }
1532         p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i_stream]->p_sys;
1533         sout_input_t *p_input = p_mux->pp_inputs[i_stream];
1534
1535         /* do we need to issue pcr */
1536         bool b_pcr = false;
1537         if( p_stream == p_pcr_stream &&
1538             i_pcr_dts + i_packet_pos * i_pcr_length / i_packet_count >=
1539             p_sys->i_pcr + p_sys->i_pcr_delay )
1540         {
1541             b_pcr = true;
1542             p_sys->i_pcr = i_pcr_dts + i_packet_pos *
1543                 i_pcr_length / i_packet_count;
1544         }
1545
1546         /* Build the TS packet */
1547         block_t *p_ts = TSNew( p_mux, p_stream, b_pcr );
1548         if( p_sys->csa != NULL &&
1549              (p_input->p_fmt->i_cat != AUDIO_ES || p_sys->b_crypt_audio) &&
1550              (p_input->p_fmt->i_cat != VIDEO_ES || p_sys->b_crypt_video) )
1551         {
1552             p_ts->i_flags |= BLOCK_FLAG_SCRAMBLED;
1553         }
1554         i_packet_pos++;
1555
1556         /* Write PAT/PMT before every keyframe if use-key-frames is enabled,
1557          * this helps to do segmenting with livehttp-output so it can cut segment
1558          * and start new one with pat,pmt,keyframe*/
1559         if( ( p_sys->b_use_key_frames ) && ( p_ts->i_flags & BLOCK_FLAG_TYPE_I ) )
1560         {
1561             if( likely( !pat_was_previous ) )
1562             {
1563                 int startcount = chain_ts.i_depth;
1564                 GetPAT( p_mux, &chain_ts );
1565                 GetPMT( p_mux, &chain_ts );
1566                 SetHeader( &chain_ts, startcount );
1567                 i_packet_count += (chain_ts.i_depth - startcount );
1568             } else {
1569                 SetHeader( &chain_ts, 0); //We just inserted pat/pmt,so just flag it instead of adding new one
1570             }
1571         }
1572         pat_was_previous = false;
1573
1574         /* */
1575         BufferChainAppend( &chain_ts, p_ts );
1576     }
1577
1578     /* 4: date and send */
1579     TSSchedule( p_mux, &chain_ts, i_pcr_length, i_pcr_dts );
1580     return false;
1581 }
1582
1583 /*****************************************************************************
1584  * Mux: Call each time there is new data for at least one stream
1585  *****************************************************************************
1586  *
1587  *****************************************************************************/
1588 static int Mux( sout_mux_t *p_mux )
1589 {
1590     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1591
1592     if( p_sys->i_pcr_pid == 0x1fff )
1593     {
1594         for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1595         {
1596             block_FifoEmpty( p_mux->pp_inputs[i]->p_fifo );
1597         }
1598         msg_Dbg( p_mux, "waiting for PCR streams" );
1599         return VLC_SUCCESS;
1600     }
1601
1602     while (!MuxStreams(p_mux))
1603         ;
1604     return VLC_SUCCESS;
1605 }
1606
1607 #define STD_PES_PAYLOAD 170
1608 static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo )
1609 {
1610     VLC_UNUSED(p_mux);
1611     block_t *p_data;
1612     size_t i_size;
1613
1614     p_data = block_FifoShow( p_fifo );
1615     i_size = p_data->i_buffer;
1616
1617     if( i_size == STD_PES_PAYLOAD )
1618     {
1619         return block_FifoGet( p_fifo );
1620     }
1621     else if( i_size > STD_PES_PAYLOAD )
1622     {
1623         block_t *p_new = block_Alloc( STD_PES_PAYLOAD );
1624         memcpy( p_new->p_buffer, p_data->p_buffer, STD_PES_PAYLOAD );
1625         p_new->i_pts = p_data->i_pts;
1626         p_new->i_dts = p_data->i_dts;
1627         p_new->i_length = p_data->i_length * STD_PES_PAYLOAD
1628                             / p_data->i_buffer;
1629         p_data->i_buffer -= STD_PES_PAYLOAD;
1630         p_data->p_buffer += STD_PES_PAYLOAD;
1631         p_data->i_pts += p_new->i_length;
1632         p_data->i_dts += p_new->i_length;
1633         p_data->i_length -= p_new->i_length;
1634         p_data->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1635         return p_new;
1636     }
1637     else
1638     {
1639         block_t *p_next;
1640         int i_copy;
1641
1642         p_data = block_FifoGet( p_fifo );
1643         p_data = block_Realloc( p_data, 0, STD_PES_PAYLOAD );
1644         p_next = block_FifoShow( p_fifo );
1645         if ( p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME )
1646         {
1647             p_data->i_flags &= ~BLOCK_FLAG_NO_KEYFRAME;
1648             p_data->i_pts = p_next->i_pts;
1649             p_data->i_dts = p_next->i_dts;
1650         }
1651         i_copy = __MIN( STD_PES_PAYLOAD - i_size, p_next->i_buffer );
1652
1653         memcpy( &p_data->p_buffer[i_size], p_next->p_buffer, i_copy );
1654         p_next->i_pts += p_next->i_length * i_copy / p_next->i_buffer;
1655         p_next->i_dts += p_next->i_length * i_copy / p_next->i_buffer;
1656         p_next->i_length -= p_next->i_length * i_copy / p_next->i_buffer;
1657         p_next->i_buffer -= i_copy;
1658         p_next->p_buffer += i_copy;
1659         p_next->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1660
1661         if( !p_next->i_buffer )
1662         {
1663             p_next = block_FifoGet( p_fifo );
1664             block_Release( p_next );
1665         }
1666         return p_data;
1667     }
1668 }
1669
1670 static block_t *Add_ADTS( block_t *p_data, es_format_t *p_fmt )
1671 {
1672 #define ADTS_HEADER_SIZE 7 /* CRC needs 2 more bytes */
1673
1674     uint8_t *p_extra = p_fmt->p_extra;
1675
1676     if( !p_data || p_fmt->i_extra < 2 || !p_extra )
1677         return p_data; /* no data to construct the headers */
1678
1679     size_t frame_length = p_data->i_buffer + ADTS_HEADER_SIZE;
1680     int i_index = ( (p_extra[0] << 1) | (p_extra[1] >> 7) ) & 0x0f;
1681     int i_profile = (p_extra[0] >> 3) - 1; /* i_profile < 4 */
1682
1683     if( i_index == 0x0f && p_fmt->i_extra < 5 )
1684         return p_data; /* not enough data */
1685
1686     int i_channels = (p_extra[i_index == 0x0f ? 4 : 1] >> 3) & 0x0f;
1687
1688     block_t *p_new_block = block_Realloc( p_data, ADTS_HEADER_SIZE,
1689                                             p_data->i_buffer );
1690     uint8_t *p_buffer = p_new_block->p_buffer;
1691
1692     /* fixed header */
1693     p_buffer[0] = 0xff;
1694     p_buffer[1] = 0xf1; /* 0xf0 | 0x00 | 0x00 | 0x01 */
1695     p_buffer[2] = (i_profile << 6) | ((i_index & 0x0f) << 2) | ((i_channels >> 2) & 0x01) ;
1696     p_buffer[3] = (i_channels << 6) | ((frame_length >> 11) & 0x03);
1697
1698     /* variable header (starts at last 2 bits of 4th byte) */
1699
1700     int i_fullness = 0x7ff; /* 0x7ff means VBR */
1701     /* XXX: We should check if it's CBR or VBR, but no known implementation
1702      * do that, and it's a pain to calculate this field */
1703
1704     p_buffer[4] = frame_length >> 3;
1705     p_buffer[5] = ((frame_length & 0x07) << 5) | ((i_fullness >> 6) & 0x1f);
1706     p_buffer[6] = ((i_fullness & 0x3f) << 2) /* | 0xfc */;
1707
1708     return p_new_block;
1709 }
1710
1711 static void TSSchedule( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1712                         mtime_t i_pcr_length, mtime_t i_pcr_dts )
1713 {
1714     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1715     sout_buffer_chain_t new_chain;
1716     int i_packet_count = p_chain_ts->i_depth;
1717
1718     BufferChainInit( &new_chain );
1719
1720     if ( i_pcr_length <= 0 )
1721     {
1722         i_pcr_length = i_packet_count;
1723     }
1724
1725     for (int i = 0; i < i_packet_count; i++ )
1726     {
1727         block_t *p_ts = BufferChainGet( p_chain_ts );
1728         mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1729
1730         BufferChainAppend( &new_chain, p_ts );
1731
1732         if (!p_ts->i_dts || p_ts->i_dts + p_sys->i_dts_delay * 2/3 >= i_new_dts)
1733             continue;
1734
1735         mtime_t i_max_diff = i_new_dts - p_ts->i_dts;
1736         mtime_t i_cut_dts = p_ts->i_dts;
1737
1738         p_ts = BufferChainPeek( p_chain_ts );
1739         i++;
1740         i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1741         while ( p_ts != NULL && i_new_dts - p_ts->i_dts >= i_max_diff )
1742         {
1743             p_ts = BufferChainGet( p_chain_ts );
1744             i_max_diff = i_new_dts - p_ts->i_dts;
1745             i_cut_dts = p_ts->i_dts;
1746             BufferChainAppend( &new_chain, p_ts );
1747
1748             p_ts = BufferChainPeek( p_chain_ts );
1749             i++;
1750             i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1751         }
1752         msg_Dbg( p_mux, "adjusting rate at %"PRId64"/%"PRId64" (%d/%d)",
1753                  i_cut_dts - i_pcr_dts, i_pcr_length, new_chain.i_depth,
1754                  p_chain_ts->i_depth );
1755         if ( new_chain.i_depth )
1756             TSDate( p_mux, &new_chain, i_cut_dts - i_pcr_dts, i_pcr_dts );
1757         if ( p_chain_ts->i_depth )
1758             TSSchedule( p_mux, p_chain_ts, i_pcr_dts + i_pcr_length - i_cut_dts,
1759                         i_cut_dts );
1760         return;
1761     }
1762
1763     if ( new_chain.i_depth )
1764         TSDate( p_mux, &new_chain, i_pcr_length, i_pcr_dts );
1765 }
1766
1767 static void TSDate( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1768                     mtime_t i_pcr_length, mtime_t i_pcr_dts )
1769 {
1770     sout_mux_sys_t  *p_sys = p_mux->p_sys;
1771     int i_packet_count = p_chain_ts->i_depth;
1772
1773     if ( i_pcr_length / 1000 > 0 )
1774     {
1775         int i_bitrate = ((uint64_t)i_packet_count * 188 * 8000)
1776                           / (uint64_t)(i_pcr_length / 1000);
1777         if ( p_sys->i_bitrate_max && p_sys->i_bitrate_max < i_bitrate )
1778         {
1779             msg_Warn( p_mux, "max bitrate exceeded at %"PRId64
1780                       " (%d bi/s for %d pkt in %"PRId64" us)",
1781                       i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
1782                       i_bitrate, i_packet_count, i_pcr_length);
1783         }
1784     }
1785     else
1786     {
1787         /* This shouldn't happen, but happens in some rare heavy load
1788          * and packet losses conditions. */
1789         i_pcr_length = i_packet_count;
1790     }
1791
1792     /* msg_Dbg( p_mux, "real pck=%d", i_packet_count ); */
1793     for (int i = 0; i < i_packet_count; i++ )
1794     {
1795         block_t *p_ts = BufferChainGet( p_chain_ts );
1796         mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1797
1798         p_ts->i_dts    = i_new_dts;
1799         p_ts->i_length = i_pcr_length / i_packet_count;
1800
1801         if( p_ts->i_flags & BLOCK_FLAG_CLOCK )
1802         {
1803             /* msg_Dbg( p_mux, "pcr=%lld ms", p_ts->i_dts / 1000 ); */
1804             TSSetPCR( p_ts, p_ts->i_dts - p_sys->i_dts_delay - p_sys->first_dts );
1805         }
1806         if( p_ts->i_flags & BLOCK_FLAG_SCRAMBLED )
1807         {
1808             vlc_mutex_lock( &p_sys->csa_lock );
1809             csa_Encrypt( p_sys->csa, p_ts->p_buffer, p_sys->i_csa_pkt_size );
1810             vlc_mutex_unlock( &p_sys->csa_lock );
1811         }
1812
1813         /* latency */
1814         p_ts->i_dts += p_sys->i_shaping_delay * 3 / 2;
1815
1816         sout_AccessOutWrite( p_mux->p_access, p_ts );
1817     }
1818 }
1819
1820 static block_t *TSNew( sout_mux_t *p_mux, sout_input_sys_t *p_stream,
1821                        bool b_pcr )
1822 {
1823     VLC_UNUSED(p_mux);
1824     block_t *p_pes = p_stream->state.chain_pes.p_first;
1825
1826     bool b_new_pes = false;
1827     bool b_adaptation_field = false;
1828
1829     int i_payload_max = 184 - ( b_pcr ? 8 : 0 );
1830
1831     if( p_stream->state.i_pes_used <= 0 )
1832     {
1833         b_new_pes = true;
1834     }
1835     int i_payload = __MIN( (int)p_pes->i_buffer - p_stream->state.i_pes_used,
1836                        i_payload_max );
1837
1838     if( b_pcr || i_payload < i_payload_max )
1839     {
1840         b_adaptation_field = true;
1841     }
1842
1843     block_t *p_ts = block_Alloc( 188 );
1844
1845     if (b_new_pes && !(p_pes->i_flags & BLOCK_FLAG_NO_KEYFRAME) && p_pes->i_flags & BLOCK_FLAG_TYPE_I)
1846     {
1847         p_ts->i_flags |= BLOCK_FLAG_TYPE_I;
1848     }
1849
1850     p_ts->i_dts = p_pes->i_dts;
1851
1852     p_ts->p_buffer[0] = 0x47;
1853     p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 ) |
1854         ( ( p_stream->ts.i_pid >> 8 )&0x1f );
1855     p_ts->p_buffer[2] = p_stream->ts.i_pid & 0xff;
1856     p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 ) |
1857         p_stream->ts.i_continuity_counter;
1858
1859     p_stream->ts.i_continuity_counter = (p_stream->ts.i_continuity_counter+1)%16;
1860     p_stream->ts.b_discontinuity = p_pes->i_flags & BLOCK_FLAG_DISCONTINUITY;
1861
1862     if( b_adaptation_field )
1863     {
1864         int i_stuffing = i_payload_max - i_payload;
1865         if( b_pcr )
1866         {
1867             p_ts->i_flags |= BLOCK_FLAG_CLOCK;
1868
1869             p_ts->p_buffer[4] = 7 + i_stuffing;
1870             p_ts->p_buffer[5] = 1 << 4; /* PCR_flag */
1871             if( p_stream->ts.b_discontinuity )
1872             {
1873                 p_ts->p_buffer[5] |= 0x80; /* flag TS dicontinuity */
1874                 p_stream->ts.b_discontinuity = false;
1875             }
1876             memset(&p_ts->p_buffer[12], 0xff, i_stuffing);
1877         }
1878         else
1879         {
1880             p_ts->p_buffer[4] = --i_stuffing;
1881             if( i_stuffing-- )
1882             {
1883                 p_ts->p_buffer[5] = 0;
1884                 memset(&p_ts->p_buffer[6], 0xff, i_stuffing);
1885             }
1886         }
1887     }
1888
1889     /* copy payload */
1890     memcpy( &p_ts->p_buffer[188 - i_payload],
1891             &p_pes->p_buffer[p_stream->state.i_pes_used], i_payload );
1892
1893     p_stream->state.i_pes_used += i_payload;
1894     p_stream->state.i_pes_dts = p_pes->i_dts + p_pes->i_length *
1895         p_stream->state.i_pes_used / p_pes->i_buffer;
1896     p_stream->state.i_pes_length -= p_pes->i_length * i_payload / p_pes->i_buffer;
1897
1898     if( p_stream->state.i_pes_used >= (int)p_pes->i_buffer )
1899     {
1900         block_Release(BufferChainGet( &p_stream->state.chain_pes ));
1901
1902         p_pes = p_stream->state.chain_pes.p_first;
1903         p_stream->state.i_pes_length = 0;
1904         if( p_pes )
1905         {
1906             p_stream->state.i_pes_dts = p_pes->i_dts;
1907             while( p_pes )
1908             {
1909                 p_stream->state.i_pes_length += p_pes->i_length;
1910                 p_pes = p_pes->p_next;
1911             }
1912         }
1913         else
1914         {
1915             p_stream->state.i_pes_dts = 0;
1916         }
1917         p_stream->state.i_pes_used = 0;
1918     }
1919
1920     return p_ts;
1921 }
1922
1923 static void TSSetPCR( block_t *p_ts, mtime_t i_dts )
1924 {
1925     mtime_t i_pcr = 9 * i_dts / 100;
1926
1927     p_ts->p_buffer[6]  = ( i_pcr >> 25 )&0xff;
1928     p_ts->p_buffer[7]  = ( i_pcr >> 17 )&0xff;
1929     p_ts->p_buffer[8]  = ( i_pcr >> 9  )&0xff;
1930     p_ts->p_buffer[9]  = ( i_pcr >> 1  )&0xff;
1931     p_ts->p_buffer[10] = ( i_pcr << 7  )&0x80;
1932     p_ts->p_buffer[10] |= 0x7e;
1933     p_ts->p_buffer[11] = 0; /* we don't set PCR extension */
1934 }
1935
1936 void GetPAT( sout_mux_t *p_mux, sout_buffer_chain_t *c )
1937 {
1938     sout_mux_sys_t       *p_sys = p_mux->p_sys;
1939
1940     BuildPAT( DVBPSI_HANDLE_PARAM(p_sys->p_dvbpsi)
1941               c, (PEStoTSCallback)BufferChainAppend,
1942               p_sys->i_tsid, p_sys->i_pat_version_number,
1943               &p_sys->pat,
1944               p_sys->i_num_pmt, p_sys->pmt, p_sys->i_pmt_program_number );
1945 }
1946
1947 static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c )
1948 {
1949     sout_mux_sys_t *p_sys = p_mux->p_sys;
1950     pes_mapped_stream_t mappeds[p_mux->i_nb_inputs];
1951
1952     for (int i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
1953     {
1954         sout_input_t *p_input = p_mux->pp_inputs[i_stream];
1955         sout_input_sys_t *p_stream = (sout_input_sys_t*)p_input->p_sys;
1956
1957         int i_pidinput = p_input->p_fmt->i_id;
1958         pmt_map_t *p_usepid = bsearch( &i_pidinput, p_sys->pmtmap,
1959                                        p_sys->i_pmtslots, sizeof(pmt_map_t), intcompare );
1960
1961         /* If there's an error somewhere, dump it to the first pmt */
1962         mappeds[i_stream].i_mapped_prog = p_usepid ? p_usepid->i_prog : 0;
1963         mappeds[i_stream].fmt = p_input->p_fmt;
1964         mappeds[i_stream].pes = &p_stream->pes;
1965         mappeds[i_stream].ts = &p_stream->ts;
1966     }
1967
1968     BuildPMT( DVBPSI_HANDLE_PARAM(p_sys->p_dvbpsi) VLC_OBJECT(p_mux),
1969               c, (PEStoTSCallback)BufferChainAppend,
1970               p_sys->i_tsid, p_sys->i_pmt_version_number,
1971               p_sys->i_pcr_pid,
1972               &p_sys->sdt,
1973               p_sys->i_num_pmt, p_sys->pmt, p_sys->i_pmt_program_number,
1974               p_mux->i_nb_inputs, mappeds );
1975 }