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