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