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