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