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