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