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