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