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