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