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