ts.c 85.3 KB
Newer Older
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 8
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
 *          Eric Petit <titer@videolan.org>
9
 *          Jean-Paul Saman <jpsaman #_at_# m2x.nl> 
10
 *          Wallace Wadge <wwadge #_at_# gmail.com>
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#include <stdlib.h>

#include <vlc/vlc.h>
#include <vlc/input.h>
#include <vlc/sout.h>

36 37
#include "iso_lang.h"

38 39
#include "bits.h"
#include "pes.h"
40
#include "csa.h"
41

42 43
#ifdef HAVE_DVBPSI_DR_H
#   include <dvbpsi/dvbpsi.h>
44
#   include <dvbpsi/demux.h>
45 46 47
#   include <dvbpsi/descriptor.h>
#   include <dvbpsi/pat.h>
#   include <dvbpsi/pmt.h>
48
#   include <dvbpsi/sdt.h>
49 50 51 52
#   include <dvbpsi/dr.h>
#   include <dvbpsi/psi.h>
#else
#   include "dvbpsi.h"
53
#   include "demux.h"
54 55 56
#   include "descriptor.h"
#   include "tables/pat.h"
#   include "tables/pmt.h"
57
#   include "tables/sdt.h"
58 59
#   include "descriptors/dr.h"
#   include "psi.h"
60 61
#endif

62 63 64 65 66
/*
 * TODO:
 *  - check PCR frequency requirement
 *  - check PAT/PMT  "        "
 *  - check PCR/PCR "soft"
67 68
 *  - check if "registration" descriptor : "AC-3" should be a program
 *    descriptor or an es one. (xine want an es one)
69 70 71 72 73 74 75 76 77 78 79 80 81 82
 *
 *  - remove creation of PAT/PMT without dvbpsi
 *  - ?
 * FIXME:
 *  - subtitle support is far from perfect. I expect some subtitles drop
 *    if they arrive a bit late
 *    (We cannot rely on the fact that the fifo should be full)
 */
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
static int     Open   ( vlc_object_t * );
static void    Close  ( vlc_object_t * );

83
#define VPID_TEXT N_("Video PID")
84 85
#define VPID_LONGTEXT N_("Assigns a fixed PID to the video stream. The PCR " \
  "PID will automatically be the video.")
86
#define APID_TEXT N_("Audio PID")
87
#define APID_LONGTEXT N_("Assigns a fixed PID to the audio stream.")
88 89
#define SPUPID_TEXT N_("SPU PID")
#define SPUPID_LONGTEXT N_("Assigns a fixed PID to the SPU.")
90
#define PMTPID_TEXT N_("PMT PID")
91
#define PMTPID_LONGTEXT N_("Assigns a fixed PID to the PMT")
92 93
#define TSID_TEXT N_("TS ID")
#define TSID_LONGTEXT N_("Assigns a fixed Transport Stream ID.")
94 95 96 97 98 99 100 101 102
#define NETID_TEXT N_("NET ID")
#define NETID_LONGTEXT N_("Assigns a fixed Network ID (for SDT table)")
#define PMTPROG_TEXT N_("PMT Program numbers (requires --sout-ts-es-id-pid)")
#define PMTPROG_LONGTEXT N_("Assigns a program number to each PMT")
#define MUXPMT_TEXT N_("Mux PMT (requires --sout-ts-es-id-pid)")
#define MUXPMT_LONGTEXT N_("Defines the pids to add to each pmt." )

#define SDTDESC_TEXT N_("SDT Descriptors (requires --sout-ts-es-id-pid)")
#define SDTDESC_LONGTEXT N_("Defines the descriptors of each SDT" )
103

104 105 106
#define PID_TEXT N_("Set PID to id of ES")
#define PID_LONGTEXT N_("set PID to id of es")

107
#define SHAPING_TEXT N_("Shaping delay (ms)")
108 109 110 111
#define SHAPING_LONGTEXT N_("If enabled, the TS muxer will cut the " \
  "stream in slices of the given duration, and ensure a constant bitrate " \
  "between the two boundaries. This avoids having huge bitrate peaks for " \
  "reference frames, in particular.")
112
#define KEYF_TEXT N_("Use keyframes")
113 114 115 116 117 118
#define KEYF_LONGTEXT N_("If enabled, and shaping is specified, " \
  "the TS muxer will place the boundaries at the end of I pictures. In " \
  "that case, the shaping duration given by the user is a worse case " \
  "used when no reference frame is available. This enhances the efficiency " \
  "of the shaping algorithm, since I frames are usually the biggest " \
  "frames in the stream.")
119 120

#define PCR_TEXT N_("PCR delay (ms)")
121 122
#define PCR_LONGTEXT N_("This option allows you to set at which interval " \
  "PCRs (Program Clock Reference) will be sent. " \
123
  "This value should be below 100ms. (default is 70)")
124

125 126 127 128 129 130
#define BMIN_TEXT N_( "Minimum B (deprecated)")
#define BMIN_LONGTEXT N_( "This setting is deprecated and not used anymore" )

#define BMAX_TEXT N_( "Maximum B (deprecated)")
#define BMAX_LONGTEXT N_( "This setting is deprecated and not used anymore")

131
#define DTS_TEXT N_("DTS delay (ms)")
132 133 134 135
#define DTS_LONGTEXT N_("This option will delay the DTS (decoding time " \
  "stamps) and PTS (presentation timestamps) of the data in the " \
  "stream, compared to the PCRs. This allows for some buffering inside " \
  "the client decoder.")
136 137 138

#define ACRYPT_TEXT N_("Crypt audio")
#define ACRYPT_LONGTEXT N_("Crypt audio using CSA")
139 140
#define VCRYPT_TEXT N_("Crypt video")
#define VCRYPT_LONGTEXT N_("Crypt video using CSA")
141 142 143

#define CK_TEXT N_("CSA Key")
#define CK_LONGTEXT N_("Defines the CSA encryption key. This must be a " \
144 145
  "16 char string (8 hexadecimal bytes).")

146 147 148 149 150
#define CPKT_TEXT N_("Packet size in bytes to encrypt")
#define CPKT_LONGTEXT N_("Specify the size of the TS packet to encrypt. " \
    "The encryption routines subtract the TS-header from the value before " \
    "encrypting. " )

151
#define SOUT_CFG_PREFIX "sout-ts-"
152 153 154 155 156 157
#ifdef HAVE_BSEARCH
#   define MAX_PMT 64       /* Maximum number of programs. FIXME: I just chose an arbitary number. Where is the maximum in the spec? */
#else
#   define MAX_PMT 1
#endif
#define MAX_PMT_PID 64       /* Maximum pids in each pmt.  FIXME: I just chose an arbitary number. Where is the maximum in the spec? */
158 159 160

vlc_module_begin();
    set_description( _("TS muxer (libdvbpsi)") );
161
    set_shortname( "MPEG-TS");
162 163
    set_category( CAT_SOUT );
    set_subcategory( SUBCAT_SOUT_MUX );
164 165
    set_capability( "sout mux", 120 );
    add_shortcut( "ts" );
166 167 168

    add_integer( SOUT_CFG_PREFIX "pid-video", 0, NULL,VPID_TEXT, VPID_LONGTEXT,
                                  VLC_TRUE );
169 170
    add_integer( SOUT_CFG_PREFIX "pid-audio", 0, NULL, APID_TEXT,
                 APID_LONGTEXT, VLC_TRUE );
171 172
    add_integer( SOUT_CFG_PREFIX "pid-spu", 0, NULL, SPUPID_TEXT,
                 SPUPID_LONGTEXT, VLC_TRUE );
173 174
    add_integer( SOUT_CFG_PREFIX "pid-pmt", 0, NULL, PMTPID_TEXT,
                 PMTPID_LONGTEXT, VLC_TRUE );
175 176
    add_integer( SOUT_CFG_PREFIX "tsid", 0, NULL, TSID_TEXT,
                 TSID_LONGTEXT, VLC_TRUE );
177 178 179 180
    add_integer( SOUT_CFG_PREFIX "netid", 0, NULL, NETID_TEXT,
                 NETID_LONGTEXT, VLC_TRUE );
    add_string( SOUT_CFG_PREFIX "program-pmt", NULL, NULL, PMTPROG_TEXT,
                PMTPROG_LONGTEXT, VLC_TRUE );
181 182
    add_bool( SOUT_CFG_PREFIX "es-id-pid", 0, NULL, PID_TEXT, PID_LONGTEXT,
              VLC_TRUE );
183 184
    add_string( SOUT_CFG_PREFIX "muxpmt", NULL, NULL, MUXPMT_TEXT, MUXPMT_LONGTEXT, VLC_TRUE );
    add_string( SOUT_CFG_PREFIX "sdtdesc", NULL, NULL, SDTDESC_TEXT, SDTDESC_LONGTEXT, VLC_TRUE );
185 186

    add_integer( SOUT_CFG_PREFIX "shaping", 200, NULL,SHAPING_TEXT,
187
                 SHAPING_LONGTEXT, VLC_TRUE );
188
    add_bool( SOUT_CFG_PREFIX "use-key-frames", VLC_FALSE, NULL, KEYF_TEXT,
189 190
              KEYF_LONGTEXT, VLC_TRUE );

191
    add_integer( SOUT_CFG_PREFIX "pcr", 70, NULL, PCR_TEXT, PCR_LONGTEXT,
192
                 VLC_TRUE );
193
    add_integer( SOUT_CFG_PREFIX "bmin", 0, NULL, BMIN_TEXT, BMIN_LONGTEXT,
194
                 VLC_TRUE );
195
    add_integer( SOUT_CFG_PREFIX "bmax", 0, NULL, BMAX_TEXT, BMAX_LONGTEXT,
196
                 VLC_TRUE );
197
    add_integer( SOUT_CFG_PREFIX "dts-delay", 400, NULL, DTS_TEXT,
198
                 DTS_LONGTEXT, VLC_TRUE );
199 200

    add_bool( SOUT_CFG_PREFIX "crypt-audio", VLC_TRUE, NULL, ACRYPT_TEXT,
201
              ACRYPT_LONGTEXT, VLC_TRUE );
202 203
    add_bool( SOUT_CFG_PREFIX "crypt-video", VLC_TRUE, NULL, VCRYPT_TEXT,
              VCRYPT_LONGTEXT, VLC_TRUE );
204

205 206
    add_string( SOUT_CFG_PREFIX "csa-ck", NULL, NULL, CK_TEXT, CK_LONGTEXT,
                VLC_TRUE );
207
    add_integer( SOUT_CFG_PREFIX "csa-pkt", 188, NULL, CPKT_TEXT, CPKT_LONGTEXT, VLC_TRUE );
208

209 210 211 212
    set_callbacks( Open, Close );
vlc_module_end();

/*****************************************************************************
213
 * Local data structures
214
 *****************************************************************************/
215
static const char *ppsz_sout_options[] = {
216
    "pid-video", "pid-audio", "pid-spu", "pid-pmt", "tsid", "netid",
217
    "es-id-pid", "shaping", "pcr", "bmin", "bmax", "use-key-frames",
218
    "dts-delay", "csa-ck", "csa-pkt", "crypt-audio", "crypt-video",
219
    "muxpmt", "sdtdesc", "program-pmt",
220
    NULL
221 222
};

223 224 225 226 227 228 229 230 231 232 233 234
typedef struct pmt_map_t   /* Holds the mapping between the pmt-pid/pmt table */
{
    int i_pid;
    unsigned long i_prog;
} pmt_map_t;

typedef struct sdt_desc_t
{
    char *psz_provider;    
    char *psz_service_name;  /* name of program */
} sdt_desc_t;

235 236
typedef struct
{
237
    int     i_depth;
238 239
    block_t *p_first;
    block_t **pp_last;
240 241 242 243 244 245 246 247
} sout_buffer_chain_t;

static inline void BufferChainInit  ( sout_buffer_chain_t *c )
{
    c->i_depth = 0;
    c->p_first = NULL;
    c->pp_last = &c->p_first;
}
248

249
static inline void BufferChainAppend( sout_buffer_chain_t *c, block_t *b )
250 251 252 253 254 255 256 257 258 259 260
{
    *c->pp_last = b;
    c->i_depth++;

    while( b->p_next )
    {
        b = b->p_next;
        c->i_depth++;
    }
    c->pp_last = &b->p_next;
}
261

262
static inline block_t *BufferChainGet( sout_buffer_chain_t *c )
263
{
264
    block_t *b = c->p_first;
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

    if( b )
    {
        c->i_depth--;
        c->p_first = b->p_next;

        if( c->p_first == NULL )
        {
            c->pp_last = &c->p_first;
        }

        b->p_next = NULL;
    }
    return b;
}
280

281
static inline block_t *BufferChainPeek( sout_buffer_chain_t *c )
282
{
283
    block_t *b = c->p_first;
284 285 286

    return b;
}
287

288 289
static inline void BufferChainClean( sout_instance_t *p_sout,
                                     sout_buffer_chain_t *c )
290
{
291
    block_t *b;
292 293 294

    while( ( b = BufferChainGet( c ) ) )
    {
295
        block_Release( b );
296 297 298
    }
    BufferChainInit( c );
}
299

300
typedef struct ts_stream_t
301 302
{
    int             i_pid;
303 304
    vlc_fourcc_t    i_codec;

305 306 307
    int             i_stream_type;
    int             i_stream_id;
    int             i_continuity_counter;
308
    vlc_bool_t      b_discontinuity;
309

310 311 312 313
    /* to be used for carriege of DIV3 */
    vlc_fourcc_t    i_bih_codec;
    int             i_bih_width, i_bih_height;

314 315 316
    /* Specific to mpeg4 in mpeg2ts */
    int             i_es_id;

317
    int             i_decoder_specific_info;
318
    uint8_t         *p_decoder_specific_info;
319

320 321 322
    /* language is iso639-2T */
    uint8_t         lang[3];

323 324 325 326
    sout_buffer_chain_t chain_pes;
    mtime_t             i_pes_dts;
    mtime_t             i_pes_length;
    int                 i_pes_used;
327
    vlc_bool_t          b_key_frame;
328

329 330
} ts_stream_t;

331
struct sout_mux_sys_t
332 333
{
    int             i_pcr_pid;
334 335
    sout_input_t    *p_pcr_input;

336 337 338
    int             i_audio_bound;
    int             i_video_bound;

339
    vlc_bool_t      b_es_id_pid;
340
    vlc_bool_t      b_sdt;
341 342
    int             i_pid_video;
    int             i_pid_audio;
343
    int             i_pid_spu;
344
    int             i_pid_free; /* first usable pid */
345

346
    int             i_tsid;
347 348 349
    int             i_netid;
    int             i_num_pmt;
    int             i_pmtslots;
350 351 352 353
    int             i_pat_version_number;
    ts_stream_t     pat;

    int             i_pmt_version_number;
354 355 356 357
    ts_stream_t     pmt[MAX_PMT];        
    pmt_map_t       pmtmap[MAX_PMT_PID];
    int             i_pmt_program_number[MAX_PMT];
    sdt_desc_t      sdt_descriptors[MAX_PMT];
358

359 360
    int             i_mpeg4_streams;

361
    int             i_null_continuity_counter;  /* Needed ? */
362 363
    ts_stream_t     sdt;        
    dvbpsi_pmt_t    *dvbpmt;
364

365 366 367
    /* for TS building */
    int64_t             i_bitrate_min;
    int64_t             i_bitrate_max;
368

369
    int64_t             i_shaping_delay;
370
    int64_t             i_pcr_delay;
Laurent Aimar's avatar
Laurent Aimar committed
371

372 373
    int64_t             i_dts_delay;

374 375
    vlc_bool_t          b_use_key_frames;

376
    mtime_t             i_pcr;  /* last PCR emited */
377 378

    csa_t               *csa;
379
    int                 i_csa_pkt_size;
380
    vlc_bool_t          b_crypt_audio;
381
    vlc_bool_t          b_crypt_video;
382
};
383

384
/* Reserve a pid and return it */
385
static int  AllocatePID( sout_mux_sys_t *p_sys, int i_cat )
386
{
387 388 389 390 391 392 393 394 395 396 397
    int i_pid;
    if ( i_cat == VIDEO_ES && p_sys->i_pid_video )
    {
        i_pid = p_sys->i_pid_video;
        p_sys->i_pid_video = 0;
    }
    else if ( i_cat == AUDIO_ES && p_sys->i_pid_audio )
    {
        i_pid = p_sys->i_pid_audio;
        p_sys->i_pid_audio = 0;
    }
398 399 400 401 402
    else if ( i_cat == SPU_ES && p_sys->i_pid_spu )
    {
        i_pid = p_sys->i_pid_spu;
        p_sys->i_pid_spu = 0;
    }
403 404 405 406 407
    else
    {
        i_pid = ++p_sys->i_pid_free;
    }
    return i_pid;
408 409
}

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
static int pmtcompare( const void *pa, const void *pb )
{
    if ( ((pmt_map_t *)pa)->i_pid  < ((pmt_map_t *)pb)->i_pid )
        return -1;
    else if ( ((pmt_map_t *)pa)->i_pid  > ((pmt_map_t *)pb)->i_pid )
        return 1;
    else
        return 0;
}

static int intcompare( const void *pa, const void *pb )
{
    if ( *(int *)pa  < *(int *)pb )
        return -1;
    else if ( *(int *)pa > *(int *)pb )
        return 1;
    else
        return 0;
}

430 431 432
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
433 434 435 436
static int Control  ( sout_mux_t *, int, va_list );
static int AddStream( sout_mux_t *, sout_input_t * );
static int DelStream( sout_mux_t *, sout_input_t * );
static int Mux      ( sout_mux_t * );
437

438
static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo );
439 440 441 442
static void TSSchedule  ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
                          mtime_t i_pcr_length, mtime_t i_pcr_dts );
static void TSDate      ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
                          mtime_t i_pcr_length, mtime_t i_pcr_dts );
443 444
static void GetPAT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
445

446 447
static block_t *TSNew( sout_mux_t *p_mux, ts_stream_t *p_stream, vlc_bool_t b_pcr );
static void TSSetPCR( block_t *p_ts, mtime_t i_dts );
448

449
static void PEStoTS  ( sout_instance_t *, sout_buffer_chain_t *, block_t *, ts_stream_t * );
450

451 452 453 454 455
/*****************************************************************************
 * Open:
 *****************************************************************************/
static int Open( vlc_object_t *p_this )
{
456
    sout_mux_t          *p_mux =(sout_mux_t*)p_this;
457
    sout_mux_sys_t      *p_sys = NULL;
458
    vlc_value_t         val;
459
    int i;
460

461
    sout_CfgParse( p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg );
462

463
    p_sys = malloc( sizeof( sout_mux_sys_t ) );
464 465
    if( !p_sys )
        return VLC_ENOMEM;
466 467 468 469
    p_sys->i_pmtslots = p_sys->b_sdt = 0;
    p_sys->i_num_pmt = 1;
    p_sys->dvbpmt = NULL;
    memset( &p_sys->pmtmap, 0, sizeof(p_sys->pmtmap) );
470

471
    p_mux->pf_control   = Control;
472 473 474 475
    p_mux->pf_addstream = AddStream;
    p_mux->pf_delstream = DelStream;
    p_mux->pf_mux       = Mux;
    p_mux->p_sys        = p_sys;
476

477
    srand( (uint32_t)mdate() );
478 479 480 481
    for ( i = 0; i < MAX_PMT; i++ )
        p_sys->sdt_descriptors[i].psz_service_name
            = p_sys->sdt_descriptors[i].psz_provider = NULL;
    memset( p_sys->sdt_descriptors, 0, sizeof(sdt_desc_t) );
482

483 484
    p_sys->i_audio_bound = 0;
    p_sys->i_video_bound = 0;
485

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
    var_Get( p_mux, SOUT_CFG_PREFIX "es-id-pid", &val );
    p_sys->b_es_id_pid = val.b_bool;

    var_Get( p_mux, SOUT_CFG_PREFIX "muxpmt", &val );
    /* 
       fetch string of pmts. Here's a sample: --sout-ts-muxpmt="0x451,0x200,0x28a,0x240,,0x450,0x201,0x28b,0x241,,0x452,0x202,0x28c,0x242"
       This would mean 0x451, 0x200, 0x28a, 0x240 would fall under one pmt (program), 0x450,0x201,0x28b,0x241 would fall under another
    */
    if( val.psz_string != NULL && *val.psz_string )
    {
        char *psz_next;
        char *psz = val.psz_string;
        uint16_t i_pid;
        psz_next = psz;

        while( psz != NULL )
        {
            i_pid = strtoul( psz, &psz_next, 0 );
    
            if ( strlen(psz_next) > 0 )
                psz = &psz_next[1];
            if ( i_pid == 0 )
            { 
                p_sys->i_num_pmt++;
                if ( p_sys->i_num_pmt > MAX_PMT )
                {
                    msg_Err( p_mux,
             "Number of PMTs greater than compiled maximum (%d)", MAX_PMT );
                    p_sys->i_num_pmt = MAX_PMT;
                }
            }
            else 
            {
                p_sys->pmtmap[p_sys->i_pmtslots].i_pid = i_pid;
                p_sys->pmtmap[p_sys->i_pmtslots].i_prog = p_sys->i_num_pmt - 1;
                p_sys->i_pmtslots++;
                if ( p_sys->i_pmtslots > MAX_PMT_PID )
                {
                    msg_Err( p_mux,
             "Number of pids in PMT greater than compiled maximum (%d)",
                             MAX_PMT_PID );
                    p_sys->i_pmtslots = MAX_PMT_PID;
                }
            }
    
            /* Now sort according to pids for fast search later on */
            qsort( (void *)p_sys->pmtmap, p_sys->i_pmtslots,
                   sizeof(pmt_map_t), &pmtcompare );
            if ( !*psz_next ) 
                psz = NULL;
        }
    }
    if( val.psz_string != NULL) free( val.psz_string );

540 541 542
    p_sys->i_pat_version_number = rand() % 32;
    p_sys->pat.i_pid = 0;
    p_sys->pat.i_continuity_counter = 0;
543

544 545 546 547 548
    var_Get( p_mux, SOUT_CFG_PREFIX "tsid", &val );
    if ( val.i_int )
        p_sys->i_tsid = val.i_int;
    else
        p_sys->i_tsid = rand() % 65536;
549 550 551 552 553
    var_Get( p_mux, SOUT_CFG_PREFIX "netid", &val );
    if ( val.i_int )
        p_sys->i_netid = val.i_int;
    else
        p_sys->i_netid = rand() % 65536;
554
    p_sys->i_pmt_version_number = rand() % 32;
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    p_sys->sdt.i_continuity_counter = 0;

    for( i = 0; i < p_sys->i_num_pmt; i++ )
        p_sys->pmt[i].i_continuity_counter = 0;

    var_Get( p_mux, SOUT_CFG_PREFIX "sdtdesc", &val );
    p_sys->b_sdt = val.psz_string && *val.psz_string ? VLC_TRUE : VLC_FALSE;
    
    /* Syntax is provider_sdt1,service_name_sdt1,provider_sdt2,service_name_sdt2... */
    if( val.psz_string != NULL && *val.psz_string )
    {

        char *psz = val.psz_string;
        char *psz_sdttoken = psz;

        i = 0;
        while ( psz_sdttoken != NULL )
        {
            char *psz_end = strchr( psz_sdttoken, ',' );
            if( psz_end != NULL )
            {
                *psz_end++ = '\0';
            }
            if ( !(i % 2) )
            {
                p_sys->sdt_descriptors[i/2].psz_provider
                    = strdup(psz_sdttoken);
            }
            else
            {
                p_sys->sdt_descriptors[i/2].psz_service_name
                    = strdup(psz_sdttoken);    
            }

            i++;
            psz_sdttoken = psz_end;
        }
    }
    if( val.psz_string != NULL ) free( val.psz_string );
594

595
    var_Get( p_mux, SOUT_CFG_PREFIX "program-pmt", &val );
596
    if( val.psz_string && *val.psz_string )
597
    {
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
        char *psz_next;
        char *psz = val.psz_string;
        uint16_t i_pid;

        psz_next = psz;
        i = 0;
        while ( psz != NULL )
        {
            i_pid = strtoul( psz, &psz_next, 0 );
            if( strlen(psz_next) > 0 )
                psz = &psz_next[1];
            else
                psz = NULL;
 
            if( i_pid == 0 )
            { 
                if( i > MAX_PMT )
                    msg_Err( p_mux, "Number of PMTs > maximum (%d)",
                             MAX_PMT );
            }
            else
            {
                p_sys->i_pmt_program_number[i] = i_pid;
                i++;
            }
        }
624 625 626
    }
    else
    {
627 628 629
        /* Option not specified, use 1, 2, 3... */
        for( i = 0; i < p_sys->i_num_pmt; i++ )
            p_sys->i_pmt_program_number[i] = i + 1;
630
    }
631
    if( val.psz_string != NULL ) free( val.psz_string );
632

633
    var_Get( p_mux, SOUT_CFG_PREFIX "pid-pmt", &val );
634
    if( val.i_int )
635
    {
636 637
        for( i = 0; i < p_sys->i_num_pmt; i++ )
            p_sys->pmt[i].i_pid = val.i_int + i; /* Does this make any sense? */
638 639 640
    }
    else
    {
641 642
        for( i = 0; i < p_sys->i_num_pmt; i++ )
            p_sys->pmt[i].i_pid = 0x42 + i;       
643 644
    }

645
    p_sys->i_pid_free = p_sys->pmt[p_sys->i_num_pmt - 1].i_pid + 1;
646

647 648 649
    var_Get( p_mux, SOUT_CFG_PREFIX "pid-video", &val );
    p_sys->i_pid_video = val.i_int;
    if ( p_sys->i_pid_video > p_sys->i_pid_free )
650
    {
651
        p_sys->i_pid_free = p_sys->i_pid_video + 1;
652
    }
653 654 655 656

    var_Get( p_mux, SOUT_CFG_PREFIX "pid-audio", &val );
    p_sys->i_pid_audio = val.i_int;
    if ( p_sys->i_pid_audio > p_sys->i_pid_free )
657
    {
658
        p_sys->i_pid_free = p_sys->i_pid_audio + 1;
659 660
    }

661 662 663 664 665 666 667
    var_Get( p_mux, SOUT_CFG_PREFIX "pid-spu", &val );
    p_sys->i_pid_spu = val.i_int;
    if ( p_sys->i_pid_spu > p_sys->i_pid_free )
    {
        p_sys->i_pid_free = p_sys->i_pid_spu + 1;
    }

668
    p_sys->i_pcr_pid = 0x1fff;
669
    p_sys->p_pcr_input = NULL;
670

671
    p_sys->i_mpeg4_streams = 0;
672

673 674 675
    p_sys->i_null_continuity_counter = 0;

    /* Allow to create constrained stream */
676
    var_Get( p_mux, SOUT_CFG_PREFIX "bmin", &val );
677
    p_sys->i_bitrate_min = val.i_int;
678 679

    var_Get( p_mux, SOUT_CFG_PREFIX "bmax", &val );
680
    p_sys->i_bitrate_max = val.i_int;
681

682 683 684
    if( p_sys->i_bitrate_min > 0 && p_sys->i_bitrate_max > 0 &&
        p_sys->i_bitrate_min > p_sys->i_bitrate_max )
    {
Gildas Bazin's avatar
 
Gildas Bazin committed
685 686
        msg_Err( p_mux, "incompatible minimum and maximum bitrate, "
                 "disabling bitrate control" );
687 688 689
        p_sys->i_bitrate_min = 0;
        p_sys->i_bitrate_max = 0;
    }
690
    if( p_sys->i_bitrate_min > 0 || p_sys->i_bitrate_max > 0 )
691
    {
692 693
        msg_Err( p_mux, "bmin and bmax no more supported "
                 "(if you need them report it)" );
694 695
    }

696 697 698
    var_Get( p_mux, SOUT_CFG_PREFIX "shaping", &val );
    p_sys->i_shaping_delay = (int64_t)val.i_int * 1000;
    if( p_sys->i_shaping_delay <= 0 )
699
    {
700
        msg_Err( p_mux,
701
                 "invalid shaping ("I64Fd"ms) resetting to 200ms",
702 703
                 p_sys->i_shaping_delay / 1000 );
        p_sys->i_shaping_delay = 200000;
704
    }
Gildas Bazin's avatar
 
Gildas Bazin committed
705

706 707 708 709
    var_Get( p_mux, SOUT_CFG_PREFIX "pcr", &val );
    p_sys->i_pcr_delay = (int64_t)val.i_int * 1000;
    if( p_sys->i_pcr_delay <= 0 ||
        p_sys->i_pcr_delay >= p_sys->i_shaping_delay )
710
    {
711
        msg_Err( p_mux,
712
                 "invalid pcr delay ("I64Fd"ms) resetting to 70ms",
713
                 p_sys->i_pcr_delay / 1000 );
714
        p_sys->i_pcr_delay = 70000;
715 716
    }

717 718 719
    var_Get( p_mux, SOUT_CFG_PREFIX "dts-delay", &val );
    p_sys->i_dts_delay = (int64_t)val.i_int * 1000;

720 721 722
    msg_Dbg( p_mux, "shaping="I64Fd" pcr="I64Fd" dts_delay="I64Fd,
             p_sys->i_shaping_delay, p_sys->i_pcr_delay, p_sys->i_dts_delay );

723 724 725
    var_Get( p_mux, SOUT_CFG_PREFIX "use-key-frames", &val );
    p_sys->b_use_key_frames = val.b_bool;

726
    /* for TS generation */
727
    p_sys->i_pcr    = 0;
728 729

    p_sys->csa      = NULL;
730
    var_Get( p_mux, SOUT_CFG_PREFIX "csa-ck", &val );
731
    if( val.psz_string && *val.psz_string )
732
    {
733 734
        char *psz = val.psz_string;

735
        /* skip 0x */
736
        if( psz[0] == '0' && ( psz[1] == 'x' || psz[1] == 'X' ) )
737
        {
738
            psz += 2;
739
        }
740
        if( strlen( psz ) != 16 )
741 742 743 744 745
        {
            msg_Dbg( p_mux, "invalid csa ck (it must be 16 chars long)" );
        }
        else
        {
746
            uint64_t i_ck = strtoull( psz, NULL, 16 );
Gildas Bazin's avatar
Gildas Bazin committed
747 748 749
            uint8_t  ck[8];
            int      i;

750 751 752 753
            for( i = 0; i < 8; i++ )
            {
                ck[i] = ( i_ck >> ( 56 - 8*i) )&0xff;
            }
754
#ifndef TS_NO_CSA_CK_MSG
755 756
            msg_Dbg( p_mux, "using CSA scrambling with ck=%x:%x:%x:%x:%x:%x:%x:%x",
                     ck[0], ck[1], ck[2], ck[3], ck[4], ck[5], ck[6], ck[7] );
757
#endif
758
            p_sys->csa = csa_New();
759 760
            if( p_sys->csa )
            {
761 762 763
                vlc_value_t pkt_val;
            
                csa_SetCW( p_sys->csa, ck, ck );                
764
                
765 766
                var_Get( p_mux, SOUT_CFG_PREFIX "csa-pkt", &pkt_val );
                if( pkt_val.i_int < 12 || pkt_val.i_int > 188 )
767
                {
768
                    msg_Err( p_mux, "wrong packet size %d specified.", pkt_val.i_int );
769 770 771
                    msg_Warn( p_mux, "using default packet size of 188 bytes" );
                    p_sys->i_csa_pkt_size = 188;
                }
772
                else p_sys->i_csa_pkt_size = pkt_val.i_int;
773 774
                msg_Dbg( p_mux, "encrypting %d bytes of packet", p_sys->i_csa_pkt_size );
            }    
775 776
        }
    }
777 778 779 780
    if( val.psz_string ) free( val.psz_string );

    var_Get( p_mux, SOUT_CFG_PREFIX "crypt-audio", &val );
    p_sys->b_crypt_audio = val.b_bool;
781

782 783 784
    var_Get( p_mux, SOUT_CFG_PREFIX "crypt-video", &val );
    p_sys->b_crypt_video = val.b_bool;

785 786 787 788 789 790 791 792
    return VLC_SUCCESS;
}

/*****************************************************************************
 * Close:
 *****************************************************************************/
static void Close( vlc_object_t * p_this )
{
793 794
    sout_mux_t          *p_mux = (sout_mux_t*)p_this;
    sout_mux_sys_t      *p_sys = p_mux->p_sys;
795
    int i;
796

797 798 799 800
    if( p_sys->csa )
    {
        csa_Delete( p_sys->csa );
    }
801 802 803 804 805 806 807 808 809 810
    for( i = 0; i < MAX_PMT; i++ )
    {
        if( p_sys->sdt_descriptors[i].psz_service_name != NULL )
            free( p_sys->sdt_descriptors[i].psz_service_name );
        if( p_sys->sdt_descriptors[i].psz_provider != NULL )
            free( p_sys->sdt_descriptors[i].psz_provider );
    }

    if( p_sys->dvbpmt != NULL )  /* safety */
        free ( p_sys->dvbpmt );
811

812
    free( p_sys );
813 814
}

815
/*****************************************************************************
816
 * Control:
817
 *****************************************************************************/
818
static int Control( sout_mux_t *p_mux, int i_query, va_list args )
819
{
820 821 822
    vlc_bool_t *pb_bool;
    char **ppsz;

823 824
   switch( i_query )
   {
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
       case MUX_CAN_ADD_STREAM_WHILE_MUXING:
           pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
           *pb_bool = VLC_TRUE;
           return VLC_SUCCESS;

       case MUX_GET_ADD_STREAM_WAIT:
           pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
           *pb_bool = VLC_FALSE;
           return VLC_SUCCESS;

       case MUX_GET_MIME:
           ppsz = (char**)va_arg( args, char ** );
           *ppsz = strdup( "video/mpeg" );  /* FIXME not sure */
           return VLC_SUCCESS;

840
        default:
841
            return VLC_EGENERIC;
842 843
   }
}
844

845 846 847
/*****************************************************************************
 * AddStream: called for each stream addition
 *****************************************************************************/
848
static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
849
{
850
    sout_mux_sys_t      *p_sys = p_mux->p_sys;
851 852
    ts_stream_t         *p_stream;

853
    p_input->p_sys = p_stream = malloc( sizeof( ts_stream_t ) );
854

855
    /* Init this new stream */
856 857 858 859
    if ( p_sys->b_es_id_pid )
        p_stream->i_pid = p_input->p_fmt->i_id & 0x1fff;
    else
        p_stream->i_pid = AllocatePID( p_sys, p_input->p_fmt->i_cat );
860
    p_stream->i_codec = p_input->p_fmt->i_codec;
861
    p_stream->i_continuity_counter    = 0;
862
    p_stream->b_discontinuity         = VLC_FALSE;
863 864
    p_stream->i_decoder_specific_info = 0;
    p_stream->p_decoder_specific_info = NULL;
865

866 867
    msg_Dbg( p_mux, "adding input codec=%4.4s pid=%d",
             (char*)&p_input->p_fmt->i_codec, p_stream->i_pid );
868

869
    /* All others fields depand on codec */
870
    switch( p_input->p_fmt->i_cat )
871 872
    {
        case VIDEO_ES:
873
            switch( p_input->p_fmt->i_codec )
874 875
            {
                case VLC_FOURCC( 'm', 'p','g', 'v' ):
876
                    /* TODO: do we need to check MPEG-I/II ? */
877
                    p_stream->i_stream_type = 0x02;
878
                    p_stream->i_stream_id = 0xe0;
879 880 881
                    break;
                case VLC_FOURCC( 'm', 'p','4', 'v' ):
                    p_stream->i_stream_type = 0x10;
882
                    p_stream->i_stream_id = 0xe0;
883
                    p_stream->i_es_id = p_stream->i_pid;
884
                    break;
885 886 887 888
                case VLC_FOURCC( 'h', '2','6', '4' ):
                    p_stream->i_stream_type = 0x1b;
                    p_stream->i_stream_id = 0xe0;
                    break;
889 890
                /* XXX dirty dirty but somebody want that:
                 *     using crapy MS-codec XXX */
891 892 893
                /* I didn't want to do that :P */
                case VLC_FOURCC( 'H', '2', '6', '3' ):
                case VLC_FOURCC( 'I', '2', '6', '3' ):
894
                case VLC_FOURCC( 'W', 'M', 'V', '3' ):
895
                case VLC_FOURCC( 'W', 'M', 'V', '2' ):
896 897 898 899
                case VLC_FOURCC( 'W', 'M', 'V', '1' ):
                case VLC_FOURCC( 'D', 'I', 'V', '3' ):
                case VLC_FOURCC( 'D', 'I', 'V', '2' ):
                case VLC_FOURCC( 'D', 'I', 'V', '1' ):
900
                case VLC_FOURCC( 'M', 'J', 'P', 'G' ):
901 902
                    p_stream->i_stream_type = 0xa0; /* private */
                    p_stream->i_stream_id = 0xa0;   /* beurk */
903 904 905
                    p_stream->i_bih_codec  = p_input->p_fmt->i_codec;
                    p_stream->i_bih_width  = p_input->p_fmt->video.i_width;
                    p_stream->i_bih_height = p_input->p_fmt->video.i_height;
906
                    break;
907
                default:
908 909
                    free( p_stream );
                    return VLC_EGENERIC;
910
            }
911
            p_sys->i_video_bound++;
912
            break;
913

914
        case AUDIO_ES:
915
            switch( p_input->p_fmt->i_codec )
916
            {
917
                case VLC_FOURCC( 'm', 'p','g', 'a' ):
918 919
                    p_stream->i_stream_type =
                        p_input->p_fmt->audio.i_rate >= 32000 ? 0x03 : 0x04;
920
                    p_stream->i_stream_id = 0xc0;
921
                    break;
922 923
                case VLC_FOURCC( 'a', '5','2', ' ' ):
                    p_stream->i_stream_type = 0x81;
924
                    p_stream->i_stream_id = 0xbd;
925
                    break;
926 927 928 929 930
                case VLC_FOURCC( 'l', 'p','c', 'm' ):
                    p_stream->i_stream_type = 0x83;
                    p_stream->i_stream_id = 0xbd;
                    break;
                case VLC_FOURCC( 'd', 't','s', ' ' ):
931
                    p_stream->i_stream_type = 0x06;
932 933
                    p_stream->i_stream_id = 0xbd;
                    break;
934 935 936
                case VLC_FOURCC( 'm', 'p','4', 'a' ):
                    p_stream->i_stream_type = 0x11;
                    p_stream->i_stream_id = 0xfa;
937
                    p_sys->i_mpeg4_streams++;
938
                    p_stream->i_es_id = p_stream->i_pid;
939 940
                    break;
                default:
941 942
                    free( p_stream );
                    return VLC_EGENERIC;
943
            }
944
            p_sys->i_audio_bound++;
945
            break;
946

947
        case SPU_ES:
948
            switch( p_input->p_fmt->i_codec )
949
            {
950 951
                case VLC_FOURCC( 's', 'p','u', ' ' ):
                    p_stream->i_stream_type = 0x82;
952
                    p_stream->i_stream_id = 0xbd;
953
                    break;
954 955 956 957 958 959
                case VLC_FOURCC( 's', 'u','b', 't' ):
                    p_stream->i_stream_type = 0x12;
                    p_stream->i_stream_id = 0xfa;
                    p_sys->i_mpeg4_streams++;
                    p_stream->i_es_id = p_stream->i_pid;
                    break;
960 961 962
                case VLC_FOURCC('d','v','b','s'):
                    p_stream->i_stream_type = 0x06;
                    p_stream->i_es_id = p_input->p_fmt->subs.dvb.i_id;
963
                    p_stream->i_stream_id = 0xbd;
964
                    break;
965 966 967 968
                case VLC_FOURCC('t','e','l','x'):
                    p_stream->i_stream_type = 0x06;
                    p_stream->i_stream_id = 0xbd; /* FIXME */
                    break;
969 970 971
                default:
                    free( p_stream );
                    return VLC_EGENERIC;
972
            }
973
            break;
974

975
        default:
976 977
            free( p_stream );
            return VLC_EGENERIC;
978 979
    }

980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    p_stream->lang[0] =
    p_stream->lang[1] =
    p_stream->lang[2] = '\0';
    if( p_input->p_fmt->psz_language )
    {
        char *psz = p_input->p_fmt->psz_language;
        const iso639_lang_t *pl = NULL;

        if( strlen( psz ) == 2 )
        {
            pl = GetLang_1( psz );
        }
        else if( strlen( psz ) == 3 )
        {
            pl = GetLang_2B( psz );
            if( !strcmp( pl->psz_iso639_1, "??" ) )
            {
                pl = GetLang_2T( psz );
            }
        }
        if( pl && strcmp( pl->psz_iso639_1, "??" ) )
        {
            p_stream->lang[0] = pl->psz_iso639_2T[0];
            p_stream->lang[1] = pl->psz_iso639_2T[1];
            p_stream->lang[2] = pl->psz_iso639_2T[2];

            msg_Dbg( p_mux, "    - lang=%c%c%c",
1007
                     p_stream->lang[0], p_stream->lang[1], p_stream->lang[2] );
1008 1009 1010
        }
    }

1011
    /* Copy extra data (VOL for MPEG-4 and extra BitMapInfoHeader for VFW */
1012
    p_stream->i_decoder_specific_info = p_input->p_fmt->i_extra;
1013 1014 1015 1016 1017
    if( p_stream->i_decoder_specific_info > 0 )
    {
        p_stream->p_decoder_specific_info =
            malloc( p_stream->i_decoder_specific_info );
        memcpy( p_stream->p_decoder_specific_info,
1018 1019
                p_input->p_fmt->p_extra,
                p_input->p_fmt->i_extra );
1020
    }
1021

1022 1023 1024 1025 1026 1027
    /* Create decoder specific info for subt */
    if( p_stream->i_codec == VLC_FOURCC( 's', 'u','b', 't' ) )
    {
        uint8_t *p;

        p_stream->i_decoder_specific_info = 55;
1028 1029
        p_stream->p_decoder_specific_info = p =
            malloc( p_stream->i_decoder_specific_info );
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040

        p[0] = 0x10;    /* textFormat, 0x10 for 3GPP TS 26.245 */
        p[1] = 0x00;    /* flags: 1b: associated video info flag
                                  3b: reserved
                                  1b: duration flag
                                  3b: reserved */
        p[2] = 52;      /* remaining size */

        p += 3;

        p[0] = p[1] = p[2] = p[3] = 0; p+=4;    /* display flags */
1041 1042
        *p++ = 0;  /* horizontal justification (-1: left, 0 center, 1 right) */
        *p++ = 1;  /* vertical   justification (-1: top, 0 center, 1 bottom) */
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069

        p[0] = p[1] = p[2] = 0x00; p+=3;/* background rgb */
        *p++ = 0xff;                    /* background a */

        p[0] = p[1] = 0; p += 2;        /* text box top */
        p[0] = p[1] = 0; p += 2;        /* text box left */
        p[0] = p[1] = 0; p += 2;        /* text box bottom */
        p[0] = p[1] = 0; p += 2;        /* text box right */

        p[0] = p[1] = 0; p += 2;        /* start char */
        p[0] = p[1] = 0; p += 2;        /* end char */
        p[0] = p[1] = 0; p += 2;        /* default font id */

        *p++ = 0;                       /* font style flags */
        *p++ = 12;                      /* font size */

        p[0] = p[1] = p[2] = 0x00; p+=3;/* foreground rgb */
        *p++ = 0x00;                    /* foreground a */

        p[0] = p[1] = p[2] = 0; p[3] = 22; p += 4;
        memcpy( p, "ftab", 4 ); p += 4;
        *p++ = 0; *p++ = 1;             /* entry count */
        p[0] = p[1] = 0; p += 2;        /* font id */
        *p++ = 9;                       /* font name length */
        memcpy( p, "Helvetica", 9 );    /* font name */
    }

1070 1071 1072 1073 1074
    /* Init pes chain */
    BufferChainInit( &p_stream->chain_pes );
    p_stream->i_pes_dts    = 0;
    p_stream->i_pes_length = 0;
    p_stream->i_pes_used   = 0;
1075
    p_stream->b_key_frame  = 0;
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086

    /* We only change PMT version (PAT isn't changed) */
    p_sys->i_pmt_version_number = ( p_sys->i_pmt_version_number + 1 )%32;

    /* Update pcr_pid */
    if( p_input->p_fmt->i_cat != SPU_ES &&
        ( p_sys->i_pcr_pid == 0x1fff || p_input->p_fmt->i_cat == VIDEO_ES ) )
    {
        if( p_sys->p_pcr_input )
        {
            /* There was already a PCR stream, so clean context */
1087
            /* FIXME */
1088 1089 1090
        }
        p_sys->i_pcr_pid   = p_stream->i_pid;
        p_sys->p_pcr_input = p_input;
1091 1092

        msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
1093 1094 1095
    }

    return VLC_SUCCESS;
1096 1097
}

1098 1099 1100
/*****************************************************************************
 * DelStream: called before a stream deletion
 *****************************************************************************/
1101
static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
1102
{
1103 1104
    sout_mux_sys_t  *p_sys = p_mux->p_sys;
    ts_stream_t     *p_stream;
1105
    vlc_value_t     val;
1106

1107
    p_stream = (ts_stream_t*)p_input->p_sys;
1108
    msg_Dbg( p_mux, "removing input pid=%d", p_stream->i_pid );
1109

1110 1111 1112 1113 1114 1115
    if( p_sys->i_pcr_pid == p_stream->i_pid )
    {
        int i;

        /* Find a new pcr stream (Prefer Video Stream) */
        p_sys->i_pcr_pid = 0x1fff;
1116
        p_sys->p_pcr_input = NULL;
1117 1118 1119 1120 1121 1122 1123 1124 1125
        for( i = 0; i < p_mux->i_nb_inputs; i++ )
        {
            if( p_mux->pp_inputs[i] == p_input )
            {
                continue;
            }

            if( p_mux->pp_inputs[i]->p_fmt->i_cat == VIDEO_ES )
            {
1126 1127
                p_sys->i_pcr_pid  =
                    ((ts_stream_t*)p_mux->pp_inputs[i]->p_sys)->i_pid;
1128 1129 1130
                p_sys->p_pcr_input= p_mux->pp_inputs[i];
                break;
            }
1131 1132
            else if( p_mux->pp_inputs[i]->p_fmt->i_cat != SPU_ES &&
                     p_sys->i_pcr_pid == 0x1fff )
1133
            {
1134 1135
                p_sys->i_pcr_pid  =
                    ((ts_stream_t*)p_mux->pp_inputs[i]->p_sys)->i_pid;
1136 1137 1138 1139 1140 1141
                p_sys->p_pcr_input= p_mux->pp_inputs[i];
            }
        }
        if( p_sys->p_pcr_input )
        {
            /* Empty TS buffer */
1142
            /* FIXME */
1143
        }
1144
        msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
1145 1146
    }

1147 1148 1149
    /* Empty all data in chain_pes */
    BufferChainClean( p_mux->p_sout, &p_stream->chain_pes );

1150 1151 1152 1153
    if( p_stream->p_decoder_specific_info )
    {
        free( p_stream->p_decoder_specific_info );
    }
1154 1155 1156
    if( p_stream->i_stream_id == 0xfa ||
        p_stream->i_stream_id == 0xfb ||
        p_stream->i_stream_id == 0xfe )
1157
    {
1158
        p_sys->i_mpeg4_streams--;
1159
    }
1160 1161 1162

    var_Get( p_mux, SOUT_CFG_PREFIX "pid-video", &val );
    if( val.i_int > 0 )
1163
    {
1164
        int i_pid_video = val.i_int;
1165 1166 1167
        if ( i_pid_video == p_stream->i_pid )
        {
            p_sys->i_pid_video = i_pid_video;
1168
            msg_Dbg( p_mux, "freeing video PID %d", i_pid_video );
1169 1170
        }
    }
1171 1172
    var_Get( p_mux, SOUT_CFG_PREFIX "pid-audio", &val );
    if( val.i_int > 0 )
1173
    {
1174
        int i_pid_audio = val.i_int;
1175 1176 1177
        if ( i_pid_audio == p_stream->i_pid )
        {
            p_sys->i_pid_audio = i_pid_audio;
1178
            msg_Dbg( p_mux, "freeing audio PID %d", i_pid_audio );
1179 1180
        }
    }
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
    var_Get( p_mux, SOUT_CFG_PREFIX "pid-spu", &val );
    if( val.i_int > 0 )
    {
        int i_pid_spu = val.i_int;
        if ( i_pid_spu == p_stream->i_pid )
        {
            p_sys->i_pid_spu = i_pid_spu;
            msg_Dbg( p_mux, "freeing spu PID %d", i_pid_spu );
        }
    }
Laurent Aimar's avatar
Laurent Aimar committed
1191 1192
    free( p_stream );

1193
    /* We only change PMT version (PAT isn't changed) */
1194
    p_sys->i_pmt_version_number++; p_sys->i_pmt_version_number %= 32;
1195

1196
    return VLC_SUCCESS;
1197 1198
}

1199 1200 1201 1202 1203 1204 1205 1206
/*****************************************************************************
 * Mux: Call each time there is new data for at least one stream
 *****************************************************************************
 *
 *****************************************************************************/
static int Mux( sout_mux_t *p_mux )
{
    sout_mux_sys_t  *p_sys = p_mux->p_sys;
1207
    ts_stream_t     *p_pcr_stream;
1208

1209 1210
    if( p_sys->i_pcr_pid == 0x1fff )
    {
1211
        msg_Dbg( p_mux, "waiting for PCR streams" );
1212 1213 1214
        msleep( 1000 );
        return VLC_SUCCESS;
    }
1215
    p_pcr_stream = (ts_stream_t*)p_sys->p_pcr_input->p_sys;
1216

1217
    for( ;; )
1218
    {
1219 1220 1221 1222 1223
        sout_buffer_chain_t chain_ts;
        int                 i_packet_count;
        int                 i_packet_pos;
        mtime_t             i_pcr_dts;
        mtime_t             i_pcr_length;
1224
        mtime_t             i_shaping_delay;
1225
        int i;
1226

1227 1228 1229 1230 1231 1232 1233 1234 1235
        if( p_pcr_stream->b_key_frame )
        {
            i_shaping_delay = p_pcr_stream->i_pes_length;
        }
        else
        {
            i_shaping_delay = p_sys->i_shaping_delay;
        }

1236 1237
        /* 1: get enough PES packet for all input */
        for( ;; )
1238
        {
1239
            vlc_bool_t b_ok = VLC_TRUE;
1240
            block_t *p_data;
1241

1242
            /* Accumulate enough data in the pcr stream (>i_shaping_delay) */
1243
            /* Accumulate enough data in all other stream ( >= length of pcr)*/
1244
            for( i = -1; i < p_mux->i_nb_inputs; i++ )
1245
            {
1246 1247
                sout_input_t *p_input;
                ts_stream_t *p_stream;
1248
                int64_t i_spu_delay = 0;
1249

1250 1251 1252 1253 1254 1255 1256 1257
                if( i == -1 )
                    p_input = p_sys->p_pcr_input;
                else if( p_mux->pp_inputs[i]->p_sys == p_pcr_stream )
                    continue;
                else
                    p_input = p_mux->pp_inputs[i];
                p_stream = (ts_stream_t*)p_input->p_sys;

1258 1259 1260 1261
                if( ( p_stream == p_pcr_stream &&
                      p_stream->i_pes_length < i_shaping_delay ) ||
                    p_stream->i_pes_dts + p_stream->i_pes_length <
                    p_pcr_stream->i_pes_dts + p_pcr_stream->i_pes_length )
1262 1263
                {
                    /* Need more data */
1264
                    if( p_input->p_fifo->i_depth <= 1 )
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
                    {
                        if( p_input->p_fmt->i_cat == AUDIO_ES ||
                            p_input->p_fmt->i_cat == VIDEO_ES )
                        {
                            /* We need more data */
                            return VLC_SUCCESS;
                        }
                        else if( p_input->p_fifo->i_depth <= 0 )
                        {
                            /* spu, only one packet is needed */
                            continue;
                        }
1277 1278 1279 1280 1281 1282 1283 1284
                        else
                        {
                            /* Don't mux the SPU yet if it is too early */
                            block_t *p_spu = block_FifoShow( p_input->p_fifo );

                            i_spu_delay =
                                p_spu->i_dts - p_pcr_stream->i_pes_dts;

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
                            if( i_spu_delay > i_shaping_delay &&
                                i_spu_delay < I64C(100000000) )
                                continue;

                            if ( i_spu_delay >= I64C(100000000)
                                  || i_spu_delay < 10000 )
                            {
                                BufferChainClean( p_mux->p_sout,
                                                  &p_stream->chain_pes );
                                p_stream->i_pes_dts = 0;
                                p_stream->i_pes_used = 0;
                                p_stream->i_pes_length = 0;
                                continue;
                            }
1299
                        }
1300 1301 1302
                    }
                    b_ok = VLC_FALSE;

1303 1304 1305 1306 1307 1308 1309
                    if( p_stream == p_pcr_stream
                         || p_input->p_fmt->i_codec !=
                             VLC_FOURCC('m', 'p', 'g', 'a') )
                        p_data = block_FifoGet( p_input->p_fifo );
                    else
                        p_data = FixPES( p_mux, p_input->p_fifo );

1310 1311
                    if( p_input->p_fifo->i_depth > 0 &&
                        p_input->p_fmt->i_cat != SPU_ES )
Laurent Aimar's avatar
Laurent Aimar committed
1312
                    {
1313
                        block_t *p_next = block_FifoShow( p_input->p_fifo );
Laurent Aimar's avatar
Laurent Aimar committed
1314 1315
                        p_data->i_length = p_next->i_dts - p_data->i_dts;
                    }
1316 1317
                    else if( p_input->p_fmt->i_codec !=
                               VLC_FOURCC('s', 'u', 'b', 't' ) )
1318
                        p_data->i_length = 1000;
1319

1320
                    if( ( p_pcr_stream->i_pes_dts > 0 &&
1321
                          p_data->i_dts - 10000000 > p_pcr_stream->i_pes_dts +
1322
                          p_pcr_stream->i_pes_length ) ||
1323
                        p_data->i_dts < p_stream->i_pes_dts ||
1324 1325
                        ( p_stream->i_pes_dts > 0 &&
                          p_input->p_fmt->i_cat != SPU_ES &&
1326
                          p_data->i_dts - 10000000 > p_stream->i_pes_dts +
1327
                          p_stream->i_pes_length ) )
1328
                    {
1329 1330 1331
                        msg_Warn( p_mux, "packet with too strange dts "
                                  "(dts="I64Fd",old="I64Fd",pcr="I64Fd")",
                                  p_data->i_dts, p_stream->i_pes_dts,
1332
                                  p_pcr_stream->i_pes_dts );
1333
                        block_Release( p_data );
1334

1335 1336
                        BufferChainClean( p_mux->p_sout,
                                          &p_stream->chain_pes );
1337 1338 1339 1340
                        p_stream->i_pes_dts = 0;
                        p_stream->i_pes_used = 0;
                        p_stream->i_pes_length = 0;

1341 1342 1343 1344 1345 1346 1347 1348
                        if( p_input->p_fmt->i_cat != SPU_ES )
                        {
                            BufferChainClean( p_mux->p_sout,
                                              &p_pcr_stream->chain_pes );
                            p_pcr_stream->i_pes_dts = 0;
                            p_pcr_stream->i_pes_used = 0;
                            p_pcr_stream->i_pes_length = 0;
                        }
1349 1350 1351
                    }
                    else
                    {
1352 1353
                        int i_header_size = 0;
                        int b_data_alignment = 0;
1354 1355
                        if( p_input->p_fmt->i_cat == SPU_ES )
                        {
1356 1357
                            if( p_input->p_fmt->i_codec ==
                                VLC_FOURCC('s','u','b','t') )
1358 1359
                            {
                                /* Prepend header */
1360 1361 1362 1363 1364 1365
                                p_data = block_Realloc( p_data, 2,
                                                        p_data->i_buffer );
                                p_data->p_buffer[0] =
                                    ( (p_data->i_buffer - 2) >> 8) & 0xff;
                                p_data->p_buffer[1] =
                                    ( (p_data->i_buffer - 2)     ) & 0xff;
1366 1367

                                /* remove trailling \0 if any */
1368 1369 1370
                                if( p_data->i_buffer > 2 &&
                                    p_data->p_buffer[p_data->i_buffer -1] ==
                                    '\0' )
1371
                                    p_data->i_buffer--;
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388

                                /* Append a empty sub (sub text only) */
                                if( p_data->i_length > 0 &&
                                    !( p_data->i_buffer == 1 &&
                                       *p_data->p_buffer == ' ' ) )
                                {
                                    block_t *p_spu = block_New( p_mux, 3 );

                                    p_spu->i_dts = p_spu->i_pts =
                                        p_data->i_dts + p_data->i_length;
                                    p_spu->i_length = 1000;

                                    p_spu->p_buffer[0] = 0;
                                    p_spu->p_buffer[1] = 1;
                                    p_spu->p_buffer[2] = ' ';

                                    E_(EStoPES)( p_mux->p_sout, &p_spu, p_spu,
1389
                                                 p_input->p_fmt,
1390
                                                 p_stream->i_stream_id, 1,
1391
                                                 0, 0, 0 );
1392 1393
                                    p_data->p_next = p_spu;
                                }
1394
                            }
1395 1396 1397 1398 1399 1400 1401
                            else if( p_input->p_fmt->i_codec ==
                                       VLC_FOURCC('t','e','l','x') )
                            {
                                /* EN 300 472 */
                                i_header_size = 0x24;
                                b_data_alignment = 1;
                            }
1402
                        }
1403 1404
                        else if( p_data->i_length < 0 ||
                                 p_data->i_length > 2000000 )
1405
                        {
1406 1407
                            /* FIXME choose a better value, but anyway we
                             * should never have to do that */
1408 1409
                            p_data->i_length = 1000;
                        }
1410

1411 1412 1413 1414 1415 1416 1417
                        p_stream->i_pes_length += p_data->i_length;
                        if( p_stream->i_pes_dts == 0 )
                        {
                            p_stream->i_pes_dts = p_data->i_dts;
                        }

                        /* Convert to pes */
1418 1419
                        if( p_stream->i_stream_id == 0xa0 &&
                            p_data->i_pts <= 0 )
1420
                        {
1421 1422
                            /* XXX yes I know, it's awfull, but it's needed,
                             * so don't remove it ... */
1423 1424
                            p_data->i_pts = p_data->i_dts;
                        }
1425

1426
                        E_( EStoPES )( p_mux->p_sout, &p_data, p_data,
1427
                                       p_input->p_fmt, p_stream->i_stream_id,
1428
                                       1, b_data_alignment, i_header_size, 0 );
1429 1430

                        BufferChainAppend( &p_stream->chain_pes, p_data );
1431 1432

                        if( p_sys->b_use_key_frames && p_stream == p_pcr_stream
1433 1434 1435
                            && (p_data->i_flags & BLOCK_FLAG_TYPE_I)
                            && !(p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME)
                            && (p_stream->i_pes_length > 400000) )
1436 1437 1438 1439
                        {
                            i_shaping_delay = p_stream->i_pes_length;
                            p_stream->b_key_frame = 1;
                        }
1440 1441 1442 1443 1444 1445 1446 1447
                    }
                }
            }

            if( b_ok )
            {
                break;
            }
1448
        }
1449

1450 1451 1452
        /* save */
        i_pcr_dts      = p_pcr_stream->i_pes_dts;
        i_pcr_length   = p_pcr_stream->i_pes_length;
1453
        p_pcr_stream->b_key_frame = 0;
1454 1455 1456 1457 1458

        /* msg_Dbg( p_mux, "starting muxing %lldms", i_pcr_length / 1000 ); */
        /* 2: calculate non accurate total size of muxed ts */
        i_packet_count = 0;
        for( i = 0; i < p_mux->i_nb_inputs; i++ )
1459
        {
1460
            ts_stream_t *p_stream = (ts_stream_t*)p_mux->pp_inputs[i]->p_sys;
1461
            block_t *p_pes;
1462

1463
            /* False for pcr stream but it will be enough to do PCR algo */
1464 1465
            for( p_pes = p_stream->chain_pes.p_first; p_pes != NULL;
                 p_pes = p_pes->p_next )
1466
            {
1467
                int i_size = p_pes->i_buffer;
1468 1469
                if( p_pes->i_dts + p_pes->i_length >
                    p_pcr_stream->i_pes_dts + p_pcr_stream->i_pes_length )
1470
                {
1471 1472
                    mtime_t i_frag = p_pcr_stream->i_pes_dts +
                        p_pcr_stream->i_pes_length - p_pes->i_dts;
1473 1474 1475 1476 1477
                    if( i_frag < 0 )
                    {
                        /* Next stream */
                        break;
                    }
1478
                    i_size = p_pes->i_buffer * i_frag / p_pes->i_length;
1479 1480 1481
                }
                i_packet_count += ( i_size + 183 ) / 184;
            }
1482
        }
1483
        /* add overhead for PCR (not really exact) */
1484
        i_packet_count += (8 * i_pcr_length / p_sys->i_pcr_delay + 175) / 176;
1485 1486 1487 1488

        /* 3: mux PES into TS */
        BufferChainInit( &chain_ts );
        /* append PAT/PMT  -> FIXME with big pcr delay it won't have enough pat/pmt */
1489
        GetPAT( p_mux, &chain_ts );
1490 1491 1492 1493
        GetPMT( p_mux, &chain_ts );
        i_packet_pos = 0;
        i_packet_count += chain_ts.i_depth;
        /* msg_Dbg( p_mux, "estimated pck=%d", i_packet_count ); */
1494

1495
        for( ;; )
1496
        {
1497 1498 1499
            int         i_stream;
            mtime_t     i_dts;
            ts_stream_t *p_stream;
1500
            sout_input_t *p_input;
1501
            block_t *p_ts;
1502
            vlc_bool_t   b_pcr;
1503

1504
            /* Select stream (lowest dts) */
1505
            for( i = 0, i_stream = -1, i_dts = 0; i < p_mux->i_nb_inputs; i++ )
1506
            {
1507
                p_input = p_mux->pp_inputs[i];
1508 1509 1510
                p_stream = (ts_stream_t*)p_mux->pp_inputs[i]->p_sys;

                if( p_stream->i_pes_dts == 0 )
1511
                {
1512
                    continue;
1513
                }
1514 1515 1516

                if( i_stream == -1 ||
                    p_stream->i_pes_dts < i_dts )
1517
                {
1518 1519
                    i_stream = i;
                    i_dts = p_stream->i_pes_dts;
1520 1521
                }
            }
1522
            if( i_stream == -1 || i_dts > i_pcr_dts + i_pcr_length )
1523 1524 1525 1526
            {
                break;
            }
            p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
1527

1528 1529 1530
            /* do we need to issue pcr */
            b_pcr = VLC_FALSE;
            if( p_stream == p_pcr_stream &&
1531 1532
                i_pcr_dts + i_packet_pos * i_pcr_length / i_packet_count >=
                p_sys->i_pcr + p_sys->i_pcr_delay )
1533
            {
1534
                b_pcr = VLC_TRUE;
1535 1536
                p_sys->i_pcr = i_pcr_dts + i_packet_pos *
                    i_pcr_length / i_packet_count;
1537
            }
1538

1539 1540
            /* Build the TS packet */
            p_ts = TSNew( p_mux, p_stream, b_pcr );
1541
            if( p_sys->csa != NULL &&
1542 1543
                 (p_input->p_fmt->i_cat != AUDIO_ES || p_sys->b_crypt_audio) &&
                 (p_input->p_fmt->i_cat != VIDEO_ES || p_sys->b_crypt_video) )
1544
            {
1545
                p_ts->i_flags |= BLOCK_FLAG_SCRAMBLED;
1546
            }
1547
            i_packet_pos++;
1548

1549 1550 1551
            /* */
            BufferChainAppend( &chain_ts, p_ts );
        }
1552

1553
        /* 4: date and send */
1554 1555 1556
        TSSchedule( p_mux, &chain_ts, i_pcr_length, i_pcr_dts );
    }
}
1557

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
#define STD_PES_PAYLOAD 170
static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo )
{
    block_t *p_data;
    int i_size;

    p_data = block_FifoShow( p_fifo );
    i_size = p_data->i_buffer;

    if( i_size == STD_PES_PAYLOAD )
    {
        return block_FifoGet( p_fifo );
    }
    else if( i_size > STD_PES_PAYLOAD )
    {
        block_t *p_new = block_New( p_mux, STD_PES_PAYLOAD );
        p_mux->p_vlc->pf_memcpy( p_new->p_buffer, p_data->p_buffer, STD_PES_PAYLOAD );
        p_new->i_pts = p_data->i_pts;
        p_new->i_dts = p_data->i_dts;
        p_new->i_length = p_data->i_length * STD_PES_PAYLOAD
                            / p_data->i_buffer;
        p_data->i_buffer -= STD_PES_PAYLOAD;
        p_data->p_buffer += STD_PES_PAYLOAD;
        p_data->i_pts += p_new->i_length;
        p_data->i_dts += p_new->i_length;
        p_data->i_length -= p_new->i_length;
        p_data->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
        return p_new;
    }
    else
    {
        block_t *p_next;
1590 1591
        int i_copy;

1592 1593 1594 1595 1596 1597 1598 1599 1600
        p_data = block_FifoGet( p_fifo );
        p_data = block_Realloc( p_data, 0, STD_PES_PAYLOAD );
        p_next = block_FifoShow( p_fifo );
        if ( p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME )
        {
            p_data->i_flags &= ~BLOCK_FLAG_NO_KEYFRAME;
            p_data->i_pts = p_next->i_pts;
            p_data->i_dts = p_next->i_dts;
        }
1601 1602
        i_copy = __MIN( STD_PES_PAYLOAD - i_size, p_next->i_buffer );

1603
        p_mux->p_vlc->pf_memcpy( &p_data->p_buffer[i_size], p_next->p_buffer,
1604 1605 1606 1607 1608 1609
                                 i_copy );
        p_next->i_pts += p_next->i_length * i_copy / p_next->i_buffer;
        p_next->i_dts += p_next->i_length * i_copy / p_next->i_buffer;
        p_next->i_length -= p_next->i_length * i_copy / p_next->i_buffer;
        p_next->i_buffer -= i_copy;
        p_next->p_buffer += i_copy;
1610
        p_next->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1611 1612 1613 1614 1615 1616

        if( !p_next->i_buffer )
        {
            p_next = block_FifoGet( p_fifo );
            block_Release( p_next );
        }
1617 1618 1619 1620
        return p_data;
    }
}

1621 1622 1623 1624 1625 1626 1627
static void TSSchedule( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
                        mtime_t i_pcr_length, mtime_t i_pcr_dts )
{
    sout_mux_sys_t  *p_sys = p_mux->p_sys;
    sout_buffer_chain_t new_chain;
    int i_packet_count = p_chain_ts->i_depth;
    int i;
1628

1629 1630 1631 1632 1633 1634 1635 1636 1637
    BufferChainInit( &new_chain );

    if ( i_pcr_length <= 0 )
    {
        i_pcr_length = i_packet_count;
    }

    for( i = 0; i < i_packet_count; i++ )
    {
1638
        block_t *p_ts = BufferChainGet( p_chain_ts );
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
        mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;

        BufferChainAppend( &new_chain, p_ts );

        if( p_ts->i_dts &&
            p_ts->i_dts + p_sys->i_dts_delay * 2/3 < i_new_dts )
        {
            mtime_t i_max_diff = i_new_dts - p_ts->i_dts;
            mtime_t i_cut_dts = p_ts->i_dts;

            p_ts = BufferChainPeek( p_chain_ts );
            i++;
            i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
            while ( p_ts != NULL && i_new_dts - p_ts->i_dts >= i_max_diff )
1653
            {
1654 1655 1656 1657 1658 1659 1660 1661
                p_ts = BufferChainGet( p_chain_ts );
                i_max_diff = i_new_dts - p_ts->i_dts;
                i_cut_dts = p_ts->i_dts;
                BufferChainAppend( &new_chain, p_ts );

                p_ts = BufferChainPeek( p_chain_ts );
                i++;
                i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1662
            }
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
            msg_Dbg( p_mux, "adjusting rate at "I64Fd"/"I64Fd" (%d/%d)",
                     i_cut_dts - i_pcr_dts, i_pcr_length, new_chain.i_depth,
                     p_chain_ts->i_depth );
            if ( new_chain.i_depth )
                TSDate( p_mux, &new_chain,
                        i_cut_dts - i_pcr_dts,
                        i_pcr_dts );
            if ( p_chain_ts->i_depth )
                TSSchedule( p_mux,
                            p_chain_ts, i_pcr_dts + i_pcr_length - i_cut_dts,
                            i_cut_dts );
            return;
        }
    }

    if ( new_chain.i_depth )
        TSDate( p_mux, &new_chain, i_pcr_length, i_pcr_dts );
}

static void TSDate( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
                    mtime_t i_pcr_length, mtime_t i_pcr_dts )
{
    sout_mux_sys_t  *p_sys = p_mux->p_sys;
    int i_packet_count = p_chain_ts->i_depth;
    int i;
1688

1689
    if ( i_pcr_length / 1000 > 0 )
1690 1691 1692 1693 1694
    {
        int i_bitrate = ((uint64_t)i_packet_count * 188 * 8000)
                          / (uint64_t)(i_pcr_length / 1000);
        if ( p_sys->i_bitrate_max && p_sys->i_bitrate_max < i_bitrate )
        {
1695 1696 1697 1698
            msg_Warn( p_mux, "max bitrate exceeded at "I64Fd
                      " (%d bi/s for %d pkt in "I64Fd" us)",
                      i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
                      i_bitrate, i_packet_count, i_pcr_length);
1699 1700 1701 1702
        }
#if 0
        else
        {
1703 1704 1705 1706
            msg_Dbg( p_mux, "starting at "I64Fd
                     " (%d bi/s for %d packets in "I64Fd" us)",
                     i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
                     i_bitrate, i_packet_count, i_pcr_length);
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
        }
#endif
    }
    else
    {
        /* This shouldn't happen, but happens in some rare heavy load
         * and packet losses conditions. */
        i_pcr_length = i_packet_count;
    }

    /* msg_Dbg( p_mux, "real pck=%d", i_packet_count ); */
    for( i = 0; i < i_packet_count; i++ )
    {
1720
        block_t *p_ts = BufferChainGet( p_chain_ts );
1721
        mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1722

1723 1724 1725
        p_ts->i_dts    = i_new_dts;
        p_ts->i_length = i_pcr_length / i_packet_count;

1726
        if( p_ts->i_flags & BLOCK_FLAG_CLOCK )
1727 1728 1729
        {
            /* msg_Dbg( p_mux, "pcr=%lld ms", p_ts->i_dts / 1000 ); */
            TSSetPCR( p_ts, p_ts->i_dts - p_sys->i_dts_delay );
1730
        }
1731
        if( p_ts->i_flags & BLOCK_FLAG_SCRAMBLED )
1732
        {
1733
            csa_Encrypt( p_sys->csa, p_ts->p_buffer, p_sys->i_csa_pkt_size, 0 );
1734 1735 1736 1737 1738 1739
        }

        /* latency */
        p_ts->i_dts += p_sys->i_shaping_delay * 3 / 2;

        sout_AccessOutWrite( p_mux->p_access, p_ts );
1740
    }
1741
}
1742

1743 1744
static block_t *TSNew( sout_mux_t *p_mux, ts_stream_t *p_stream,
                       vlc_bool_t b_pcr )
1745
{
1746 1747
    block_t *p_pes = p_stream->chain_pes.p_first;
    block_t *p_ts;
1748

1749 1750
    vlc_bool_t b_new_pes = VLC_FALSE;
    vlc_bool_t b_adaptation_field = VLC_FALSE;
1751

1752 1753 1754 1755 1756 1757 1758
    int        i_payload_max = 184 - ( b_pcr ? 8 : 0 );
    int        i_payload;

    if( p_stream->i_pes_used <= 0 )
    {
        b_new_pes = VLC_TRUE;
    }
1759 1760
    i_payload = __MIN( (int)p_pes->i_buffer - p_stream->i_pes_used,
                       i_payload_max );
1761

1762 1763 1764 1765
    if( b_pcr || i_payload < i_payload_max )
    {
        b_adaptation_field = VLC_TRUE;
    }
1766

1767
    p_ts = block_New( p_mux, 188 );
1768
    p_ts->i_dts = p_pes->i_dts;
1769

1770
    p_ts->p_buffer[0] = 0x47;
1771 1772
    p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 ) |
        ( ( p_stream->i_pid >> 8 )&0x1f );
1773
    p_ts->p_buffer[2] = p_stream->i_pid & 0xff;
1774 1775
    p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 ) |
        p_stream->i_continuity_counter;
1776 1777

    p_stream->i_continuity_counter = (p_stream->i_continuity_counter+1)%16;
1778
    p_stream->b_discontinuity = (p_pes->i_flags & BLOCK_FLAG_DISCONTINUITY);
1779 1780

    if( b_adaptation_field )
1781
    {
1782
        int i;
1783

1784
        if( b_pcr )
1785
        {
1786
            int     i_stuffing = i_payload_max - i_payload;
1787

1788
            p_ts->i_flags |= BLOCK_FLAG_CLOCK;
1789

1790 1791
            p_ts->p_buffer[4] = 7 + i_stuffing;
            p_ts->p_buffer[5] = 0x10;   /* flags */
1792 1793 1794 1795 1796
            if( p_stream->b_discontinuity )
            {
                p_ts->p_buffer[5] |= 0x80; /* flag TS dicontinuity */
                p_stream->b_discontinuity = VLC_FALSE;
            }            
1797 1798 1799 1800
            p_ts->p_buffer[6] = ( 0 )&0xff;
            p_ts->p_buffer[7] = ( 0 )&0xff;
            p_ts->p_buffer[8] = ( 0 )&0xff;
            p_ts->p_buffer[9] = ( 0 )&0xff;
1801
            p_ts->p_buffer[10]= ( ( 0 )&0x80 ) | 0x7e;
1802 1803 1804
            p_ts->p_buffer[11]= 0;

            for( i = 12; i < 12 + i_stuffing; i++ )
1805
            {
1806
                p_ts->p_buffer[i] = 0xff;
1807
            }
1808 1809 1810 1811 1812 1813 1814
        }
        else
        {
            int i_stuffing = i_payload_max - i_payload;

            p_ts->p_buffer[4] = i_stuffing - 1;
            if( i_stuffing > 1 )
1815
            {
1816 1817 1818 1819 1820
                p_ts->p_buffer[5] = 0x00;
                for( i = 6; i < 6 + i_stuffing - 2; i++ )
                {
                    p_ts->p_buffer[i] = 0xff;
                }
1821
            }
1822
        }
1823
    }
1824

1825
    /* copy payload */
1826 1827
    memcpy( &p_ts->p_buffer[188 - i_payload],
            &p_pes->p_buffer[p_stream->i_pes_used], i_payload );
1828

1829
    p_stream->i_pes_used += i_payload;
1830 1831 1832
    p_stream->i_pes_dts = p_pes->i_dts + p_pes->i_length *
        p_stream->i_pes_used / p_pes->i_buffer;
    p_stream->i_pes_length -= p_pes->i_length * i_payload / p_pes->i_buffer;
1833

1834
    if( p_stream->i_pes_used >= (int)p_pes->i_buffer )
1835 1836
    {
        p_pes = BufferChainGet( &p_stream->chain_pes );
1837
        block_Release( p_pes );
1838 1839 1840 1841 1842 1843 1844

        p_pes = p_stream->chain_pes.p_first;
        if( p_pes )
        {
            p_stream->i_pes_dts    = p_pes->i_dts;
            p_stream->i_pes_length = 0;
            while( p_pes )
1845
            {
1846 1847 1848
                p_stream->i_pes_length += p_pes->i_length;

                p_pes = p_pes->p_next;
1849
            }
1850
        }
1851
        else
1852
        {
1853 1854
            p_stream->i_pes_dts = 0;
            p_stream->i_pes_length = 0;
1855
        }
1856
        p_stream->i_pes_used = 0;
1857 1858
    }

1859 1860
    return p_ts;
}
1861

1862
static void TSSetPCR( block_t *p_ts, mtime_t i_dts )
1863
{
1864
    mtime_t i_pcr = 9 * i_dts / 100;
1865

1866 1867 1868 1869 1870
    p_ts->p_buffer[6]  = ( i_pcr >> 25 )&0xff;
    p_ts->p_buffer[7]  = ( i_pcr >> 17 )&0xff;
    p_ts->p_buffer[8]  = ( i_pcr >> 9  )&0xff;
    p_ts->p_buffer[9]  = ( i_pcr >> 1  )&0xff;
    p_ts->p_buffer[10]|= ( i_pcr << 7  )&0x80;
1871 1872
}

1873
#if 0
1874 1875 1876
static void TSSetConstraints( sout_mux_t *p_mux, sout_buffer_chain_t *c,
                              mtime_t i_length, int i_bitrate_min,
                              int i_bitrate_max )
1877
{
1878 1879 1880 1881 1882 1883
    sout_mux_sys_t  *p_sys = p_mux->p_sys;
    sout_buffer_chain_t s = *c;

    int i_packets = 0;
    int i_packets_min = 0;
    int i_packets_max = 0;
1884

1885
    if( i_length <= 0 )
1886
    {
1887
        return;
1888 1889
    }

1890 1891 1892 1893 1894
    i_packets     = c->i_depth;
    i_packets_min = ( (int64_t)i_bitrate_min * i_length / 8 / 1000000  + 187 ) / 188;
    i_packets_max = ( (int64_t)i_bitrate_max * i_length / 8 / 1000000  + 187 ) / 188;

    if( i_packets < i_packets_min && i_packets_min > 0 )
1895
    {
1896
        block_t *p_pk;
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
        int i_div = ( i_packets_min - i_packets ) / i_packets;
        int i_mod = ( i_packets_min - i_packets ) % i_packets;
        int i_rest = 0;

        /* We need to pad with null packets (pid=0x1fff)
         * We try to melt null packets with true packets */
        msg_Dbg( p_mux,
                 "packets=%d but min=%d -> adding %d packets of padding",
                 i_packets, i_packets_min, i_packets_min - i_packets );

        BufferChainInit( c );
        while( ( p_pk = BufferChainGet( &s ) ) )
        {
            int i, i_null;

            BufferChainAppend( c, p_pk );

            i_null = i_div + ( i_rest + i_mod ) / i_packets;

            for( i = 0; i < i_null; i++ )
            {
1918
                block_t *p_null;
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930

                p_null = sout_BufferNew( p_mux->p_sout, 188 );
                p_null->p_buffer[0] = 0x47;
                p_null->p_buffer[1] = 0x1f;
                p_null->p_buffer[2] = 0xff;
                p_null->p_buffer[3] = 0x10 | p_sys->i_null_continuity_counter;
                memset( &p_null->p_buffer[4], 0, 184 );
                p_sys->i_null_continuity_counter =
                    ( p_sys->i_null_continuity_counter + 1 ) % 16;

                BufferChainAppend( c, p_null );
            }
1931

1932 1933 1934 1935 1936
            i_rest = ( i_rest + i_mod ) % i_packets;
        }
    }
    else if( i_packets > i_packets_max && i_packets_max > 0 )
    {
1937
        block_t *p_pk;
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
        int           i;

        /* Arg, we need to drop packets, I don't do something clever (like
         * dropping complete pid, b frames, ... ), I just get the right amount
         * of packets and discard the others */
        msg_Warn( p_mux,
                  "packets=%d but max=%d -> removing %d packets -> stream broken",
                  i_packets, i_packets_max, i_packets - i_packets_max );

        BufferChainInit( c );
        for( i = 0; i < i_packets_max; i++ )
        {
            BufferChainAppend( c, BufferChainGet( &s ) );
        }

        while( ( p_pk = BufferChainGet( &s ) ) )
        {
            sout_BufferDelete( p_mux->p_sout, p_pk );
        }
1957 1958
    }
}
1959
#endif
1960

1961
static void PEStoTS( sout_instance_t *p_sout,
1962
                     sout_buffer_chain_t *c, block_t *p_pes,
1963
                     ts_stream_t *p_stream )
1964 1965 1966 1967
{
    uint8_t *p_data;
    int     i_size;
    int     b_new_pes;
1968

1969
    /* get PES total size */
1970
    i_size = p_pes->i_buffer;
1971
    p_data = p_pes->p_buffer;
1972

1973 1974 1975 1976 1977 1978
    b_new_pes = VLC_TRUE;

    for( ;; )
    {
        int           b_adaptation_field;
        int           i_copy;
1979
        block_t *p_ts;
1980

1981
        p_ts = block_New( p_sout, 188 );
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
        /* write header
         * 8b   0x47    sync byte
         * 1b           transport_error_indicator
         * 1b           payload_unit_start
         * 1b           transport_priority
         * 13b          pid
         * 2b           transport_scrambling_control
         * 2b           if adaptation_field 0x03 else 0x01
         * 4b           continuity_counter
         */

1993 1994
        i_copy    = __MIN( i_size, 184 );
        b_adaptation_field = i_size < 184 ? VLC_TRUE : VLC_FALSE;
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006

        p_ts->p_buffer[0] = 0x47;
        p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 )|
                            ( ( p_stream->i_pid >> 8 )&0x1f );
        p_ts->p_buffer[2] = p_stream->i_pid & 0xff;
        p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 )|
                            p_stream->i_continuity_counter;

        b_new_pes = VLC_FALSE;
        p_stream->i_continuity_counter = (p_stream->i_continuity_counter+1)%16;

        if( b_adaptation_field )
2007
        {
2008
            int i_stuffing = 184 - i_copy;
2009 2010
            int i;

2011 2012
            p_ts->p_buffer[4] = i_stuffing - 1;
            if( i_stuffing > 1 )
2013
            {
2014
                p_ts->p_buffer[5] = 0x00;
2015 2016 2017 2018 2019
                if( p_stream->b_discontinuity )
                {
                    p_ts->p_buffer[5] |= 0x80;
                    p_stream->b_discontinuity = VLC_FALSE;
                }
2020
                for( i = 6; i < 6 + i_stuffing - 2; i++ )
2021 2022 2023 2024
                {
                    p_ts->p_buffer[i] = 0xff;
                }
            }
2025
        }
2026 2027 2028 2029
        /* copy payload */
        memcpy( &p_ts->p_buffer[188 - i_copy], p_data, i_copy );
        p_data += i_copy;
        i_size -= i_copy;
2030

2031
        BufferChainAppend( c, p_ts );
2032

2033 2034
        if( i_size <= 0 )
        {
2035
            block_t *p_next = p_pes->p_next;
2036 2037

            p_pes->p_next = NULL;
2038
            block_Release( p_pes );
2039 2040 2041 2042 2043 2044
            if( p_next == NULL )
            {
                break;
            }
            b_new_pes = VLC_TRUE;
            p_pes = p_next;
2045
            i_size = p_pes->i_buffer;
2046 2047
            p_data = p_pes->p_buffer;
        }
2048 2049
    }

2050
    return;
2051 2052
}

2053
static block_t *WritePSISection( sout_instance_t *p_sout,
2054
                                       dvbpsi_psi_section_t* p_section )
2055
{
2056
    block_t   *p_psi, *p_first = NULL;
2057

2058
    while( p_section )
2059
    {
2060
        int             i_size;
2061

2062
        i_size =  (uint32_t)( p_section->p_payload_end - p_section->p_data )+
2063 2064
                  ( p_section->b_syntax_indicator ? 4 : 0 );

2065
        p_psi = block_New( p_sout, i_size + 1 );
2066 2067 2068
        p_psi->i_pts = 0;
        p_psi->i_dts = 0;
        p_psi->i_length = 0;
2069
        p_psi->i_buffer = i_size + 1;
2070

2071
        p_psi->p_buffer[0] = 0; /* pointer */
2072 2073 2074 2075
        memcpy( p_psi->p_buffer + 1,
                p_section->p_data,
                i_size );

2076
        block_ChainAppend( &p_first, p_psi );
2077 2078

        p_section = p_section->p_next;
2079
    }
2080 2081

    return( p_first );
2082 2083
}

2084 2085
static void GetPAT( sout_mux_t *p_mux,
                    sout_buffer_chain_t *c )
2086
{
2087
    sout_mux_sys_t       *p_sys = p_mux->p_sys;
2088
    block_t              *p_pat;
2089 2090
    dvbpsi_pat_t         pat;
    dvbpsi_psi_section_t *p_section;
2091
    int i;
2092

2093
    dvbpsi_InitPAT( &pat, p_sys->i_tsid, p_sys->i_pat_version_number,
2094
                    1 );      /* b_current_next */
2095 2096 2097 2098 2099
    /* add all programs */
    for ( i = 0; i < p_sys->i_num_pmt; i++ )
        dvbpsi_PATAddProgram( &pat,
                              p_sys->i_pmt_program_number[i],
                              p_sys->pmt[i].i_pid );   
2100

2101
    p_section = dvbpsi_GenPATSections( &pat,
2102
                                       0 );     /* max program per section */
2103

2104
    p_pat = WritePSISection( p_mux->p_sout, p_section );
2105

2106
    PEStoTS( p_mux->p_sout, c, p_pat, &p_sys->pat );
2107

2108 2109 2110
    dvbpsi_DeletePSISections( p_section );
    dvbpsi_EmptyPAT( &pat );
}
2111

2112 2113
static uint32_t GetDescriptorLength24b( int i_length )
{
2114
    uint32_t i_l1, i_l2, i_l3;
2115

2116 2117 2118
    i_l1 = i_length&0x7f;
    i_l2 = ( i_length >> 7 )&0x7f;
    i_l3 = ( i_length >> 14 )&0x7f;
2119

2120 2121 2122
    return( 0x808000 | ( i_l3 << 16 ) | ( i_l2 << 8 ) | i_l1 );
}

2123
static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c )
2124
{
2125
    sout_mux_sys_t  *p_sys = p_mux->p_sys;
2126 2127
    block_t   *p_pmt[MAX_PMT];
    block_t   *p_sdt;
2128

2129
    dvbpsi_sdt_t        sdt;
2130
    dvbpsi_pmt_es_t     *p_es;
2131 2132 2133 2134 2135 2136 2137 2138
    dvbpsi_psi_section_t *p_section[MAX_PMT], *p_section2;
    dvbpsi_sdt_service_t *p_service;
    char            *psz_sdt_desc;
    int             i_pidinput;

    int             i_stream;
    int             i;
    int             *p_usepid = NULL;
2139

2140 2141 2142 2143
    if( p_sys->dvbpmt == NULL )
        p_sys->dvbpmt = malloc( p_sys->i_num_pmt * sizeof(dvbpsi_pmt_t) ); 
    if( p_sys->b_sdt )
        dvbpsi_InitSDT( &sdt, p_sys->i_tsid, 1, 1, p_sys->i_netid ); 
2144

2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
    for( i = 0; i < p_sys->i_num_pmt; i++ )
    {
        dvbpsi_InitPMT( &p_sys->dvbpmt[i],
                        p_sys->i_pmt_program_number[i],   /* program number */
                        p_sys->i_pmt_version_number,
                        1,      /* b_current_next */
                        p_sys->i_pcr_pid );

        if( p_sys->b_sdt )
        {
            p_service = dvbpsi_SDTAddService( &sdt, 
                p_sys->i_pmt_program_number[i],  /* service id */
                0,         /* eit schedule */
                0,         /* eit present */
                4,         /* running status ("4=RUNNING") */
                0 );       /* free ca */

#define psz_sdtprov p_sys->sdt_descriptors[i].psz_provider
#define psz_sdtserv p_sys->sdt_descriptors[i].psz_service_name

            /* FIXME: Ineffecient malloc's & ugly code......  */
            if( psz_sdtprov != NULL && psz_sdtserv != NULL )
            {
                psz_sdt_desc = malloc( 3 + strlen(psz_sdtprov)
                                         + strlen(psz_sdtserv) );
                psz_sdt_desc[0] = 0x01; /* digital television service */

                /* service provider name length */
                psz_sdt_desc[1] = (char)strlen(psz_sdtprov); 
                memcpy( &psz_sdt_desc[2], psz_sdtprov, strlen(psz_sdtprov) );

                /* service name length */
                psz_sdt_desc[ 2 + strlen(psz_sdtprov) ]
                    = (char)strlen(psz_sdtserv); 
                memcpy( &psz_sdt_desc[3+strlen(psz_sdtprov)], psz_sdtserv,
                        strlen(psz_sdtserv) );

                dvbpsi_SDTServiceAddDescriptor( p_service, 0x48,
                        3 + strlen(psz_sdtprov) + strlen(psz_sdtserv),
                        psz_sdt_desc ); 
                free( psz_sdt_desc );
            }
#undef psz_sdtprov
#undef psz_sdtserv
        }
    }
2191

2192
    if( p_sys->i_mpeg4_streams > 0 )
2193 2194 2195 2196 2197
    {
        uint8_t iod[4096];
        bits_buffer_t bits;
        bits_buffer_t bits_fix_IOD;

2198 2199 2200 2201 2202
        /* Make valgrind happy : it works at byte level not bit one so
         * bit_write confuse it (but DON'T CHANGE the way that bit_write is
         * working (needed when fixing some bits) */
        memset( iod, 0, 4096 );

2203
        bits_initwrite( &bits, 4096, iod );
2204
        /* IOD_label_scope */
2205
        bits_write( &bits, 8,   0x11 );
2206
        /* IOD_label */
2207
        bits_write( &bits, 8,   0x01 );
2208
        /* InitialObjectDescriptor */
2209
        bits_align( &bits );
2210 2211
        bits_write( &bits, 8,   0x02 );     /* tag */
        bits_fix_IOD = bits;    /* save states to fix length later */
2212
        bits_write( &bits, 24,
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
            GetDescriptorLength24b( 0 ) );  /* variable length (fixed later) */
        bits_write( &bits, 10,  0x01 );     /* ObjectDescriptorID */
        bits_write( &bits, 1,   0x00 );     /* URL Flag */
        bits_write( &bits, 1,   0x00 );     /* includeInlineProfileLevelFlag */
        bits_write( &bits, 4,   0x0f );     /* reserved */
        bits_write( &bits, 8,   0xff );     /* ODProfile (no ODcapability ) */
        bits_write( &bits, 8,   0xff );     /* sceneProfile */
        bits_write( &bits, 8,   0xfe );     /* audioProfile (unspecified) */
        bits_write( &bits, 8,   0xfe );     /* visualProfile( // ) */
        bits_write( &bits, 8,   0xff );     /* graphicProfile (no ) */
2223
        for( i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
2224
        {
2225
            ts_stream_t *p_stream;
2226
            p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
2227

2228 2229 2230
            if( p_stream->i_stream_id == 0xfa ||
                p_stream->i_stream_id == 0xfb ||
                p_stream->i_stream_id == 0xfe )
2231 2232 2233 2234
            {
                bits_buffer_t bits_fix_ESDescr, bits_fix_Decoder;
                /* ES descriptor */
                bits_align( &bits );
2235
                bits_write( &bits, 8,   0x03 );     /* ES_DescrTag */
2236
                bits_fix_ESDescr = bits;
2237
                bits_write( &bits, 24,
2238 2239 2240 2241 2242 2243 2244 2245
                            GetDescriptorLength24b( 0 ) ); /* variable size */
                bits_write( &bits, 16,  p_stream->i_es_id ); 
                bits_write( &bits, 1,   0x00 );     /* streamDependency */
                bits_write( &bits, 1,   0x00 );     /* URL Flag */
                bits_write( &bits, 1,   0x00 );     /* OCRStreamFlag */
                bits_write( &bits, 5,   0x1f );     /* streamPriority */

                /* DecoderConfigDesciptor */
2246
                bits_align( &bits );
2247
                bits_write( &bits, 8,   0x04 ); /* DecoderConfigDescrTag */
2248 2249 2250 2251
                bits_fix_Decoder = bits;
                bits_write( &bits, 24,  GetDescriptorLength24b( 0 ) );
                if( p_stream->i_stream_type == 0x10 )
                {
2252 2253
                    bits_write( &bits, 8, 0x20 );   /* Visual 14496-2 */
                    bits_write( &bits, 6, 0x04 );   /* VisualStream */
2254
                }
2255 2256
                else if( p_stream->i_stream_type == 0x1b )
                {
2257 2258
                    bits_write( &bits, 8, 0x21 );   /* Visual 14496-2 */
                    bits_write( &bits, 6, 0x04 );   /* VisualStream */
2259 2260
                }
                else if( p_stream->i_stream_type == 0x11  || p_stream->i_stream_type == 0x0f )
2261
                {
2262 2263
                    bits_write( &bits, 8, 0x40 );   /* Audio 14496-3 */
                    bits_write( &bits, 6, 0x05 );   /* AudioStream */
2264
                }
2265 2266
                else if( p_stream->i_stream_type == 0x12 &&
                         p_stream->i_codec == VLC_FOURCC('s','u','b','t') )
2267
                {
2268 2269
                    bits_write( &bits, 8, 0x0B );   /* Text Stream */
                    bits_write( &bits, 6, 0x04 );   /* VisualStream */
2270
                }
2271 2272 2273 2274 2275
                else
                {
                    bits_write( &bits, 8, 0x00 );
                    bits_write( &bits, 6, 0x00 );

2276 2277
                    msg_Err( p_mux->p_sout,"Unsupported stream_type => "
                             "broken IOD" );
2278
                }
2279 2280 2281 2282 2283
                bits_write( &bits, 1,   0x00 );         /* UpStream */
                bits_write( &bits, 1,   0x01 );         /* reserved */
                bits_write( &bits, 24,  1024 * 1024 );  /* bufferSizeDB */
                bits_write( &bits, 32,  0x7fffffff );   /* maxBitrate */
                bits_write( &bits, 32,  0 );            /* avgBitrate */
2284

2285
                if( p_stream->i_decoder_specific_info > 0 )
2286 2287
                {
                    int i;
2288
                    /* DecoderSpecificInfo */
2289
                    bits_align( &bits );
2290
                    bits_write( &bits, 8,   0x05 ); /* tag */
2291 2292
                    bits_write( &bits, 24, GetDescriptorLength24b(
                                p_stream->i_decoder_specific_info ) );
2293
                    for( i = 0; i < p_stream->i_decoder_specific_info; i++ )
2294
                    {
2295 2296
                        bits_write( &bits, 8,
                            ((uint8_t*)p_stream->p_decoder_specific_info)[i] );
2297 2298 2299 2300
                    }
                }
                /* fix Decoder length */
                bits_write( &bits_fix_Decoder, 24,
2301 2302
                            GetDescriptorLength24b( bits.i_data -
                            bits_fix_Decoder.i_data - 3 ) );
2303

2304
                /* SLConfigDescriptor : predefined (0x01) */
2305
                bits_align( &bits );
2306
                bits_write( &bits, 8,   0x06 ); /* tag */
2307
                bits_write( &bits, 24,  GetDescriptorLength24b( 8 ) );
2308 2309 2310 2311 2312
                bits_write( &bits, 8,   0x01 );/* predefined */
                bits_write( &bits, 1,   0 );   /* durationFlag */
                bits_write( &bits, 32,  0 );   /* OCRResolution */
                bits_write( &bits, 8,   0 );   /* OCRLength */
                bits_write( &bits, 8,   0 );   /* InstantBitrateLength */
2313 2314
                bits_align( &bits );

2315 2316
                /* fix ESDescr length */
                bits_write( &bits_fix_ESDescr, 24,
2317 2318
                            GetDescriptorLength24b( bits.i_data -
                            bits_fix_ESDescr.i_data - 3 ) );
2319
            }
2320
        }
2321 2322 2323
        bits_align( &bits );
        /* fix IOD length */
        bits_write( &bits_fix_IOD, 24,
2324 2325
                    GetDescriptorLength24b( bits.i_data -
                                            bits_fix_IOD.i_data - 3 ) );
2326

2327 2328
#if 0//def HAVE_BSEARCH /* FIXME!!! This can't possibly work */
        i_pidinput = p_mux->pp_inputs[i]->p_fmt->i_id;
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
        p_usepid = bsearch( &i_pidinput, p_sys->pmtmap, p_sys->i_pmtslots,
                            sizeof(pmt_map_t), intcompare ); 
        p_usepid = bsearch( &p_usepid, p_sys->pmtmap, p_sys->i_num_pmt,
                            sizeof(pmt_map_t), pmtcompare ); 
        if( p_usepid != NULL )
            dvbpsi_PMTAddDescriptor(
                    &p_sys->dvbpmt[((pmt_map_t *)p_usepid)->i_prog], 0x1d,
                    bits.i_data, bits.p_data );
        else
            msg_Err( p_mux, "Received an unmapped PID" );
#else
        dvbpsi_PMTAddDescriptor( &p_sys->dvbpmt[0], 0x1d, bits.i_data,
                                 bits.p_data );
#endif
2343 2344
    }

2345
    for( i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
2346 2347 2348
    {
        ts_stream_t *p_stream;

2349 2350 2351 2352
        p_stream = (ts_stream_t *)p_mux->pp_inputs[i_stream]->p_sys;

#ifdef HAVE_BSEARCH
        i_pidinput = p_mux->pp_inputs[i_stream]->p_fmt->i_id;
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
        p_usepid = bsearch( &i_pidinput, p_sys->pmtmap, p_sys->i_pmtslots,
                            sizeof(pmt_map_t), intcompare ); 

        if( p_usepid != NULL )
            p_es = dvbpsi_PMTAddES(
                    &p_sys->dvbpmt[((pmt_map_t *)p_usepid)->i_prog],
                    p_stream->i_stream_type, p_stream->i_pid );
        else
            /* If there's an error somewhere, dump it to the first pmt */
#endif
            p_es = dvbpsi_PMTAddES( &p_sys->dvbpmt[0], p_stream->i_stream_type,
                                    p_stream->i_pid );
2365 2366

        if( p_stream->i_stream_id == 0xfa || p_stream->i_stream_id == 0xfb )
2367
        {
2368
            uint8_t     es_id[2];
2369

2370
            /* SL descriptor */
2371 2372 2373
            es_id[0] = (p_stream->i_es_id >> 8)&0xff;
            es_id[1] = (p_stream->i_es_id)&0xff;
            dvbpsi_PMTESAddDescriptor( p_es, 0x1f, 2, es_id );
2374
        }
2375
        else if( p_stream->i_stream_type == 0xa0 )
2376
        {
2377 2378
            uint8_t data[512];
            int i_extra = __MIN( p_stream->i_decoder_specific_info, 502 );
2379

2380
            /* private DIV3 descripor */
2381
            memcpy( &data[0], &p_stream->i_bih_codec, 4 );
2382 2383 2384 2385 2386 2387
            data[4] = ( p_stream->i_bih_width >> 8 )&0xff;
            data[5] = ( p_stream->i_bih_width      )&0xff;
            data[6] = ( p_stream->i_bih_height>> 8 )&0xff;
            data[7] = ( p_stream->i_bih_height     )&0xff;
            data[8] = ( i_extra >> 8 )&0xff;
            data[9] = ( i_extra      )&0xff;
2388
            if( i_extra > 0 )
2389
            {
2390
                memcpy( &data[10], p_stream->p_decoder_specific_info, i_extra );
2391
            }
2392 2393

            /* 0xa0 is private */
2394
            dvbpsi_PMTESAddDescriptor( p_es, 0xa0, i_extra + 10, data );
2395 2396 2397 2398 2399 2400 2401
        }
        else if( p_stream->i_stream_type == 0x81 )
        {
            uint8_t format[4] = { 0x41, 0x43, 0x2d, 0x33 };

            /* "registration" descriptor : "AC-3" */
            dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, format );
2402
        }
2403 2404 2405 2406 2407 2408 2409 2410
        else if( p_stream->i_codec == VLC_FOURCC('d','t','s',' ') )
        {
            /* DTS registration descriptor (ETSI TS 101 154 Annex F) */

            /* DTS format identifier, frame size 1024 - FIXME */
            uint8_t data[4] = { 0x44, 0x54, 0x53, 0x32 };
            dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, data );
        }
2411 2412 2413 2414 2415 2416
        else if( p_stream->i_codec == VLC_FOURCC('t','e','l','x') )
        {
            dvbpsi_PMTESAddDescriptor( p_es, 0x56,
                                       p_stream->i_decoder_specific_info,
                                       p_stream->p_decoder_specific_info );
        }
2417
#ifdef _DVBPSI_DR_59_H_
2418 2419 2420 2421 2422 2423 2424 2425
        else if( p_stream->i_codec == VLC_FOURCC('d','v','b','s') )
        {
            /* DVB subtitles */
            dvbpsi_subtitling_dr_t descr;
            dvbpsi_subtitle_t sub;
            dvbpsi_descriptor_t *p_descr;

            memcpy( sub.i_iso6392_language_code, p_stream->lang, 3 );
2426
            sub.i_subtitling_type = 0x10; /* no aspect-ratio criticality */
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
            sub.i_composition_page_id = p_stream->i_es_id & 0xFF;
            sub.i_ancillary_page_id = p_stream->i_es_id >> 16;

            descr.i_subtitles_number = 1;
            descr.p_subtitle[0] = sub;

            p_descr = dvbpsi_GenSubtitlingDr( &descr, 0 );
            /* Work around bug in old libdvbpsi */ p_descr->i_length = 8;
            dvbpsi_PMTESAddDescriptor( p_es, p_descr->i_tag,
                                       p_descr->i_length, p_descr->p_data );
            continue;
        }
2439
#endif /* _DVBPSI_DR_59_H_ */
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453

        if( p_stream->lang[0] != 0 )
        {
            uint8_t data[4];

            /* I construct the content myself, way faster than looking at
             * over complicated/mind broken libdvbpsi way */
            data[0] = p_stream->lang[0];
            data[1] = p_stream->lang[1];
            data[2] = p_stream->lang[2];
            data[3] = 0x00; /* audio type: 0x00 undefined */

            dvbpsi_PMTESAddDescriptor( p_es, 0x0a, 4, data );
        }
2454 2455
    }

2456 2457 2458 2459 2460 2461 2462 2463
    for( i = 0; i < p_sys->i_num_pmt; i++ )
    {
        p_section[i] = dvbpsi_GenPMTSections( &p_sys->dvbpmt[i] );
        p_pmt[i] = WritePSISection( p_mux->p_sout, p_section[i] );
        PEStoTS( p_mux->p_sout, c, p_pmt[i], &p_sys->pmt[i] );
        dvbpsi_DeletePSISections( p_section[i] );
        dvbpsi_EmptyPMT( &p_sys->dvbpmt[i] );
    }
2464

2465 2466 2467 2468 2469 2470 2471 2472 2473
    if( p_sys->b_sdt )
    {
        p_section2 = dvbpsi_GenSDTSections( &sdt ); 
        p_sdt = WritePSISection( p_mux->p_sout, p_section2 );
        p_sys->sdt.i_pid = 0x11;
        PEStoTS( p_mux->p_sout, c, p_sdt, &p_sys->sdt );
        dvbpsi_DeletePSISections( p_section2 );
        dvbpsi_EmptySDT( &sdt );
    }
2474
}