demux.c 110 KB
Newer Older
1 2 3
/*****************************************************************************
 * demux.c
 *****************************************************************************
4
 * Copyright (C) 2004, 2008-2011, 2015-2018 VideoLAN
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * Authors: Christophe Massiot <massiot@via.ecp.fr>
 *          Andy Gatward <a.j.gatward@reading.ac.uk>
 *          Marian Ďurkovič <md@bts.sk>
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include <stdlib.h>
26
#include <stdio.h>
27
#include <stdint.h>
28
#include <stdbool.h>
29
#include <stddef.h>
30
#include <string.h>
31 32
#include <stdarg.h>
#include <inttypes.h>
33 34 35
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
36
#include <ev.h>
37 38 39

#include "dvblast.h"
#include "en50221.h"
40
#include "mrtg-cnt.h"
41

42 43 44 45 46 47 48 49 50 51 52
#ifdef HAVE_ICONV
#include <iconv.h>
#endif

#include <bitstream/mpeg/ts.h>
#include <bitstream/mpeg/pes.h>
#include <bitstream/mpeg/psi.h>
#include <bitstream/dvb/si.h>
#include <bitstream/dvb/si_print.h>
#include <bitstream/mpeg/psi_print.h>

53 54 55
/*****************************************************************************
 * Local declarations
 *****************************************************************************/
56
#define MIN_SECTION_FRAGMENT    PSI_HEADER_SIZE_SYNTAX1
57 58 59 60

typedef struct ts_pid_t
{
    int i_refcount;
61 62 63
    int i_psi_refcount;
    bool b_pes;
    int8_t i_last_cc;
64
    int i_demux_fd;
65 66 67 68 69 70 71 72 73 74 75 76
    /* b_emm is set to true when PID carries EMM packet
       and should be outputed in all services */
    bool b_emm;

    /* PID info and stats */
    mtime_t i_bytes_ts;
    unsigned long i_packets_passed;
    ts_pid_info_t info;

    /* biTStream PSI section gathering */
    uint8_t *p_psi_buffer;
    uint16_t i_psi_buffer_used;
77 78 79

    output_t **pp_outputs;
    int i_nb_outputs;
80 81 82

    int i_pes_status; /* pes + unscrambled */
    struct ev_timer timeout_watcher;
83 84
} ts_pid_t;

85 86 87 88 89 90 91 92
struct eit_sections {
    PSI_TABLE_DECLARE(data);
};

/* EIT is carried in several separate tables, we need to track each table
   separately, otherwise one table overwrites sections of another table */
#define MAX_EIT_TABLES ( EIT_TABLE_ID_SCHED_ACTUAL_LAST - EIT_TABLE_ID_PF_ACTUAL )

93 94 95
typedef struct sid_t
{
    uint16_t i_sid, i_pmt_pid;
96
    uint8_t *p_current_pmt;
97
    struct eit_sections eit_table[MAX_EIT_TABLES];
98 99
} sid_t;

100 101 102
mtime_t i_wallclock = 0;

static ts_pid_t p_pids[MAX_PIDS];
103 104 105
static sid_t **pp_sids = NULL;
static int i_nb_sids = 0;

106 107 108 109 110 111 112 113 114
static PSI_TABLE_DECLARE(pp_current_pat_sections);
static PSI_TABLE_DECLARE(pp_next_pat_sections);
static PSI_TABLE_DECLARE(pp_current_cat_sections);
static PSI_TABLE_DECLARE(pp_next_cat_sections);
static PSI_TABLE_DECLARE(pp_current_nit_sections);
static PSI_TABLE_DECLARE(pp_next_nit_sections);
static PSI_TABLE_DECLARE(pp_current_sdt_sections);
static PSI_TABLE_DECLARE(pp_next_sdt_sections);
static mtime_t i_last_dts = -1;
115
static int i_demux_fd;
116 117 118 119 120
static uint64_t i_nb_packets = 0;
static uint64_t i_nb_invalids = 0;
static uint64_t i_nb_discontinuities = 0;
static uint64_t i_nb_errors = 0;
static int i_tuner_errors = 0;
121
static mtime_t i_last_error = 0;
122 123
static mtime_t i_last_reset = 0;
static struct ev_timer print_watcher;
124 125 126 127

#ifdef HAVE_ICONV
static iconv_t iconv_handle = (iconv_t)-1;
#endif
128 129 130 131 132

/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
static void demux_Handle( block_t *p_ts );
133
static void SetDTS( block_t *p_list );
134
static void SetPID( uint16_t i_pid );
135
static void SetPID_EMM( uint16_t i_pid );
136 137 138
static void UnsetPID( uint16_t i_pid );
static void StartPID( output_t *p_output, uint16_t i_pid );
static void StopPID( output_t *p_output, uint16_t i_pid );
139
static void SelectPID( uint16_t i_sid, uint16_t i_pid, bool b_pcr );
140
static void UnselectPID( uint16_t i_sid, uint16_t i_pid );
141 142
static void SelectPMT( uint16_t i_sid, uint16_t i_pid );
static void UnselectPMT( uint16_t i_sid, uint16_t i_pid );
143
static void GetPIDS( uint16_t **ppi_wanted_pids, int *pi_nb_wanted_pids,
144
                     uint16_t *pi_pcr_pid, uint16_t i_sid,
145
                     const uint16_t *pi_pids, int i_nb_pids );
146 147 148 149 150
static bool SIDIsSelected( uint16_t i_sid );
static bool PIDWouldBeSelected( uint8_t *p_es );
static bool PMTNeedsDescrambling( uint8_t *p_pmt );
static void FlushEIT( output_t *p_output, mtime_t i_dts );
static void SendTDT( block_t *p_ts );
151
static void SendEMM( block_t *p_ts );
152 153
static void NewPAT( output_t *p_output );
static void NewPMT( output_t *p_output );
154 155 156 157
static void NewNIT( output_t *p_output );
static void NewSDT( output_t *p_output );
static void HandlePSIPacket( uint8_t *p_ts, mtime_t i_dts );
static const char *get_pid_desc(uint16_t i_pid, uint16_t *i_sid);
158

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
/*
 * Remap an ES pid to a fixed value.
 * Multiple streams of the same type use sequential pids
 * Returns the new pid and updates the map tables
*/
static uint16_t map_es_pid(output_t * p_output, uint8_t *p_es, uint16_t i_pid)
{
    uint16_t i_newpid = i_pid;
    uint16_t i_stream_type = pmtn_get_streamtype(p_es);

    if ( !b_do_remap && !p_output->config.b_do_remap )
        return i_pid;

    msg_Dbg(NULL, "REMAP: Found elementary stream type 0x%02x with original PID 0x%x (%u):", i_stream_type, i_pid, i_pid);

    switch ( i_stream_type )
    {
        case 0x03: /* audio MPEG-1 */
177
        case 0x04: /* audio MPEG-2 */
178 179 180 181 182 183 184 185 186 187
        case 0x0f: /* audio AAC ADTS */
        case 0x11: /* audio AAC LATM */
        case 0x81: /* ATSC AC-3 */
        case 0x87: /* ATSC Enhanced AC-3 */
            if ( b_do_remap )
                i_newpid = pi_newpids[I_APID];
            else
                i_newpid = p_output->config.pi_confpids[I_APID];
            break;
        case 0x01: /* video MPEG-1 */
188
        case 0x02: /* video MPEG-2 */
189 190
        case 0x10: /* video MPEG-4 */
        case 0x1b: /* video H264 */
191 192
        case 0x24: /* video H265 */
        case 0x42: /* video AVS */
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
            if ( b_do_remap )
                i_newpid = pi_newpids[I_VPID];
            else
                i_newpid = p_output->config.pi_confpids[I_VPID];
            break;
        case 0x06: { /* PES Private Data - We must check the descriptors */
            /* By default, nothing identified */
            uint8_t SubStreamType = N_MAP_PIDS;
            uint16_t j = 0;
            const uint8_t *p_desc;
            /* Loop over the descriptors */
            while ( (p_desc = descs_get_desc( pmtn_get_descs( p_es ), j )) != NULL )
            {
                /* Get the descriptor tag */
                uint8_t i_tag = desc_get_tag( p_desc );
                j++;
                /* Check if the tag is: A/52, Enhanced A/52, DTS, AAC */
                if (i_tag == 0x6a || i_tag == 0x7a || i_tag == 0x7b || i_tag == 0x7c)
                    SubStreamType=I_APID;
                /* Check if the tag is: VBI + teletext, teletext, dvbsub */
                if (i_tag == 0x46 || i_tag == 0x56 || i_tag == 0x59)
                    SubStreamType=I_SPUPID;
            }
            /* Audio found */
            if (SubStreamType==I_APID) {
                msg_Dbg(NULL, "REMAP: PES Private Data stream identified as [Audio]");
                if ( b_do_remap )
                    i_newpid = pi_newpids[I_APID];
                else
                    i_newpid = p_output->config.pi_confpids[I_APID];
            }
            /* Subtitle found */
            if (SubStreamType==I_SPUPID) {
                msg_Dbg(NULL, "REMAP: PES Private Data stream identified as [Subtitle]");
                if ( b_do_remap )
                    i_newpid = pi_newpids[I_SPUPID];
                else
                    i_newpid = p_output->config.pi_confpids[I_SPUPID];
            }
            break;
        }
    }

    if (!i_newpid)
        return i_pid;

    /* Got the new base for the mapped pid. Find the next free one
       we do this to ensure that multiple audios get unique pids */
    while (p_output->pi_freepids[i_newpid] != UNUSED_PID)
        i_newpid++;
    p_output->pi_freepids[i_newpid] = i_pid;  /* Mark as in use */
    p_output->pi_newpids[i_pid] = i_newpid;   /* Save the new pid */

    msg_Dbg(NULL, "REMAP: => Elementary stream is remapped to PID 0x%x (%u)", i_newpid, i_newpid);

    return i_newpid;
}

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
/*****************************************************************************
 * FindSID
 *****************************************************************************/
static inline sid_t *FindSID( uint16_t i_sid )
{
    int i;

    for ( i = 0; i < i_nb_sids; i++ )
    {
        sid_t *p_sid = pp_sids[i];
        if ( p_sid->i_sid == i_sid )
            return p_sid;
    }
    return NULL;
}

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
/*****************************************************************************
 * Print info
 *****************************************************************************/
static void PrintCb( struct ev_loop *loop, struct ev_timer *w, int revents )
{
    uint64_t i_bitrate = i_nb_packets * TS_SIZE * 8 * 1000000 / i_print_period;
    switch (i_print_type)
    {
        case PRINT_XML:
            fprintf(print_fh,
                    "<STATUS type=\"bitrate\" status=\"%d\" value=\"%"PRIu64"\" />\n",
                    i_bitrate ? 1 : 0, i_bitrate);
            break;
        case PRINT_TEXT:
            fprintf(print_fh, "bitrate: %"PRIu64"\n", i_bitrate);
            break;
        default:
            break;
    }
    i_nb_packets = 0;

    if ( i_nb_invalids )
    {
        switch (i_print_type)
        {
            case PRINT_XML:
                fprintf(print_fh,
                        "<ERROR type=\"invalid_ts\" number=\"%"PRIu64"\" />\n",
                        i_nb_invalids);
                break;
            case PRINT_TEXT:
                fprintf(print_fh, "invalids: %"PRIu64"\n", i_nb_invalids);
                break;
            default:
                break;
        }
        i_nb_invalids = 0;
    }

    if ( i_nb_discontinuities )
    {
        switch (i_print_type)
        {
            case PRINT_XML:
                fprintf(print_fh,
                        "<ERROR type=\"invalid_discontinuity\" number=\"%"PRIu64"\" />\n",
                        i_nb_discontinuities);
                break;
            case PRINT_TEXT:
                fprintf(print_fh, "discontinuities: %"PRIu64"\n",
                        i_nb_discontinuities);
                break;
            default:
                break;
        }
        i_nb_discontinuities = 0;
    }

    if ( i_nb_errors )
    {
        switch (i_print_type)
        {
            case PRINT_XML:
                fprintf(print_fh,
                        "<ERROR type=\"transport_error\" number=\"%"PRIu64"\" />\n",
                        i_nb_errors);
                break;
            case PRINT_TEXT:
                fprintf(print_fh, "errors: %"PRIu64"\n", i_nb_errors);
                break;
            default:
                break;
        }
        i_nb_errors = 0;
    }
}

static void PrintESCb( struct ev_loop *loop, struct ev_timer *w, int revents )
{
    ts_pid_t *p_pid = container_of( w, ts_pid_t, timeout_watcher );
    uint16_t i_pid = p_pid - p_pids;

    switch (i_print_type)
    {
        case PRINT_XML:
            fprintf(print_fh,
                    "<STATUS type=\"pid\" pid=\"%"PRIu16"\" status=\"0\" />\n",
                    i_pid);
            break;
        case PRINT_TEXT:
            fprintf(print_fh, "pid: %"PRIu16" down\n", i_pid);
            break;
        default:
            break;
    }

    ev_timer_stop( loop, w );
    p_pid->i_pes_status = -1;
}

static void PrintES( uint16_t i_pid )
{
    const ts_pid_t *p_pid = &p_pids[i_pid];

    switch (i_print_type)
    {
        case PRINT_XML:
            fprintf(print_fh,
                    "<STATUS type=\"pid\" pid=\"%"PRIu16"\" status=\"1\" pes=\"%d\" />\n",
                    i_pid, p_pid->i_pes_status == 1 ? 1 : 0);
            break;
        case PRINT_TEXT:
            fprintf(print_fh, "pid: %"PRIu16" up%s\n",
                    i_pid, p_pid->i_pes_status == 1 ? " pes" : "");
            break;
        default:
            break;
    }
}

387 388 389 390 391 392 393 394 395
/*****************************************************************************
 * demux_Open
 *****************************************************************************/
void demux_Open( void )
{
    int i;

    memset( p_pids, 0, sizeof(p_pids) );

396
    pf_Open();
397

398
    for ( i = 0; i < MAX_PIDS; i++ )
399 400 401
    {
        p_pids[i].i_last_cc = -1;
        p_pids[i].i_demux_fd = -1;
402 403
        psi_assemble_init( &p_pids[i].p_psi_buffer,
                           &p_pids[i].i_psi_buffer_used );
404
        p_pids[i].i_pes_status = -1;
405 406 407
    }

    if ( b_budget_mode )
408
        i_demux_fd = pf_SetFilter(8192);
409

410 411 412 413 414
    psi_table_init( pp_current_pat_sections );
    psi_table_init( pp_next_pat_sections );
    SetPID(PAT_PID);
    p_pids[PAT_PID].i_psi_refcount++;

415 416
    if ( b_enable_emm )
    {
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
        psi_table_init( pp_current_cat_sections );
        psi_table_init( pp_next_cat_sections );
        SetPID_EMM(CAT_PID);
        p_pids[CAT_PID].i_psi_refcount++;
    }

    SetPID(NIT_PID);
    p_pids[NIT_PID].i_psi_refcount++;

    psi_table_init( pp_current_sdt_sections );
    psi_table_init( pp_next_sdt_sections );
    SetPID(SDT_PID);
    p_pids[SDT_PID].i_psi_refcount++;

    SetPID(EIT_PID);
    p_pids[EIT_PID].i_psi_refcount++;

    SetPID(RST_PID);

    SetPID(TDT_PID);
437 438 439 440 441 442 443

    if ( i_print_period )
    {
        ev_timer_init( &print_watcher, PrintCb,
                       i_print_period / 1000000., i_print_period / 1000000. );
        ev_timer_start( event_loop, &print_watcher );
    }
444
}
445

446 447 448 449 450
/*****************************************************************************
 * demux_Close
 *****************************************************************************/
void demux_Close( void )
{
451
    int i, r;
452 453 454 455 456 457 458 459 460 461 462

    psi_table_free( pp_current_pat_sections );
    psi_table_free( pp_next_pat_sections );
    psi_table_free( pp_current_cat_sections );
    psi_table_free( pp_next_cat_sections );
    psi_table_free( pp_current_nit_sections );
    psi_table_free( pp_next_nit_sections );
    psi_table_free( pp_current_sdt_sections );
    psi_table_free( pp_next_sdt_sections );

    for ( i = 0; i < MAX_PIDS; i++ )
463
    {
464
        ev_timer_stop( event_loop, &p_pids[i].timeout_watcher );
465
        free( p_pids[i].p_psi_buffer );
466
        free( p_pids[i].pp_outputs );
467
    }
468

469 470 471
    for ( i = 0; i < i_nb_sids; i++ )
    {
        sid_t *p_sid = pp_sids[i];
472 473 474
        for ( r = 0; r < MAX_EIT_TABLES; r++ ) {
            psi_table_free( p_sid->eit_table[r].data );
        }
475 476 477 478
        free( p_sid->p_current_pmt );
        free( p_sid );
    }
    free( pp_sids );
479

480 481 482 483
#ifdef HAVE_ICONV
    if (iconv_handle != (iconv_t)-1) {
        iconv_close(iconv_handle);
        iconv_handle = (iconv_t)-1;
484
    }
485
#endif
486 487 488

    if ( i_print_period )
        ev_timer_stop( event_loop, &print_watcher );
489 490 491 492 493
}

/*****************************************************************************
 * demux_Run
 *****************************************************************************/
494
void demux_Run( block_t *p_ts )
495
{
496 497
    i_wallclock = mdate();
    mrtgAnalyse( p_ts );
498
    SetDTS( p_ts );
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

    while ( p_ts != NULL )
    {
        block_t *p_next = p_ts->p_next;
        p_ts->p_next = NULL;
        demux_Handle( p_ts );
        p_ts = p_next;
    }
}

/*****************************************************************************
 * demux_Handle
 *****************************************************************************/
static void demux_Handle( block_t *p_ts )
{
514
    uint16_t i_pid = ts_get_pid( p_ts->p_ts );
515
    ts_pid_t *p_pid = &p_pids[i_pid];
516
    uint8_t i_cc = ts_get_cc( p_ts->p_ts );
517 518
    int i;

519 520
    i_nb_packets++;

521
    if ( !ts_validate( p_ts->p_ts ) )
522
    {
523
        msg_Warn( NULL, "lost TS sync" );
524
        block_Delete( p_ts );
525
        i_nb_invalids++;
526 527 528
        return;
    }

529
    if ( i_pid != PADDING_PID )
530
        p_pid->info.i_scrambling = ts_get_scrambling( p_ts->p_ts );
531

532 533
    p_pid->info.i_last_packet_ts = i_wallclock;
    p_pid->info.i_packets++;
534

535
    p_pid->i_packets_passed++;
536 537

    /* Calculate bytes_per_sec */
538 539 540 541
    if ( i_wallclock > p_pid->i_bytes_ts + 1000000 ) {
        p_pid->info.i_bytes_per_sec = p_pid->i_packets_passed * TS_SIZE;
        p_pid->i_packets_passed = 0;
        p_pid->i_bytes_ts = i_wallclock;
542
    }
543

544 545
    if ( p_pid->info.i_first_packet_ts == 0 )
        p_pid->info.i_first_packet_ts = i_wallclock;
546

547 548 549
    if ( i_pid != PADDING_PID && p_pid->i_last_cc != -1
          && !ts_check_duplicate( i_cc, p_pid->i_last_cc )
          && ts_check_discontinuity( i_cc, p_pid->i_last_cc ) )
550
    {
551
        unsigned int expected_cc = (p_pid->i_last_cc + 1) & 0x0f;
552 553 554
        uint16_t i_sid = 0;
        const char *pid_desc = get_pid_desc(i_pid, &i_sid);

555 556
        p_pid->info.i_cc_errors++;
        i_nb_discontinuities++;
557 558 559 560 561 562 563 564 565 566

        msg_Warn( NULL, "TS discontinuity on pid %4hu expected_cc %2u got %2u (%s, sid %d)",
                i_pid, expected_cc, i_cc, pid_desc, i_sid );
    }

    if ( ts_get_transporterror( p_ts->p_ts ) )
    {
        uint16_t i_sid = 0;
        const char *pid_desc = get_pid_desc(i_pid, &i_sid);

567
        p_pid->info.i_transport_errors++;
568 569 570 571 572

        msg_Warn( NULL, "transport_error_indicator on pid %hu (%s, sid %u)",
                   i_pid, pid_desc, i_sid );

        i_nb_errors++;
573
        i_tuner_errors++;
574
        i_last_error = i_wallclock;
575
    }
576
    else if ( i_wallclock > i_last_error + WATCHDOG_WAIT )
577
        i_tuner_errors = 0;
578

579
    if ( i_tuner_errors > MAX_ERRORS )
580
    {
581
        i_tuner_errors = 0;
582 583
        msg_Warn( NULL,
                 "too many transport errors, tuning again" );
584 585 586 587 588 589 590 591 592 593
        switch (i_print_type) {
        case PRINT_XML:
            fprintf(print_fh, "<EVENT type=\"reset\" cause=\"transport\" />\n");
            break;
        case PRINT_TEXT:
            fprintf(print_fh, "reset cause: transport\n");
            break;
        default:
            break;
        }
594 595
        pf_Reset();
    }
596

597
    if ( i_es_timeout )
598
    {
599 600 601 602 603 604 605 606 607
        int i_pes_status = -1;
        if ( ts_get_scrambling( p_ts->p_ts ) )
            i_pes_status = 0;
        else if ( ts_get_unitstart( p_ts->p_ts ) )
        {
            uint8_t *p_payload = ts_payload( p_ts->p_ts );
            if ( p_payload + 3 < p_ts->p_ts + TS_SIZE )
                i_pes_status = pes_validate( p_payload ) ? 1 : 0;
        }
608

609
        if ( i_pes_status != -1 )
610
        {
611 612 613 614
            if ( p_pid->i_pes_status == -1 )
            {
                p_pid->i_pes_status = i_pes_status;
                PrintES( i_pid );
615

616 617 618 619 620 621 622 623 624 625 626 627 628 629
                if ( i_pid != TDT_PID )
                {
                    ev_timer_init( &p_pid->timeout_watcher, PrintESCb,
                                   i_es_timeout / 1000000.,
                                   i_es_timeout / 1000000. );
                    ev_timer_start( event_loop, &p_pid->timeout_watcher );
                }
                else
                {
                    ev_timer_init( &p_pid->timeout_watcher, PrintESCb, 30, 30 );
                    ev_timer_start( event_loop, &p_pid->timeout_watcher );
                }
            }
            else
630
            {
631
                if ( p_pid->i_pes_status != i_pes_status )
632
                {
633 634
                    p_pid->i_pes_status = i_pes_status;
                    PrintES( i_pid );
635
                }
636 637

                ev_timer_again( event_loop, &p_pid->timeout_watcher );
638 639 640 641
            }
        }
    }

642 643 644 645 646 647 648 649 650 651 652 653 654
    if ( !ts_get_transporterror( p_ts->p_ts ) )
    {
        /* PSI parsing */
        if ( i_pid == TDT_PID || i_pid == RST_PID )
            SendTDT( p_ts );
        else if ( p_pid->i_psi_refcount )
            HandlePSIPacket( p_ts->p_ts, p_ts->i_dts );

        if ( b_enable_emm && p_pid->b_emm )
            SendEMM( p_ts );
    }

    p_pid->i_last_cc = i_cc;
655 656

    /* Output */
657
    for ( i = 0; i < p_pid->i_nb_outputs; i++ )
658
    {
659
        output_t *p_output = p_pid->pp_outputs[i];
660 661
        if ( p_output != NULL )
        {
662 663
            if ( i_ca_handle && (p_output->config.i_config & OUTPUT_WATCH) &&
                 ts_get_unitstart( p_ts->p_ts ) )
664 665 666
            {
                uint8_t *p_payload;

667
                if ( ts_get_scrambling( p_ts->p_ts ) ||
668
                     ( p_pid->b_pes
669 670 671
                        && (p_payload = ts_payload( p_ts->p_ts )) + 3
                             < p_ts->p_ts + TS_SIZE
                          && !pes_validate(p_payload) ) )
672
                {
673 674 675 676 677 678
                    if ( i_wallclock >
                            i_last_reset + WATCHDOG_REFRACTORY_PERIOD )
                    {
                        p_output->i_nb_errors++;
                        p_output->i_last_error = i_wallclock;
                    }
679 680 681 682 683 684 685 686 687 688 689
                }
                else if ( i_wallclock > p_output->i_last_error + WATCHDOG_WAIT )
                    p_output->i_nb_errors = 0;

                if ( p_output->i_nb_errors > MAX_ERRORS )
                {
                    int j;
                    for ( j = 0; j < i_nb_outputs; j++ )
                        pp_outputs[j]->i_nb_errors = 0;

                    msg_Warn( NULL,
690
                             "too many errors for stream %s, resetting",
691
                             p_output->config.psz_displayname );
692 693 694 695 696 697 698 699 700 701 702 703

                    switch (i_print_type) {
                    case PRINT_XML:
                        fprintf(print_fh, "<EVENT type=\"reset\" cause=\"scrambling\" />\n");
                        break;
                    case PRINT_TEXT:
                        fprintf(print_fh, "reset cause: scrambling");
                        break;
                    default:
                        break;
                    }
                    i_last_reset = i_wallclock;
704 705 706 707
                    en50221_Reset();
                }
            }

708 709 710 711 712
            if ( p_output->i_pcr_pid != i_pid
                  || (ts_has_adaptation(p_ts->p_ts)
                       && ts_get_adaptation(p_ts->p_ts)
                       && tsaf_has_pcr(p_ts->p_ts)) )
                output_Put( p_output, p_ts );
713 714 715 716 717

            if ( p_output->p_eit_ts_buffer != NULL
                  && p_ts->i_dts > p_output->p_eit_ts_buffer->i_dts
                                    + MAX_EIT_RETENTION )
                FlushEIT( p_output, p_ts->i_dts );
718 719 720
        }
    }

721 722 723 724 725 726 727 728 729 730 731
    for ( i = 0; i < i_nb_outputs; i++ )
    {
        output_t *p_output = pp_outputs[i];

        if ( !(p_output->config.i_config & OUTPUT_VALID) ||
             !p_output->config.b_passthrough )
            continue;

        output_Put( p_output, p_ts );
    }

732
    if ( output_dup.config.i_config & OUTPUT_VALID )
733 734
        output_Put( &output_dup, p_ts );

735 736 737
    if ( b_passthrough )
        fwrite(p_ts->p_ts, TS_SIZE, 1, stdout);

738 739 740 741 742 743 744 745
    p_ts->i_refcount--;
    if ( !p_ts->i_refcount )
        block_Delete( p_ts );
}

/*****************************************************************************
 * demux_Change : called from main thread
 *****************************************************************************/
746
static bool IsIn( const uint16_t *pi_pids, int i_nb_pids, uint16_t i_pid )
747 748 749 750 751 752 753
{
    int i;
    for ( i = 0; i < i_nb_pids; i++ )
        if ( i_pid == pi_pids[i] ) break;
    return ( i != i_nb_pids );
}

754
void demux_Change( output_t *p_output, const output_config_t *p_config )
755 756 757
{
    uint16_t *pi_wanted_pids, *pi_current_pids;
    int i_nb_wanted_pids, i_nb_current_pids;
758
    uint16_t i_wanted_pcr_pid, i_current_pcr_pid;
759

760 761 762 763 764 765 766 767 768 769 770
    uint16_t i_old_sid = p_output->config.i_sid;
    uint16_t i_sid = p_config->i_sid;
    uint16_t *pi_old_pids = p_output->config.pi_pids;
    uint16_t *pi_pids = p_config->pi_pids;
    int i_old_nb_pids = p_output->config.i_nb_pids;
    int i_nb_pids = p_config->i_nb_pids;

    bool b_sid_change = i_sid != i_old_sid;
    bool b_pid_change = false, b_tsid_change = false;
    bool b_dvb_change = !!((p_output->config.i_config ^ p_config->i_config)
                             & OUTPUT_DVB);
771 772
    bool b_epg_change = !!((p_output->config.i_config ^ p_config->i_config)
                             & OUTPUT_EPG);
773 774 775
    bool b_network_change =
        (dvb_string_cmp(&p_output->config.network_name, &p_config->network_name) ||
         p_output->config.i_network_id != p_config->i_network_id);
776
    bool b_service_name_change =
777 778 779
        (dvb_string_cmp(&p_output->config.service_name, &p_config->service_name) ||
         dvb_string_cmp(&p_output->config.provider_name, &p_config->provider_name));
    bool b_remap_change = p_output->config.i_new_sid != p_config->i_new_sid ||
780
        p_output->config.i_onid != p_config->i_onid ||
781 782 783 784 785
        p_output->config.b_do_remap != p_config->b_do_remap ||
        p_output->config.pi_confpids[I_PMTPID] != p_config->pi_confpids[I_PMTPID] ||
        p_output->config.pi_confpids[I_APID] != p_config->pi_confpids[I_APID] ||
        p_output->config.pi_confpids[I_VPID] != p_config->pi_confpids[I_VPID] ||
        p_output->config.pi_confpids[I_SPUPID] != p_config->pi_confpids[I_SPUPID];
786 787 788
    int i;

    p_output->config.i_config = p_config->i_config;
789 790
    p_output->config.i_network_id = p_config->i_network_id;
    p_output->config.i_new_sid = p_config->i_new_sid;
791
    p_output->config.i_onid = p_config->i_onid;
792 793 794 795 796 797 798 799 800 801 802 803 804 805
    p_output->config.b_do_remap = p_config->b_do_remap;
    memcpy(p_output->config.pi_confpids, p_config->pi_confpids,
           sizeof(uint16_t) * N_MAP_PIDS);

    /* Change output settings related to names. */
    dvb_string_clean( &p_output->config.network_name );
    dvb_string_clean( &p_output->config.service_name );
    dvb_string_clean( &p_output->config.provider_name );
    dvb_string_copy( &p_output->config.network_name,
                     &p_config->network_name );
    dvb_string_copy( &p_output->config.service_name,
                     &p_config->service_name );
    dvb_string_copy( &p_output->config.provider_name,
                     &p_config->provider_name );
806 807 808

    if ( p_config->i_tsid != -1 && p_output->config.i_tsid != p_config->i_tsid )
    {
809
        p_output->i_tsid = p_output->config.i_tsid = p_config->i_tsid;
810 811 812 813
        b_tsid_change = true;
    }
    if ( p_config->i_tsid == -1 && p_output->config.i_tsid != -1 )
    {
814
        p_output->config.i_tsid = p_config->i_tsid;
815 816 817 818 819 820 821 822
        if ( psi_table_validate(pp_current_pat_sections) && !b_random_tsid )
            p_output->i_tsid =
                psi_table_get_tableidext(pp_current_pat_sections);
        else
            p_output->i_tsid = rand() & 0xffff;
        b_tsid_change = true;
    }

823 824
    if ( p_config->b_passthrough == p_output->config.b_passthrough &&
         !b_sid_change && p_config->i_nb_pids == p_output->config.i_nb_pids &&
825 826 827 828
         (!p_config->i_nb_pids ||
          !memcmp( p_output->config.pi_pids, p_config->pi_pids,
                   p_config->i_nb_pids * sizeof(uint16_t) )) )
        goto out_change;
829

830 831 832 833
    GetPIDS( &pi_wanted_pids, &i_nb_wanted_pids, &i_wanted_pcr_pid,
             i_sid, pi_pids, i_nb_pids );
    GetPIDS( &pi_current_pids, &i_nb_current_pids, &i_current_pcr_pid,
             i_old_sid, pi_old_pids, i_old_nb_pids );
834

835
    if ( b_sid_change && i_old_sid )
836
    {
837
        sid_t *p_old_sid = FindSID( i_old_sid );
838
        p_output->config.i_sid = p_config->i_sid;
839 840

        if ( p_old_sid != NULL )
841
        {
842 843
            if ( i_sid != i_old_sid )
                UnselectPMT( i_old_sid, p_old_sid->i_pmt_pid );
844

845 846 847 848
            if ( i_ca_handle && !SIDIsSelected( i_old_sid )
                  && p_old_sid->p_current_pmt != NULL
                  && PMTNeedsDescrambling( p_old_sid->p_current_pmt ) )
                en50221_DeletePMT( p_old_sid->p_current_pmt );
849 850 851 852 853
        }
    }

    for ( i = 0; i < i_nb_current_pids; i++ )
    {
854
        if ( !IsIn( pi_wanted_pids, i_nb_wanted_pids, pi_current_pids[i] ) )
855 856
        {
            StopPID( p_output, pi_current_pids[i] );
857
            b_pid_change = true;
858 859 860
        }
    }

861 862
    if ( b_sid_change && i_ca_handle && i_old_sid &&
         SIDIsSelected( i_old_sid ) )
863
    {
864 865 866 867
        sid_t *p_old_sid = FindSID( i_old_sid );
        if ( p_old_sid != NULL && p_old_sid->p_current_pmt != NULL
              && PMTNeedsDescrambling( p_old_sid->p_current_pmt ) )
            en50221_UpdatePMT( p_old_sid->p_current_pmt );
868 869 870 871
    }

    for ( i = 0; i < i_nb_wanted_pids; i++ )
    {
872
        if ( !IsIn( pi_current_pids, i_nb_current_pids, pi_wanted_pids[i] ) )
873 874
        {
            StartPID( p_output, pi_wanted_pids[i] );
875
            b_pid_change = true;
876 877 878 879 880
        }
    }

    free( pi_wanted_pids );
    free( pi_current_pids );
881
    p_output->i_pcr_pid = i_wanted_pcr_pid;
882

883
    if ( b_sid_change && i_sid )
884
    {
885
        sid_t *p_sid = FindSID( i_sid );
886
        p_output->config.i_sid = i_old_sid;
887 888

        if ( p_sid != NULL )
889
        {
890 891
            if ( i_sid != i_old_sid )
                SelectPMT( i_sid, p_sid->i_pmt_pid );
892

893 894 895 896
            if ( i_ca_handle && !SIDIsSelected( i_sid )
                  && p_sid->p_current_pmt != NULL
                  && PMTNeedsDescrambling( p_sid->p_current_pmt ) )
                en50221_AddPMT( p_sid->p_current_pmt );
897 898 899 900 901
        }
    }

    if ( i_ca_handle && i_sid && SIDIsSelected( i_sid ) )
    {
902 903 904 905
        sid_t *p_sid = FindSID( i_sid );
        if ( p_sid != NULL && p_sid->p_current_pmt != NULL
              && PMTNeedsDescrambling( p_sid->p_current_pmt ) )
            en50221_UpdatePMT( p_sid->p_current_pmt );
906 907
    }

908
    p_output->config.b_passthrough = p_config->b_passthrough;
909 910 911 912 913
    p_output->config.i_sid = i_sid;
    free( p_output->config.pi_pids );
    p_output->config.pi_pids = malloc( sizeof(uint16_t) * i_nb_pids );
    memcpy( p_output->config.pi_pids, pi_pids, sizeof(uint16_t) * i_nb_pids );
    p_output->config.i_nb_pids = i_nb_pids;
914

915
out_change:
916 917 918 919 920 921 922 923 924 925 926 927 928
    if ( b_sid_change || b_pid_change || b_tsid_change || b_dvb_change ||
         b_network_change || b_service_name_change || b_remap_change )
    {
        msg_Dbg( NULL, "change %s%s%s%s%s%s%s",
                 b_sid_change ? "sid " : "",
                 b_pid_change ? "pid " : "",
                 b_tsid_change ? "tsid " : "",
                 b_dvb_change ? "dvb " : "",
                 b_network_change ? "network " : "",
                 b_service_name_change ? "service_name " : "",
                 b_remap_change ? "remap " : "" );
    }

929
    if ( b_sid_change || b_remap_change )
930 931
    {
        NewSDT( p_output );
932
        NewNIT( p_output );
933 934 935
        NewPAT( p_output );
        NewPMT( p_output );
    }
936 937 938 939 940 941 942 943 944 945 946 947 948
    else
    {
        if ( b_tsid_change )
        {
            NewSDT( p_output );
            NewNIT( p_output );
            NewPAT( p_output );
        }
        else if ( b_dvb_change )
        {
            NewNIT( p_output );
            NewPAT( p_output );
        }
949 950 951
        else if ( b_network_change )
            NewNIT( p_output );

952
        if ( !b_tsid_change && (b_service_name_change || b_epg_change) )
953
            NewSDT( p_output );
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991

        if ( b_pid_change )
            NewPMT( p_output );
    }
}

/*****************************************************************************
 * SetDTS
 *****************************************************************************/
static void SetDTS( block_t *p_list )
{
    int i_nb_ts = 0, i;
    mtime_t i_duration;
    block_t *p_ts = p_list;

    while ( p_ts != NULL )
    {
        i_nb_ts++;
        p_ts = p_ts->p_next;
    }

    /* We suppose the stream is CBR, at least between two consecutive read().
     * This is especially true in budget mode */
    if ( i_last_dts == -1 )
        i_duration = 0;
    else
        i_duration = i_wallclock - i_last_dts;

    p_ts = p_list;
    i = i_nb_ts - 1;
    while ( p_ts != NULL )
    {
        p_ts->i_dts = i_wallclock - i_duration * i / i_nb_ts;
        i--;
        p_ts = p_ts->p_next;
    }

    i_last_dts = i_wallclock;
992 993 994 995 996 997 998 999 1000 1001 1002
}

/*****************************************************************************
 * SetPID/UnsetPID
 *****************************************************************************/
static void SetPID( uint16_t i_pid )
{
    p_pids[i_pid].i_refcount++;

    if ( !b_budget_mode && p_pids[i_pid].i_refcount
          && p_pids[i_pid].i_demux_fd == -1 )
1003
        p_pids[i_pid].i_demux_fd = pf_SetFilter( i_pid );
1004 1005
}

1006 1007 1008 1009 1010 1011
static void SetPID_EMM( uint16_t i_pid )
{
    SetPID( i_pid );
    p_pids[i_pid].b_emm = true;
}

1012 1013 1014 1015 1016 1017 1018
static void UnsetPID( uint16_t i_pid )
{
    p_pids[i_pid].i_refcount--;

    if ( !b_budget_mode && !p_pids[i_pid].i_refcount
          && p_pids[i_pid].i_demux_fd != -1 )
    {
1019
        pf_UnsetFilter( p_pids[i_pid].i_demux_fd, i_pid );
1020
        p_pids[i_pid].i_demux_fd = -1;
1021
        p_pids[i_pid].b_emm = false;
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 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 1070 1071 1072 1073 1074 1075 1076 1077
    }
}

/*****************************************************************************
 * StartPID/StopPID
 *****************************************************************************/
static void StartPID( output_t *p_output, uint16_t i_pid )
{
    int j;

    for ( j = 0; j < p_pids[i_pid].i_nb_outputs; j++ )
        if ( p_pids[i_pid].pp_outputs[j] == p_output )
            break;

    if ( j == p_pids[i_pid].i_nb_outputs )
    {
        for ( j = 0; j < p_pids[i_pid].i_nb_outputs; j++ )
            if ( p_pids[i_pid].pp_outputs[j] == NULL )
                break;

        if ( j == p_pids[i_pid].i_nb_outputs )
        {
            p_pids[i_pid].i_nb_outputs++;
            p_pids[i_pid].pp_outputs = realloc( p_pids[i_pid].pp_outputs,
                                                sizeof(output_t *)
                                                * p_pids[i_pid].i_nb_outputs );
        }

        p_pids[i_pid].pp_outputs[j] = p_output;
        SetPID( i_pid );
    }
}

static void StopPID( output_t *p_output, uint16_t i_pid )
{
    int j;

    for ( j = 0; j < p_pids[i_pid].i_nb_outputs; j++ )
    {
        if ( p_pids[i_pid].pp_outputs[j] != NULL )
        {
            if ( p_pids[i_pid].pp_outputs[j] == p_output )
                break;
        }
    }

    if ( j != p_pids[i_pid].i_nb_outputs )
    {
        p_pids[i_pid].pp_outputs[j] = NULL;
        UnsetPID( i_pid );
    }
}

/*****************************************************************************
 * SelectPID/UnselectPID
 *****************************************************************************/
1078
static void SelectPID( uint16_t i_sid, uint16_t i_pid, bool b_pcr )
1079 1080 1081 1082
{
    int i;

    for ( i = 0; i < i_nb_outputs; i++ )
1083
    {
1084
        if ( (pp_outputs[i]->config.i_config & OUTPUT_VALID)
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
              && pp_outputs[i]->config.i_sid == i_sid )
        {
            if ( pp_outputs[i]->config.i_nb_pids &&
                !IsIn( pp_outputs[i]->config.pi_pids,
                       pp_outputs[i]->config.i_nb_pids, i_pid ) )
            {
                if ( b_pcr )
                    pp_outputs[i]->i_pcr_pid = i_pid;
                else
                    continue;
            }
1096
            StartPID( pp_outputs[i], i_pid );
1097 1098
        }
    }
1099 1100 1101 1102 1103 1104 1105
}

static void UnselectPID( uint16_t i_sid, uint16_t i_pid )
{
    int i;

    for ( i = 0; i < i_nb_outputs; i++ )
1106 1107 1108
        if ( (pp_outputs[i]->config.i_config & OUTPUT_VALID)
              && pp_outputs[i]->config.i_sid == i_sid
              && !pp_outputs[i]->config.i_nb_pids )
1109 1110 1111 1112
            StopPID( pp_outputs[i], i_pid );
}

/*****************************************************************************
1113
 * SelectPMT/UnselectPMT
1114
 *****************************************************************************/
1115
static void SelectPMT( uint16_t i_sid, uint16_t i_pid )
1116 1117 1118
{
    int i;

1119 1120 1121 1122 1123 1124 1125 1126
    p_pids[i_pid].i_psi_refcount++;
    p_pids[i_pid].b_pes = false;

    if ( b_select_pmts )
        SetPID( i_pid );
    else for ( i = 0; i < i_nb_outputs; i++ )
        if ( (pp_outputs[i]->config.i_config & OUTPUT_VALID)
              && pp_outputs[i]->config.i_sid == i_sid )
1127 1128 1129
            SetPID( i_pid );
}

1130
static void UnselectPMT( uint16_t i_sid, uint16_t i_pid )
1131 1132 1133
{
    int i;

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
    p_pids[i_pid].i_psi_refcount--;
    if ( !p_pids[i_pid].i_psi_refcount )
        psi_assemble_reset( &p_pids[i_pid].p_psi_buffer,
                            &p_pids[i_pid].i_psi_buffer_used );

    if ( b_select_pmts )
        UnsetPID( i_pid );
    else for ( i = 0; i < i_nb_outputs; i++ )
        if ( (pp_outputs[i]->config.i_config & OUTPUT_VALID)
              && pp_outputs[i]->config.i_sid == i_sid )
1144 1145 1146 1147 1148 1149 1150
            UnsetPID( i_pid );
}

/*****************************************************************************
 * GetPIDS
 *****************************************************************************/
static void GetPIDS( uint16_t **ppi_wanted_pids, int *pi_nb_wanted_pids,
1151
                     uint16_t *pi_wanted_pcr_pid, uint16_t i_sid,
1152 1153
                     const uint16_t *pi_pids, int i_nb_pids )
{
1154 1155
    sid_t *p_sid;
    uint8_t *p_pmt;
1156 1157 1158
    uint16_t i_pmt_pid, i_pcr_pid;
    uint8_t *p_es;
    uint8_t j;
1159 1160 1161
    const uint8_t *p_desc;

    *pi_wanted_pcr_pid = 0;
1162 1163 1164 1165 1166 1167

    if ( i_nb_pids || i_sid == 0 )
    {
        *pi_nb_wanted_pids = i_nb_pids;
        *ppi_wanted_pids = malloc( sizeof(uint16_t) * i_nb_pids );
        memcpy( *ppi_wanted_pids, pi_pids, sizeof(uint16_t) * i_nb_pids );
1168 1169 1170 1171 1172 1173 1174
        if ( i_sid == 0 )
            return;
    }
    else
    {
        *pi_nb_wanted_pids = 0;
        *ppi_wanted_pids = NULL;
1175 1176
    }

1177 1178
    p_sid = FindSID( i_sid );
    if ( p_sid == NULL )
1179 1180
        return;

1181 1182
    p_pmt = p_sid->p_current_pmt;
    i_pmt_pid = p_sid->i_pmt_pid;
1183 1184 1185 1186
    if ( p_pmt == NULL ) {
        msg_Dbg(NULL, "no current PMT on sid %d\n", i_sid);
        return;
    }
1187

1188 1189 1190 1191 1192
    i_pcr_pid = pmt_get_pcrpid( p_pmt );
    j = 0;
    while ( (p_es = pmt_get_es( p_pmt, j )) != NULL )
    {
        j++;
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229

        uint16_t i_pid = pmtn_get_pid( p_es );
        bool b_select;
        if ( i_nb_pids )
            b_select = IsIn( pi_pids, i_nb_pids, i_pid );
        else
        {
            b_select = PIDWouldBeSelected( p_es );
            if ( b_select )
            {
                *ppi_wanted_pids = realloc( *ppi_wanted_pids,
                        (*pi_nb_wanted_pids + 1) * sizeof(uint16_t) );
                (*ppi_wanted_pids)[(*pi_nb_wanted_pids)++] = i_pid;
            }
        }

        if ( b_select && b_enable_ecm )
        {
            uint8_t k = 0;

            while ((p_desc = descs_get_desc( pmtn_get_descs( p_es ), k++ )) != NULL)
            {
                if ( desc_get_tag( p_desc ) != 0x09 || !desc09_validate( p_desc ) )
                    continue;
                *ppi_wanted_pids = realloc( *ppi_wanted_pids,
                                      (*pi_nb_wanted_pids + 1) * sizeof(uint16_t) );
                (*ppi_wanted_pids)[(*pi_nb_wanted_pids)++] =  desc09_get_pid( p_desc );
            }
        }
    }


    if ( b_enable_ecm )
    {
        j = 0;

        while ((p_desc = descs_get_desc( pmt_get_descs( p_pmt ), j++ )) != NULL)
1230
        {
1231 1232 1233
            if ( desc_get_tag( p_desc ) != 0x09 ||
                 !desc09_validate( p_desc ) )
                continue;
1234 1235
            *ppi_wanted_pids = realloc( *ppi_wanted_pids,
                                  (*pi_nb_wanted_pids + 1) * sizeof(uint16_t) );
1236
            (*ppi_wanted_pids)[(*pi_nb_wanted_pids)++] = desc09_get_pid( p_desc );
1237
        }
1238
    }
1239

1240 1241
    if ( i_pcr_pid != PADDING_PID && i_pcr_pid != i_pmt_pid
          && !IsIn( *ppi_wanted_pids, *pi_nb_wanted_pids, i_pcr_pid ) )
1242 1243 1244
    {
        *ppi_wanted_pids = realloc( *ppi_wanted_pids,
                              (*pi_nb_wanted_pids + 1) * sizeof(uint16_t) );
1245
        (*ppi_wanted_pids)[(*pi_nb_wanted_pids)++] = i_pcr_pid;
1246 1247 1248
        /* We only need the PCR packets of this stream (incomplete) */
        *pi_wanted_pcr_pid = i_pcr_pid;
        msg_Dbg( NULL, "Requesting partial PCR PID %"PRIu16, i_pcr_pid );
1249 1250 1251 1252
    }
}

/*****************************************************************************
1253
 * OutputPSISection
1254
 *****************************************************************************/
1255 1256 1257 1258
static void OutputPSISection( output_t *p_output, uint8_t *p_section,
                              uint16_t i_pid, uint8_t *pi_cc, mtime_t i_dts,
                              block_t **pp_ts_buffer,
                              uint8_t *pi_ts_buffer_offset )
1259
{
1260 1261
    uint16_t i_section_length = psi_get_length(p_section) + PSI_HEADER_SIZE;
    uint16_t i_section_offset = 0;
1262 1263 1264

    do
    {
1265 1266 1267 1268
        block_t *p_block;
        uint8_t *p;
        uint8_t i_ts_offset;
        bool b_append = (pp_ts_buffer != NULL && *pp_ts_buffer != NULL);
1269

1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
        if ( b_append )
        {
            p_block = *pp_ts_buffer;
            i_ts_offset = *pi_ts_buffer_offset;
        }
        else
        {
            p_block = block_New();
            p_block->i_dts = i_dts;
            i_ts_offset = 0;
        }
        p = p_block->p_ts;
1282

1283
        psi_split_section( p, &i_ts_offset, p_section, &i_section_offset );
1284

1285 1286 1287 1288 1289 1290 1291
        if ( !b_append )
        {
            ts_set_pid( p, i_pid );
            ts_set_cc( p, *pi_cc );
            (*pi_cc)++;
            *pi_cc &= 0xf;
        }
1292

1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
        if ( i_section_offset == i_section_length )
        {
            if ( i_ts_offset < TS_SIZE - MIN_SECTION_FRAGMENT
                  && pp_ts_buffer != NULL )
            {
                *pp_ts_buffer = p_block;
                *pi_ts_buffer_offset = i_ts_offset;
                break;
            }
            else
                psi_split_end( p, &i_ts_offset );
        }
1305

1306 1307 1308 1309 1310 1311 1312 1313
        p_block->i_dts = i_dts;
        p_block->i_refcount--;
        output_Put( p_output, p_block );
        if ( pp_ts_buffer != NULL )
        {
            *pp_ts_buffer = NULL;
            *pi_ts_buffer_offset = 0;
        }
1314
    }
1315
    while ( i_section_offset < i_section_length );
1316 1317 1318 1319 1320
}

/*****************************************************************************
 * SendPAT
 *****************************************************************************/
1321
static void SendPAT( mtime_t i_dts )
1322 1323 1324 1325 1326
{
    int i;

    for ( i = 0; i < i_nb_outputs; i++ )
    {
1327 1328
        output_t *p_output = pp_outputs[i];

1329 1330
        if ( !(p_output->config.i_config & OUTPUT_VALID) ||
             p_output->config.b_passthrough )
1331 1332
            continue;

1333 1334
        if ( p_output->p_pat_section == NULL &&
             psi_table_validate(pp_current_pat_sections) )
1335
        {
1336 1337 1338
            /* SID doesn't exist - build an empty PAT. */
            uint8_t *p;
            p_output->i_pat_version++;
1339

1340 1341 1342 1343 1344 1345 1346 1347 1348
            p = p_output->p_pat_section = psi_allocate();
            pat_init( p );
            pat_set_length( p, 0 );
            pat_set_tsid( p, p_output->i_tsid );
            psi_set_version( p, p_output->i_pat_version );
            psi_set_current( p );
            psi_set_section( p, 0 );
            psi_set_lastsection( p, 0 );
            psi_set_crc( p_output->p_pat_section );
1349 1350 1351
        }


1352 1353 1354 1355 1356
        if ( p_output->p_pat_section != NULL )
            OutputPSISection( p_output, p_output->p_pat_section, PAT_PID,
                              &p_output->i_pat_cc, i_dts, NULL, NULL );
    }
}
1357

1358 1359 1360 1361 1362 1363
/*****************************************************************************
 * SendPMT
 *****************************************************************************/
static void SendPMT( sid_t *p_sid, mtime_t i_dts )
{
    int i;
1364 1365 1366 1367
    int i_pmt_pid = p_sid->i_pmt_pid;

    if ( b_do_remap )
        i_pmt_pid = pi_newpids[ I_PMTPID ];
1368 1369 1370 1371 1372 1373 1374 1375

    for ( i = 0; i < i_nb_outputs; i++ )
    {
        output_t *p_output = pp_outputs[i];

        if ( (p_output->config.i_config & OUTPUT_VALID)
               && p_output->config.i_sid == p_sid->i_sid
               && p_output->p_pmt_section != NULL )
1376 1377 1378 1379
        {
            if ( p_output->config.b_do_remap && p_output->config.pi_confpids[I_PMTPID] )
                i_pmt_pid = p_output->config.pi_confpids[I_PMTPID];

1380
            OutputPSISection( p_output, p_output->p_pmt_section,
1381
                              i_pmt_pid, &p_output->i_pmt_cc, i_dts,
1382
                              NULL, NULL );
1383
        }
1384 1385 1386 1387
    }
}

/*****************************************************************************
1388
 * SendNIT
1389
 *****************************************************************************/
1390
static void SendNIT( mtime_t i_dts )
1391 1392 1393 1394 1395
{
    int i;

    for ( i = 0; i < i_nb_outputs; i++ )
    {
1396
        output_t *p_output = pp_outputs[i];
1397

1398
        if ( (p_output->config.i_config & OUTPUT_VALID)
1399
               && !p_output->config.b_passthrough
1400 1401 1402 1403
               && (p_output->config.i_config & OUTPUT_DVB)
               && p_output->p_nit_section != NULL )
            OutputPSISection( p_output, p_output->p_nit_section, NIT_PID,
                              &p_output->i_nit_cc, i_dts, NULL, NULL );
1404 1405 1406 1407
    }
}

/*****************************************************************************
1408
 * SendSDT
1409
 *****************************************************************************/
1410
static void SendSDT( mtime_t i_dts )
1411 1412 1413 1414 1415
{
    int i;

    for ( i = 0; i < i_nb_outputs; i++ )
    {
1416
        output_t *p_output = pp_outputs[i];
1417

1418
        if ( (p_output->config.i_config & OUTPUT_VALID)
1419
               && !p_output->config.b_passthrough
1420 1421 1422 1423
               && (p_output->config.i_config & OUTPUT_DVB)
               && p_output->p_sdt_section != NULL )
            OutputPSISection( p_output, p_output->p_sdt_section, SDT_PID,
                              &p_output->i_sdt_cc, i_dts, NULL, NULL );
1424 1425 1426 1427 1428 1429
    }
}

/*****************************************************************************
 * SendEIT
 *****************************************************************************/
1430 1431 1432 1433 1434 1435 1436
static bool handle_epg( int i_table_id )
{
    return (i_table_id == EIT_TABLE_ID_PF_ACTUAL ||
       (i_table_id >= EIT_TABLE_ID_SCHED_ACTUAL_FIRST &&
        i_table_id <= EIT_TABLE_ID_SCHED_ACTUAL_LAST));
}

1437
static void SendEIT( sid_t *p_sid, mtime_t i_dts, uint8_t *p_eit )
1438
{
1439
    uint8_t i_table_id = psi_get_tableid( p_eit );
1440 1441
    bool b_epg = handle_epg( i_table_id );
    uint16_t i_onid = eit_get_onid(p_eit);
1442 1443
    int i;

1444
    for ( i = 0; i < i_nb_outputs; i++ )
1445
    {
1446
        output_t *p_output = pp_outputs[i];
1447

1448
        if ( (p_output->config.i_config & OUTPUT_VALID)
1449
               && !p_output->config.b_passthrough
1450 1451 1452 1453
               && (p_output->config.i_config & OUTPUT_DVB)
               && (!b_epg || (p_output->config.i_config & OUTPUT_EPG))
               && p_output->config.i_sid == p_sid->i_sid )
        {
1454 1455 1456 1457 1458 1459 1460
            eit_set_tsid( p_eit, p_output->i_tsid );

            if ( p_output->config.i_new_sid )
                eit_set_sid( p_eit, p_output->config.i_new_sid );
            else
                eit_set_sid( p_eit, p_output->config.i_sid );

1461 1462 1463
            if ( p_output->config.i_onid )
                eit_set_onid( p_eit, p_output->config.i_onid );

1464
            psi_set_crc( p_eit );
1465

1466 1467 1468
            OutputPSISection( p_output, p_eit, EIT_PID, &p_output->i_eit_cc,
                              i_dts, &p_output->p_eit_ts_buffer,
                              &p_output->i_eit_ts_buffer_offset );
1469 1470 1471

            if ( p_output->config.i_onid )
                eit_set_onid( p_eit, i_onid );
1472 1473 1474 1475
        }
    }
}

1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
/*****************************************************************************
 * FlushEIT
 *****************************************************************************/
static void FlushEIT( output_t *p_output, mtime_t i_dts )
{
    block_t *p_block = p_output->p_eit_ts_buffer;

    psi_split_end( p_block->p_ts, &p_output->i_eit_ts_buffer_offset );
    p_block->i_dts = i_dts;
    p_block->i_refcount--;
    output_Put( p_output, p_block );
    p_output->p_eit_ts_buffer = NULL;
    p_output->i_eit_ts_buffer_offset = 0;
}

/*****************************************************************************
 * SendTDT
 *****************************************************************************/
static void SendTDT( block_t *p_ts )
{
    int i;

    for ( i = 0; i < i_nb_outputs; i++ )
    {
        output_t *p_output = pp_outputs[i];

        if ( (p_output->config.i_config & OUTPUT_VALID)
1503
               && !p_output->config.b_passthrough
1504 1505 1506 1507 1508
               && (p_output->config.i_config & OUTPUT_DVB)
               && p_output->p_sdt_section != NULL )
            output_Put( p_output, p_ts );
    }
}
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
/*****************************************************************************
 * SendEMM
 *****************************************************************************/
static void SendEMM( block_t *p_ts )
{
    int i;

    for ( i = 0; i < i_nb_outputs; i++ )
    {
        output_t *p_output = pp_outputs[i];

1520 1521
        if ( (p_output->config.i_config & OUTPUT_VALID)
               && !p_output->config.b_passthrough )
1522 1523 1524
            output_Put( p_output, p_ts );
    }
}
1525

1526 1527 1528 1529 1530
/*****************************************************************************
 * NewPAT
 *****************************************************************************/
static void NewPAT( output_t *p_output )
{
1531 1532 1533
    const uint8_t *p_program;
    uint8_t *p;
    uint8_t k = 0;
1534

1535
    free( p_output->p_pat_section );
1536 1537 1538
    p_output->p_pat_section = NULL;
    p_output->i_pat_version++;

1539 1540
    if ( !p_output->config.i_sid ) return;
    if ( !psi_table_validate(pp_current_pat_sections) ) return;
1541

1542 1543
    p_program = pat_table_find_program( pp_current_pat_sections,
                                        p_output->config.i_sid );
1544 1545
    if ( p_program == NULL ) return;

1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
    p = p_output->p_pat_section = psi_allocate();
    pat_init( p );
    psi_set_length( p, PSI_MAX_SIZE );
    pat_set_tsid( p, p_output->i_tsid );
    psi_set_version( p, p_output->i_pat_version );
    psi_set_current( p );
    psi_set_section( p, 0 );
    psi_set_lastsection( p, 0 );

    if ( p_output->config.i_config & OUTPUT_DVB )
    {
        /* NIT */
        p = pat_get_program( p_output->p_pat_section, k++ );
        patn_init( p );
        patn_set_program( p, 0 );
        patn_set_pid( p, NIT_PID );
    }
1563

1564 1565
    p = pat_get_program( p_output->p_pat_section, k++ );
    patn_init( p );
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
    if ( p_output->config.i_new_sid )
    {
        msg_Dbg( NULL, "Mapping PAT SID %d to %d", p_output->config.i_sid,
                 p_output->config.i_new_sid );
        patn_set_program( p, p_output->config.i_new_sid );
    }
    else
        patn_set_program( p, p_output->config.i_sid );

    if ( b_do_remap )
    {
        msg_Dbg( NULL, "Mapping PMT PID %d to %d", patn_get_pid( p_program ), pi_newpids[I_PMTPID] );
        patn_set_pid( p, pi_newpids[I_PMTPID]);
    } else if ( p_output->config.b_do_remap && p_output->config.pi_confpids[I_PMTPID] ) {
        msg_Dbg( NULL, "Mapping PMT PID %d to %d", patn_get_pid( p_program ), p_output->config.pi_confpids[I_PMTPID] );
        patn_set_pid( p, p_output->config.pi_confpids[I_PMTPID]);
    } else {
        patn_set_pid( p, patn_get_pid( p_program ) );
    }
1585

1586 1587 1588 1589
    p = pat_get_program( p_output->p_pat_section, k );
    pat_set_length( p_output->p_pat_section,
                    p - p_output->p_pat_section - PAT_HEADER_SIZE );
    psi_set_crc( p_output->p_pat_section );
1590 1591 1592
}

/*****************************************************************************
1593
 * NewPMT
1594
 *****************************************************************************/
1595
static void CopyDescriptors( uint8_t *p_descs, uint8_t *p_current_descs )
1596
{
1597 1598 1599
    uint8_t *p_desc;
    const uint8_t *p_current_desc;
    uint16_t j = 0, k = 0;