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