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