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