]> git.sesse.net Git - vlc/blobdiff - modules/demux/ts.c
demux: ts: rewrite/split IOD parsing
[vlc] / modules / demux / ts.c
index 641c785323e5b21893a5fcbc1297f3f4cebd044c..2e36f05ba63187b56a3e817602684341b486d7b1 100644 (file)
 # include <dvbpsi/tot.h>
 
 #include "../mux/mpeg/dvbpsi_compat.h"
+#include "../mux/mpeg/streams.h"
+#include "../mux/mpeg/tsutil.h"
+#include "../mux/mpeg/tables.h"
 
 #include "../codec/opus_header.h"
 
 #include "opus.h"
 
-#undef TS_DEBUG
-VLC_FORMAT(1, 2) static void ts_debug(const char *format, ...)
-{
-#ifdef TS_DEBUG
-    va_list ap;
-    va_start(ap, format);
-    vfprintf(stderr, format, ap);
-    va_end(ap);
-#else
-    (void)format;
-#endif
-}
+#include "mpeg4_iod.h"
 
 #ifdef HAVE_ARIBB24
  #include <aribb24/aribb24.h>
@@ -199,62 +191,49 @@ static const char *const ppsz_teletext_type[] = {
  N_("Teletext subtitles: hearing impaired")
 };
 
-typedef struct
-{
-    uint8_t                 i_objectTypeIndication;
-    uint8_t                 i_streamType;
-
-    int                     i_extra;
-    uint8_t                 *p_extra;
-
-} decoder_config_descriptor_t;
+typedef struct ts_pid_t ts_pid_t;
 
 typedef struct
 {
-    bool                    b_ok;
-    uint16_t                i_es_id;
-
-    char                    *psz_url;
-
-    decoder_config_descriptor_t    dec_descr;
-
-} es_mpeg4_descriptor_t;
-
-#define ES_DESCRIPTOR_COUNT 255
-typedef struct
-{
-    /* IOD */
-    char                    *psz_url;
-
-    es_mpeg4_descriptor_t   es_descr[ES_DESCRIPTOR_COUNT];
+    int             i_version;
+    int             i_ts_id;
+    dvbpsi_t       *handle;
+    DECL_ARRAY(ts_pid_t *) programs;
 
-} iod_descriptor_t;
+} ts_pat_t;
 
 typedef struct
 {
-    dvbpsi_handle   handle;
+    dvbpsi_t       *handle;
     int             i_version;
     int             i_number;
     int             i_pid_pcr;
-    int             i_pid_pmt;
-    mtime_t         i_pcr_value;
     /* IOD stuff (mpeg4) */
     iod_descriptor_t *iod;
 
-} ts_prg_psi_t;
+    DECL_ARRAY(ts_pid_t *) e_streams;
 
-typedef struct
-{
-    /* for special PAT/SDT case */
-    dvbpsi_handle   handle; /* PAT/SDT/EIT */
-    int             i_pat_version;
-    int             i_sdt_version;
+    struct
+    {
+        mtime_t i_current;
+        mtime_t i_first; // seen <> != -1
+        /* broken PCR handling */
+        mtime_t i_first_dts;
+        mtime_t i_pcroffset;
+        bool    b_disable; /* ignore PCR field, use dts */
+        bool    b_fix_done;
+    } pcr;
 
-    /* For PMT */
-    int             i_prg;
-    ts_prg_psi_t    **prg;
+    mtime_t i_last_dts;
 
-} ts_psi_t;
+} ts_pmt_t;
+
+typedef struct
+{
+    es_format_t  fmt;
+    es_out_id_t *id;
+    const es_mpeg4_descriptor_t *p_mpeg4desc;
+} ts_pes_es_t;
 
 typedef enum
 {
@@ -262,71 +241,120 @@ typedef enum
     TS_ES_DATA_TABLE_SECTION
 } ts_es_data_type_t;
 
-typedef enum
-{
-    TS_PMT_REGISTRATION_NONE = 0,
-    TS_PMT_REGISTRATION_HDMV
-} ts_pmt_registration_type_t;
-
 typedef struct
 {
-    es_format_t  fmt;
-    es_out_id_t *id;
+    ts_pes_es_t es;
+    /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
+    DECL_ARRAY( ts_pes_es_t * ) extra_es;
+
     ts_es_data_type_t data_type;
     int         i_data_size;
     int         i_data_gathered;
     block_t     *p_data;
     block_t     **pp_last;
 
-    es_mpeg4_descriptor_t *p_mpeg4desc;
+    block_t *   p_prepcr_outqueue;
+
+} ts_pes_t;
 
-} ts_es_t;
 
 typedef struct
 {
-    int         i_pid;
+    /* for special PAT/SDT case */
+    dvbpsi_t       *handle; /* PAT/SDT/EIT */
+    int             i_version;
+
+} ts_psi_t;
+
+typedef enum
+{
+    TS_PMT_REGISTRATION_NONE = 0,
+    TS_PMT_REGISTRATION_HDMV
+} ts_pmt_registration_type_t;
+
+typedef enum
+{
+    TYPE_FREE = 0,
+    TYPE_PAT,
+    TYPE_PMT,
+    TYPE_PES,
+    TYPE_SDT,
+    TYPE_TDT,
+    TYPE_EIT,
+} ts_pid_type_t;
+
+enum
+{
+    FLAGS_NONE = 0,
+    FLAG_SEEN  = 1,
+    FLAG_SCRAMBLED = 2,
+    FLAG_FILTERED = 4
+};
 
-    bool        b_seen;
-    bool        b_valid;
-    int         i_cc;   /* countinuity counter */
-    bool        b_scrambled;
+#define SEEN(x) ((x)->i_flags & FLAG_SEEN)
+#define SCRAMBLED(x) ((x).i_flags & FLAG_SCRAMBLED)
+
+struct ts_pid_t
+{
+    uint16_t    i_pid;
+
+    uint8_t     i_flags;
+    uint8_t     i_cc;   /* countinuity counter */
+    uint8_t     type;
 
     /* PSI owner (ie PMT -> PAT, ES -> PMT */
-    ts_psi_t   *p_owner;
-    int         i_owner_number;
+    uint8_t     i_refcount;
+    ts_pid_t   *p_parent;
 
     /* */
-    ts_psi_t    *psi;
-    ts_es_t     *es;
+    union
+    {
+        ts_pat_t    *p_pat;
+        ts_pmt_t    *p_pmt;
+        ts_pes_t    *p_pes;
+        ts_psi_t    *p_psi;
+    } u;
 
-    /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
-    ts_es_t     **extra_es;
-    int         i_extra_es;
+    struct
+    {
+        vlc_fourcc_t i_fourcc;
+        int i_type;
+        int i_pcr_count;
+    } probed;
 
-} ts_pid_t;
+};
+
+typedef struct
+{
+    int i_service;
+} vdr_info_t;
+
+#define MIN_ES_PID 4    /* Should be 32.. broken muxers */
+#define MAX_ES_PID 8190
+#define MIN_PAT_INTERVAL CLOCK_FREQ // DVB is 500ms
+
+#define FROM_SCALE(x) (VLC_TS_0 + ((x) * 100 / 9))
+#define TO_SCALE(x)   (((x) - VLC_TS_0) * 9 / 100)
+
+#define PID_ALLOC_CHUNK 16
 
 struct demux_sys_t
 {
+    stream_t   *stream;
+    bool        b_canseek;
+    bool        b_canfastseek;
     vlc_mutex_t     csa_lock;
 
     /* TS packet size (188, 192, 204) */
-    int         i_packet_size;
+    unsigned    i_packet_size;
 
     /* Additional TS packet header size (BluRay TS packets have 4-byte header before sync byte) */
-    int         i_packet_header_size;
+    unsigned    i_packet_header_size;
 
     /* how many TS packet we read at once */
-    int         i_ts_read;
+    unsigned    i_ts_read;
 
-    /* to determine length and time */
-    int         i_pid_ref_pcr;
-    mtime_t     i_first_pcr;
-    mtime_t     i_current_pcr;
-    mtime_t     i_last_pcr;
     bool        b_force_seek_per_percent;
-    int         i_pcrs_num;
-    mtime_t     *p_pcrs;
-    int64_t     *p_pos;
 
     struct
     {
@@ -334,19 +362,39 @@ struct demux_sys_t
 #ifdef HAVE_ARIBB24
         arib_instance_t *p_instance;
 #endif
+        stream_t     *b25stream;
     } arib;
 
     /* All pid */
-    ts_pid_t    pid[8192];
+    struct
+    {
+        ts_pid_t pat;
+        ts_pid_t dummy;
+        /* all non commons ones, dynamically allocated */
+        ts_pid_t **pp_all;
+        int        i_all;
+        int        i_all_alloc;
+        /* last recently used */
+        uint16_t   i_last_pid;
+        ts_pid_t  *p_last;
+    } pids;
 
-    /* All PMT */
     bool        b_user_pmt;
-    int         i_pmt;
-    ts_pid_t    **pmt;
     int         i_pmt_es;
+    bool        b_es_all; /* If we need to return all es/programs */
+
+    enum
+    {
+        NO_ES, /* for preparse */
+        DELAY_ES,
+        CREATE_ES
+    } es_creation;
+    #define PREPARSING p_sys->es_creation == NO_ES
 
     /* */
     bool        b_es_id_pid;
+    uint16_t    i_next_extraid;
+
     csa_t       *csa;
     int         i_csa_pkt_size;
     bool        b_split_es;
@@ -355,6 +403,7 @@ struct demux_sys_t
 
     /* */
     bool        b_access_control;
+    bool        b_end_preparse;
 
     /* */
     bool        b_dvb_meta;
@@ -363,9 +412,18 @@ struct demux_sys_t
     int64_t     i_dvb_length;
     bool        b_broken_charset; /* True if broken encoding is used in EPG/SDT */
 
-    /* */
-    int         i_current_program;
-    vlc_list_t  programs_list;
+    /* Selected programs */
+    DECL_ARRAY( int ) programs; /* List of selected/access-filtered programs */
+    bool        b_default_selection; /* True if set by default to first pmt seen (to get data from filtered access) */
+
+    struct
+    {
+        mtime_t i_first_dts;     /* first dts encountered for the stream */
+        int     i_timesourcepid; /* which pid we saved the dts from */
+        bool    b_pat_deadline;  /* set if we haven't seen PAT within MIN_PAT_INTERVAL */
+    } patfix;
+
+    vdr_info_t  vdr;
 
     /* */
     bool        b_start_record;
@@ -374,148 +432,93 @@ struct demux_sys_t
 static int Demux    ( demux_t *p_demux );
 static int Control( demux_t *p_demux, int i_query, va_list args );
 
-static void PIDInit ( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner );
-static void PIDClean( demux_t *, ts_pid_t *pid );
 static void PIDFillFormat( es_format_t *fmt, int i_stream_type );
 
+static bool PIDSetup( demux_t *p_demux, ts_pid_type_t i_type, ts_pid_t *pid, ts_pid_t *p_parent );
+static void PIDRelease( demux_t *p_demux, ts_pid_t *pid );
+
 static void PATCallBack( void*, dvbpsi_pat_t * );
 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt );
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
 static void PSINewTableCallBack( dvbpsi_t *handle, uint8_t  i_table_id,
                                  uint16_t i_extension, demux_t * );
-#else
-static void PSINewTableCallBack( demux_t *, dvbpsi_handle,
-                                 uint8_t  i_table_id, uint16_t i_extension );
-#endif
 
 static int ChangeKeyCallback( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
 
+/* Structs */
+static ts_pat_t *ts_pat_New( demux_t * );
+static void ts_pat_Del( demux_t *, ts_pat_t * );
+static ts_pmt_t *ts_pmt_New( demux_t * );
+static void ts_pmt_Del( demux_t *, ts_pmt_t * );
+static ts_pes_t *ts_pes_New( demux_t * );
+static void ts_pes_Del( demux_t *, ts_pes_t * );
+static ts_psi_t *ts_psi_New( demux_t * );
+static void ts_psi_Del( demux_t *, ts_psi_t * );
+
+/* Helpers */
+static ts_pid_t *PID( demux_sys_t *, uint16_t i_pid );
+static ts_pmt_t * GetProgramByID( demux_sys_t *, int i_program );
+static bool ProgramIsSelected( demux_sys_t *, uint16_t i_pgrm );
+static void UpdatePESFilters( demux_t *p_demux, bool b_all );
+static inline void FlushESBuffer( ts_pes_t *p_pes );
+static void UpdateScrambledState( demux_t *p_demux, ts_pid_t *p_pid, bool );
 static inline int PIDGet( block_t *p )
 {
     return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
 }
 
 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
+static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid, bool );
+static void ProgramSetPCR( demux_t *p_demux, ts_pmt_t *p_prg, mtime_t i_pcr );
 
 static block_t* ReadTSPacket( demux_t *p_demux );
-static int Seek( demux_t *p_demux, double f_percent );
-static void GetFirstPCR( demux_t *p_demux );
-static void GetLastPCR( demux_t *p_demux );
-static void CheckPCR( demux_t *p_demux );
+static int ProbeStart( demux_t *p_demux, int i_program );
+static int ProbeEnd( demux_t *p_demux, int i_program );
+static int SeekToTime( demux_t *p_demux, ts_pmt_t *, int64_t time );
+static void ReadyQueuesPostSeek( demux_t *p_demux );
 static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );
-
-static void              IODFree( iod_descriptor_t * );
+static void PCRFixHandle( demux_t *, ts_pmt_t *, block_t * );
+static int64_t TimeStampWrapAround( ts_pmt_t *, int64_t );
 
 #define TS_USER_PMT_NUMBER (0)
 static int UserPmt( demux_t *p_demux, const char * );
 
-static int  SetPIDFilter( demux_t *, int i_pid, bool b_selected );
-static void SetPrgFilter( demux_t *, int i_prg, bool b_selected );
+static int  SetPIDFilter( demux_sys_t *, ts_pid_t *, bool b_selected );
 
 #define TS_PACKET_SIZE_188 188
 #define TS_PACKET_SIZE_192 192
 #define TS_PACKET_SIZE_204 204
 #define TS_PACKET_SIZE_MAX 204
+#define TS_HEADER_SIZE 4
 
-static int DetectPacketSize( demux_t *p_demux, int *pi_header_size )
+static int DetectPacketSize( demux_t *p_demux, unsigned *pi_header_size, int i_offset )
 {
     const uint8_t *p_peek;
+
     if( stream_Peek( p_demux->s,
-                     &p_peek, TS_PACKET_SIZE_MAX ) < TS_PACKET_SIZE_MAX )
+                     &p_peek, i_offset + TS_PACKET_SIZE_MAX ) < i_offset + TS_PACKET_SIZE_MAX )
         return -1;
 
-    *pi_header_size = 0;
-
-    if( memcmp( p_peek, "TFrc", 4 ) == 0 )
-    {
-#if 0
-        /* I used the TF5000PVR 2004 Firmware .doc header documentation,
-         * http://www.i-topfield.com/data/product/firmware/Structure%20of%20Recorded%20File%20in%20TF5000PVR%20(Feb%2021%202004).doc
-         * but after the filename the offsets seem to be incorrect.  - DJ */
-        int i_duration, i_name;
-        char *psz_name = xmalloc(25);
-        char *psz_event_name;
-        char *psz_event_text = xmalloc(130);
-        char *psz_ext_text = xmalloc(1025);
-
-        // 2 bytes version Uimsbf (4,5)
-        // 2 bytes reserved (6,7)
-        // 2 bytes duration in minutes Uimsbf (8,9(
-        i_duration = (int) (p_peek[8] << 8) | p_peek[9];
-        msg_Dbg( p_demux, "Topfield recording length: +/- %d minutes", i_duration);
-        // 2 bytes service number in channel list (10, 11)
-        // 2 bytes service type Bslbf 0=TV 1=Radio Bslb (12, 13)
-        // 4 bytes of reserved + tuner info (14,15,16,17)
-        // 2 bytes of Service ID  Bslbf (18,19)
-        // 2 bytes of PMT PID  Uimsbf (20,21)
-        // 2 bytes of PCR PID  Uimsbf (22,23)
-        // 2 bytes of Video PID  Uimsbf (24,25)
-        // 2 bytes of Audio PID  Uimsbf (26,27)
-        // 24 bytes filename Bslbf
-        memcpy( psz_name, &p_peek[28], 24 );
-        psz_name[24] = '\0';
-        msg_Dbg( p_demux, "recordingname=%s", psz_name );
-        // 1 byte of sat index Uimsbf  (52)
-        // 3 bytes (1 bit of polarity Bslbf +23 bits reserved)
-        // 4 bytes of freq. Uimsbf (56,57,58,59)
-        // 2 bytes of symbol rate Uimsbf (60,61)
-        // 2 bytes of TS stream ID Uimsbf (62,63)
-        // 4 bytes reserved
-        // 2 bytes reserved
-        // 2 bytes duration Uimsbf (70,71)
-        //i_duration = (int) (p_peek[70] << 8) | p_peek[71];
-        //msg_Dbg( p_demux, "Topfield 2nd duration field: +/- %d minutes", i_duration);
-        // 4 bytes EventID Uimsbf (72-75)
-        // 8 bytes of Start and End time info (76-83)
-        // 1 byte reserved (84)
-        // 1 byte event name length Uimsbf (89)
-        i_name = (int)(p_peek[89]&~0x81);
-        msg_Dbg( p_demux, "event name length = %d", i_name);
-        psz_event_name = xmalloc( i_name+1 );
-        // 1 byte parental rating (90)
-        // 129 bytes of event text
-        memcpy( psz_event_name, &p_peek[91], i_name );
-        psz_event_name[i_name] = '\0';
-        memcpy( psz_event_text, &p_peek[91+i_name], 129-i_name );
-        psz_event_text[129-i_name] = '\0';
-        msg_Dbg( p_demux, "event name=%s", psz_event_name );
-        msg_Dbg( p_demux, "event text=%s", psz_event_text );
-        // 12 bytes reserved (220)
-        // 6 bytes reserved
-        // 2 bytes Event Text Length Uimsbf
-        // 4 bytes EventID Uimsbf
-        // FIXME We just have 613 bytes. not enough for this entire text
-        // 1024 bytes Extended Event Text Bslbf
-        memcpy( psz_ext_text, p_peek+372, 1024 );
-        psz_ext_text[1024] = '\0';
-        msg_Dbg( p_demux, "extended event text=%s", psz_ext_text );
-        // 52 bytes reserved Bslbf
-#endif
-        msg_Dbg( p_demux, "this is a topfield file" );
-        return TS_PACKET_SIZE_188;
-    }
-
     for( int i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
     {
-        if( p_peek[i_sync] != 0x47 )
+        if( p_peek[i_offset + i_sync] != 0x47 )
             continue;
 
         /* Check next 3 sync bytes */
-        int i_peek = TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
+        int i_peek = i_offset + TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
         if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
         {
             msg_Err( p_demux, "cannot peek" );
             return -1;
         }
-        if( p_peek[i_sync + 1 * TS_PACKET_SIZE_188] == 0x47 &&
-            p_peek[i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
-            p_peek[i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
+        if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_188] == 0x47 &&
+            p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
+            p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
         {
             return TS_PACKET_SIZE_188;
         }
-        else if( p_peek[i_sync + 1 * TS_PACKET_SIZE_192] == 0x47 &&
-                 p_peek[i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
-                 p_peek[i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
+        else if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_192] == 0x47 &&
+                 p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
+                 p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
         {
             if( i_sync == 4 )
             {
@@ -523,9 +526,9 @@ static int DetectPacketSize( demux_t *p_demux, int *pi_header_size )
             }
             return TS_PACKET_SIZE_192;
         }
-        else if( p_peek[i_sync + 1 * TS_PACKET_SIZE_204] == 0x47 &&
-                 p_peek[i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
-                 p_peek[i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
+        else if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_204] == 0x47 &&
+                 p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
+                 p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
         {
             return TS_PACKET_SIZE_204;
         }
@@ -540,49 +543,410 @@ static int DetectPacketSize( demux_t *p_demux, int *pi_header_size )
     return -1;
 }
 
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-static void vlc_dvbpsi_reset( demux_t *p_demux )
+#define TOPFIELD_HEADER_SIZE 3712
+
+static int DetectPVRHeadersAndHeaderSize( demux_t *p_demux, unsigned *pi_header_size, vdr_info_t *p_vdr )
+{
+    const uint8_t *p_peek;
+    *pi_header_size = 0;
+    int i_packet_size = -1;
+
+    if( stream_Peek( p_demux->s,
+                     &p_peek, TS_PACKET_SIZE_MAX ) < TS_PACKET_SIZE_MAX )
+        return -1;
+
+    if( memcmp( p_peek, "TFrc", 4 ) == 0 &&
+        p_peek[6] == 0 && memcmp( &p_peek[53], "\x80\x00\x00", 4 ) == 0 &&
+        stream_Peek( p_demux->s, &p_peek, TOPFIELD_HEADER_SIZE + TS_PACKET_SIZE_MAX )
+            == TOPFIELD_HEADER_SIZE + TS_PACKET_SIZE_MAX )
+    {
+        i_packet_size = DetectPacketSize( p_demux, pi_header_size, TOPFIELD_HEADER_SIZE );
+        if( i_packet_size != -1 )
+        {
+            msg_Dbg( p_demux, "this is a topfield file" );
+#if 0
+            /* I used the TF5000PVR 2004 Firmware .doc header documentation,
+             * http://www.i-topfield.com/data/product/firmware/Structure%20of%20Recorded%20File%20in%20TF5000PVR%20(Feb%2021%202004).doc
+             * but after the filename the offsets seem to be incorrect.  - DJ */
+            int i_duration, i_name;
+            char *psz_name = xmalloc(25);
+            char *psz_event_name;
+            char *psz_event_text = xmalloc(130);
+            char *psz_ext_text = xmalloc(1025);
+
+            // 2 bytes version Uimsbf (4,5)
+            // 2 bytes reserved (6,7)
+            // 2 bytes duration in minutes Uimsbf (8,9(
+            i_duration = (int) (p_peek[8] << 8) | p_peek[9];
+            msg_Dbg( p_demux, "Topfield recording length: +/- %d minutes", i_duration);
+            // 2 bytes service number in channel list (10, 11)
+            // 2 bytes service type Bslbf 0=TV 1=Radio Bslb (12, 13)
+            // 4 bytes of reserved + tuner info (14,15,16,17)
+            // 2 bytes of Service ID  Bslbf (18,19)
+            // 2 bytes of PMT PID  Uimsbf (20,21)
+            // 2 bytes of PCR PID  Uimsbf (22,23)
+            // 2 bytes of Video PID  Uimsbf (24,25)
+            // 2 bytes of Audio PID  Uimsbf (26,27)
+            // 24 bytes filename Bslbf
+            memcpy( psz_name, &p_peek[28], 24 );
+            psz_name[24] = '\0';
+            msg_Dbg( p_demux, "recordingname=%s", psz_name );
+            // 1 byte of sat index Uimsbf  (52)
+            // 3 bytes (1 bit of polarity Bslbf +23 bits reserved)
+            // 4 bytes of freq. Uimsbf (56,57,58,59)
+            // 2 bytes of symbol rate Uimsbf (60,61)
+            // 2 bytes of TS stream ID Uimsbf (62,63)
+            // 4 bytes reserved
+            // 2 bytes reserved
+            // 2 bytes duration Uimsbf (70,71)
+            //i_duration = (int) (p_peek[70] << 8) | p_peek[71];
+            //msg_Dbg( p_demux, "Topfield 2nd duration field: +/- %d minutes", i_duration);
+            // 4 bytes EventID Uimsbf (72-75)
+            // 8 bytes of Start and End time info (76-83)
+            // 1 byte reserved (84)
+            // 1 byte event name length Uimsbf (89)
+            i_name = (int)(p_peek[89]&~0x81);
+            msg_Dbg( p_demux, "event name length = %d", i_name);
+            psz_event_name = xmalloc( i_name+1 );
+            // 1 byte parental rating (90)
+            // 129 bytes of event text
+            memcpy( psz_event_name, &p_peek[91], i_name );
+            psz_event_name[i_name] = '\0';
+            memcpy( psz_event_text, &p_peek[91+i_name], 129-i_name );
+            psz_event_text[129-i_name] = '\0';
+            msg_Dbg( p_demux, "event name=%s", psz_event_name );
+            msg_Dbg( p_demux, "event text=%s", psz_event_text );
+            // 12 bytes reserved (220)
+            // 6 bytes reserved
+            // 2 bytes Event Text Length Uimsbf
+            // 4 bytes EventID Uimsbf
+            // FIXME We just have 613 bytes. not enough for this entire text
+            // 1024 bytes Extended Event Text Bslbf
+            memcpy( psz_ext_text, p_peek+372, 1024 );
+            psz_ext_text[1024] = '\0';
+            msg_Dbg( p_demux, "extended event text=%s", psz_ext_text );
+            // 52 bytes reserved Bslbf
+#endif
+            p_vdr->i_service = GetWBE(&p_peek[18]);
+
+            return i_packet_size;
+            //return TS_PACKET_SIZE_188;
+        }
+    }
+
+    return DetectPacketSize( p_demux, pi_header_size, 0 );
+}
+
+static inline mtime_t ExtractPESTimestamp( const uint8_t *p_data )
+{
+    return ((mtime_t)(p_data[ 0]&0x0e ) << 29)|
+             (mtime_t)(p_data[1] << 22)|
+            ((mtime_t)(p_data[2]&0xfe) << 14)|
+             (mtime_t)(p_data[3] << 7)|
+             (mtime_t)(p_data[4] >> 1);
+}
+
+static void ProbePES( demux_t *p_demux, ts_pid_t *pid, const uint8_t *p_pesstart, size_t i_data, bool b_adaptfield )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
+    const uint8_t *p_pes = p_pesstart;
+    pid->probed.i_type = -1;
 
-    ts_pid_t *pat = &p_sys->pid[0];
-    ts_pid_t *sdt = &p_sys->pid[0x11];
-    ts_pid_t *eit = &p_sys->pid[0x12];
-    ts_pid_t *tdt = &p_sys->pid[0x14];
+    if( b_adaptfield )
+    {
+        if ( i_data < 2 )
+            return;
 
-    if( pat->psi->handle )
+        uint8_t len = *p_pes;
+        p_pes++; i_data--;
+
+        if(len == 0)
+        {
+            p_pes++; i_data--;/* stuffing */
+        }
+        else
+        {
+            if( i_data < len )
+                return;
+            if( len >= 7 && (p_pes[1] & 0x10) )
+                pid->probed.i_pcr_count++;
+            p_pes += len;
+            i_data -= len;
+        }
+    }
+
+    if( i_data < 9 )
+        return;
+
+    if( p_pes[0] != 0 || p_pes[1] != 0 || p_pes[2] != 1 )
+        return;
+
+    size_t i_pesextoffset = 8;
+    mtime_t i_dts = -1;
+    if( p_pes[7] & 0x80 ) // PTS
+    {
+        i_pesextoffset += 5;
+        if ( i_data < i_pesextoffset )
+            return;
+        i_dts = ExtractPESTimestamp( &p_pes[9] );
+    }
+    if( p_pes[7] & 0x40 ) // DTS
+    {
+        i_pesextoffset += 5;
+        if ( i_data < i_pesextoffset )
+            return;
+        i_dts = ExtractPESTimestamp( &p_pes[14] );
+    }
+    if( p_pes[7] & 0x20 ) // ESCR
+        i_pesextoffset += 6;
+    if( p_pes[7] & 0x10 ) // ESrate
+        i_pesextoffset += 3;
+    if( p_pes[7] & 0x08 ) // DSM
+        i_pesextoffset += 1;
+    if( p_pes[7] & 0x04 ) // CopyInfo
+        i_pesextoffset += 1;
+    if( p_pes[7] & 0x02 ) // PESCRC
+        i_pesextoffset += 2;
+
+    if ( i_data < i_pesextoffset )
+        return;
+
+     /* HeaderdataLength */
+    const size_t i_payloadoffset = 8 + 1 + p_pes[8];
+    i_pesextoffset += 1;
+
+    if ( i_data < i_pesextoffset || i_data < i_payloadoffset )
+        return;
+
+    i_data -= 8 + 1 + p_pes[8];
+
+    if( p_pes[7] & 0x01 ) // PESExt
     {
-        if( dvbpsi_decoder_present( pat->psi->handle ) )
-            dvbpsi_pat_detach( pat->psi->handle );
-        dvbpsi_delete( pat->psi->handle );
-        pat->psi->handle = NULL;
+        size_t i_extension2_offset = 1;
+        if ( p_pes[i_pesextoffset] & 0x80 ) // private data
+            i_extension2_offset += 16;
+        if ( p_pes[i_pesextoffset] & 0x40 ) // pack
+            i_extension2_offset += 1;
+        if ( p_pes[i_pesextoffset] & 0x20 ) // seq
+            i_extension2_offset += 2;
+        if ( p_pes[i_pesextoffset] & 0x10 ) // P-STD
+            i_extension2_offset += 2;
+        if ( p_pes[i_pesextoffset] & 0x01 ) // Extension 2
+        {
+            uint8_t i_len = p_pes[i_pesextoffset + i_extension2_offset] & 0x7F;
+            i_extension2_offset += i_len;
+        }
+        if( i_data < i_extension2_offset )
+            return;
+
+        i_data -= i_extension2_offset;
     }
+    /* (i_payloadoffset - i_pesextoffset) 0xFF stuffing */
+
+    if ( i_data < 4 )
+        return;
+
+    const uint8_t *p_data = &p_pes[i_payloadoffset];
+    /* AUDIO STREAM */
+    if(p_pes[3] >= 0xC0 && p_pes[3] <= 0xDF)
+    {
+        if( !memcmp( p_data, "\x7F\xFE\x80\x01", 4 ) )
+        {
+            pid->probed.i_type = 0x06;
+            pid->probed.i_fourcc = VLC_CODEC_DTS;
+        }
+        else if( !memcmp( p_data, "\x0B\x77", 2 ) )
+        {
+            pid->probed.i_type = 0x06;
+            pid->probed.i_fourcc = VLC_CODEC_EAC3;
+        }
+        else if( p_data[0] == 0xFF && (p_data[1] & 0xE0) == 0xE0 )
+        {
+            switch(p_data[1] & 18)
+            {
+            /* 10 - MPEG Version 2 (ISO/IEC 13818-3)
+               11 - MPEG Version 1 (ISO/IEC 11172-3) */
+                case 0x10:
+                    pid->probed.i_type = 0x04;
+                    break;
+                case 0x18:
+                    pid->probed.i_type = 0x03;
+                default:
+                    break;
+            }
 
-    if( sdt->psi->handle )
+            switch(p_data[1] & 6)
+            {
+            /* 01 - Layer III
+               10 - Layer II
+               11 - Layer I */
+                case 0x06:
+                    pid->probed.i_type = 0x04;
+                    pid->probed.i_fourcc = VLC_CODEC_MPGA;
+                    break;
+                case 0x04:
+                    pid->probed.i_type = 0x04;
+                    pid->probed.i_fourcc = VLC_CODEC_MP2;
+                    break;
+                case 0x02:
+                    pid->probed.i_type = 0x04;
+                    pid->probed.i_fourcc = VLC_CODEC_MP3;
+                default:
+                    break;
+            }
+        }
+    }
+    /* VIDEO STREAM */
+    else if( p_pes[3] >= 0xE0 && p_pes[3] <= 0xEF )
     {
-        if( dvbpsi_decoder_present( sdt->psi->handle ) )
-            dvbpsi_DetachDemux( sdt->psi->handle );
-        dvbpsi_delete( sdt->psi->handle );
-        sdt->psi->handle = NULL;
+        if( !memcmp( p_data, "\x00\x00\x00", 4 ) )
+        {
+            pid->probed.i_type = 0x1b;
+            pid->probed.i_fourcc = VLC_CODEC_H264;
+        }
+        else if( !memcmp( p_data, "\x00\x00\x01", 4 ) )
+        {
+            pid->probed.i_type = 0x02;
+            pid->probed.i_fourcc = VLC_CODEC_MPGV;
+        }
     }
 
-    if( eit->psi->handle )
+    /* Track timestamps and flag missing PAT */
+    if( !p_sys->patfix.i_timesourcepid && i_dts > -1 )
+    {
+        p_sys->patfix.i_first_dts = i_dts;
+        p_sys->patfix.i_timesourcepid = pid->i_pid;
+    }
+    else if( p_sys->patfix.i_timesourcepid == pid->i_pid && i_dts > -1 &&
+             !p_sys->patfix.b_pat_deadline )
     {
-        if( dvbpsi_decoder_present( eit->psi->handle ) )
-            dvbpsi_DetachDemux( eit->psi->handle );
-        dvbpsi_delete( eit->psi->handle );
-        eit->psi->handle = NULL;
+        if( i_dts - p_sys->patfix.i_first_dts > TO_SCALE(MIN_PAT_INTERVAL) )
+            p_sys->patfix.b_pat_deadline = true;
     }
 
-    if( tdt->psi->handle )
+}
+
+static void BuildPATCallback( void *p_opaque, block_t *p_block )
+{
+    ts_pid_t *pat_pid = (ts_pid_t *) p_opaque;
+    dvbpsi_packet_push( pat_pid->u.p_pat->handle, p_block->p_buffer );
+}
+
+static void BuildPMTCallback( void *p_opaque, block_t *p_block )
+{
+    ts_pid_t *program_pid = (ts_pid_t *) p_opaque;
+    assert(program_pid->type == TYPE_PMT);
+    while( p_block )
     {
-        if( dvbpsi_decoder_present( tdt->psi->handle ) )
-            dvbpsi_DetachDemux( tdt->psi->handle );
-        dvbpsi_delete( tdt->psi->handle );
-        tdt->psi->handle = NULL;
+        dvbpsi_packet_push( program_pid->u.p_pmt->handle,
+                            p_block->p_buffer );
+        p_block = p_block->p_next;
     }
 }
-#endif
+
+static void MissingPATPMTFixup( demux_t *p_demux )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    int i_program_number = 1234;
+    int i_program_pid = 1337;
+    int i_pcr_pid = 0x1FFF;
+    int i_num_pes = 0;
+
+    ts_pid_t *p_program_pid = PID( p_sys, i_program_pid );
+    if( SEEN(p_program_pid) )
+    {
+        /* Find a free one */
+        for( i_program_pid = MIN_ES_PID;
+             i_program_pid <= MAX_ES_PID && SEEN(p_program_pid);
+             i_program_pid++ )
+        {
+            p_program_pid = PID( p_sys, i_program_pid );
+        }
+    }
+
+    for( int i=0; i<p_sys->pids.i_all; i++ )
+    {
+        const ts_pid_t *p_pid = p_sys->pids.pp_all[i];
+        if( !SEEN(p_pid) ||
+            p_pid->probed.i_type == -1 )
+            continue;
+
+        if( i_pcr_pid == 0x1FFF && ( p_pid->probed.i_type == 0x03 ||
+                                     p_pid->probed.i_pcr_count ) )
+            i_pcr_pid = p_pid->i_pid;
+
+        i_num_pes++;
+    }
+
+    if( i_num_pes == 0 )
+        return;
+
+    ts_stream_t patstream =
+    {
+        .i_pid = 0,
+        .i_continuity_counter = 0x10,
+        .b_discontinuity = false
+    };
+
+    ts_stream_t pmtprogramstream =
+    {
+        .i_pid = i_program_pid,
+        .i_continuity_counter = 0x0,
+        .b_discontinuity = false
+    };
+
+    BuildPAT( PID(p_sys, 0)->u.p_pat->handle,
+            &p_sys->pids.pat, BuildPATCallback,
+            0, 1,
+            &patstream,
+            1, &pmtprogramstream, &i_program_number );
+
+    /* PAT callback should have been triggered */
+    if( p_program_pid->type != TYPE_PMT )
+    {
+        msg_Err( p_demux, "PAT creation failed" );
+        return;
+    }
+
+    struct esstreams_t
+    {
+        pes_stream_t pes;
+        ts_stream_t ts;
+    };
+    es_format_t esfmt = {0};
+    struct esstreams_t *esstreams = calloc( i_num_pes, sizeof(struct esstreams_t) );
+    pes_mapped_stream_t *mapped = calloc( i_num_pes, sizeof(pes_mapped_stream_t) );
+    if( esstreams && mapped )
+    {
+        int j=0;
+        for( int i=0; i<p_sys->pids.i_all; i++ )
+        {
+            const ts_pid_t *p_pid = p_sys->pids.pp_all[i];
+
+            if( !SEEN(p_pid) ||
+                p_pid->probed.i_type == -1 )
+                continue;
+
+            esstreams[j].pes.i_stream_type = p_pid->probed.i_type;
+            esstreams[j].pes.i_stream_type = p_pid->probed.i_type;
+            esstreams[j].ts.i_pid = p_pid->i_pid;
+            mapped[j].pes = &esstreams[j].pes;
+            mapped[j].ts = &esstreams[j].ts;
+            mapped[j].fmt = &esfmt;
+            j++;
+        }
+
+        BuildPMT( PID(p_sys, 0)->u.p_pat->handle, VLC_OBJECT(p_demux),
+                p_program_pid, BuildPMTCallback,
+                0, 1,
+                i_pcr_pid,
+                NULL,
+                1, &pmtprogramstream, &i_program_number,
+                i_num_pes, mapped );
+    }
+    free(esstreams);
+    free(mapped);
+}
 
 /*****************************************************************************
  * Open
@@ -592,12 +956,14 @@ static int Open( vlc_object_t *p_this )
     demux_t     *p_demux = (demux_t*)p_this;
     demux_sys_t *p_sys;
 
-    int          i_packet_size, i_packet_header_size = 0;
+    int          i_packet_size;
+    unsigned     i_packet_header_size = 0;
 
-    ts_pid_t    *pat;
+    ts_pid_t    *patpid;
+    vdr_info_t   vdr = {0};
 
     /* Search first sync byte */
-    i_packet_size = DetectPacketSize( p_demux, &i_packet_header_size );
+    i_packet_size = DetectPVRHeadersAndHeaderSize( p_demux, &i_packet_header_size, &vdr );
     if( i_packet_size < 0 )
         return VLC_EGENERIC;
 
@@ -613,123 +979,86 @@ static int Open( vlc_object_t *p_this )
     /* Init p_sys field */
     p_sys->b_dvb_meta = true;
     p_sys->b_access_control = true;
-    p_sys->i_current_program = 0;
-    p_sys->programs_list.i_count = 0;
-    p_sys->programs_list.p_values = NULL;
+    p_sys->b_end_preparse = false;
+    ARRAY_INIT( p_sys->programs );
+    p_sys->b_default_selection = false;
     p_sys->i_tdt_delta = 0;
     p_sys->i_dvb_start = 0;
     p_sys->i_dvb_length = 0;
 
+    p_sys->vdr = vdr;
+
+    p_sys->arib.b25stream = NULL;
+    p_sys->stream = p_demux->s;
+
     p_sys->b_broken_charset = false;
 
-    for( int i = 0; i < 8192; i++ )
-    {
-        ts_pid_t *pid = &p_sys->pid[i];
-        pid->i_pid      = i;
-        pid->b_seen     = false;
-        pid->b_valid    = false;
-    }
-    /* PID 8191 is padding */
-    p_sys->pid[8191].b_seen = true;
+    p_sys->pids.dummy.i_pid = 8191;
+    p_sys->pids.dummy.i_flags = FLAG_SEEN;
+
     p_sys->i_packet_size = i_packet_size;
     p_sys->i_packet_header_size = i_packet_header_size;
     p_sys->i_ts_read = 50;
     p_sys->csa = NULL;
     p_sys->b_start_record = false;
 
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
 # define VLC_DVBPSI_DEMUX_TABLE_INIT(table,obj) \
     do { \
-        (table)->psi->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG ); \
-        if( ! (table)->psi->handle ) \
+        if( !dvbpsi_AttachDemux( (table)->u.p_psi->handle, (dvbpsi_demux_new_cb_t)PSINewTableCallBack, (obj) ) ) \
         { \
-            vlc_mutex_destroy( &p_sys->csa_lock ); \
-            free( p_sys ); \
-            return VLC_ENOMEM; \
+            msg_Warn( obj, "Can't dvbpsi_AttachDemux on pid %d", (table)->i_pid );\
         } \
-        (table)->psi->handle->p_sys = (void *) VLC_OBJECT(obj); \
-        if( !dvbpsi_AttachDemux( (table)->psi->handle, (dvbpsi_demux_new_cb_t)PSINewTableCallBack, (obj) ) ) \
-        { \
-            vlc_dvbpsi_reset( obj ); \
-            vlc_mutex_destroy( &p_sys->csa_lock ); \
-            free( p_sys ); \
-            return VLC_EGENERIC; \
-        } \
-    } while (0);
-#endif
+    } while (0)
 
     /* Init PAT handler */
-    pat = &p_sys->pid[0];
-    PIDInit( pat, true, NULL );
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-    pat->psi->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
-    if( !pat->psi->handle )
+    patpid = PID(p_sys, 0);
+    if ( !PIDSetup( p_demux, TYPE_PAT, patpid, NULL ) )
     {
         vlc_mutex_destroy( &p_sys->csa_lock );
         free( p_sys );
         return VLC_ENOMEM;
     }
-    pat->psi->handle->p_sys = (void *) p_demux;
-    if( !dvbpsi_pat_attach( pat->psi->handle, PATCallBack, p_demux ) )
+    if( !dvbpsi_pat_attach( patpid->u.p_pat->handle, PATCallBack, p_demux ) )
     {
-        vlc_dvbpsi_reset( p_demux );
+        PIDRelease( p_demux, patpid );
         vlc_mutex_destroy( &p_sys->csa_lock );
         free( p_sys );
         return VLC_EGENERIC;
     }
-#else
-    pat->psi->handle = dvbpsi_AttachPAT( PATCallBack, p_demux );
-#endif
+
     if( p_sys->b_dvb_meta )
     {
-        ts_pid_t *sdt = &p_sys->pid[0x11];
-        ts_pid_t *eit = &p_sys->pid[0x12];
-
-        PIDInit( sdt, true, NULL );
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-        VLC_DVBPSI_DEMUX_TABLE_INIT( sdt, p_demux )
-#else
-        sdt->psi->handle =
-            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
-                                p_demux );
-#endif
-        PIDInit( eit, true, NULL );
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-        VLC_DVBPSI_DEMUX_TABLE_INIT( eit, p_demux )
-#else
-        eit->psi->handle =
-            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
-                                p_demux );
-#endif
-        ts_pid_t *tdt = &p_sys->pid[0x14];
-        PIDInit( tdt, true, NULL );
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-        VLC_DVBPSI_DEMUX_TABLE_INIT( tdt, p_demux )
-#else
-        tdt->psi->handle =
-            dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
-                                p_demux );
-#endif
-
-        if( p_sys->b_access_control )
-        {
-            if( SetPIDFilter( p_demux, 0x11, true ) ||
-                SetPIDFilter( p_demux, 0x14, true ) ||
-                SetPIDFilter( p_demux, 0x12, true ) )
-                p_sys->b_access_control = false;
-        }
+          if( !PIDSetup( p_demux, TYPE_SDT, PID(p_sys, 0x11), NULL ) ||
+              !PIDSetup( p_demux, TYPE_EIT, PID(p_sys, 0x12), NULL ) ||
+              !PIDSetup( p_demux, TYPE_TDT, PID(p_sys, 0x14), NULL ) )
+          {
+              PIDRelease( p_demux, PID(p_sys, 0x11) );
+              PIDRelease( p_demux, PID(p_sys, 0x12) );
+              PIDRelease( p_demux, PID(p_sys, 0x14) );
+              p_sys->b_dvb_meta = false;
+          }
+          else
+          {
+              VLC_DVBPSI_DEMUX_TABLE_INIT(PID(p_sys, 0x11), p_demux);
+              VLC_DVBPSI_DEMUX_TABLE_INIT(PID(p_sys, 0x12), p_demux);
+              VLC_DVBPSI_DEMUX_TABLE_INIT(PID(p_sys, 0x14), p_demux);
+              if( p_sys->b_access_control &&
+                  ( SetPIDFilter( p_sys, PID(p_sys, 0x11), true ) ||
+                    SetPIDFilter( p_sys, PID(p_sys, 0x14), true ) ||
+                    SetPIDFilter( p_sys, PID(p_sys, 0x12), true ) )
+                 )
+                     p_sys->b_access_control = false;
+          }
     }
 
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
 # undef VLC_DVBPSI_DEMUX_TABLE_INIT
-#endif
 
-    /* Init PMT array */
-    TAB_INIT( p_sys->i_pmt, p_sys->pmt );
     p_sys->i_pmt_es = 0;
+    p_sys->b_es_all = false;
 
     /* Read config */
     p_sys->b_es_id_pid = var_CreateGetBool( p_demux, "ts-es-id-pid" );
+    p_sys->i_next_extraid = 1;
 
     p_sys->b_trust_pcr = var_CreateGetBool( p_demux, "ts-trust-pcr" );
 
@@ -789,42 +1118,27 @@ static int Open( vlc_object_t *p_this )
 
     p_sys->b_split_es = var_InheritBool( p_demux, "ts-split-es" );
 
-    p_sys->i_pid_ref_pcr = -1;
-    p_sys->i_first_pcr = -1;
-    p_sys->i_current_pcr = -1;
-    p_sys->i_last_pcr = -1;
+    p_sys->b_canseek = false;
+    p_sys->b_canfastseek = false;
     p_sys->b_force_seek_per_percent = var_InheritBool( p_demux, "ts-seek-percent" );
-    p_sys->i_pcrs_num = 10;
-    p_sys->p_pcrs = (mtime_t *)calloc( p_sys->i_pcrs_num, sizeof( mtime_t ) );
-    p_sys->p_pos = (int64_t *)calloc( p_sys->i_pcrs_num, sizeof( int64_t ) );
 
     p_sys->arib.e_mode = var_InheritInteger( p_demux, "ts-arib" );
 
-    if( !p_sys->p_pcrs || !p_sys->p_pos )
-    {
-        Close( p_this );
-        return VLC_ENOMEM;
-    }
+    stream_Control( p_sys->stream, STREAM_CAN_SEEK, &p_sys->b_canseek );
+    stream_Control( p_sys->stream, STREAM_CAN_FASTSEEK, &p_sys->b_canfastseek );
 
-    bool can_seek = false;
-    stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &can_seek );
-    if( can_seek  )
+    /* Preparse time */
+    if( p_sys->b_canseek )
     {
-        GetFirstPCR( p_demux );
-        CheckPCR( p_demux );
-        GetLastPCR( p_demux );
-    }
-    if( p_sys->i_first_pcr < 0 || p_sys->i_last_pcr < 0 )
-    {
-        msg_Dbg( p_demux, "Force Seek Per Percent: PCR's not found,");
-        p_sys->b_force_seek_per_percent = true;
+        p_sys->es_creation = NO_ES;
+        while( !p_sys->i_pmt_es && !p_sys->b_end_preparse )
+            if( Demux( p_demux ) != VLC_DEMUXER_SUCCESS )
+                break;
+        p_sys->es_creation = DELAY_ES;
     }
+    else
+        p_sys->es_creation = ( p_sys->b_access_control ? CREATE_ES : DELAY_ES );
 
-    while( p_sys->i_pmt_es <= 0 && vlc_object_alive( p_demux ) )
-    {
-        if( Demux( p_demux ) != 1 )
-            break;
-    }
     return VLC_SUCCESS;
 }
 
@@ -836,60 +1150,13 @@ static void Close( vlc_object_t *p_this )
     demux_t     *p_demux = (demux_t*)p_this;
     demux_sys_t *p_sys = p_demux->p_sys;
 
-    msg_Dbg( p_demux, "pid list:" );
-    for( int i = 0; i < 8192; i++ )
-    {
-        ts_pid_t *pid = &p_sys->pid[i];
-
-        if( pid->b_valid && pid->psi )
-        {
-            switch( pid->i_pid )
-            {
-            case 0: /* PAT */
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-                if( dvbpsi_decoder_present( pid->psi->handle ) )
-                    dvbpsi_pat_detach( pid->psi->handle );
-                dvbpsi_delete( pid->psi->handle );
-                pid->psi->handle = NULL;
-#else
-                dvbpsi_DetachPAT( pid->psi->handle );
-#endif
-                free( pid->psi );
-                break;
-            case 1: /* CAT */
-                free( pid->psi );
-                break;
-            default:
-                if( p_sys->b_dvb_meta && ( pid->i_pid == 0x11 || pid->i_pid == 0x12 || pid->i_pid == 0x14 ) )
-                {
-                    /* SDT or EIT or TDT */
-                    dvbpsi_DetachDemux( pid->psi->handle );
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-                    dvbpsi_delete( pid->psi->handle );
-                    pid->psi->handle = NULL;
-#endif
-                    free( pid->psi );
-                }
-                else
-                {
-                    PIDClean( p_demux, pid );
-                }
-                break;
-            }
-        }
-        else if( pid->b_valid && pid->es )
-        {
-            PIDClean( p_demux, pid );
-        }
-
-        if( pid->b_seen )
-        {
-            msg_Dbg( p_demux, "  - pid[%d] seen", pid->i_pid );
-        }
+    PIDRelease( p_demux, PID(p_sys, 0) );
 
-        /* too much */
-        if( pid->i_pid > 0 )
-            SetPIDFilter( p_demux, pid->i_pid, false );
+    if( p_sys->b_dvb_meta )
+    {
+        PIDRelease( p_demux, PID(p_sys, 0x11) );
+        PIDRelease( p_demux, PID(p_sys, 0x12) );
+        PIDRelease( p_demux, PID(p_sys, 0x14) );
     }
 
     vlc_mutex_lock( &p_sys->csa_lock );
@@ -901,19 +1168,33 @@ static void Close( vlc_object_t *p_this )
     }
     vlc_mutex_unlock( &p_sys->csa_lock );
 
-    TAB_CLEAN( p_sys->i_pmt, p_sys->pmt );
-
-    free( p_sys->programs_list.p_values );
-
-    free( p_sys->p_pcrs );
-    free( p_sys->p_pos );
+    ARRAY_RESET( p_sys->programs );
 
 #ifdef HAVE_ARIBB24
     if ( p_sys->arib.p_instance )
         arib_instance_destroy( p_sys->arib.p_instance );
 #endif
 
+    if ( p_sys->arib.b25stream )
+    {
+        p_sys->arib.b25stream->p_source = NULL; /* don't chain kill demuxer's source */
+        stream_Delete( p_sys->arib.b25stream );
+    }
+
     vlc_mutex_destroy( &p_sys->csa_lock );
+
+    /* Release all non default pids */
+    for( int i = 0; i < p_sys->pids.i_all; i++ )
+    {
+        ts_pid_t *pid = p_sys->pids.pp_all[i];
+#ifndef NDEBUG
+        if( pid->type != TYPE_FREE )
+            msg_Err( p_demux, "PID %d type %d not freed", pid->i_pid, pid->type );
+#endif
+        free( pid );
+    }
+    free( p_sys->pids.pp_all );
+
     free( p_sys );
 }
 
@@ -947,67 +1228,108 @@ static int Demux( demux_t *p_demux )
     demux_sys_t *p_sys = p_demux->p_sys;
     bool b_wait_es = p_sys->i_pmt_es <= 0;
 
+    /* If we had no PAT within MIN_PAT_INTERVAL, create PAT/PMT from probed streams */
+    if( p_sys->i_pmt_es == 0 && !SEEN(PID(p_sys, 0)) && p_sys->patfix.b_pat_deadline )
+        MissingPATPMTFixup( p_demux );
+
     /* We read at most 100 TS packet or until a frame is completed */
-    for( int i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
+    for( unsigned i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
     {
         bool         b_frame = false;
         block_t     *p_pkt;
         if( !(p_pkt = ReadTSPacket( p_demux )) )
         {
-            return 0;
+            return VLC_DEMUXER_EOF;
         }
 
         if( p_sys->b_start_record )
         {
             /* Enable recording once synchronized */
-            stream_Control( p_demux->s, STREAM_SET_RECORD_STATE, true, "ts" );
+            stream_Control( p_sys->stream, STREAM_SET_RECORD_STATE, true, "ts" );
             p_sys->b_start_record = false;
         }
 
         /* Parse the TS packet */
-        ts_pid_t *p_pid = &p_sys->pid[PIDGet( p_pkt )];
+        ts_pid_t *p_pid = PID( p_sys, PIDGet( p_pkt ) );
+
+        if( SCRAMBLED(*p_pid) != !!(p_pkt->p_buffer[3] & 0x80) )
+            UpdateScrambledState( p_demux, p_pid, p_pkt->p_buffer[3] & 0x80 );
 
-        if( p_pid->b_valid )
+        if( !SEEN(p_pid) )
         {
-            if( p_pid->psi )
-            {
-                if( p_pid->i_pid == 0 || ( p_sys->b_dvb_meta && ( p_pid->i_pid == 0x11 || p_pid->i_pid == 0x12 || p_pid->i_pid == 0x14 ) ) )
-                {
-                    dvbpsi_PushPacket( p_pid->psi->handle, p_pkt->p_buffer );
-                }
-                else
-                {
-                    for( int i_prg = 0; i_prg < p_pid->psi->i_prg; i_prg++ )
-                    {
-                        dvbpsi_PushPacket( p_pid->psi->prg[i_prg]->handle,
-                                           p_pkt->p_buffer );
-                    }
-                }
-                block_Release( p_pkt );
-            }
-            else
-            {
-                b_frame = GatherData( p_demux, p_pid, p_pkt );
-            }
+            if( p_pid->type == TYPE_FREE )
+                msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid );
+            p_pid->i_flags |= FLAG_SEEN;
         }
-        else
+
+        if ( SCRAMBLED(*p_pid) && !p_demux->p_sys->csa )
         {
-            if( !p_pid->b_seen )
+            block_Release( p_pkt );
+            continue;
+        }
+
+        /* Probe streams to build PAT/PMT after MIN_PAT_INTERVAL in case we don't see any PAT */
+        if( !SEEN( PID( p_sys, 0 ) ) &&
+            (p_pid->probed.i_type == 0 || p_pid->i_pid == p_sys->patfix.i_timesourcepid) &&
+            (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
+            (p_pkt->p_buffer[3] & 0xD0) == 0x10 )  /* Has payload but is not encrypted */
+        {
+            ProbePES( p_demux, p_pid, p_pkt->p_buffer + TS_HEADER_SIZE,
+                      p_pkt->i_buffer - TS_HEADER_SIZE, p_pkt->p_buffer[3] & 0x20 /* Adaptation field */);
+        }
+
+        switch( p_pid->type )
+        {
+        case TYPE_PAT:
+            dvbpsi_packet_push( p_pid->u.p_pat->handle, p_pkt->p_buffer );
+            block_Release( p_pkt );
+            break;
+
+        case TYPE_PMT:
+            dvbpsi_packet_push( p_pid->u.p_pmt->handle, p_pkt->p_buffer );
+            block_Release( p_pkt );
+            break;
+
+        case TYPE_PES:
+            p_sys->b_end_preparse = true;
+
+            if( p_sys->es_creation == DELAY_ES ) /* No longer delay ES since that pid's program sends data */
             {
-                msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid );
+                msg_Dbg( p_demux, "Creating delayed ES" );
+                AddAndCreateES( p_demux, p_pid, true );
+            }
+
+            if( !p_sys->b_access_control && !(p_pid->i_flags & FLAG_FILTERED) )
+            {
+                /* That packet is for an unselected ES, don't waste time/memory gathering its data */
+                block_Release( p_pkt );
+                continue;
             }
+
+            b_frame = GatherData( p_demux, p_pid, p_pkt );
+            break;
+
+        case TYPE_SDT:
+        case TYPE_TDT:
+        case TYPE_EIT:
+            if( p_sys->b_dvb_meta )
+                dvbpsi_packet_push( p_pid->u.p_psi->handle, p_pkt->p_buffer );
+            block_Release( p_pkt );
+            break;
+
+        default:
             /* We have to handle PCR if present */
             PCRHandle( p_demux, p_pid, p_pkt );
             block_Release( p_pkt );
+            break;
         }
-        p_pid->b_seen = true;
 
         if( b_frame || ( b_wait_es && p_sys->i_pmt_es > 0 ) )
             break;
     }
 
     demux_UpdateTitleFromStream( p_demux );
-    return 1;
+    return VLC_DEMUXER_SUCCESS;
 }
 
 /*****************************************************************************
@@ -1037,6 +1359,50 @@ static int DVBEventInformation( demux_t *p_demux, int64_t *pi_time, int64_t *pi_
     return VLC_EGENERIC;
 }
 
+static void UpdatePESFilters( demux_t *p_demux, bool b_all )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
+    for( int i=0; i< p_pat->programs.i_size; i++ )
+    {
+        ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
+        bool b_program_selected;
+        if( (p_sys->b_default_selection && !p_sys->b_access_control) || b_all )
+             b_program_selected = true;
+        else
+             b_program_selected = ProgramIsSelected( p_sys, p_pmt->i_number );
+
+        SetPIDFilter( p_sys, p_pat->programs.p_elems[i], b_program_selected );
+
+        for( int j=0; j<p_pmt->e_streams.i_size; j++ )
+        {
+            ts_pid_t *espid = p_pmt->e_streams.p_elems[j];
+            bool b_stream_selected = b_program_selected;
+            if( b_program_selected && !b_all && espid->u.p_pes->es.id )
+                es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
+                                espid->u.p_pes->es.id, &b_stream_selected );
+
+            if( !p_sys->b_es_all && espid->u.p_pes->es.fmt.i_cat == UNKNOWN_ES )
+                b_stream_selected = false;
+
+            if( b_stream_selected )
+                msg_Dbg( p_demux, "enabling pid %d from program %d", espid->i_pid, p_pmt->i_number );
+
+            SetPIDFilter( p_sys, espid, b_stream_selected );
+            if( !b_stream_selected )
+                FlushESBuffer( espid->u.p_pes );
+        }
+
+        /* Select pcr last in case it is handled by unselected ES */
+        if( p_pmt->i_pid_pcr > 0 )
+        {
+            SetPIDFilter( p_sys, PID(p_sys, p_pmt->i_pid_pcr), b_program_selected );
+            if( b_program_selected )
+                msg_Dbg( p_demux, "enabling pcr pid %d from program %d", p_pmt->i_pid_pcr, p_pmt->i_number );
+        }
+    }
+}
+
 static int Control( demux_t *p_demux, int i_query, va_list args )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
@@ -1045,89 +1411,165 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
     int64_t i64;
     int64_t *pi64;
     int i_int;
+    ts_pmt_t *p_pmt;
+    int i_first_program = ( p_sys->programs.i_size ) ? p_sys->programs.p_elems[0] : 0;
+
+    if( PREPARSING || !i_first_program || p_sys->b_default_selection )
+    {
+        if( likely(PID(p_sys, 0)->type == TYPE_PAT) )
+        {
+            ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
+            /* Set default program for preparse time (no program has been selected) */
+            for( int i = 0; i < p_pat->programs.i_size; i++ )
+            {
+                assert(p_pat->programs.p_elems[i]->type == TYPE_PMT);
+                p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
+                if( ( p_pmt->pcr.i_first > -1 || p_pmt->pcr.i_first_dts > VLC_TS_INVALID ) && p_pmt->i_last_dts > 0 )
+                {
+                    i_first_program = p_pmt->i_number;
+                    break;
+                }
+            }
+        }
+    }
 
     switch( i_query )
     {
     case DEMUX_GET_POSITION:
         pf = (double*) va_arg( args, double* );
 
-        if( p_sys->b_force_seek_per_percent ||
-            (p_sys->b_dvb_meta && p_sys->b_access_control) ||
-            p_sys->i_current_pcr - p_sys->i_first_pcr < 0 ||
-            p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
+        /* Access control test is because EPG for recordings is not relevant */
+        if( p_sys->b_dvb_meta && p_sys->b_access_control )
         {
             int64_t i_time, i_length;
             if( !DVBEventInformation( p_demux, &i_time, &i_length ) && i_length > 0 )
-                *pf = (double)i_time/(double)i_length;
-            else if( (i64 = stream_Size( p_demux->s) ) > 0 )
             {
-                int64_t offset = stream_Tell( p_demux->s );
-
-                *pf = (double)offset / (double)i64;
+                *pf = (double)i_time/(double)i_length;
+                return VLC_SUCCESS;
             }
-            else
-                *pf = 0.0;
         }
-        else
+
+        if( (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
+             p_pmt->pcr.i_first > -1 && p_pmt->i_last_dts > VLC_TS_INVALID &&
+             p_pmt->pcr.i_current > -1 )
         {
-            *pf = (double)(p_sys->i_current_pcr - p_sys->i_first_pcr) / (double)(p_sys->i_last_pcr - p_sys->i_first_pcr);
+            double i_length = TimeStampWrapAround( p_pmt,
+                                                   p_pmt->i_last_dts ) - p_pmt->pcr.i_first;
+            i_length += p_pmt->pcr.i_pcroffset;
+            double i_pos = TimeStampWrapAround( p_pmt,
+                                                p_pmt->pcr.i_current ) - p_pmt->pcr.i_first;
+            *pf = i_pos / i_length;
+            return VLC_SUCCESS;
         }
-        return VLC_SUCCESS;
+
+        if( (i64 = stream_Size( p_sys->stream) ) > 0 )
+        {
+            int64_t offset = stream_Tell( p_sys->stream );
+            *pf = (double)offset / (double)i64;
+            return VLC_SUCCESS;
+        }
+        break;
 
     case DEMUX_SET_POSITION:
         f = (double) va_arg( args, double );
 
-        if( p_sys->b_force_seek_per_percent ||
-            (p_sys->b_dvb_meta && p_sys->b_access_control) ||
-            p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
+        if(!p_sys->b_canseek)
+            break;
+
+        if( p_sys->b_dvb_meta && p_sys->b_access_control &&
+           !p_sys->b_force_seek_per_percent &&
+           (p_pmt = GetProgramByID( p_sys, i_first_program )) )
         {
-            i64 = stream_Size( p_demux->s );
-            if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
-                return VLC_EGENERIC;
+            int64_t i_time, i_length;
+            if( !DVBEventInformation( p_demux, &i_time, &i_length ) &&
+                 i_length > 0 && !SeekToTime( p_demux, p_pmt, TO_SCALE(i_length) * f ) )
+            {
+                ReadyQueuesPostSeek( p_demux );
+                es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
+                                TO_SCALE(i_length) * f );
+                return VLC_SUCCESS;
+            }
         }
-        else
+
+        if( !p_sys->b_force_seek_per_percent &&
+            (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
+             p_pmt->pcr.i_first > -1 && p_pmt->i_last_dts > VLC_TS_INVALID &&
+             p_pmt->pcr.i_current > -1 )
         {
-            if( Seek( p_demux, f ) )
+            double i_length = TimeStampWrapAround( p_pmt,
+                                                   p_pmt->i_last_dts ) - p_pmt->pcr.i_first;
+            if( !SeekToTime( p_demux, p_pmt, p_pmt->pcr.i_first + i_length * f ) )
             {
-                p_sys->b_force_seek_per_percent = true;
-                return VLC_EGENERIC;
+                ReadyQueuesPostSeek( p_demux );
+                es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
+                                FROM_SCALE(p_pmt->pcr.i_first + i_length * f) );
+                return VLC_SUCCESS;
             }
         }
-        return VLC_SUCCESS;
+
+        i64 = stream_Size( p_sys->stream );
+        if( i64 > 0 &&
+            stream_Seek( p_sys->stream, (int64_t)(i64 * f) ) == VLC_SUCCESS )
+        {
+            ReadyQueuesPostSeek( p_demux );
+            return VLC_SUCCESS;
+        }
+        break;
+
+    case DEMUX_SET_TIME:
+        i64 = (int64_t)va_arg( args, int64_t );
+
+        if( p_sys->b_canseek &&
+           (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
+            p_pmt->pcr.i_first > -1 &&
+           !SeekToTime( p_demux, p_pmt, p_pmt->pcr.i_first + TO_SCALE(i64) ) )
+        {
+            ReadyQueuesPostSeek( p_demux );
+            es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
+                            FROM_SCALE(p_pmt->pcr.i_first) + i64 - VLC_TS_0 );
+            return VLC_SUCCESS;
+        }
+        break;
 
     case DEMUX_GET_TIME:
         pi64 = (int64_t*)va_arg( args, int64_t * );
-        if( (p_sys->b_dvb_meta && p_sys->b_access_control) ||
-            p_sys->b_force_seek_per_percent ||
-            p_sys->i_current_pcr - p_sys->i_first_pcr < 0 )
+
+        if( p_sys->b_dvb_meta && p_sys->b_access_control )
         {
-            if( DVBEventInformation( p_demux, pi64, NULL ) )
-            {
-                *pi64 = 0;
-            }
+            if( !DVBEventInformation( p_demux, pi64, NULL ) )
+                return VLC_SUCCESS;
         }
-        else
+
+        if( (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
+             p_pmt->pcr.i_current > -1 && p_pmt->pcr.i_first > -1 )
         {
-            *pi64 = (p_sys->i_current_pcr - p_sys->i_first_pcr) * 100 / 9;
+            int64_t i_pcr = TimeStampWrapAround( p_pmt, p_pmt->pcr.i_current );
+            *pi64 = FROM_SCALE(i_pcr - p_pmt->pcr.i_first);
+            return VLC_SUCCESS;
         }
-        return VLC_SUCCESS;
+        break;
 
     case DEMUX_GET_LENGTH:
         pi64 = (int64_t*)va_arg( args, int64_t * );
-        if( (p_sys->b_dvb_meta && p_sys->b_access_control) ||
-            p_sys->b_force_seek_per_percent ||
-            p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
+
+        if( p_sys->b_dvb_meta && p_sys->b_access_control )
         {
-            if( DVBEventInformation( p_demux, NULL, pi64 ) )
-            {
-                *pi64 = 0;
-            }
+            if( !DVBEventInformation( p_demux, NULL, pi64 ) )
+                return VLC_SUCCESS;
         }
-        else
+
+        if( (p_pmt = GetProgramByID( p_sys, i_first_program )) &&
+           ( p_pmt->pcr.i_first > -1 || p_pmt->pcr.i_first_dts > VLC_TS_INVALID ) &&
+             p_pmt->i_last_dts > 0 )
         {
-            *pi64 = (p_sys->i_last_pcr - p_sys->i_first_pcr) * 100 / 9;
+            int64_t i_start = (p_pmt->pcr.i_first > -1) ? p_pmt->pcr.i_first :
+                              TO_SCALE(p_pmt->pcr.i_first_dts);
+            int64_t i_last = TimeStampWrapAround( p_pmt, p_pmt->i_last_dts );
+            i_last += p_pmt->pcr.i_pcroffset;
+            *pi64 = FROM_SCALE(i_last - i_start);
+            return VLC_SUCCESS;
         }
-        return VLC_SUCCESS;
+        break;
 
     case DEMUX_SET_GROUP:
     {
@@ -1137,47 +1579,46 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
         p_list = (vlc_list_t *)va_arg( args, vlc_list_t * );
         msg_Dbg( p_demux, "DEMUX_SET_GROUP %d %p", i_int, p_list );
 
-        if( i_int == 0 && p_sys->i_current_program > 0 )
-            i_int = p_sys->i_current_program;
-
-        if( p_sys->i_current_program > 0 )
-        {
-            if( p_sys->i_current_program != i_int )
-                SetPrgFilter( p_demux, p_sys->i_current_program, false );
-        }
-        else if( p_sys->i_current_program < 0 )
+        if( i_int != 0 ) /* If not default program */
         {
-            for( int i = 0; i < p_sys->programs_list.i_count; i++ )
-                SetPrgFilter( p_demux, p_sys->programs_list.p_values[i].i_int, false );
-        }
+            /* Deselect/filter current ones */
 
-        if( i_int > 0 )
-        {
-            p_sys->i_current_program = i_int;
-            SetPrgFilter( p_demux, p_sys->i_current_program, true );
-        }
-        else if( i_int < 0 )
-        {
-            p_sys->i_current_program = -1;
-            p_sys->programs_list.i_count = 0;
-            if( p_list )
+            if( i_int != -1 )
             {
-                vlc_list_t *p_dst = &p_sys->programs_list;
-                free( p_dst->p_values );
-
-                p_dst->p_values = calloc( p_list->i_count,
-                                          sizeof(*p_dst->p_values) );
-                if( p_dst->p_values )
-                {
-                    p_dst->i_count = p_list->i_count;
-                    for( int i = 0; i < p_list->i_count; i++ )
-                    {
-                        p_dst->p_values[i] = p_list->p_values[i];
-                        SetPrgFilter( p_demux, p_dst->p_values[i].i_int, true );
-                    }
-                }
+                p_sys->b_es_all = false;
+                ARRAY_APPEND( p_sys->programs, i_int );
+                UpdatePESFilters( p_demux, false );
             }
+            else if( likely( p_list != NULL ) )
+            {
+                p_sys->b_es_all = false;
+                for( int i = 0; i < p_list->i_count; i++ )
+                   ARRAY_APPEND( p_sys->programs, p_list->p_values[i].i_int );
+                UpdatePESFilters( p_demux, false );
+            }
+            else // All ES Mode
+            {
+                p_sys->b_es_all = true;
+                ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
+                for( int i = 0; i < p_pat->programs.i_size; i++ )
+                   ARRAY_APPEND( p_sys->programs, p_pat->programs.p_elems[i]->i_pid );
+                UpdatePESFilters( p_demux, true );
+            }
+
+            p_sys->b_default_selection = false;
         }
+
+        return VLC_SUCCESS;
+    }
+
+    case DEMUX_SET_ES:
+    {
+        i_int = (int)va_arg( args, int );
+        msg_Dbg( p_demux, "DEMUX_SET_ES %d", i_int );
+
+        if( !p_sys->b_es_all ) /* Won't change anything */
+            UpdatePESFilters( p_demux, false );
+
         return VLC_SUCCESS;
     }
 
@@ -1188,17 +1629,17 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
 
         *va_arg( args, int* ) = 0; /* Title offset */
         *va_arg( args, int* ) = 0; /* Chapter offset */
-        return stream_Control( p_demux->s, STREAM_GET_TITLE_INFO, v, c );
+        return stream_Control( p_sys->stream, STREAM_GET_TITLE_INFO, v, c );
     }
 
     case DEMUX_SET_TITLE:
-        return stream_vaControl( p_demux->s, STREAM_SET_TITLE, args );
+        return stream_vaControl( p_sys->stream, STREAM_SET_TITLE, args );
 
     case DEMUX_SET_SEEKPOINT:
-        return stream_vaControl( p_demux->s, STREAM_SET_SEEKPOINT, args );
+        return stream_vaControl( p_sys->stream, STREAM_SET_SEEKPOINT, args );
 
     case DEMUX_GET_META:
-        return stream_vaControl( p_demux->s, STREAM_GET_META, args );
+        return stream_vaControl( p_sys->stream, STREAM_GET_META, args );
 
     case DEMUX_CAN_RECORD:
         pb_bool = (bool*)va_arg( args, bool * );
@@ -1209,16 +1650,18 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
         b_bool = (bool)va_arg( args, int );
 
         if( !b_bool )
-            stream_Control( p_demux->s, STREAM_SET_RECORD_STATE, false );
+            stream_Control( p_sys->stream, STREAM_SET_RECORD_STATE, false );
         p_sys->b_start_record = b_bool;
         return VLC_SUCCESS;
 
     case DEMUX_GET_SIGNAL:
-        return stream_vaControl( p_demux->s, STREAM_GET_SIGNAL, args );
+        return stream_vaControl( p_sys->stream, STREAM_GET_SIGNAL, args );
 
     default:
-        return VLC_EGENERIC;
+        break;
     }
+
+    return VLC_EGENERIC;
 }
 
 /*****************************************************************************
@@ -1231,7 +1674,6 @@ static int UserPmt( demux_t *p_demux, const char *psz_fmt )
     char *psz = psz_dup;
     int  i_pid;
     int  i_number;
-    ts_prg_psi_t *prg = NULL;
 
     if( !psz_dup )
         return VLC_ENOMEM;
@@ -1247,39 +1689,24 @@ static int UserPmt( demux_t *p_demux, const char *psz_fmt )
         i_number = strtol( &psz[1], &psz, 0 );
 
     /* */
-    ts_pid_t *pmt = &p_sys->pid[i_pid];
+    ts_pid_t *pmtpid = PID(p_sys, i_pid);
 
     msg_Dbg( p_demux, "user pmt specified (pid=%d,number=%d)", i_pid, i_number );
-    PIDInit( pmt, true, NULL );
-
-    /* Dummy PMT */
-    prg = calloc( 1, sizeof( ts_prg_psi_t ) );
-    if( !prg )
+    if ( !PIDSetup( p_demux, TYPE_PMT, pmtpid, PID(p_sys, 0) ) )
         goto error;
 
-    prg->i_pid_pcr  = -1;
-    prg->i_pid_pmt  = -1;
-    prg->i_version  = -1;
-    prg->i_number   = i_number != 0 ? i_number : TS_USER_PMT_NUMBER;
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-    prg->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
-    if( !prg->handle )
-        goto error;
-    prg->handle->p_sys = (void *) VLC_OBJECT(p_demux);
-    if( !dvbpsi_pmt_attach( prg->handle,
+    /* Dummy PMT */
+    ts_pmt_t *p_pmt = pmtpid->u.p_pmt;
+    p_pmt->i_number   = i_number != 0 ? i_number : TS_USER_PMT_NUMBER;
+    if( !dvbpsi_pmt_attach( p_pmt->handle,
                             ((i_number != TS_USER_PMT_NUMBER ? i_number : 1)),
                             PMTCallBack, p_demux ) )
     {
-        dvbpsi_delete( prg->handle );
-        prg->handle = NULL;
+        PIDRelease( p_demux, pmtpid );
         goto error;
     }
-#else
-    prg->handle     = dvbpsi_AttachPMT(
-        ((i_number != TS_USER_PMT_NUMBER) ? i_number : 1),
-        PMTCallBack, p_demux );
-#endif
-    TAB_APPEND( pmt->psi->i_prg, pmt->psi->prg, prg );
+
+    ARRAY_APPEND( PID(p_sys, 0)->u.p_pat->programs, pmtpid );
 
     psz = strchr( psz, '=' );
     if( psz )
@@ -1299,26 +1726,31 @@ static int UserPmt( demux_t *p_demux, const char *psz_fmt )
         char *psz_opt = &psz[1];
         if( !strcmp( psz_opt, "pcr" ) )
         {
-            prg->i_pid_pcr = i_pid;
+            p_pmt->i_pid_pcr = i_pid;
         }
-        else if( !p_sys->pid[i_pid].b_valid )
+        else if( PID(p_sys, i_pid)->type == TYPE_FREE )
         {
-            ts_pid_t *pid = &p_sys->pid[i_pid];
+            ts_pid_t *pid = PID(p_sys, i_pid);
 
             char *psz_arg = strchr( psz_opt, '=' );
             if( psz_arg )
                 *psz_arg++ = '\0';
 
-            PIDInit( pid, false, pmt->psi);
-            if( prg->i_pid_pcr <= 0 )
-                prg->i_pid_pcr = i_pid;
+            if ( !PIDSetup( p_demux, TYPE_PES, pid, pmtpid ) )
+                continue;
+
+            ARRAY_APPEND( p_pmt->e_streams, pid );
+
+            if( p_pmt->i_pid_pcr <= 0 )
+                p_pmt->i_pid_pcr = i_pid;
+
+            es_format_t *fmt = &pid->u.p_pes->es.fmt;
 
             if( psz_arg && strlen( psz_arg ) == 4 )
             {
                 const vlc_fourcc_t i_codec = VLC_FOURCC( psz_arg[0], psz_arg[1],
                                                          psz_arg[2], psz_arg[3] );
                 int i_cat = UNKNOWN_ES;
-                es_format_t *fmt = &pid->es->fmt;
 
                 if( !strcmp( psz_opt, "video" ) )
                     i_cat = VIDEO_ES;
@@ -1333,18 +1765,18 @@ static int UserPmt( demux_t *p_demux, const char *psz_fmt )
             else
             {
                 const int i_stream_type = strtol( psz_opt, NULL, 0 );
-                PIDFillFormat( &pid->es->fmt, i_stream_type );
+                PIDFillFormat( fmt, i_stream_type );
             }
-            pid->es->fmt.i_group = i_number;
+
+            fmt->i_group = i_number;
             if( p_sys->b_es_id_pid )
-                pid->es->fmt.i_id = i_pid;
+                fmt->i_id = i_pid;
 
-            if( pid->es->fmt.i_cat != UNKNOWN_ES )
+            if( fmt->i_cat != UNKNOWN_ES )
             {
                 msg_Dbg( p_demux, "  * es pid=%d fcc=%4.4s", i_pid,
-                         (char*)&pid->es->fmt.i_codec );
-                pid->es->id = es_out_Add( p_demux->out,
-                                          &pid->es->fmt );
+                         (char*)&fmt->i_codec );
+                pid->u.p_pes->es.id = es_out_Add( p_demux->out, fmt );
                 p_sys->i_pmt_es++;
             }
         }
@@ -1354,206 +1786,157 @@ static int UserPmt( demux_t *p_demux, const char *psz_fmt )
     }
 
     p_sys->b_user_pmt = true;
-    TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
     free( psz_dup );
     return VLC_SUCCESS;
 
 error:
-    free( prg );
     free( psz_dup );
     return VLC_EGENERIC;
 }
 
-static int SetPIDFilter( demux_t *p_demux, int i_pid, bool b_selected )
+static int SetPIDFilter( demux_sys_t *p_sys, ts_pid_t *p_pid, bool b_selected )
 {
-    demux_sys_t *p_sys = p_demux->p_sys;
+    if( b_selected )
+        p_pid->i_flags |= FLAG_FILTERED;
+    else
+        p_pid->i_flags &= ~FLAG_FILTERED;
 
     if( !p_sys->b_access_control )
-        return VLC_EGENERIC;
-
-    return stream_Control( p_demux->s, STREAM_SET_PRIVATE_ID_STATE,
-                           i_pid, b_selected );
-}
-
-static void SetPrgFilter( demux_t *p_demux, int i_prg_id, bool b_selected )
-{
-    demux_sys_t *p_sys = p_demux->p_sys;
-    ts_prg_psi_t *p_prg = NULL;
-    int i_pmt_pid = -1;
-
-    /* Search pmt to be unselected */
-    for( int i = 0; i < p_sys->i_pmt; i++ )
-    {
-        ts_pid_t *pmt = p_sys->pmt[i];
-
-        for( int i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
-        {
-            if( pmt->psi->prg[i_prg]->i_number == i_prg_id )
-            {
-                i_pmt_pid = p_sys->pmt[i]->i_pid;
-                p_prg = p_sys->pmt[i]->psi->prg[i_prg];
-                break;
-            }
-        }
-        if( i_pmt_pid > 0 )
-            break;
-    }
-    if( i_pmt_pid <= 0 )
-        return;
-    assert( p_prg );
-
-    SetPIDFilter( p_demux, i_pmt_pid, b_selected );
-    if( p_prg->i_pid_pcr > 0 )
-        SetPIDFilter( p_demux, p_prg->i_pid_pcr, b_selected );
-
-    /* All ES */
-    for( int i = 2; i < 8192; i++ )
-    {
-        ts_pid_t *pid = &p_sys->pid[i];
-
-        if( !pid->b_valid || pid->psi )
-            continue;
-
-        for( int i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
-        {
-            if( pid->p_owner->prg[i_prg]->i_pid_pmt == i_pmt_pid && pid->es->id )
-            {
-                /* We only remove/select es that aren't defined by extra pmt */
-                SetPIDFilter( p_demux, i, b_selected );
-                break;
-            }
-        }
-    }
+        return VLC_EGENERIC;
+
+    return stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_STATE,
+                           p_pid->i_pid, b_selected );
 }
 
-static void PIDInit( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner )
+static void PIDReset( ts_pid_t *pid )
 {
-    bool b_old_valid = pid->b_valid;
-
-    pid->b_valid    = true;
+    assert(pid->i_refcount == 0);
     pid->i_cc       = 0xff;
-    pid->b_scrambled = false;
-    pid->p_owner    = p_owner;
-    pid->i_owner_number = 0;
+    pid->i_flags    &= ~FLAG_SCRAMBLED;
+    pid->p_parent    = NULL;
+    pid->type = TYPE_FREE;
+}
 
-    TAB_INIT( pid->i_extra_es, pid->extra_es );
+static bool PIDSetup( demux_t *p_demux, ts_pid_type_t i_type, ts_pid_t *pid, ts_pid_t *p_parent )
+{
+    if( pid == p_parent || pid->i_pid == 0x1FFF )
+        return false;
 
-    if( b_psi )
+    if( pid->i_refcount == 0 )
     {
-        pid->es  = NULL;
-
-        if( !b_old_valid )
+        assert( pid->type == TYPE_FREE );
+        switch( i_type )
         {
-            pid->psi = xmalloc( sizeof( ts_psi_t ) );
-            pid->psi->handle = NULL;
-            TAB_INIT( pid->psi->i_prg, pid->psi->prg );
-        }
-        assert( pid->psi );
+        case TYPE_FREE: /* nonsense ?*/
+            PIDReset( pid );
+            return true;
 
-        pid->psi->i_pat_version  = -1;
-        pid->psi->i_sdt_version  = -1;
-        if( p_owner )
-        {
-            ts_prg_psi_t *prg = malloc( sizeof( ts_prg_psi_t ) );
-            if( !prg )
-                return;
-            /* PMT */
-            prg->i_version  = -1;
-            prg->i_number   = -1;
-            prg->i_pid_pcr  = -1;
-            prg->i_pid_pmt  = -1;
-            prg->i_pcr_value= -1;
-            prg->iod        = NULL;
-            prg->handle     = NULL;
+        case TYPE_PAT:
+            PIDReset( pid );
+            pid->u.p_pat = ts_pat_New( p_demux );
+            if( !pid->u.p_pat )
+                return false;
+            break;
+
+        case TYPE_PMT:
+            PIDReset( pid );
+            pid->u.p_pmt = ts_pmt_New( p_demux );
+            if( !pid->u.p_pmt )
+                return false;
+            break;
+
+        case TYPE_PES:
+            PIDReset( pid );
+            pid->u.p_pes = ts_pes_New( p_demux );
+            if( !pid->u.p_pes )
+                return false;
+            break;
 
-            TAB_APPEND( pid->psi->i_prg, pid->psi->prg, prg );
+        case TYPE_SDT:
+        case TYPE_TDT:
+        case TYPE_EIT:
+            PIDReset( pid );
+            pid->u.p_psi = ts_psi_New( p_demux );
+            if( !pid->u.p_psi )
+                return false;
+            break;
+
+        default:
+            assert(false);
+            break;
         }
+
+        pid->i_refcount++;
+        pid->type = i_type;
+        pid->p_parent = p_parent;
+    }
+    else if( pid->type == i_type && pid->i_refcount < UINT8_MAX )
+    {
+        pid->i_refcount++;
     }
     else
     {
-        pid->psi = NULL;
-        pid->es  = calloc( 1, sizeof( ts_es_t ) );
-        if( !pid->es )
-            return;
-
-        es_format_Init( &pid->es->fmt, UNKNOWN_ES, 0 );
-        pid->es->data_type = TS_ES_DATA_PES;
-        pid->es->pp_last = &pid->es->p_data;
+        if( pid->type != TYPE_FREE )
+            msg_Warn( p_demux, "Tried to redeclare pid %d with another type", pid->i_pid );
+        return false;
     }
+
+    return true;
 }
 
-static void PIDClean( demux_t *p_demux, ts_pid_t *pid )
+static void PIDRelease( demux_t *p_demux, ts_pid_t *pid )
 {
-    demux_sys_t *p_sys = p_demux->p_sys;
-    es_out_t *out = p_demux->out;
-
-    if( pid->psi )
+    if( pid->i_refcount == 0 )
     {
-        if( pid->psi->handle )
-        {
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-            if( dvbpsi_decoder_present( pid->psi->handle ) )
-                dvbpsi_pmt_detach( pid->psi->handle );
-            dvbpsi_delete( pid->psi->handle );
-            pid->psi->handle = NULL;
-#else
-            dvbpsi_DetachPMT( pid->psi->handle );
-#endif
-        }
-        for( int i = 0; i < pid->psi->i_prg; i++ )
-        {
-            if( pid->psi->prg[i]->iod )
-                IODFree( pid->psi->prg[i]->iod );
-            if( pid->psi->prg[i]->handle )
-            {
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-                if( dvbpsi_decoder_present( pid->psi->prg[i]->handle ) )
-                    dvbpsi_pmt_detach( pid->psi->prg[i]->handle );
-                dvbpsi_delete( pid->psi->prg[i]->handle );
-#else
-                dvbpsi_DetachPMT( pid->psi->prg[i]->handle );
-#endif
-            }
-            free( pid->psi->prg[i] );
-        }
-        free( pid->psi->prg );
-        free( pid->psi );
+        assert( pid->type == TYPE_FREE );
+        return;
     }
-    else
+    else if( pid->i_refcount == 1 )
     {
-        if( pid->es->id )
-        {
-            es_out_Del( out, pid->es->id );
-            p_sys->i_pmt_es--;
-        }
-
-        if( pid->es->p_data )
-            block_ChainRelease( pid->es->p_data );
+        pid->i_refcount--;
+    }
+    else if( pid->i_refcount > 1 )
+    {
+        assert( pid->type != TYPE_FREE && pid->type != TYPE_PAT );
+        pid->i_refcount--;
+    }
 
-        es_format_Clean( &pid->es->fmt );
+    if( pid->i_refcount == 0 )
+    {
+        switch( pid->type )
+        {
+        default:
+        case TYPE_FREE: /* nonsense ?*/
+            assert( pid->type != TYPE_FREE );
+            break;
 
-        free( pid->es );
+        case TYPE_PAT:
+            ts_pat_Del( p_demux, pid->u.p_pat );
+            pid->u.p_pat = NULL;
+            break;
 
-        for( int i = 0; i < pid->i_extra_es; i++ )
-        {
-            if( pid->extra_es[i]->id )
-            {
-                es_out_Del( out, pid->extra_es[i]->id );
-                p_sys->i_pmt_es--;
-            }
+        case TYPE_PMT:
+            ts_pmt_Del( p_demux, pid->u.p_pmt );
+            pid->u.p_pmt = NULL;
+            break;
 
-            if( pid->extra_es[i]->p_data )
-                block_ChainRelease( pid->extra_es[i]->p_data );
+        case TYPE_PES:
+            ts_pes_Del( p_demux, pid->u.p_pes );
+            pid->u.p_pes = NULL;
+            break;
 
-            es_format_Clean( &pid->extra_es[i]->fmt );
+        case TYPE_SDT:
+        case TYPE_TDT:
+        case TYPE_EIT:
+            ts_psi_Del( p_demux, pid->u.p_psi );
+            pid->u.p_psi = NULL;
+            break;
 
-            free( pid->extra_es[i] );
         }
-        if( pid->i_extra_es )
-            free( pid->extra_es );
-    }
 
-    pid->b_valid = false;
+        SetPIDFilter( p_demux->p_sys, pid, false );
+        PIDReset( pid );
+    }
 }
 
 static int16_t read_opus_flag(uint8_t **buf, size_t *len)
@@ -1638,7 +2021,7 @@ static block_t *Opus_Parse(demux_t *demux, block_t *block)
         last = &au->p_next;
 
         au->i_nb_samples = opus_frame_duration(buf, au_size);
-        if (end_trim && end_trim <= au->i_nb_samples)
+        if (end_trim && (uint16_t) end_trim <= au->i_nb_samples)
             au->i_length = end_trim; /* Blatant abuse of the i_length field. */
         else
             au->i_length = 0;
@@ -1660,30 +2043,15 @@ static block_t *Opus_Parse(demux_t *demux, block_t *block)
 /****************************************************************************
  * gathering stuff
  ****************************************************************************/
-static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
+static int ParsePESHeader( demux_t *p_demux, const uint8_t *p_header, size_t i_header,
+                           unsigned *pi_skip, mtime_t *pi_dts, mtime_t *pi_pts )
 {
-    demux_sys_t *p_sys = p_demux->p_sys;
-    uint8_t header[34];
-    unsigned i_pes_size = 0;
-    unsigned i_skip = 0;
-    mtime_t i_dts = -1;
-    mtime_t i_pts = -1;
-    mtime_t i_length = 0;
-
-    /* FIXME find real max size */
-    /* const int i_max = */ block_ChainExtract( p_pes, header, 34 );
+    unsigned i_skip;
 
-    if( pid->b_scrambled || header[0] != 0 || header[1] != 0 || header[2] != 1 )
-    {
-        if ( !pid->b_scrambled )
-            msg_Warn( p_demux, "invalid header [0x%02x:%02x:%02x:%02x] (pid: %d)",
-                        header[0], header[1],header[2],header[3], pid->i_pid );
-        block_ChainRelease( p_pes );
-        return;
-    }
+    if ( i_header < 9 )
+        return VLC_EGENERIC;
 
-    /* TODO check size */
-    switch( header[3] )
+    switch( p_header[3] )
     {
     case 0xBC:  /* Program stream map */
     case 0xBE:  /* Padding */
@@ -1696,63 +2064,61 @@ static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
         i_skip = 6;
         break;
     default:
-        if( ( header[6]&0xC0 ) == 0x80 )
+        if( ( p_header[6]&0xC0 ) == 0x80 )
         {
             /* mpeg2 PES */
-            i_skip = header[8] + 9;
+            i_skip = p_header[8] + 9;
 
-            if( header[7]&0x80 )    /* has pts */
+            if( p_header[7]&0x80 )    /* has pts */
             {
-                i_pts = ((mtime_t)(header[ 9]&0x0e ) << 29)|
-                         (mtime_t)(header[10] << 22)|
-                        ((mtime_t)(header[11]&0xfe) << 14)|
-                         (mtime_t)(header[12] << 7)|
-                         (mtime_t)(header[13] >> 1);
+                if( i_header < 9 + 5 )
+                    return VLC_EGENERIC;
+                *pi_pts = ExtractPESTimestamp( &p_header[9] );
 
-                if( header[7]&0x40 )    /* has dts */
+                if( p_header[7]&0x40 )    /* has dts */
                 {
-                     i_dts = ((mtime_t)(header[14]&0x0e ) << 29)|
-                             (mtime_t)(header[15] << 22)|
-                            ((mtime_t)(header[16]&0xfe) << 14)|
-                             (mtime_t)(header[17] << 7)|
-                             (mtime_t)(header[18] >> 1);
+                    if( i_header < 14 + 5 )
+                        return VLC_EGENERIC;
+                    *pi_dts = ExtractPESTimestamp( &p_header[14] );
                 }
             }
         }
         else
         {
             i_skip = 6;
-            while( i_skip < 23 && header[i_skip] == 0xff )
+            if( i_header < i_skip + 1 )
+                return VLC_EGENERIC;
+            while( i_skip < 23 && p_header[i_skip] == 0xff )
             {
                 i_skip++;
+                if( i_header < i_skip + 1 )
+                    return VLC_EGENERIC;
             }
             if( i_skip == 23 )
             {
                 msg_Err( p_demux, "too much MPEG-1 stuffing" );
-                block_ChainRelease( p_pes );
-                return;
+                return VLC_EGENERIC;
             }
-            if( ( header[i_skip] & 0xC0 ) == 0x40 )
+            if( ( p_header[i_skip] & 0xC0 ) == 0x40 )
             {
                 i_skip += 2;
             }
 
-            if(  header[i_skip]&0x20 )
+            if( i_header < i_skip + 1 )
+                return VLC_EGENERIC;
+
+            if(  p_header[i_skip]&0x20 )
             {
-                 i_pts = ((mtime_t)(header[i_skip]&0x0e ) << 29)|
-                          (mtime_t)(header[i_skip+1] << 22)|
-                         ((mtime_t)(header[i_skip+2]&0xfe) << 14)|
-                          (mtime_t)(header[i_skip+3] << 7)|
-                          (mtime_t)(header[i_skip+4] >> 1);
+                if( i_header < i_skip + 5 )
+                    return VLC_EGENERIC;
+                *pi_pts = ExtractPESTimestamp( &p_header[i_skip] );
 
-                if( header[i_skip]&0x10 )    /* has dts */
+                if( p_header[i_skip]&0x10 )    /* has dts */
                 {
-                     i_dts = ((mtime_t)(header[i_skip+5]&0x0e ) << 29)|
-                              (mtime_t)(header[i_skip+6] << 22)|
-                             ((mtime_t)(header[i_skip+7]&0xfe) << 14)|
-                              (mtime_t)(header[i_skip+8] << 7)|
-                              (mtime_t)(header[i_skip+9] >> 1);
-                     i_skip += 10;
+                    if( i_header < i_skip + 10 )
+                        return VLC_EGENERIC;
+                    *pi_dts = ExtractPESTimestamp( &p_header[i_skip+5] );
+                    i_skip += 10;
                 }
                 else
                 {
@@ -1767,21 +2133,66 @@ static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
         break;
     }
 
-    if( pid->es->fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
-        pid->es->fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
+    *pi_skip = i_skip;
+    return VLC_SUCCESS;
+}
+
+static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
+{
+    uint8_t header[34];
+    unsigned i_pes_size = 0;
+    unsigned i_skip = 0;
+    mtime_t i_dts = -1;
+    mtime_t i_pts = -1;
+    mtime_t i_length = 0;
+
+    assert(pid->type == TYPE_PES);
+    assert(pid->p_parent && pid->p_parent->type == TYPE_PMT);
+
+    const int i_max = block_ChainExtract( p_pes, header, 34 );
+    if ( i_max < 4 )
+    {
+        block_ChainRelease( p_pes );
+        return;
+    }
+
+    if( SCRAMBLED(*pid) || header[0] != 0 || header[1] != 0 || header[2] != 1 )
+    {
+        if ( !SCRAMBLED(*pid) )
+            msg_Warn( p_demux, "invalid header [0x%02x:%02x:%02x:%02x] (pid: %d)",
+                        header[0], header[1],header[2],header[3], pid->i_pid );
+        block_ChainRelease( p_pes );
+        return;
+    }
+
+    if( ParsePESHeader( p_demux, (uint8_t*)&header, i_max, &i_skip, &i_dts, &i_pts ) == VLC_EGENERIC )
+    {
+        block_ChainRelease( p_pes );
+        return;
+    }
+    else
+    {
+        if( i_pts != -1 )
+            i_pts = TimeStampWrapAround( pid->p_parent->u.p_pmt, i_pts );
+        if( i_dts != -1 )
+            i_dts = TimeStampWrapAround( pid->p_parent->u.p_pmt, i_dts );
+    }
+
+    if( pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
+        pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
     {
         i_skip += 4;
     }
-    else if( pid->es->fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
-             pid->es->fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
-             pid->es->fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
+    else if( pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
+             pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
+             pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
     {
         i_skip += 1;
     }
-    else if( pid->es->fmt.i_codec == VLC_CODEC_SUBT &&
-             pid->es->p_mpeg4desc )
+    else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SUBT &&
+             pid->u.p_pes->es.p_mpeg4desc )
     {
-        decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
+        const decoder_config_descriptor_t *dcd = &pid->u.p_pes->es.p_mpeg4desc->dec_descr;
 
         if( dcd->i_extra > 2 &&
             dcd->p_extra[0] == 0x10 &&
@@ -1835,7 +2246,7 @@ static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
         p_pes->i_length = i_length * 100 / 9;
 
         p_block = block_ChainGather( p_pes );
-        if( pid->es->fmt.i_codec == VLC_CODEC_SUBT )
+        if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SUBT )
         {
             if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
             {
@@ -1847,26 +2258,23 @@ static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
                 return;
             p_block->p_buffer[p_block->i_buffer -1] = '\0';
         }
-        else if( pid->es->fmt.i_codec == VLC_CODEC_TELETEXT )
+        else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_TELETEXT )
         {
-            if( p_block->i_pts <= VLC_TS_INVALID )
+            if( p_block->i_pts <= VLC_TS_INVALID && pid->p_parent )
             {
                 /* Teletext may have missing PTS (ETSI EN 300 472 Annexe A)
                  * In this case use the last PCR + 40ms */
-                for( int i = 0; pid->p_owner && i < pid->p_owner->i_prg; i++ )
+                assert( pid->p_parent->type == TYPE_PMT );
+                if( likely(pid->p_parent->type == TYPE_PMT) )
                 {
-                    if( pid->i_owner_number == pid->p_owner->prg[i]->i_number )
-                    {
-                        mtime_t i_pcr = pid->p_owner->prg[i]->i_pcr_value;
-                        if( i_pcr > VLC_TS_INVALID )
-                            p_block->i_pts = VLC_TS_0 + i_pcr * 100 / 9 + 40000;
-                        break;
-                    }
+                    mtime_t i_pcr = pid->p_parent->u.p_pmt->pcr.i_current;
+                    if( i_pcr > VLC_TS_INVALID )
+                        p_block->i_pts = VLC_TS_0 + i_pcr * 100 / 9 + 40000;
                 }
             }
         }
-        else if( pid->es->fmt.i_codec == VLC_CODEC_ARIB_A ||
-                 pid->es->fmt.i_codec == VLC_CODEC_ARIB_C )
+        else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_ARIB_A ||
+                 pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_ARIB_C )
         {
             if( p_block->i_pts <= VLC_TS_INVALID )
             {
@@ -1881,25 +2289,82 @@ static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
                 p_block->p_buffer[p_block->i_buffer -1] = '\0';
             }
         }
-        else if( pid->es->fmt.i_codec == VLC_CODEC_OPUS)
+        else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_OPUS)
         {
             p_block = Opus_Parse(p_demux, p_block);
         }
 
+        if( !pid->p_parent || pid->p_parent->type != TYPE_PMT )
+        {
+            block_Release( p_block );
+            return;
+        }
+
+        ts_pmt_t *p_pmt = pid->p_parent->u.p_pmt;
+
         while (p_block) {
             block_t *p_next = p_block->p_next;
             p_block->p_next = NULL;
-            for( int i = 0; i < pid->i_extra_es; i++ )
+
+            if( !p_pmt->pcr.b_fix_done ) /* Not seen yet */
+                PCRFixHandle( p_demux, p_pmt, p_block );
+
+            if( pid->u.p_pes->es.id && (p_pmt->pcr.i_current > -1 || p_pmt->pcr.b_disable) )
             {
-                es_out_Send( p_demux->out, pid->extra_es[i]->id,
-                        block_Duplicate( p_block ) );
-            }
+                if( pid->u.p_pes->p_prepcr_outqueue )
+                {
+                    block_ChainAppend( &pid->u.p_pes->p_prepcr_outqueue, p_block );
+                    p_block = pid->u.p_pes->p_prepcr_outqueue;
+                    p_next = p_block->p_next;
+                    p_block->p_next = NULL;
+                    pid->u.p_pes->p_prepcr_outqueue = NULL;
+                }
 
-            if (!p_sys->b_trust_pcr)
-                es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
-                        pid->i_owner_number, p_block->i_pts);
+                if ( p_pmt->pcr.b_disable && p_block->i_dts > VLC_TS_INVALID &&
+                     ( p_pmt->i_pid_pcr == pid->i_pid || p_pmt->i_pid_pcr == 0x1FFF ) )
+                {
+                    ProgramSetPCR( p_demux, p_pmt, (p_block->i_dts - VLC_TS_0) * 9 / 100 - 120000 );
+                }
+
+                /* Compute PCR/DTS offset if any */
+                if( p_pmt->pcr.i_pcroffset == -1 && p_block->i_dts > VLC_TS_INVALID &&
+                    p_pmt->pcr.i_current > VLC_TS_INVALID )
+                {
+                    int64_t i_dts27 = (p_block->i_dts - VLC_TS_0) * 9 / 100;
+                    int64_t i_pcr = TimeStampWrapAround( p_pmt, p_pmt->pcr.i_current );
+                    if( i_dts27 < i_pcr )
+                    {
+                        p_pmt->pcr.i_pcroffset = i_pcr - i_dts27 + 80000;
+                        msg_Warn( p_demux, "Broken stream: pid %d sends packets with dts %"PRId64
+                                           "us later than pcr, applying delay",
+                                  pid->i_pid, p_pmt->pcr.i_pcroffset * 100 / 9 );
+                    }
+                    else p_pmt->pcr.i_pcroffset = 0;
+                }
+
+                if( p_pmt->pcr.i_pcroffset != -1 )
+                {
+                    if( p_block->i_dts > VLC_TS_INVALID )
+                        p_block->i_dts += (p_pmt->pcr.i_pcroffset * 100 / 9);
+                    if( p_block->i_pts > VLC_TS_INVALID )
+                        p_block->i_pts += (p_pmt->pcr.i_pcroffset * 100 / 9);
+                }
+
+                for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
+                {
+                    es_out_Send( p_demux->out, pid->u.p_pes->extra_es.p_elems[i]->id,
+                            block_Duplicate( p_block ) );
+                }
+
+                es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_block );
+            }
+            else
+            {
+                if( !p_pmt->pcr.b_fix_done ) /* Not seen yet */
+                    PCRFixHandle( p_demux, p_pmt, p_block );
 
-            es_out_Send( p_demux->out, pid->es->id, p_block );
+                block_ChainAppend( &pid->u.p_pes->p_prepcr_outqueue, p_block );
+            }
 
             p_block = p_next;
         }
@@ -1913,19 +2378,13 @@ static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
 static void ParseTableSection( demux_t *p_demux, ts_pid_t *pid, block_t *p_data )
 {
     block_t *p_content = block_ChainGather( p_data );
-    mtime_t i_date = -1;
-    for( int i = 0; pid->p_owner && i < pid->p_owner->i_prg; i++ )
-    {
-        if( pid->i_owner_number == pid->p_owner->prg[i]->i_number )
-        {
-            i_date = pid->p_owner->prg[i]->i_pcr_value;
-            if( i_date >= 0 )
-                break;
-        }
-    }
-    if( i_date >= 0 )
+
+    if ( pid->p_parent && pid->p_parent->type == TYPE_PMT )
     {
-        if( pid->es->fmt.i_codec == VLC_CODEC_SCTE_27 )
+        ts_pmt_t *p_pmt = pid->p_parent->u.p_pmt;
+        mtime_t i_date = p_pmt->pcr.i_current;
+
+        if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SCTE_27 )
         {
             /* We need to extract the truncated pts stored inside the payload */
             if( p_content->i_buffer > 9 && p_content->p_buffer[0] == 0xc6 )
@@ -1935,7 +2394,7 @@ static void ParseTableSection( demux_t *p_demux, ts_pid_t *pid, block_t *p_data
                 if( p_content->p_buffer[3] & 0x40 )
                 {
                     i_index = ((p_content->p_buffer[7] & 0x0f) << 8) |
-                              p_content->p_buffer[8];
+                             p_content->p_buffer[8];
                     i_offset = 9;
                 }
                 if( i_index == 0 && p_content->i_buffer > i_offset + 8 )
@@ -1953,26 +2412,32 @@ static void ParseTableSection( demux_t *p_demux, ts_pid_t *pid, block_t *p_data
                 }
             }
         }
-        p_content->i_dts =
-        p_content->i_pts = VLC_TS_0 + i_date * 100 / 9;
+
+        p_content->i_dts = p_content->i_pts = VLC_TS_0 + i_date * 100 / 9;
+        PCRFixHandle( p_demux, p_pmt, p_content );
     }
-    es_out_Send( p_demux->out, pid->es->id, p_content );
+
+    es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_content );
 }
+
 static void ParseData( demux_t *p_demux, ts_pid_t *pid )
 {
-    block_t *p_data = pid->es->p_data;
+    block_t *p_data = pid->u.p_pes->p_data;
+    assert(p_data);
+    if(!p_data)
+        return;
 
     /* remove the pes from pid */
-    pid->es->p_data = NULL;
-    pid->es->i_data_size = 0;
-    pid->es->i_data_gathered = 0;
-    pid->es->pp_last = &pid->es->p_data;
+    pid->u.p_pes->p_data = NULL;
+    pid->u.p_pes->i_data_size = 0;
+    pid->u.p_pes->i_data_gathered = 0;
+    pid->u.p_pes->pp_last = &pid->u.p_pes->p_data;
 
-    if( pid->es->data_type == TS_ES_DATA_PES )
+    if( pid->u.p_pes->data_type == TS_ES_DATA_PES )
     {
         ParsePES( p_demux, pid, p_data );
     }
-    else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
+    else if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION )
     {
         ParseTableSection( p_demux, pid, p_data );
     }
@@ -1989,9 +2454,18 @@ static block_t* ReadTSPacket( demux_t *p_demux )
     block_t     *p_pkt;
 
     /* Get a new TS packet */
-    if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
+    if( !( p_pkt = stream_Block( p_sys->stream, p_sys->i_packet_size ) ) )
+    {
+        if( stream_Tell( p_sys->stream ) == stream_Size( p_sys->stream ) )
+            msg_Dbg( p_demux, "EOF at %"PRId64, stream_Tell( p_sys->stream ) );
+        else
+            msg_Dbg( p_demux, "Can't read TS packet at %"PRId64, stream_Tell(p_sys->stream) );
+        return NULL;
+    }
+
+    if( p_pkt->i_buffer < TS_HEADER_SIZE + p_sys->i_packet_header_size )
     {
-        msg_Dbg( p_demux, "eof ?" );
+        block_Release( p_pkt );
         return NULL;
     }
 
@@ -2007,14 +2481,15 @@ static block_t* ReadTSPacket( demux_t *p_demux )
     {
         msg_Warn( p_demux, "lost synchro" );
         block_Release( p_pkt );
-        while( vlc_object_alive (p_demux) )
+        for( ;; )
         {
             const uint8_t *p_peek;
-            int i_peek, i_skip = 0;
+            int i_peek = 0;
+            unsigned i_skip = 0;
 
-            i_peek = stream_Peek( p_demux->s, &p_peek,
+            i_peek = stream_Peek( p_sys->stream, &p_peek,
                     p_sys->i_packet_size * 10 );
-            if( i_peek < p_sys->i_packet_size + 1 )
+            if( i_peek < 0 || (unsigned)i_peek < p_sys->i_packet_size + 1 )
             {
                 msg_Dbg( p_demux, "eof ?" );
                 return NULL;
@@ -2030,14 +2505,14 @@ static block_t* ReadTSPacket( demux_t *p_demux )
                 i_skip++;
             }
             msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
-            stream_Read( p_demux->s, NULL, i_skip );
+            stream_Read( p_sys->stream, NULL, i_skip );
 
             if( i_skip < i_peek - p_sys->i_packet_size )
             {
                 break;
             }
         }
-        if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
+        if( !( p_pkt = stream_Block( p_sys->stream, p_sys->i_packet_size ) ) )
         {
             msg_Dbg( p_demux, "eof ?" );
             return NULL;
@@ -2046,25 +2521,13 @@ static block_t* ReadTSPacket( demux_t *p_demux )
     return p_pkt;
 }
 
-static mtime_t AdjustPCRWrapAround( demux_t *p_demux, mtime_t i_pcr )
+static int64_t TimeStampWrapAround( ts_pmt_t *p_pmt, int64_t i_time )
 {
-    demux_sys_t   *p_sys = p_demux->p_sys;
-    /*
-     * PCR is 33bit. If PCR reaches to 0x1FFFFFFFF (26:30:43.717), ressets from 0.
-     * So, need to add 0x1FFFFFFFF, for calculating duration or current position.
-     */
-    mtime_t i_adjust = 0;
-    int64_t i_pos = stream_Tell( p_demux->s );
-    int i;
-    for( i = 1; i < p_sys->i_pcrs_num && p_sys->p_pos[i] <= i_pos; ++i )
-    {
-        if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
-            i_adjust += 0x1FFFFFFFF;
-    }
-    if( p_sys->p_pcrs[i-1] > i_pcr )
-        i_adjust += 0x1FFFFFFFF;
+    int64_t i_adjust = 0;
+    if( p_pmt && p_pmt->pcr.i_first > 0x0FFFFFFFF && i_time < 0x0FFFFFFFF )
+        i_adjust = 0x1FFFFFFFF;
 
-    return i_pcr + i_adjust;
+    return i_time + i_adjust;
 }
 
 static mtime_t GetPCR( block_t *p_pkt )
@@ -2087,237 +2550,441 @@ static mtime_t GetPCR( block_t *p_pkt )
     return i_pcr;
 }
 
-static int SeekToPCR( demux_t *p_demux, int64_t i_pos )
+static void UpdateScrambledState( demux_t *p_demux, ts_pid_t *p_pid, bool b_scrambled )
 {
-    demux_sys_t *p_sys = p_demux->p_sys;
-
-    mtime_t i_pcr = -1;
-    const int64_t i_initial_pos = stream_Tell( p_demux->s );
-
-    if( i_pos < 0 )
-        return VLC_EGENERIC;
+    if( !SCRAMBLED(*p_pid) == !b_scrambled )
+        return;
 
-    int64_t i_last_pos = stream_Size( p_demux->s ) - p_sys->i_packet_size;
-    if( i_pos > i_last_pos )
-        i_pos = i_last_pos;
+    msg_Warn( p_demux, "scrambled state changed on pid %d (%d->%d)",
+              p_pid->i_pid, SCRAMBLED(*p_pid), b_scrambled );
 
-    if( stream_Seek( p_demux->s, i_pos ) )
-        return VLC_EGENERIC;
+    p_pid->i_flags |= (b_scrambled) ? FLAG_SCRAMBLED : FLAGS_NONE;
 
-    while( vlc_object_alive( p_demux ) )
+    if( p_pid->type == TYPE_PES && p_pid->u.p_pes->es.id )
     {
-        block_t *p_pkt;
-
-        if( !( p_pkt = ReadTSPacket( p_demux ) ) )
-        {
-            break;
-        }
-        if( PIDGet( p_pkt ) == p_sys->i_pid_ref_pcr )
+        for( int i = 0; i < p_pid->u.p_pes->extra_es.i_size; i++ )
         {
-            i_pcr = GetPCR( p_pkt );
+            if( p_pid->u.p_pes->extra_es.p_elems[i]->id )
+                es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
+                                p_pid->u.p_pes->extra_es.p_elems[i]->id, b_scrambled );
         }
-        block_Release( p_pkt );
-        if( i_pcr >= 0 )
-            break;
-        if( stream_Tell( p_demux->s ) >= i_last_pos )
-            break;
+        es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
+                        p_pid->u.p_pes->es.id, b_scrambled );
     }
-    if( i_pcr < 0 )
+}
+
+static inline void FlushESBuffer( ts_pes_t *p_pes )
+{
+    if( p_pes->p_data )
     {
-        stream_Seek( p_demux->s, i_initial_pos );
-        assert( i_initial_pos == stream_Tell( p_demux->s ) );
-        return VLC_EGENERIC;
+        p_pes->i_data_gathered = p_pes->i_data_size = 0;
+        block_ChainRelease( p_pes->p_data );
+        p_pes->p_data = NULL;
+        p_pes->pp_last = &p_pes->p_data;
     }
-
-    p_sys->i_current_pcr = i_pcr;
-    return VLC_SUCCESS;
 }
 
-static int Seek( demux_t *p_demux, double f_percent )
+static void ReadyQueuesPostSeek( demux_t *p_demux )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
 
-    int64_t i_initial_pos = stream_Tell( p_demux->s );
-    mtime_t i_initial_pcr = p_sys->i_current_pcr;
-
-    /*
-     * Find the time position by using binary search algorithm.
-     */
-    mtime_t i_target_pcr = (p_sys->i_last_pcr - p_sys->i_first_pcr) * f_percent + p_sys->i_first_pcr;
-
-    int64_t i_head_pos = 0;
-    int64_t i_tail_pos;
+    ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
+    for( int i=0; i< p_pat->programs.i_size; i++ )
     {
-        mtime_t i_adjust = 0;
-        int i;
-        for( i = 1; i < p_sys->i_pcrs_num; ++i )
+        ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
+        for( int j=0; j<p_pmt->e_streams.i_size; j++ )
         {
-            if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
-                i_adjust += 0x1FFFFFFFF;
-            if( p_sys->p_pcrs[i] + i_adjust > i_target_pcr )
-                break;
+            ts_pid_t *pid = p_pmt->e_streams.p_elems[j];
+
+            if( pid->type != TYPE_PES )
+                continue;
+
+            if( pid->u.p_pes->es.id )
+            {
+                block_t *p_block = block_Alloc(1);
+                if( p_block )
+                {
+                    p_block->i_buffer = 0;
+                    p_block->i_flags = BLOCK_FLAG_DISCONTINUITY | BLOCK_FLAG_CORRUPTED;
+                    es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_block );
+                }
+            }
+
+            pid->i_cc = 0xff;
+
+            if( pid->u.p_pes->p_prepcr_outqueue )
+            {
+                block_ChainRelease( pid->u.p_pes->p_prepcr_outqueue );
+                pid->u.p_pes->p_prepcr_outqueue = NULL;
+            }
+
+            FlushESBuffer( pid->u.p_pes );
         }
-        i_head_pos = p_sys->p_pos[i-1];
-        i_tail_pos = ( i < p_sys->i_pcrs_num ) ?  p_sys->p_pos[i] : stream_Size( p_demux->s );
+        p_pmt->pcr.i_current = -1;
     }
-    msg_Dbg( p_demux, "Seek():i_head_pos:%"PRId64", i_tail_pos:%"PRId64, i_head_pos, i_tail_pos);
+}
+
+static int SeekToTime( demux_t *p_demux, ts_pmt_t *p_pmt, int64_t i_scaledtime )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+
+    /* Deal with common but worst binary search case */
+    if( p_pmt->pcr.i_first == i_scaledtime && p_sys->b_canseek )
+        return stream_Seek( p_sys->stream, 0 );
+
+    if( !p_sys->b_canfastseek )
+        return VLC_EGENERIC;
+
+    int64_t i_initial_pos = stream_Tell( p_sys->stream );
+
+    /* Find the time position by using binary search algorithm. */
+    int64_t i_head_pos = 0;
+    int64_t i_tail_pos = stream_Size( p_sys->stream ) - p_sys->i_packet_size;
+    if( i_head_pos >= i_tail_pos )
+        return VLC_EGENERIC;
 
     bool b_found = false;
-    int i_cnt = 0;
-    while( i_head_pos <= i_tail_pos )
+    while( (i_head_pos + p_sys->i_packet_size) <= i_tail_pos && !b_found )
     {
         /* Round i_pos to a multiple of p_sys->i_packet_size */
-        int64_t i_pos = i_head_pos + (i_tail_pos - i_head_pos) / 2;
-        int64_t i_div = i_pos % p_sys->i_packet_size;
-        i_pos -= i_div;
-        if( SeekToPCR( p_demux, i_pos ) )
+        int64_t i_splitpos = i_head_pos + (i_tail_pos - i_head_pos) / 2;
+        int64_t i_div = i_splitpos % p_sys->i_packet_size;
+        i_splitpos -= i_div;
+
+        if ( stream_Seek( p_sys->stream, i_splitpos ) != VLC_SUCCESS )
             break;
-        p_sys->i_current_pcr = AdjustPCRWrapAround( p_demux, p_sys->i_current_pcr );
-        int64_t i_diff_msec = (p_sys->i_current_pcr - i_target_pcr) * 100 / 9 / 1000;
-        if( i_diff_msec > 500 )
-        {
-            i_tail_pos = i_pos - p_sys->i_packet_size;
-        }
-        else if( i_diff_msec < -500 )
+
+        int64_t i_pos = i_splitpos;
+        while( i_pos > -1 && i_pos < i_tail_pos )
         {
-            i_head_pos = i_pos + p_sys->i_packet_size;
+            int64_t i_pcr = -1;
+            block_t *p_pkt = ReadTSPacket( p_demux );
+            if( !p_pkt )
+            {
+                i_head_pos = i_tail_pos;
+                break;
+            }
+            else
+                i_pos = stream_Tell( p_sys->stream );
+
+            int i_pid = PIDGet( p_pkt );
+            if( i_pid != 0x1FFF && PID(p_sys, i_pid)->type == TYPE_PES &&
+                PID(p_sys, i_pid)->p_parent->u.p_pmt == p_pmt &&
+               (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
+               (p_pkt->p_buffer[3] & 0xD0) == 0x10    /* Has payload but is not encrypted */
+            )
+            {
+                unsigned i_skip = 4;
+                if ( p_pkt->p_buffer[3] & 0x20 ) // adaptation field
+                {
+                    if( p_pkt->i_buffer >= 4 + 2 + 5 )
+                    {
+                        i_pcr = GetPCR( p_pkt );
+                        i_skip += 1 + p_pkt->p_buffer[4];
+                    }
+                }
+                else
+                {
+                    mtime_t i_dts = -1;
+                    mtime_t i_pts = -1;
+                    if ( VLC_SUCCESS == ParsePESHeader( p_demux, &p_pkt->p_buffer[i_skip],
+                                                        p_pkt->i_buffer - i_skip, &i_skip, &i_dts, &i_pts ) )
+                    {
+                        if( i_dts > -1 )
+                            i_pcr = i_dts;
+                    }
+                }
+            }
+            block_Release( p_pkt );
+
+            if( i_pcr != -1 )
+            {
+                int64_t i_diff = i_scaledtime - TimeStampWrapAround( p_pmt, i_pcr );
+                if ( i_diff < 0 )
+                    i_tail_pos = i_splitpos - p_sys->i_packet_size;
+                else if( i_diff < TO_SCALE(VLC_TS_0 + CLOCK_FREQ / 2) ) // 500ms
+                    b_found = true;
+                else
+                    i_head_pos = i_pos;
+                break;
+            }
         }
-        else
+
+        if ( !b_found && i_pos > i_tail_pos - p_sys->i_packet_size )
+            i_tail_pos = i_splitpos - p_sys->i_packet_size;
+    }
+
+    if( !b_found )
+    {
+        msg_Dbg( p_demux, "Seek():cannot find a time position." );
+        stream_Seek( p_sys->stream, i_initial_pos );
+        return VLC_EGENERIC;
+    }
+    return VLC_SUCCESS;
+}
+
+static ts_pid_t *PID( demux_sys_t *p_sys, uint16_t i_pid )
+{
+    switch( i_pid )
+    {
+        case 0:
+            return &p_sys->pids.pat;
+        case 0x1FFF:
+            return &p_sys->pids.dummy;
+        default:
+            if( p_sys->pids.i_last_pid == i_pid )
+                return p_sys->pids.p_last;
+        break;
+    }
+
+    for( int i=0; i < p_sys->pids.i_all; i++ )
+    {
+        if( p_sys->pids.pp_all[i]->i_pid == i_pid )
         {
-            // diff time <= 500msec
-            b_found = true;
-            break;
+            p_sys->pids.p_last = p_sys->pids.pp_all[i];
+            p_sys->pids.i_last_pid = i_pid;
+            return p_sys->pids.p_last;
         }
-        ++i_cnt;
     }
-    if( !b_found )
+
+    if( p_sys->pids.i_all >= p_sys->pids.i_all_alloc )
     {
-        msg_Dbg( p_demux, "Seek():cannot find a time position. i_cnt:%d", i_cnt );
-        stream_Seek( p_demux->s, i_initial_pos );
-        p_sys->i_current_pcr = i_initial_pcr;
-        return VLC_EGENERIC;
+        ts_pid_t **p_realloc = realloc( p_sys->pids.pp_all,
+                                       (p_sys->pids.i_all_alloc + PID_ALLOC_CHUNK) * sizeof(ts_pid_t *) );
+        if( !p_realloc )
+            return NULL;
+        p_sys->pids.pp_all = p_realloc;
+        p_sys->pids.i_all_alloc += PID_ALLOC_CHUNK;
     }
-    else
+
+    ts_pid_t *p_pid = calloc( 1, sizeof(*p_pid) );
+    if( !p_pid )
     {
-        msg_Dbg( p_demux, "Seek():can find a time position. i_cnt:%d", i_cnt );
-        return VLC_SUCCESS;
+        abort();
+        //return NULL;
     }
+
+    p_pid->i_pid = i_pid;
+    p_sys->pids.pp_all[p_sys->pids.i_all++] = p_pid;
+
+    p_sys->pids.p_last = p_pid;
+    p_sys->pids.i_last_pid = i_pid;
+
+    return p_pid;
 }
 
-static void GetFirstPCR( demux_t *p_demux )
+static ts_pmt_t * GetProgramByID( demux_sys_t *p_sys, int i_program )
 {
-    demux_sys_t *p_sys = p_demux->p_sys;
+    if(unlikely(PID(p_sys, 0)->type != TYPE_PAT))
+        return NULL;
+
+    ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
+    for( int i = 0; i < p_pat->programs.i_size; i++ )
+    {
+        assert(p_pat->programs.p_elems[i]->type == TYPE_PMT);
+        ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
+        if( p_pmt->i_number == i_program )
+            return p_pmt;
+    }
+    return NULL;
+}
 
-    int64_t i_initial_pos = stream_Tell( p_demux->s );
+#define PROBE_CHUNK_COUNT 250
 
-    if( stream_Seek( p_demux->s, 0 ) )
-        return;
+static int ProbeChunk( demux_t *p_demux, int i_program, bool b_end, int64_t *pi_pcr, bool *pb_found )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    int i_count = 0;
+    block_t *p_pkt = NULL;
 
-    while( vlc_object_alive (p_demux) )
+    for( ;; )
     {
-        block_t     *p_pkt;
+        *pi_pcr = -1;
 
-        if( !( p_pkt = ReadTSPacket( p_demux ) ) )
+        if( i_count++ > PROBE_CHUNK_COUNT || !( p_pkt = ReadTSPacket( p_demux ) ) )
         {
             break;
         }
-        mtime_t i_pcr = GetPCR( p_pkt );
-        if( i_pcr >= 0 )
+
+        const int i_pid = PIDGet( p_pkt );
+        ts_pid_t *p_pid = PID(p_sys, i_pid);
+
+        p_pid->i_flags |= FLAG_SEEN;
+
+        if( i_pid != 0x1FFF && (p_pkt->p_buffer[1] & 0x80) == 0 ) /* not corrupt */
         {
-            p_sys->i_pid_ref_pcr = PIDGet( p_pkt );
-            p_sys->i_first_pcr = i_pcr;
-            p_sys->i_current_pcr = i_pcr;
+            bool b_pcrresult = true;
+            bool b_adaptfield = p_pkt->p_buffer[3] & 0x20;
+
+            if( b_adaptfield && p_pkt->i_buffer >= 4 + 2 + 5 )
+                *pi_pcr = GetPCR( p_pkt );
+
+            if( *pi_pcr == -1 &&
+                (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* payload start */
+                (p_pkt->p_buffer[3] & 0xD0) == 0x10 && /* Has payload but is not encrypted */
+                p_pid->type == TYPE_PES &&
+                p_pid->u.p_pes->es.fmt.i_cat != UNKNOWN_ES
+              )
+            {
+                b_pcrresult = false;
+                mtime_t i_dts = -1;
+                mtime_t i_pts = -1;
+                unsigned i_skip = 4;
+                if ( b_adaptfield ) // adaptation field
+                    i_skip += 1 + p_pkt->p_buffer[4];
+
+                if ( VLC_SUCCESS == ParsePESHeader( p_demux, &p_pkt->p_buffer[i_skip],
+                                                    p_pkt->i_buffer - i_skip,
+                                                    &i_skip, &i_dts, &i_pts ) )
+                {
+                    if( i_dts != -1 )
+                        *pi_pcr = i_dts;
+                    else if( i_pts != -1 )
+                        *pi_pcr = i_pts;
+                }
+            }
+
+            if( *pi_pcr != -1 )
+            {
+                ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
+                for( int i=0; i<p_pat->programs.i_size; i++ )
+                {
+                    ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
+                    if( ( p_pmt->i_pid_pcr == p_pid->i_pid ||
+                        ( p_pmt->i_pid_pcr == 0x1FFF && p_pid->p_parent == p_pat->programs.p_elems[i] ) ) )
+                    {
+                        if( b_end )
+                        {
+                            p_pmt->i_last_dts = *pi_pcr;
+                        }
+                        /* Start, only keep first */
+                        else if( b_pcrresult && p_pmt->pcr.i_first == -1 )
+                        {
+                            p_pmt->pcr.i_first = *pi_pcr;
+                        }
+                        else if( p_pmt->pcr.i_first_dts < VLC_TS_0 )
+                        {
+                            p_pmt->pcr.i_first_dts = FROM_SCALE(*pi_pcr);
+                        }
+
+                        if( i_program == 0 || i_program == p_pmt->i_number )
+                            *pb_found = true;
+                    }
+                }
+            }
         }
+
         block_Release( p_pkt );
-        if( p_sys->i_first_pcr >= 0 )
-            break;
     }
-    stream_Seek( p_demux->s, i_initial_pos );
+
+    return i_count;
 }
 
-static void GetLastPCR( demux_t *p_demux )
+static int ProbeStart( demux_t *p_demux, int i_program )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
+    const int64_t i_initial_pos = stream_Tell( p_sys->stream );
+    int64_t i_stream_size = stream_Size( p_sys->stream );
 
-    const int64_t i_initial_pos = stream_Tell( p_demux->s );
-    mtime_t i_initial_pcr = p_sys->i_current_pcr;
+    int i_probe_count = 0;
+    int64_t i_pos;
+    mtime_t i_pcr = -1;
+    bool b_found = false;
 
-    int64_t i_stream_size = stream_Size( p_demux->s );
-    int64_t i_last_pos = i_stream_size - p_sys->i_packet_size;
-    /* Round i_pos to a multiple of p_sys->i_packet_size */
-    int64_t i_pos = i_last_pos - p_sys->i_packet_size * 4500; /* FIXME if the value is not reasonable, please change it. */
-    int64_t i_div = i_pos % p_sys->i_packet_size;
-    i_pos -= i_div;
+    do
+    {
+        i_pos = p_sys->i_packet_size * i_probe_count;
+        i_pos = __MIN( i_pos, i_stream_size );
 
-    if( i_pos <= i_initial_pos && i_pos >= i_stream_size )
-        i_pos = i_initial_pos + p_sys->i_packet_size;
-    if( i_pos < 0 && i_pos >= i_stream_size )
-        return;
+        if( stream_Seek( p_sys->stream, i_pos ) )
+            return VLC_EGENERIC;
 
-    while( vlc_object_alive( p_demux ) )
-    {
-        if( SeekToPCR( p_demux, i_pos ) )
-            break;
-        p_sys->i_last_pcr = AdjustPCRWrapAround( p_demux, p_sys->i_current_pcr );
-        if( ( i_pos = stream_Tell( p_demux->s ) ) >= i_last_pos )
-            break;
-    }
-    if( p_sys->i_last_pcr >= 0 )
-    {
-        int64_t i_size = stream_Size( p_demux->s );
-        mtime_t i_duration_msec = ( p_sys->i_last_pcr - p_sys->i_first_pcr ) * 100 / 9 / 1000;
-        int64_t i_rate = ( i_size < 0 || i_duration_msec <= 0 ) ? 0 : i_size * 1000 * 8 / i_duration_msec;
-        const int64_t TS_SUPPOSED_MAXRATE = 55 * 1000 * 1000; //FIXME I think it's enough.
-        const int64_t TS_SUPPOSED_MINRATE = 0.5 * 1000 * 1000; //FIXME
-        if( i_rate < TS_SUPPOSED_MINRATE || i_rate > TS_SUPPOSED_MAXRATE )
-        {
-            msg_Dbg( p_demux, "calculated bitrate (%"PRId64"bit/s) is too low or too high. min bitrate (%"PRId64"bit/s) max bitrate (%"PRId64"bit/s)",
-                     i_rate, TS_SUPPOSED_MINRATE, TS_SUPPOSED_MAXRATE );
-            p_sys->i_last_pcr = -1;
-        }
-    }
-    stream_Seek( p_demux->s, i_initial_pos );
-    assert( i_initial_pos == stream_Tell( p_demux->s ) );
-    p_sys->i_current_pcr = i_initial_pcr;
+        ProbeChunk( p_demux, i_program, false, &i_pcr, &b_found );
+
+        /* Go ahead one more chunk if end of file contained only stuffing packets */
+        i_probe_count += PROBE_CHUNK_COUNT;
+    } while( i_pos > 0 && (i_pcr == -1 || !b_found) && i_probe_count < (2 * PROBE_CHUNK_COUNT) );
+
+    stream_Seek( p_sys->stream, i_initial_pos );
+
+    return (b_found) ? VLC_SUCCESS : VLC_EGENERIC;
 }
 
-static void CheckPCR( demux_t *p_demux )
+static int ProbeEnd( demux_t *p_demux, int i_program )
 {
-    demux_sys_t   *p_sys = p_demux->p_sys;
+    demux_sys_t *p_sys = p_demux->p_sys;
+    const int64_t i_initial_pos = stream_Tell( p_sys->stream );
+    int64_t i_stream_size = stream_Size( p_sys->stream );
+
+    int i_probe_count = PROBE_CHUNK_COUNT;
+    int64_t i_pos;
+    mtime_t i_pcr = -1;
+    bool b_found = false;
+
+    do
+    {
+        i_pos = i_stream_size - (p_sys->i_packet_size * i_probe_count);
+        i_pos = __MAX( i_pos, 0 );
+
+        if( stream_Seek( p_sys->stream, i_pos ) )
+            return VLC_EGENERIC;
+
+        ProbeChunk( p_demux, i_program, true, &i_pcr, &b_found );
 
-    int64_t i_initial_pos = stream_Tell( p_demux->s );
-    mtime_t i_initial_pcr = p_sys->i_current_pcr;
+        /* Go ahead one more chunk if end of file contained only stuffing packets */
+        i_probe_count += PROBE_CHUNK_COUNT;
+    } while( i_pos > 0 && (i_pcr == -1 || !b_found) && i_probe_count < (6 * PROBE_CHUNK_COUNT) );
 
-    int64_t i_size = stream_Size( p_demux->s );
+    stream_Seek( p_sys->stream, i_initial_pos );
 
-    int i = 0;
-    p_sys->p_pcrs[0] = p_sys->i_first_pcr;
-    p_sys->p_pos[0] = i_initial_pos;
+    return (b_found) ? VLC_SUCCESS : VLC_EGENERIC;
+}
+
+static void ProgramSetPCR( demux_t *p_demux, ts_pmt_t *p_pmt, mtime_t i_pcr )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
 
-    for( i = 1; i < p_sys->i_pcrs_num && vlc_object_alive( p_demux ); ++i )
+    /* Check if we have enqueued blocks waiting the/before the
+       PCR barrier, and then adapt pcr so they have valid PCR when dequeuing */
+    if( p_pmt->pcr.i_current == -1 && p_pmt->pcr.b_fix_done )
     {
-        /* Round i_pos to a multiple of p_sys->i_packet_size */
-        int64_t i_pos = i_size / p_sys->i_pcrs_num * i;
-        int64_t i_div = i_pos % p_sys->i_packet_size;
-        i_pos -= i_div;
-        if( SeekToPCR( p_demux, i_pos ) )
-            break;
-        p_sys->p_pcrs[i] = p_sys->i_current_pcr;
-        p_sys->p_pos[i] = stream_Tell( p_demux->s );
-        if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
+        mtime_t i_mindts = -1;
+
+        ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
+        for( int i=0; i< p_pat->programs.i_size; i++ )
+        {
+            ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
+            for( int j=0; j<p_pmt->e_streams.i_size; j++ )
+            {
+                ts_pid_t *p_pid = p_pmt->e_streams.p_elems[j];
+                block_t *p_block = p_pid->u.p_pes->p_prepcr_outqueue;
+                while( p_block && p_block->i_dts == VLC_TS_INVALID )
+                    p_block = p_block->p_next;
+
+                if( p_block && ( i_mindts == -1 || p_block->i_dts < i_mindts ) )
+                    i_mindts = p_block->i_dts;
+            }
+        }
+
+        if( i_mindts > VLC_TS_INVALID )
         {
-            msg_Dbg( p_demux, "PCR Wrap Around found between %d%% and %d%% (pcr:%"PRId64"(0x%09"PRIx64") pcr:%"PRId64"(0x%09"PRIx64"))",
-                    (int)((i-1)*100/p_sys->i_pcrs_num), (int)(i*100/p_sys->i_pcrs_num), p_sys->p_pcrs[i-1], p_sys->p_pcrs[i-1], p_sys->p_pcrs[i], p_sys->p_pcrs[i] );
+            msg_Dbg( p_demux, "Program %d PCR prequeue fixup %"PRId64"->%"PRId64,
+                     p_pmt->i_number, TO_SCALE(i_mindts), i_pcr );
+            i_pcr = TO_SCALE(i_mindts);
         }
     }
-    if( i < p_sys->i_pcrs_num )
+
+    p_pmt->pcr.i_current = i_pcr;
+    if( p_pmt->pcr.i_first == -1 )
     {
-        msg_Dbg( p_demux, "Force Seek Per Percent: Seeking failed at %d%%.", (int)(i*100/p_sys->i_pcrs_num) );
-        p_sys->b_force_seek_per_percent = true;
+        p_pmt->pcr.i_first = i_pcr; // now seen
     }
 
-    stream_Seek( p_demux->s, i_initial_pos );
-    p_sys->i_current_pcr = i_initial_pcr;
+    if ( p_sys->i_pmt_es )
+    {
+        es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
+                        p_pmt->i_number, VLC_TS_0 + i_pcr * 100 / 9 );
+    }
 }
 
 static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
@@ -2331,37 +2998,101 @@ static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
     if( i_pcr < 0 )
         return;
 
-    if( p_sys->i_pid_ref_pcr == pid->i_pid )
-        p_sys->i_current_pcr = AdjustPCRWrapAround( p_demux, i_pcr );
+    pid->probed.i_pcr_count++;
+
+    if(unlikely(PID(p_sys, 0)->type != TYPE_PAT))
+        return;
 
     /* Search program and set the PCR */
-    int i_group = -1;
-    for( int i = 0; i < p_sys->i_pmt && i_group < 0 ; i++ )
+    ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
+    for( int i = 0; i < p_pat->programs.i_size; i++ )
     {
-        bool b_pmt_has_es = false;
+        ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
+        mtime_t i_program_pcr = TimeStampWrapAround( p_pmt, i_pcr );
+
+        if( p_pmt->i_pid_pcr == 0x1FFF ) /* That program has no dedicated PCR pid ISO/IEC 13818-1 2.4.4.9 */
+        {
+            if( pid->p_parent == p_pat->programs.p_elems[i] ) /* PCR shall be on pid itself */
+            {
+                /* ? update PCR for the whole group program ? */
+                ProgramSetPCR( p_demux, p_pmt, i_program_pcr );
+            }
+        }
+        else /* set PCR provided by current pid to program(s) referencing it */
+        {
+            /* Can be dedicated PCR pid (no owned then) or another pid (owner == pmt) */
+            if( p_pmt->i_pid_pcr == pid->i_pid ) /* If that program references current pid as PCR */
+            {
+                /* We've found a target group for update */
+                ProgramSetPCR( p_demux, p_pmt, i_program_pcr );
+            }
+        }
+
+    }
+}
+
+static int FindPCRCandidate( ts_pmt_t *p_pmt )
+{
+    ts_pid_t *p_cand = NULL;
+    int i_previous = p_pmt->i_pid_pcr;
 
-        for( int i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
+    for( int i=0; i<p_pmt->e_streams.i_size; i++ )
+    {
+        ts_pid_t *p_pid = p_pmt->e_streams.p_elems[i];
+        if( SEEN(p_pid) &&
+            (!p_cand || p_cand->i_pid != i_previous) )
         {
-            if( pid->i_pid == p_sys->pmt[i]->psi->prg[i_prg]->i_pid_pcr )
+            if( p_pid->probed.i_pcr_count ) /* check PCR frequency first */
             {
-                /* We've found our target group */
-                p_sys->pmt[i]->psi->prg[i_prg]->i_pcr_value = i_pcr;
-                i_group = p_sys->pmt[i]->psi->prg[i_prg]->i_number;
-                for( int j = 0; j < 8192; j++ )
+                if( !p_cand || p_pid->probed.i_pcr_count > p_cand->probed.i_pcr_count )
                 {
-                    const ts_pid_t *pid = &p_sys->pid[j];
-                    if( pid->b_valid && pid->p_owner == p_sys->pmt[i]->psi && pid->es )
-                    {
-                        b_pmt_has_es = true;
-                        break;
-                    }
+                    p_cand = p_pid;
+                    continue;
                 }
             }
+
+            if( p_pid->u.p_pes->es.fmt.i_cat == AUDIO_ES )
+            {
+                if( !p_cand )
+                    p_cand = p_pid;
+            }
+            else if ( p_pid->u.p_pes->es.fmt.i_cat == VIDEO_ES ) /* Otherwise prioritize video dts */
+            {
+                if( !p_cand || p_cand->u.p_pes->es.fmt.i_cat == AUDIO_ES )
+                    p_cand = p_pid;
+            }
         }
+    }
+
+    if( p_cand )
+        return p_cand->i_pid;
+    else
+        return 0x1FFF;
+}
 
-        if ( p_sys->b_trust_pcr && i_group > 0 && b_pmt_has_es )
-            es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
-              i_group, VLC_TS_0 + i_pcr * 100 / 9 );
+/* Tries to reselect a new PCR when none has been received */
+static void PCRFixHandle( demux_t *p_demux, ts_pmt_t *p_pmt, block_t *p_block )
+{
+    if ( p_pmt->pcr.b_disable || p_pmt->pcr.b_fix_done )
+    {
+        return;
+    }
+    /* Record the first data packet timestamp in case there wont be any PCR */
+    else if( !p_pmt->pcr.i_first_dts )
+    {
+        p_pmt->pcr.i_first_dts = p_block->i_dts;
+    }
+    else if( p_block->i_dts - p_pmt->pcr.i_first_dts > CLOCK_FREQ / 2 ) /* "PCR repeat rate shall not exceed 100ms" */
+    {
+        if( p_pmt->pcr.i_current < 0 )
+        {
+            int i_cand = FindPCRCandidate( p_pmt );
+            p_pmt->i_pid_pcr = i_cand;
+            msg_Warn( p_demux, "No PCR received for program %d, set up workaround using pid %d",
+                      p_pmt->i_number, i_cand );
+            UpdatePESFilters( p_demux, p_demux->p_sys->b_es_all );
+            p_pmt->pcr.b_fix_done = true;
+        }
     }
 }
 
@@ -2369,7 +3100,6 @@ static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
 {
     const uint8_t *p = p_bk->p_buffer;
     const bool b_unit_start = p[1]&0x40;
-    const bool b_scrambled  = p[3]&0x80;
     const bool b_adaptation = p[3]&0x20;
     const bool b_payload    = p[3]&0x10;
     const int  i_cc         = p[3]&0x0f; /* continuity counter */
@@ -2393,8 +3123,8 @@ static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
     {
         msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
                  pid->i_pid );
-        if( pid->es->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
-            pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
+        if( pid->u.p_pes->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
+            pid->u.p_pes->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
     }
 
     if( p_demux->p_sys->csa )
@@ -2418,7 +3148,7 @@ static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
         {
             /* discontinuity indicator found in stream */
             b_discontinuity = (p[5]&0x80) ? true : false;
-            if( b_discontinuity && pid->es->p_data )
+            if( b_discontinuity && pid->u.p_pes->p_data )
             {
                 msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
                             pid->i_pid );
@@ -2457,48 +3187,31 @@ static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
                       i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );
 
             pid->i_cc = i_cc;
-            if( pid->es->p_data && pid->es->fmt.i_cat != VIDEO_ES &&
-                pid->es->fmt.i_cat != AUDIO_ES )
+            if( pid->u.p_pes->p_data && pid->u.p_pes->es.fmt.i_cat != VIDEO_ES &&
+                pid->u.p_pes->es.fmt.i_cat != AUDIO_ES )
             {
                 /* Small audio/video artifacts are usually better than
                  * dropping full frames */
-                pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
+                pid->u.p_pes->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
             }
         }
     }
 
     PCRHandle( p_demux, pid, p_bk );
 
-    if( i_skip >= 188 || pid->es->id == NULL )
+    if( i_skip >= 188 )
     {
         block_Release( p_bk );
         return i_ret;
     }
 
-    /* */
-    if( !pid->b_scrambled != !b_scrambled )
-    {
-        msg_Warn( p_demux, "scrambled state changed on pid %d (%d->%d)",
-                  pid->i_pid, pid->b_scrambled, b_scrambled );
-
-        pid->b_scrambled = b_scrambled;
-
-        for( int i = 0; i < pid->i_extra_es; i++ )
-        {
-            es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
-                            pid->extra_es[i]->id, b_scrambled );
-        }
-        es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
-                        pid->es->id, b_scrambled );
-    }
-
     /* We have to gather it */
     p_bk->p_buffer += i_skip;
     p_bk->i_buffer -= i_skip;
 
     if( b_unit_start )
     {
-        if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
+        if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
         {
             int i_pointer_field = __MIN( p_bk->p_buffer[0], p_bk->i_buffer - 1 );
             block_t *p = block_Duplicate( p_bk );
@@ -2506,39 +3219,39 @@ static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
             {
                 p->i_buffer = i_pointer_field;
                 p->p_buffer++;
-                block_ChainLastAppend( &pid->es->pp_last, p );
+                block_ChainLastAppend( &pid->u.p_pes->pp_last, p );
             }
             p_bk->i_buffer -= 1 + i_pointer_field;
             p_bk->p_buffer += 1 + i_pointer_field;
         }
-        if( pid->es->p_data )
+        if( pid->u.p_pes->p_data )
         {
             ParseData( p_demux, pid );
             i_ret = true;
         }
 
-        block_ChainLastAppend( &pid->es->pp_last, p_bk );
-        if( pid->es->data_type == TS_ES_DATA_PES )
+        block_ChainLastAppend( &pid->u.p_pes->pp_last, p_bk );
+        if( pid->u.p_pes->data_type == TS_ES_DATA_PES )
         {
             if( p_bk->i_buffer > 6 )
             {
-                pid->es->i_data_size = GetWBE( &p_bk->p_buffer[4] );
-                if( pid->es->i_data_size > 0 )
+                pid->u.p_pes->i_data_size = GetWBE( &p_bk->p_buffer[4] );
+                if( pid->u.p_pes->i_data_size > 0 )
                 {
-                    pid->es->i_data_size += 6;
+                    pid->u.p_pes->i_data_size += 6;
                 }
             }
         }
-        else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
+        else if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION )
         {
             if( p_bk->i_buffer > 3 && p_bk->p_buffer[0] != 0xff )
             {
-                pid->es->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
+                pid->u.p_pes->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
             }
         }
-        pid->es->i_data_gathered += p_bk->i_buffer;
-        if( pid->es->i_data_size > 0 &&
-            pid->es->i_data_gathered >= pid->es->i_data_size )
+        pid->u.p_pes->i_data_gathered += p_bk->i_buffer;
+        if( pid->u.p_pes->i_data_size > 0 &&
+            pid->u.p_pes->i_data_gathered >= pid->u.p_pes->i_data_size )
         {
             ParseData( p_demux, pid );
             i_ret = true;
@@ -2546,18 +3259,18 @@ static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
     }
     else
     {
-        if( pid->es->p_data == NULL )
+        if( pid->u.p_pes->p_data == NULL )
         {
             /* msg_Dbg( p_demux, "broken packet" ); */
             block_Release( p_bk );
         }
         else
         {
-            block_ChainLastAppend( &pid->es->pp_last, p_bk );
-            pid->es->i_data_gathered += p_bk->i_buffer;
+            block_ChainLastAppend( &pid->u.p_pes->pp_last, p_bk );
+            pid->u.p_pes->i_data_gathered += p_bk->i_buffer;
 
-            if( pid->es->i_data_size > 0 &&
-                pid->es->i_data_gathered >= pid->es->i_data_size )
+            if( pid->u.p_pes->i_data_size > 0 &&
+                pid->u.p_pes->i_data_gathered >= pid->u.p_pes->i_data_size )
             {
                 ParseData( p_demux, pid );
                 i_ret = true;
@@ -2643,250 +3356,17 @@ static void PIDFillFormat( es_format_t *fmt, int i_stream_type )
     fmt->b_packetized = false;
 }
 
-/*****************************************************************************
- * MP4 specific functions (IOD parser)
- *****************************************************************************/
-static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
-{
-    unsigned int i_b;
-    unsigned int i_len = 0;
-    do
-    {
-        i_b = **pp_data;
-        (*pp_data)++;
-        (*pi_data)--;
-        i_len = ( i_len << 7 ) + ( i_b&0x7f );
-
-    } while( i_b&0x80 && *pi_data > 0 );
-
-    if (i_len > *pi_data)
-        i_len = *pi_data;
-
-    return i_len;
-}
-
-static int IODGetBytes( int *pi_data, uint8_t **pp_data, size_t bytes )
-{
-    uint32_t res = 0;
-    while( *pi_data > 0 && bytes-- )
-    {
-        res <<= 8;
-        res |= **pp_data;
-        (*pp_data)++;
-        (*pi_data)--;
-    }
-
-    return res;
-}
-
-static char* IODGetURL( int *pi_data, uint8_t **pp_data )
-{
-    int len = IODGetBytes( pi_data, pp_data, 1 );
-    if (len > *pi_data)
-        len = *pi_data;
-    char *url = strndup( (char*)*pp_data, len );
-    *pp_data += len;
-    *pi_data -= len;
-    return url;
-}
-
-static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
-{
-    uint8_t i_iod_tag, i_iod_label, byte1, byte2, byte3;
-
-    iod_descriptor_t *p_iod = calloc( 1, sizeof( iod_descriptor_t ) );
-    if( !p_iod )
-        return NULL;
-
-    if( i_data < 3 )
-    {
-        return p_iod;
-    }
-
-    byte1 = IODGetBytes( &i_data, &p_data, 1 );
-    byte2 = IODGetBytes( &i_data, &p_data, 1 );
-    byte3 = IODGetBytes( &i_data, &p_data, 1 );
-    if( byte2 == 0x02 ) //old vlc's buggy implementation of the IOD_descriptor
-    {
-        i_iod_label = byte1;
-        i_iod_tag = byte2;
-    }
-    else  //correct implementation of the IOD_descriptor
-    {
-        i_iod_label = byte2;
-        i_iod_tag = byte3;
-    }
-
-    ts_debug( "\n* iod label:%d tag:0x%x", i_iod_label, i_iod_tag );
-
-    if( i_iod_tag != 0x02 )
-    {
-        ts_debug( "\n ERR: tag %02x != 0x02", i_iod_tag );
-        return p_iod;
-    }
-
-    IODDescriptorLength( &i_data, &p_data );
-
-    uint16_t i_od_id = ( IODGetBytes( &i_data, &p_data, 1 ) << 2 );
-    uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
-    i_od_id |= i_flags >> 6;
-    ts_debug( "\n* od_id:%d", i_od_id );
-    ts_debug( "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
-    if ((i_flags >> 5) & 0x01)
-    {
-        p_iod->psz_url = IODGetURL( &i_data, &p_data );
-        ts_debug( "\n* url string:%s", p_iod->psz_url );
-        ts_debug( "\n*****************************\n" );
-        return p_iod;
-    }
-    else
-    {
-        p_iod->psz_url = NULL;
-    }
-
-    /* Profile Level Indication */
-    IODGetBytes( &i_data, &p_data, 1 ); /* OD */
-    IODGetBytes( &i_data, &p_data, 1 ); /* scene */
-    IODGetBytes( &i_data, &p_data, 1 ); /* audio */
-    IODGetBytes( &i_data, &p_data, 1 ); /* visual */
-    IODGetBytes( &i_data, &p_data, 1 ); /* graphics */
-
-    int i_length = 0;
-    int i_data_sav = i_data;
-    uint8_t *p_data_sav = p_data;
-    for (int i = 0; i_data > 0 && i < ES_DESCRIPTOR_COUNT; i++)
-    {
-        es_mpeg4_descriptor_t *es_descr = &p_iod->es_descr[i];
-
-        p_data = p_data_sav + i_length;
-        i_data = i_data_sav - i_length;
-
-        int i_tag = IODGetBytes( &i_data, &p_data, 1 );
-        i_length = IODDescriptorLength( &i_data, &p_data );
-
-        i_data_sav = i_data;
-        p_data_sav = p_data;
-
-        i_data = i_length;
-
-        if ( i_tag != 0x03 )
-        {
-            ts_debug( "\n* - OD tag:0x%x Unsupported", i_tag );
-            continue;
-        }
-
-        es_descr->i_es_id = IODGetBytes( &i_data, &p_data, 2 );
-        int i_flags = IODGetBytes( &i_data, &p_data, 1 );
-        bool b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
-        if( b_streamDependenceFlag )
-            IODGetBytes( &i_data, &p_data, 2 ); /* dependOn_es_id */
-
-        if( (i_flags >> 6) & 0x01 )
-            es_descr->psz_url = IODGetURL( &i_data, &p_data );
-
-        bool b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
-        if( b_OCRStreamFlag )
-            IODGetBytes( &i_data, &p_data, 2 ); /* OCR_es_id */
-
-        if( IODGetBytes( &i_data, &p_data, 1 ) != 0x04 )
-        {
-            ts_debug( "\n* ERR missing DecoderConfigDescr" );
-            continue;
-        }
-        int i_config_desc_length = IODDescriptorLength( &i_data, &p_data ); /* DecoderConfigDescr_length */
-        decoder_config_descriptor_t *dec_descr = &es_descr->dec_descr;
-        dec_descr->i_objectTypeIndication = IODGetBytes( &i_data, &p_data, 1 );
-        i_flags = IODGetBytes( &i_data, &p_data, 1 );
-        dec_descr->i_streamType = i_flags >> 2;
-
-        IODGetBytes( &i_data, &p_data, 3); /* bufferSizeDB */
-        IODGetBytes( &i_data, &p_data, 4); /* maxBitrate */
-        IODGetBytes( &i_data, &p_data, 4 ); /* avgBitrate */
-
-        if( i_config_desc_length > 13 && IODGetBytes( &i_data, &p_data, 1 ) == 0x05 )
-        {
-            dec_descr->i_extra = IODDescriptorLength( &i_data, &p_data );
-            if( dec_descr->i_extra > 0 )
-            {
-                dec_descr->p_extra = xmalloc( dec_descr->i_extra );
-                memcpy(dec_descr->p_extra, p_data, dec_descr->i_extra);
-                p_data += dec_descr->i_extra;
-                i_data -= dec_descr->i_extra;
-            }
-        }
-        else
-        {
-            dec_descr->i_extra = 0;
-            dec_descr->p_extra = NULL;
-        }
-
-        if( IODGetBytes( &i_data, &p_data, 1 ) != 0x06 )
-        {
-            ts_debug( "\n* ERR missing SLConfigDescr" );
-            continue;
-        }
-        IODDescriptorLength( &i_data, &p_data ); /* SLConfigDescr_length */
-        switch( IODGetBytes( &i_data, &p_data, 1 ) /* predefined */ )
-        {
-        default:
-            ts_debug( "\n* ERR unsupported SLConfigDescr predefined" );
-        case 0x01:
-            // FIXME
-            break;
-        }
-        es_descr->b_ok = true;
-    }
-
-    return p_iod;
-}
-
-static void IODFree( iod_descriptor_t *p_iod )
-{
-    if( p_iod->psz_url )
-    {
-        free( p_iod->psz_url );
-        free( p_iod );
-        return;
-    }
-
-    for( int i = 0; i < 255; i++ )
-    {
-#define es_descr p_iod->es_descr[i]
-        if( es_descr.b_ok )
-        {
-            if( es_descr.psz_url )
-                free( es_descr.psz_url );
-            else
-                free( es_descr.dec_descr.p_extra );
-        }
-#undef  es_descr
-    }
-    free( p_iod );
-}
-
 /****************************************************************************
  ****************************************************************************
  ** libdvbpsi callbacks
  ****************************************************************************
  ****************************************************************************/
-static bool ProgramIsSelected( demux_t *p_demux, uint16_t i_pgrm )
+static bool ProgramIsSelected( demux_sys_t *p_sys, uint16_t i_pgrm )
 {
-    demux_sys_t          *p_sys = p_demux->p_sys;
-
-    if( ( p_sys->i_current_program == -1 && p_sys->programs_list.i_count == 0 ) ||
-        p_sys->i_current_program == 0 )
-        return true;
-    if( p_sys->i_current_program == i_pgrm )
-        return true;
+    for(int i=0; i<p_sys->programs.i_size; i++)
+        if( p_sys->programs.p_elems[i] == i_pgrm )
+            return true;
 
-    if( p_sys->programs_list.i_count != 0 )
-    {
-        for( int i = 0; i < p_sys->programs_list.i_count; i++ )
-        {
-            if( i_pgrm == p_sys->programs_list.p_values[i].i_int )
-                return true;
-        }
-    }
     return false;
 }
 
@@ -2902,26 +3382,9 @@ static void ValidateDVBMeta( demux_t *p_demux, int i_pid )
     /* This doesn't look like a DVB stream so don't try
      * parsing the SDT/EDT/TDT */
 
-    for( int i = 0x11; i <= 0x14; i++ )
-    {
-        if( i == 0x13 ) continue;
-        ts_pid_t *p_pid = &p_sys->pid[i];
-        if( p_pid->psi )
-        {
-
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-            if( dvbpsi_decoder_present( p_pid->psi->handle ))
-                dvbpsi_DetachDemux( p_pid->psi->handle );
-            dvbpsi_delete( p_pid->psi->handle );
-#else
-            dvbpsi_DetachDemux( p_pid->psi->handle );
-#endif
-            free( p_pid->psi );
-            p_pid->psi = NULL;
-            p_pid->b_valid = false;
-        }
-        SetPIDFilter( p_demux, i, false );
-    }
+    PIDRelease( p_demux, PID(p_sys, 0x11) );
+    PIDRelease( p_demux, PID(p_sys, 0x12) );
+    PIDRelease( p_demux, PID(p_sys, 0x14) );
     p_sys->b_dvb_meta = false;
 }
 
@@ -2977,26 +3440,22 @@ static char *EITConvertToUTF8( demux_t *p_demux,
 static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
 {
     demux_sys_t          *p_sys = p_demux->p_sys;
-    ts_pid_t             *sdt = &p_sys->pid[0x11];
+    ts_pid_t             *sdt = PID(p_sys, 0x11);
     dvbpsi_sdt_service_t *p_srv;
 
     msg_Dbg( p_demux, "SDTCallBack called" );
 
-    if( sdt->psi->i_sdt_version != -1 &&
-        ( !p_sdt->b_current_next ||
-          p_sdt->i_version == sdt->psi->i_sdt_version ) )
+    if( p_sys->es_creation != CREATE_ES ||
+       !p_sdt->b_current_next ||
+        p_sdt->i_version == sdt->u.p_psi->i_version )
     {
-        dvbpsi_DeleteSDT( p_sdt );
+        dvbpsi_sdt_delete( p_sdt );
         return;
     }
 
     msg_Dbg( p_demux, "new SDT ts_id=%d version=%d current_next=%d "
              "network_id=%d",
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
              p_sdt->i_extension,
-#else
-             p_sdt->i_ts_id,
-#endif
              p_sdt->i_version, p_sdt->b_current_next,
              p_sdt->i_network_id );
 
@@ -3016,6 +3475,13 @@ static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
                  p_srv->b_eit_present, p_srv->i_running_status,
                  p_srv->b_free_ca );
 
+        if( p_sys->vdr.i_service && p_srv->i_service_id != p_sys->vdr.i_service )
+        {
+            msg_Dbg( p_demux, "  * service id=%d skipped (not declared in vdr header)",
+                     p_sys->vdr.i_service );
+            continue;
+        }
+
         p_meta = vlc_meta_New();
         for( p_dr = p_srv->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
         {
@@ -3110,8 +3576,8 @@ static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
         vlc_meta_Delete( p_meta );
     }
 
-    sdt->psi->i_sdt_version = p_sdt->i_version;
-    dvbpsi_DeleteSDT( p_sdt );
+    sdt->u.p_psi->i_version = p_sdt->i_version;
+    dvbpsi_sdt_delete( p_sdt );
 }
 
 /* i_year: year - 1900  i_month: 0-11  i_mday: 1-31 i_hour: 0-23 i_minute: 0-59 i_second: 0-59 */
@@ -3179,7 +3645,7 @@ static void TDTCallBack( demux_t *p_demux, dvbpsi_tot_t *p_tdt )
 
     p_sys->i_tdt_delta = CLOCK_FREQ * EITConvertStartTime( p_tdt->i_utc_time )
                          - mdate();
-    dvbpsi_DeleteTOT(p_tdt);
+    dvbpsi_tot_delete(p_tdt);
 }
 
 
@@ -3193,18 +3659,14 @@ static void EITCallBack( demux_t *p_demux,
     msg_Dbg( p_demux, "EITCallBack called" );
     if( !p_eit->b_current_next )
     {
-        dvbpsi_DeleteEIT( p_eit );
+        dvbpsi_eit_delete( p_eit );
         return;
     }
 
     msg_Dbg( p_demux, "new EIT service_id=%d version=%d current_next=%d "
              "ts_id=%d network_id=%d segment_last_section_number=%d "
              "last_table_id=%d",
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
              p_eit->i_extension,
-#else
-             p_eit->i_service_id,
-#endif
              p_eit->i_version, p_eit->b_current_next,
              p_eit->i_ts_id, p_eit->i_network_id,
              p_eit->i_segment_last_section_number, p_eit->i_last_table_id );
@@ -3373,13 +3835,9 @@ static void EITCallBack( demux_t *p_demux,
     if( p_epg->i_event > 0 )
     {
         if( b_current_following &&
-            (  p_sys->i_current_program == -1 ||
-               p_sys->i_current_program ==
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
+            (  p_sys->programs.i_size == 0 ||
+               p_sys->programs.p_elems[0] ==
                     p_eit->i_extension
-#else
-                    p_eit->i_service_id
-#endif
                 ) )
         {
             p_sys->i_dvb_length = 0;
@@ -3392,16 +3850,12 @@ static void EITCallBack( demux_t *p_demux,
             }
         }
         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_EPG,
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
                         p_eit->i_extension,
-#else
-                        p_eit->i_service_id,
-#endif
                         p_epg );
     }
     vlc_epg_Delete( p_epg );
 
-    dvbpsi_DeleteEIT( p_eit );
+    dvbpsi_eit_delete( p_eit );
 }
 static void EITCallBackCurrentFollowing( demux_t *p_demux, dvbpsi_eit_t *p_eit )
 {
@@ -3412,32 +3866,24 @@ static void EITCallBackSchedule( demux_t *p_demux, dvbpsi_eit_t *p_eit )
     EITCallBack( p_demux, p_eit, false );
 }
 
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
 static void PSINewTableCallBack( dvbpsi_t *h, uint8_t i_table_id,
                                  uint16_t i_extension, demux_t *p_demux )
-#else
-static void PSINewTableCallBack( demux_t *p_demux, dvbpsi_handle h,
-                                 uint8_t  i_table_id, uint16_t i_extension )
-#endif
 {
+    demux_sys_t *p_sys = p_demux->p_sys;
     assert( h );
 #if 0
     msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
              i_table_id, i_table_id, i_extension, i_extension );
 #endif
-    if( p_demux->p_sys->pid[0].psi->i_pat_version != -1 && i_table_id == 0x42 )
+    if( PID(p_sys, 0)->u.p_pat->i_version != -1 && i_table_id == 0x42 )
     {
         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
                  i_table_id, i_table_id, i_extension, i_extension );
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
+
         if( !dvbpsi_sdt_attach( h, i_table_id, i_extension, (dvbpsi_sdt_callback)SDTCallBack, p_demux ) )
             msg_Err( p_demux, "PSINewTableCallback: failed attaching SDTCallback" );
-#else
-        dvbpsi_AttachSDT( h, i_table_id, i_extension,
-                          (dvbpsi_sdt_callback)SDTCallBack, p_demux );
-#endif
     }
-    else if( p_demux->p_sys->pid[0x11].psi->i_sdt_version != -1 &&
+    else if( PID(p_sys, 0x11)->u.p_psi->i_version != -1 &&
              ( i_table_id == 0x4e || /* Current/Following */
                (i_table_id >= 0x50 && i_table_id <= 0x5f) ) ) /* Schedule */
     {
@@ -3447,25 +3893,18 @@ static void PSINewTableCallBack( demux_t *p_demux, dvbpsi_handle h,
         dvbpsi_eit_callback cb = i_table_id == 0x4e ?
                                     (dvbpsi_eit_callback)EITCallBackCurrentFollowing :
                                     (dvbpsi_eit_callback)EITCallBackSchedule;
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
+
         if( !dvbpsi_eit_attach( h, i_table_id, i_extension, cb, p_demux ) )
             msg_Err( p_demux, "PSINewTableCallback: failed attaching EITCallback" );
-#else
-        dvbpsi_AttachEIT( h, i_table_id, i_extension, cb, p_demux );
-#endif
     }
-    else if( p_demux->p_sys->pid[0x11].psi->i_sdt_version != -1 &&
+    else if( PID(p_sys, 0x11)->u.p_psi->i_version != -1 &&
             (i_table_id == 0x70 /* TDT */ || i_table_id == 0x73 /* TOT */) )
     {
          msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
                  i_table_id, i_table_id, i_extension, i_extension );
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
+
         if( !dvbpsi_tot_attach( h, i_table_id, i_extension, (dvbpsi_tot_callback)TDTCallBack, p_demux ) )
             msg_Err( p_demux, "PSINewTableCallback: failed attaching TDTCallback" );
-#else
-         dvbpsi_AttachTOT( h, i_table_id, i_extension,
-                           (dvbpsi_tot_callback)TDTCallBack, p_demux);
-#endif
     }
 }
 
@@ -3511,54 +3950,94 @@ static bool PMTEsHasComponentTag( const dvbpsi_pmt_es_t *p_es,
     return p_si->i_component_tag == i_component_tag;
 }
 
-static void PMTSetupEsISO14496( demux_t *p_demux, ts_pid_t *pid,
-                                const ts_prg_psi_t *prg, const dvbpsi_pmt_es_t *p_es )
+static const es_mpeg4_descriptor_t * GetMPEG4DescByEsId( const iod_descriptor_t *iod,
+                                                         uint16_t i_es_id )
 {
-    es_format_t *p_fmt = &pid->es->fmt;
+    if( iod )
+    for( int i = 0; i < ES_DESCRIPTOR_COUNT; i++ )
+    {
+        if( iod->es_descr[i].i_es_id == i_es_id )
+        {
+            if ( iod->es_descr[i].b_ok )
+                return &iod->es_descr[i];
+        }
+    }
+    return NULL;
+}
 
-    /* MPEG-4 stream: search FMC_DESCRIPTOR (SL Packetized stream) */
-    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x1f );
+static void PMTSetupEsISO14496( demux_t *p_demux, ts_pes_es_t *p_es,
+                                const ts_pmt_t *p_pmt, const dvbpsi_pmt_es_t *p_dvbpsies )
+{
+    es_format_t *p_fmt = &p_es->fmt;
 
-    if( p_dr && p_dr->i_length == 2 )
+    const dvbpsi_descriptor_t *p_dr = p_dvbpsies->p_first_descriptor;
+    while( p_dr )
     {
-        const int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
-
-        msg_Dbg( p_demux, "found FMC_descriptor declaring sl packetization on es_id=%d", i_es_id );
+        const es_mpeg4_descriptor_t *p_esdescr = NULL;
+        uint16_t i_es_id;
+        uint8_t i_length = p_dr->i_length;
 
-        pid->es->p_mpeg4desc = NULL;
+        switch( p_dr->i_tag )
+        {
+            case 0x1f: /* FMC Descriptor */
+                while( i_length >= 3 && !p_esdescr )
+                {
+                    i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
+                    p_esdescr = GetMPEG4DescByEsId( p_pmt->iod, i_es_id );
+                    /* FIXME: add flexmux channel */
+                    i_length -= 3;
+                    if( p_esdescr )
+                        msg_Dbg( p_demux, "found FMC_descriptor declaring sl packetization on es_id=%"PRIu16, i_es_id );
+                }
+                break;
+            case 0x1e: /* SL Descriptor */
+                if( i_length == 2 )
+                {
+                    i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
+                    p_esdescr = GetMPEG4DescByEsId( p_pmt->iod, i_es_id );
+                    if( p_esdescr )
+                        msg_Dbg( p_demux, "found SL_descriptor declaring sl packetization on es_id=%"PRIu16, i_es_id );
+                }
+                break;
+            default:
+                break;
+        }
 
-        for( int i = 0; i < ES_DESCRIPTOR_COUNT; i++ )
+        if( p_esdescr )
         {
-            iod_descriptor_t *iod = prg->iod;
-            if( iod->es_descr[i].i_es_id == i_es_id )
+            if( !p_esdescr->b_ok )
             {
-                if ( iod->es_descr[i].b_ok )
-                    pid->es->p_mpeg4desc = &iod->es_descr[i];
-                else
-                    msg_Dbg( p_demux, "MPEG-4 descriptor not yet available on es_id=%d", i_es_id );
+                msg_Dbg( p_demux, "MPEG-4 descriptor not yet available on es_id=%"PRIu16, i_es_id );
+            }
+            else
+            {
+                p_es->p_mpeg4desc = p_esdescr;
                 break;
             }
         }
+
+        p_dr = p_dr->p_next;
     }
-    if( !pid->es->p_mpeg4desc )
+
+    if( !p_es->p_mpeg4desc )
     {
-        switch( p_es->i_type )
+        switch( p_dvbpsies->i_type )
         {
         /* non fatal, set by packetizer */
         case 0x0f: /* ADTS */
         case 0x11: /* LOAS */
             msg_Info( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
-                      pid->i_pid, p_es->i_type );
+                      p_dvbpsies->i_pid, p_dvbpsies->i_type );
             break;
         default:
             msg_Err( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
-                     pid->i_pid, p_es->i_type );
+                     p_dvbpsies->i_pid, p_dvbpsies->i_type );
             break;
         }
         return;
     }
 
-    const decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
+    const decoder_config_descriptor_t *dcd = &p_es->p_mpeg4desc->dec_descr;
     if( dcd->i_streamType == 0x04 )    /* VisualStream */
     {
         p_fmt->i_cat = VIDEO_ES;
@@ -3625,7 +4104,7 @@ static void PMTSetupEsISO14496( demux_t *p_demux, ts_pid_t *pid,
 
     if( p_fmt->i_cat != UNKNOWN_ES )
     {
-        p_fmt->i_extra = dcd->i_extra;
+        p_fmt->i_extra = __MIN(dcd->i_extra, INT32_MAX);
         if( p_fmt->i_extra > 0 )
         {
             p_fmt->p_extra = malloc( p_fmt->i_extra );
@@ -3645,20 +4124,18 @@ typedef struct
     char p_iso639[3];
 } ts_teletext_page_t;
 
-static void PMTSetupEsTeletext( demux_t *p_demux, ts_pid_t *pid,
-                                const dvbpsi_pmt_es_t *p_es )
+static void PMTSetupEsTeletext( demux_t *p_demux, ts_pes_t *p_pes,
+                                const dvbpsi_pmt_es_t *p_dvbpsies )
 {
-    es_format_t *p_fmt = &pid->es->fmt;
+    es_format_t *p_fmt = &p_pes->es.fmt;
 
     ts_teletext_page_t p_page[2 * 64 + 20];
     unsigned i_page = 0;
 
     /* Gather pages information */
-#if defined _DVBPSI_DR_56_H_ && \
-    defined DVBPSI_VERSION && DVBPSI_VERSION_INT > DVBPSI_VERSION_WANTED(0,1,5)
     for( unsigned i_tag_idx = 0; i_tag_idx < 2; i_tag_idx++ )
     {
-        dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, i_tag_idx == 0 ? 0x46 : 0x56 );
+        dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, i_tag_idx == 0 ? 0x46 : 0x56 );
         if( !p_dr )
             continue;
 
@@ -3684,9 +4161,8 @@ static void PMTSetupEsTeletext( demux_t *p_demux, ts_pid_t *pid,
             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
         }
     }
-#endif
 
-    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
+    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
     if( p_dr )
     {
         dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
@@ -3728,9 +4204,9 @@ static void PMTSetupEsTeletext( demux_t *p_demux, ts_pid_t *pid,
         p_fmt->psz_description = strdup( vlc_gettext(ppsz_teletext_type[1]) );
 
         dvbpsi_descriptor_t *p_dr;
-        p_dr = PMTEsFindDescriptor( p_es, 0x46 );
+        p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x46 );
         if( !p_dr )
-            p_dr = PMTEsFindDescriptor( p_es, 0x56 );
+            p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x56 );
 
         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
         {
@@ -3747,61 +4223,53 @@ static void PMTSetupEsTeletext( demux_t *p_demux, ts_pid_t *pid,
     {
         for( unsigned i = 0; i < i_page; i++ )
         {
-            ts_es_t *p_es;
+            ts_pes_es_t *p_page_es;
 
             /* */
             if( i == 0 )
             {
-                p_es = pid->es;
+                p_page_es = &p_pes->es;
             }
             else
             {
-                p_es = malloc( sizeof(*p_es) );
-                if( !p_es )
+                p_page_es = calloc( 1, sizeof(*p_page_es) );
+                if( !p_page_es )
                     break;
 
-                es_format_Copy( &p_es->fmt, &pid->es->fmt );
-                free( p_es->fmt.psz_language );
-                free( p_es->fmt.psz_description );
-                p_es->fmt.psz_language = NULL;
-                p_es->fmt.psz_description = NULL;
-
-                p_es->id      = NULL;
-                p_es->p_data  = NULL;
-                p_es->i_data_size = 0;
-                p_es->i_data_gathered = 0;
-                p_es->pp_last = &p_es->p_data;
-                p_es->data_type = TS_ES_DATA_PES;
-                p_es->p_mpeg4desc = NULL;
-
-                TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
+                es_format_Copy( &p_page_es->fmt, p_fmt );
+                free( p_page_es->fmt.psz_language );
+                free( p_page_es->fmt.psz_description );
+                p_page_es->fmt.psz_language = NULL;
+                p_page_es->fmt.psz_description = NULL;
+
+                ARRAY_APPEND( p_pes->extra_es, p_page_es );
             }
 
             /* */
             const ts_teletext_page_t *p = &p_page[i];
-            p_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ?
+            p_page_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ?
                       ES_PRIORITY_SELECTABLE_MIN : ES_PRIORITY_NOT_DEFAULTABLE;
-            p_es->fmt.psz_language = strndup( p->p_iso639, 3 );
-            p_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
-            p_es->fmt.subs.teletext.i_magazine = p->i_magazine;
-            p_es->fmt.subs.teletext.i_page = p->i_page;
+            p_page_es->fmt.psz_language = strndup( p->p_iso639, 3 );
+            p_page_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
+            p_page_es->fmt.subs.teletext.i_magazine = p->i_magazine;
+            p_page_es->fmt.subs.teletext.i_page = p->i_page;
 
             msg_Dbg( p_demux,
                          "    * ttxt type=%s lan=%s page=%d%02x",
-                         p_es->fmt.psz_description,
-                         p_es->fmt.psz_language,
+                         p_page_es->fmt.psz_description,
+                         p_page_es->fmt.psz_language,
                          p->i_magazine, p->i_page );
         }
     }
 }
-static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pid_t *pid,
-                                   const dvbpsi_pmt_es_t *p_es )
+static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pes_t *p_pes,
+                                   const dvbpsi_pmt_es_t *p_dvbpsies )
 {
-    es_format_t *p_fmt = &pid->es->fmt;
+    es_format_t *p_fmt = &p_pes->es.fmt;
 
     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_DVBS );
 
-    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
+    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
     int i_page = 0;
     dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
     for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
@@ -3832,39 +4300,31 @@ static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pid_t *pid,
     {
         for( int i = 0; i < p_sub->i_subtitles_number; i++ )
         {
-            ts_es_t *p_es;
+            ts_pes_es_t *p_subs_es;
 
             /* */
             if( i == 0 )
             {
-                p_es = pid->es;
+                p_subs_es = &p_pes->es;
             }
             else
             {
-                p_es = malloc( sizeof(*p_es) );
-                if( !p_es )
+                p_subs_es = malloc( sizeof(*p_subs_es) );
+                if( !p_subs_es )
                     break;
 
-                es_format_Copy( &p_es->fmt, &pid->es->fmt );
-                free( p_es->fmt.psz_language );
-                free( p_es->fmt.psz_description );
-                p_es->fmt.psz_language = NULL;
-                p_es->fmt.psz_description = NULL;
-
-                p_es->id      = NULL;
-                p_es->p_data   = NULL;
-                p_es->i_data_size = 0;
-                p_es->i_data_gathered = 0;
-                p_es->pp_last = &p_es->p_data;
-                p_es->data_type = TS_ES_DATA_PES;
-                p_es->p_mpeg4desc = NULL;
-
-                TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
+                es_format_Copy( &p_subs_es->fmt, p_fmt );
+                free( p_subs_es->fmt.psz_language );
+                free( p_subs_es->fmt.psz_description );
+                p_subs_es->fmt.psz_language = NULL;
+                p_subs_es->fmt.psz_description = NULL;
+
+                ARRAY_APPEND( p_pes->extra_es, p_subs_es );
             }
 
             /* */
             const dvbpsi_subtitle_t *p = &p_sub->p_subtitle[i];
-            p_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
+            p_subs_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
             switch( p->i_subtitling_type )
             {
             case 0x10: /* unspec. */
@@ -3872,21 +4332,21 @@ static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pid_t *pid,
             case 0x12: /* 16:9 */
             case 0x13: /* 2.21:1 */
             case 0x14: /* HD monitor */
-                p_es->fmt.psz_description = strdup( _("DVB subtitles") );
+                p_subs_es->fmt.psz_description = strdup( _("DVB subtitles") );
                 break;
             case 0x20: /* Hearing impaired unspec. */
             case 0x21: /* h.i. 4:3 */
             case 0x22: /* h.i. 16:9 */
             case 0x23: /* h.i. 2.21:1 */
             case 0x24: /* h.i. HD monitor */
-                p_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
+                p_subs_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
                 break;
             default:
                 break;
             }
 
             /* Hack, FIXME */
-            p_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id <<  0 ) |
+            p_subs_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id <<  0 ) |
                                       ( p->i_ancillary_page_id   << 16 );
         }
     }
@@ -4010,41 +4470,41 @@ explicit_config_too_short:
     msg_Err(demux, "Opus descriptor too short");
 }
 
-static void PMTSetupEs0x06( demux_t *p_demux, ts_pid_t *pid,
-                            const dvbpsi_pmt_es_t *p_es )
+static void PMTSetupEs0x06( demux_t *p_demux, ts_pes_t *p_pes,
+                            const dvbpsi_pmt_es_t *p_dvbpsies )
 {
-    es_format_t *p_fmt = &pid->es->fmt;
-    dvbpsi_descriptor_t *p_subs_dr = PMTEsFindDescriptor( p_es, 0x59 );
+    es_format_t *p_fmt = &p_pes->es.fmt;
+    dvbpsi_descriptor_t *p_subs_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
     dvbpsi_descriptor_t *desc;
 
-    if( PMTEsHasRegistration( p_demux, p_es, "AC-3" ) ||
-        PMTEsFindDescriptor( p_es, 0x6a ) ||
-        PMTEsFindDescriptor( p_es, 0x81 ) )
+    if( PMTEsHasRegistration( p_demux, p_dvbpsies, "AC-3" ) ||
+        PMTEsFindDescriptor( p_dvbpsies, 0x6a ) ||
+        PMTEsFindDescriptor( p_dvbpsies, 0x81 ) )
     {
         p_fmt->i_cat = AUDIO_ES;
         p_fmt->i_codec = VLC_CODEC_A52;
     }
-    else if( (desc = PMTEsFindDescriptor( p_es, 0x7f ) ) && desc->i_length >= 2 &&
-              desc->p_data[0] == 0x80)
+    else if( (desc = PMTEsFindDescriptor( p_dvbpsies, 0x7f ) ) && desc->i_length >= 2 &&
+              PMTEsHasRegistration(p_demux, p_dvbpsies, "Opus"))
     {
         OpusSetup(p_demux, desc->p_data, desc->i_length, p_fmt);
     }
-    else if( PMTEsFindDescriptor( p_es, 0x7a ) )
+    else if( PMTEsFindDescriptor( p_dvbpsies, 0x7a ) )
     {
         /* DVB with stream_type 0x06 (ETS EN 300 468) */
         p_fmt->i_cat = AUDIO_ES;
         p_fmt->i_codec = VLC_CODEC_EAC3;
     }
-    else if( PMTEsHasRegistration( p_demux, p_es, "DTS1" ) ||
-             PMTEsHasRegistration( p_demux, p_es, "DTS2" ) ||
-             PMTEsHasRegistration( p_demux, p_es, "DTS3" ) ||
-             PMTEsFindDescriptor( p_es, 0x73 ) )
+    else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS1" ) ||
+             PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS2" ) ||
+             PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS3" ) ||
+             PMTEsFindDescriptor( p_dvbpsies, 0x73 ) )
     {
         /*registration descriptor(ETSI TS 101 154 Annex F)*/
         p_fmt->i_cat = AUDIO_ES;
         p_fmt->i_codec = VLC_CODEC_DTS;
     }
-    else if( PMTEsHasRegistration( p_demux, p_es, "BSSD" ) && !p_subs_dr )
+    else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "BSSD" ) && !p_subs_dr )
     {
         /* BSSD is AES3 DATA, but could also be subtitles
          * we need to check for secondary descriptor then s*/
@@ -4052,7 +4512,7 @@ static void PMTSetupEs0x06( demux_t *p_demux, ts_pid_t *pid,
         p_fmt->b_packetized = true;
         p_fmt->i_codec = VLC_CODEC_302M;
     }
-    else if( PMTEsHasRegistration( p_demux, p_es, "HEVC" ) )
+    else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "HEVC" ) )
     {
         p_fmt->i_cat = VIDEO_ES;
         p_fmt->i_codec = VLC_CODEC_HEVC;
@@ -4060,29 +4520,29 @@ static void PMTSetupEs0x06( demux_t *p_demux, ts_pid_t *pid,
     else if ( p_demux->p_sys->arib.e_mode == ARIBMODE_ENABLED )
     {
         /* Lookup our data component descriptor first ARIB STD B10 6.4 */
-        dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0xFD );
+        dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xFD );
         /* and check that it maps to something ARIB STD B14 Table 5.1/5.2 */
         if ( p_dr && p_dr->i_length >= 2 )
         {
             if( !memcmp( p_dr->p_data, "\x00\x08", 2 ) &&  (
-                    PMTEsHasComponentTag( p_es, 0x30 ) ||
-                    PMTEsHasComponentTag( p_es, 0x31 ) ||
-                    PMTEsHasComponentTag( p_es, 0x32 ) ||
-                    PMTEsHasComponentTag( p_es, 0x33 ) ||
-                    PMTEsHasComponentTag( p_es, 0x34 ) ||
-                    PMTEsHasComponentTag( p_es, 0x35 ) ||
-                    PMTEsHasComponentTag( p_es, 0x36 ) ||
-                    PMTEsHasComponentTag( p_es, 0x37 ) ) )
+                    PMTEsHasComponentTag( p_dvbpsies, 0x30 ) ||
+                    PMTEsHasComponentTag( p_dvbpsies, 0x31 ) ||
+                    PMTEsHasComponentTag( p_dvbpsies, 0x32 ) ||
+                    PMTEsHasComponentTag( p_dvbpsies, 0x33 ) ||
+                    PMTEsHasComponentTag( p_dvbpsies, 0x34 ) ||
+                    PMTEsHasComponentTag( p_dvbpsies, 0x35 ) ||
+                    PMTEsHasComponentTag( p_dvbpsies, 0x36 ) ||
+                    PMTEsHasComponentTag( p_dvbpsies, 0x37 ) ) )
             {
-                es_format_Init( &pid->es->fmt, SPU_ES, VLC_CODEC_ARIB_A );
+                es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_A );
                 p_fmt->psz_language = strndup ( "jpn", 3 );
                 p_fmt->psz_description = strdup( _("ARIB subtitles") );
             }
             else if( !memcmp( p_dr->p_data, "\x00\x12", 2 ) && (
-                     PMTEsHasComponentTag( p_es, 0x87 ) ||
-                     PMTEsHasComponentTag( p_es, 0x88 ) ) )
+                     PMTEsHasComponentTag( p_dvbpsies, 0x87 ) ||
+                     PMTEsHasComponentTag( p_dvbpsies, 0x88 ) ) )
             {
-                es_format_Init( &pid->es->fmt, SPU_ES, VLC_CODEC_ARIB_C );
+                es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_C );
                 p_fmt->psz_language = strndup ( "jpn", 3 );
                 p_fmt->psz_description = strdup( _("ARIB subtitles") );
             }
@@ -4104,7 +4564,7 @@ static void PMTSetupEs0x06( demux_t *p_demux, ts_pid_t *pid,
                 case 0x01: /* EBU Teletext subtitles */
                 case 0x02: /* Associated EBU Teletext */
                 case 0x03: /* VBI data */
-                    PMTSetupEsTeletext( p_demux, pid, p_es );
+                    PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
                     break;
                 case 0x10: /* DVB Subtitle (normal) with no monitor AR critical */
                 case 0x11: /*                 ...   on 4:3 AR monitor */
@@ -4116,7 +4576,7 @@ static void PMTSetupEs0x06( demux_t *p_demux, ts_pid_t *pid,
                 case 0x22: /*                 ...   on 16:9 AR monitor */
                 case 0x23: /*                 ...   on 2.21:1 AR monitor */
                 case 0x24: /*                 ...   for display on a high definition monitor */
-                    PMTSetupEsDvbSubtitle( p_demux, pid, p_es );
+                    PMTSetupEsDvbSubtitle( p_demux, p_pes, p_dvbpsies );
                     break;
                 default:
                     msg_Err( p_demux, "Unrecognized DVB subtitle type (0x%x)",
@@ -4127,36 +4587,36 @@ static void PMTSetupEs0x06( demux_t *p_demux, ts_pid_t *pid,
         }
 
         if( p_fmt->i_cat == UNKNOWN_ES &&
-            ( PMTEsFindDescriptor( p_es, 0x45 ) ||  /* VBI Data descriptor */
-              PMTEsFindDescriptor( p_es, 0x46 ) ||  /* VBI Teletext descriptor */
-              PMTEsFindDescriptor( p_es, 0x56 ) ) ) /* EBU Teletext descriptor */
+            ( PMTEsFindDescriptor( p_dvbpsies, 0x45 ) ||  /* VBI Data descriptor */
+              PMTEsFindDescriptor( p_dvbpsies, 0x46 ) ||  /* VBI Teletext descriptor */
+              PMTEsFindDescriptor( p_dvbpsies, 0x56 ) ) ) /* EBU Teletext descriptor */
         {
             /* Teletext/VBI */
-            PMTSetupEsTeletext( p_demux, pid, p_es );
+            PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
         }
     }
 
     /* FIXME is it useful ? */
-    if( PMTEsFindDescriptor( p_es, 0x52 ) )
+    if( PMTEsFindDescriptor( p_dvbpsies, 0x52 ) )
     {
-        dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x52 );
+        dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x52 );
         dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
 
         msg_Dbg( p_demux, "    * Stream Component Identifier: %d", p_si->i_component_tag );
     }
 }
 
-static void PMTSetupEs0xEA( demux_t *p_demux, ts_pid_t *pid,
-                           const dvbpsi_pmt_es_t *p_es )
+static void PMTSetupEs0xEA( demux_t *p_demux, ts_pes_es_t *p_es,
+                           const dvbpsi_pmt_es_t *p_dvbpsies )
 {
     /* Registration Descriptor */
-    if( !PMTEsHasRegistration( p_demux, p_es, "VC-1" ) )
+    if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "VC-1" ) )
     {
         msg_Err( p_demux, "Registration descriptor not found or invalid" );
         return;
     }
 
-    es_format_t *p_fmt = &pid->es->fmt;
+    es_format_t *p_fmt = &p_es->fmt;
 
     /* registration descriptor for VC-1 (SMPTE rp227) */
     p_fmt->i_cat = VIDEO_ES;
@@ -4168,17 +4628,17 @@ static void PMTSetupEs0xEA( demux_t *p_demux, ts_pid_t *pid,
      * The packetizer will take care of that. */
 }
 
-static void PMTSetupEs0xD1( demux_t *p_demux, ts_pid_t *pid,
-                           const dvbpsi_pmt_es_t *p_es )
+static void PMTSetupEs0xD1( demux_t *p_demux, ts_pes_es_t *p_es,
+                           const dvbpsi_pmt_es_t *p_dvbpsies )
 {
     /* Registration Descriptor */
-    if( !PMTEsHasRegistration( p_demux, p_es, "drac" ) )
+    if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "drac" ) )
     {
         msg_Err( p_demux, "Registration descriptor not found or invalid" );
         return;
     }
 
-    es_format_t *p_fmt = &pid->es->fmt;
+    es_format_t *p_fmt = &p_es->fmt;
 
     /* registration descriptor for Dirac
      * (backwards compatable with VC-2 (SMPTE Sxxxx:2008)) */
@@ -4186,11 +4646,11 @@ static void PMTSetupEs0xD1( demux_t *p_demux, ts_pid_t *pid,
     p_fmt->i_codec = VLC_CODEC_DIRAC;
 }
 
-static void PMTSetupEs0xA0( demux_t *p_demux, ts_pid_t *pid,
-                           const dvbpsi_pmt_es_t *p_es )
+static void PMTSetupEs0xA0( demux_t *p_demux, ts_pes_es_t *p_es,
+                           const dvbpsi_pmt_es_t *p_dvbpsies )
 {
     /* MSCODEC sent by vlc */
-    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0xa0 );
+    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xa0 );
     if( !p_dr || p_dr->i_length < 10 )
     {
         msg_Warn( p_demux,
@@ -4198,7 +4658,7 @@ static void PMTSetupEs0xA0( demux_t *p_demux, ts_pid_t *pid,
         return;
     }
 
-    es_format_t *p_fmt = &pid->es->fmt;
+    es_format_t *p_fmt = &p_es->fmt;
     p_fmt->i_cat = VIDEO_ES;
     p_fmt->i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
                                  p_dr->p_data[2], p_dr->p_data[3] );
@@ -4221,33 +4681,37 @@ static void PMTSetupEs0xA0( demux_t *p_demux, ts_pid_t *pid,
     p_fmt->b_packetized = true;
 }
 
-static void PMTSetupEs0x83( const dvbpsi_pmt_t *p_pmt, ts_pid_t *pid )
+static void PMTSetupEs0x83( const dvbpsi_pmt_t *p_pmt, ts_pes_es_t *p_es, int i_pid )
 {
     /* WiDi broadcasts without registration on PMT 0x1, PCR 0x1000 and
      * with audio track pid being 0x1100..0x11FF */
     if ( p_pmt->i_program_number == 0x1 &&
          p_pmt->i_pcr_pid == 0x1000 &&
-        ( pid->i_pid >> 8 ) == 0x11 )
+        ( i_pid >> 8 ) == 0x11 )
     {
         /* Not enough ? might contain 0x83 private descriptor, 2 bytes 0x473F */
-        es_format_Init( &pid->es->fmt, AUDIO_ES, VLC_CODEC_WIDI_LPCM );
+        es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_WIDI_LPCM );
     }
     else
-        es_format_Init( &pid->es->fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
+        es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
 }
 
-static bool PMTSetupEsHDMV( demux_t *p_demux, ts_pid_t *pid,
-                            const dvbpsi_pmt_es_t *p_es )
+static bool PMTSetupEsHDMV( demux_t *p_demux, ts_pes_es_t *p_es,
+                            const dvbpsi_pmt_es_t *p_dvbpsies )
 {
-    es_format_t *p_fmt = &pid->es->fmt;
+    es_format_t *p_fmt = &p_es->fmt;
 
     /* Blu-Ray mapping */
-    switch( p_es->i_type )
+    switch( p_dvbpsies->i_type )
     {
     case 0x80:
         p_fmt->i_cat = AUDIO_ES;
         p_fmt->i_codec = VLC_CODEC_BD_LPCM;
         break;
+    case 0x81:
+        p_fmt->i_cat = AUDIO_ES;
+        p_fmt->i_codec = VLC_CODEC_A52;
+        break;
     case 0x82:
     case 0x85: /* DTS-HD High resolution audio */
     case 0x86: /* DTS-HD Master audio */
@@ -4273,17 +4737,21 @@ static bool PMTSetupEsHDMV( demux_t *p_demux, ts_pid_t *pid,
     case 0x91: /* Interactive graphics */
     case 0x92: /* Subtitle */
         return false;
+    case 0xEA:
+        p_fmt->i_cat = VIDEO_ES;
+        p_fmt->i_codec = VLC_CODEC_VC1;
+        break;
     default:
         msg_Info( p_demux, "HDMV registration not implemented for pid 0x%x type 0x%x",
-                  p_es->i_pid, p_es->i_type );
+                  p_dvbpsies->i_pid, p_dvbpsies->i_type );
         return false;
         break;
     }
     return true;
 }
 
-static bool PMTSetupEsRegistration( demux_t *p_demux, ts_pid_t *pid,
-                                    const dvbpsi_pmt_es_t *p_es )
+static bool PMTSetupEsRegistration( demux_t *p_demux, ts_pes_es_t *p_es,
+                                    const dvbpsi_pmt_es_t *p_dvbpsies )
 {
     static const struct
     {
@@ -4300,15 +4768,15 @@ static bool PMTSetupEsRegistration( demux_t *p_demux, ts_pid_t *pid,
         { "drac", VIDEO_ES, VLC_CODEC_DIRAC },
         { "", UNKNOWN_ES, 0 }
     };
-    es_format_t *p_fmt = &pid->es->fmt;
+    es_format_t *p_fmt = &p_es->fmt;
 
     for( int i = 0; p_regs[i].i_cat != UNKNOWN_ES; i++ )
     {
-        if( PMTEsHasRegistration( p_demux, p_es, p_regs[i].psz_tag ) )
+        if( PMTEsHasRegistration( p_demux, p_dvbpsies, p_regs[i].psz_tag ) )
         {
             p_fmt->i_cat   = p_regs[i].i_cat;
             p_fmt->i_codec = p_regs[i].i_codec;
-            if (p_es->i_type == 0x87)
+            if (p_dvbpsies->i_type == 0x87)
                 p_fmt->i_codec = VLC_CODEC_EAC3;
             return true;
         }
@@ -4332,11 +4800,11 @@ static char *GetAudioTypeDesc(demux_t *p_demux, int type)
 
     return NULL;
 }
-static void PMTParseEsIso639( demux_t *p_demux, ts_pid_t *pid,
-                              const dvbpsi_pmt_es_t *p_es )
+static void PMTParseEsIso639( demux_t *p_demux, ts_pes_es_t *p_es,
+                              const dvbpsi_pmt_es_t *p_dvbpsies )
 {
     /* get language descriptor */
-    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x0a );
+    dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x0a );
 
     if( !p_dr )
         return;
@@ -4349,114 +4817,185 @@ static void PMTParseEsIso639( demux_t *p_demux, ts_pid_t *pid,
     }
 
 #if defined(DR_0A_API_VER) && (DR_0A_API_VER >= 2)
-    pid->es->fmt.psz_language = malloc( 4 );
-    if( pid->es->fmt.psz_language )
+    p_es->fmt.psz_language = malloc( 4 );
+    if( p_es->fmt.psz_language )
     {
-        memcpy( pid->es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
-        pid->es->fmt.psz_language[3] = 0;
-        msg_Dbg( p_demux, "found language: %s", pid->es->fmt.psz_language);
+        memcpy( p_es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
+        p_es->fmt.psz_language[3] = 0;
+        msg_Dbg( p_demux, "found language: %s", p_es->fmt.psz_language);
     }
     int type = p_decoded->code[0].i_audio_type;
-    pid->es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
+    p_es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
     if (type == 0)
-        pid->es->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1; // prioritize normal audio tracks
+        p_es->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1; // prioritize normal audio tracks
 
-    pid->es->fmt.i_extra_languages = p_decoded->i_code_count-1;
-    if( pid->es->fmt.i_extra_languages > 0 )
-        pid->es->fmt.p_extra_languages =
-            malloc( sizeof(*pid->es->fmt.p_extra_languages) *
-                    pid->es->fmt.i_extra_languages );
-    if( pid->es->fmt.p_extra_languages )
+    p_es->fmt.i_extra_languages = p_decoded->i_code_count-1;
+    if( p_es->fmt.i_extra_languages > 0 )
+        p_es->fmt.p_extra_languages =
+            malloc( sizeof(*p_es->fmt.p_extra_languages) *
+                    p_es->fmt.i_extra_languages );
+    if( p_es->fmt.p_extra_languages )
     {
-        for( int i = 0; i < pid->es->fmt.i_extra_languages; i++ )
+        for( unsigned i = 0; i < p_es->fmt.i_extra_languages; i++ )
         {
-            pid->es->fmt.p_extra_languages[i].psz_language = malloc(4);
-            if( pid->es->fmt.p_extra_languages[i].psz_language )
+            p_es->fmt.p_extra_languages[i].psz_language = malloc(4);
+            if( p_es->fmt.p_extra_languages[i].psz_language )
             {
-                memcpy( pid->es->fmt.p_extra_languages[i].psz_language,
+                memcpy( p_es->fmt.p_extra_languages[i].psz_language,
                     p_decoded->code[i+1].iso_639_code, 3 );
-                pid->es->fmt.p_extra_languages[i].psz_language[3] = '\0';
+                p_es->fmt.p_extra_languages[i].psz_language[3] = '\0';
             }
             int type = p_decoded->code[i].i_audio_type;
-            pid->es->fmt.p_extra_languages[i].psz_description = GetAudioTypeDesc(p_demux, type);
+            p_es->fmt.p_extra_languages[i].psz_description = GetAudioTypeDesc(p_demux, type);
         }
     }
 #else
-    pid->es->fmt.psz_language = malloc( 4 );
-    if( pid->es->fmt.psz_language )
+    p_es->fmt.psz_language = malloc( 4 );
+    if( p_es->fmt.psz_language )
     {
-        memcpy( pid->es->fmt.psz_language,
+        memcpy( p_es->fmt.psz_language,
                 p_decoded->i_iso_639_code, 3 );
-        pid->es->fmt.psz_language[3] = 0;
+        p_es->fmt.psz_language[3] = 0;
     }
 #endif
 }
 
-static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt )
+static inline void SetExtraESGroupAndID( demux_sys_t *p_sys, es_format_t *p_fmt,
+                                         const es_format_t *p_parent_fmt )
+{
+    if ( p_sys->b_es_id_pid ) /* pid is 13 bits */
+        p_fmt->i_id = (p_sys->i_next_extraid++ << 13) | p_parent_fmt->i_id;
+    p_fmt->i_group = p_parent_fmt->i_group;
+}
+
+static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid, bool b_create_delayed )
+{
+    demux_sys_t  *p_sys = p_demux->p_sys;
+
+    if( b_create_delayed )
+        p_sys->es_creation = CREATE_ES;
+
+    if( pid && p_sys->es_creation == CREATE_ES )
+    {
+        /* FIXME: other owners / shared pid */
+        pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
+        for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
+        {
+            es_format_t *p_fmt = &pid->u.p_pes->extra_es.p_elems[i]->fmt;
+            SetExtraESGroupAndID( p_sys, p_fmt, &pid->u.p_pes->es.fmt );
+            pid->u.p_pes->extra_es.p_elems[i]->id = es_out_Add( p_demux->out, p_fmt );
+        }
+        p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
+
+        /* Update the default program == first created ES group */
+        if( p_sys->b_default_selection )
+        {
+            p_sys->b_default_selection = false;
+            assert(p_sys->programs.i_size == 1);
+            if( p_sys->programs.p_elems[0] != pid->p_parent->u.p_pmt->i_number )
+                p_sys->programs.p_elems[0] = pid->p_parent->u.p_pmt->i_number;
+            msg_Dbg( p_demux, "Default program is %d", pid->p_parent->u.p_pmt->i_number );
+        }
+    }
+
+    if( b_create_delayed )
+    {
+        ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
+        for( int i=0; i< p_pat->programs.i_size; i++ )
+        {
+            ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
+            for( int j=0; j<p_pmt->e_streams.i_size; j++ )
+            {
+                ts_pid_t *pid = p_pmt->e_streams.p_elems[j];
+                if( pid->u.p_pes->es.id )
+                    continue;
+
+                pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
+                for( int k = 0; k < pid->u.p_pes->extra_es.i_size; k++ )
+                {
+                    es_format_t *p_fmt = &pid->u.p_pes->extra_es.p_elems[k]->fmt;
+                    SetExtraESGroupAndID( p_sys, p_fmt, &pid->u.p_pes->es.fmt );
+                    pid->u.p_pes->extra_es.p_elems[k]->id = es_out_Add( p_demux->out, p_fmt );
+                }
+                p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
+            }
+        }
+    }
+
+    UpdatePESFilters( p_demux, p_sys->b_es_all );
+}
+
+static void PMTCallBack( void *data, dvbpsi_pmt_t *p_dvbpsipmt )
 {
     demux_t      *p_demux = data;
     demux_sys_t  *p_sys = p_demux->p_sys;
 
-    ts_pid_t     *pmt = NULL;
-    ts_prg_psi_t *prg;
+    ts_pid_t     *pmtpid = NULL;
+    ts_pmt_t     *p_pmt = NULL;
 
     msg_Dbg( p_demux, "PMTCallBack called" );
 
+    if (unlikely(PID(p_sys, 0)->type != TYPE_PAT))
+    {
+        assert(PID(p_sys, 0)->type == TYPE_PAT);
+        dvbpsi_pmt_delete(p_dvbpsipmt);
+    }
+
+    const ts_pat_t *p_pat = PID(p_sys, 0)->u.p_pat;
+
     /* First find this PMT declared in PAT */
-    for( int i = 0; !pmt && i < p_sys->i_pmt; i++ )
-        for( int i_prg = 0; !pmt && i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
+    for( int i = 0; !pmtpid && i < p_pat->programs.i_size; i++ )
+    {
+        const int i_pmt_prgnumber = p_pat->programs.p_elems[i]->u.p_pmt->i_number;
+        if( i_pmt_prgnumber != TS_USER_PMT_NUMBER &&
+            i_pmt_prgnumber == p_dvbpsipmt->i_program_number )
         {
-            const int i_pmt_number = p_sys->pmt[i]->psi->prg[i_prg]->i_number;
-            if( i_pmt_number != TS_USER_PMT_NUMBER &&
-                i_pmt_number == p_pmt->i_program_number )
-            {
-                pmt = p_sys->pmt[i];
-                prg = p_sys->pmt[i]->psi->prg[i_prg];
-            }
+            pmtpid = p_pat->programs.p_elems[i];
+            assert(pmtpid->type == TYPE_PMT);
+            p_pmt = pmtpid->u.p_pmt;
         }
+    }
 
-    if( pmt == NULL )
+    if( pmtpid == NULL )
     {
         msg_Warn( p_demux, "unreferenced program (broken stream)" );
-        dvbpsi_DeletePMT(p_pmt);
+        dvbpsi_pmt_delete(p_dvbpsipmt);
         return;
     }
 
+    pmtpid->i_flags |= FLAG_SEEN;
 
-    if( prg->i_version != -1 &&
-        ( !p_pmt->b_current_next || prg->i_version == p_pmt->i_version ) )
+    if( p_pmt->i_version != -1 &&
+        ( !p_dvbpsipmt->b_current_next || p_pmt->i_version == p_dvbpsipmt->i_version ) )
     {
-        dvbpsi_DeletePMT( p_pmt );
+        dvbpsi_pmt_delete( p_dvbpsipmt );
         return;
     }
 
-    ts_pid_t **pp_clean = NULL;
-    int      i_clean = 0;
-    /* Clean this program (remove all es) */
-    for( int i = 0; i < 8192; i++ )
-    {
-        ts_pid_t *pid = &p_sys->pid[i];
+    /* Save old es array */
+    DECL_ARRAY(ts_pid_t *) old_es_rm;
+    old_es_rm.i_alloc = p_pmt->e_streams.i_alloc;
+    old_es_rm.i_size = p_pmt->e_streams.i_size;
+    old_es_rm.p_elems = p_pmt->e_streams.p_elems;
+    ARRAY_INIT(p_pmt->e_streams);
 
-        if( pid->b_valid && pid->p_owner == pmt->psi &&
-            pid->i_owner_number == prg->i_number && pid->psi == NULL )
-        {
-            TAB_APPEND( i_clean, pp_clean, pid );
-        }
-    }
-    if( prg->iod )
+    if( p_pmt->iod )
     {
-        IODFree( prg->iod );
-        prg->iod = NULL;
+        IODFree( p_pmt->iod );
+        p_pmt->iod = NULL;
+        for( int i=0; i<old_es_rm.i_size; i++ )
+            old_es_rm.p_elems[i]->u.p_pes->es.p_mpeg4desc = NULL;
     }
 
     msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
-             p_pmt->i_program_number, p_pmt->i_version, p_pmt->i_pcr_pid );
-    prg->i_pid_pcr = p_pmt->i_pcr_pid;
-    prg->i_version = p_pmt->i_version;
+             p_dvbpsipmt->i_program_number, p_dvbpsipmt->i_version, p_dvbpsipmt->i_pcr_pid );
+    p_pmt->i_pid_pcr = p_dvbpsipmt->i_pcr_pid;
+    p_pmt->i_version = p_dvbpsipmt->i_version;
+
+    ValidateDVBMeta( p_demux, p_pmt->i_pid_pcr );
 
-    ValidateDVBMeta( p_demux, prg->i_pid_pcr );
-    if( ProgramIsSelected( p_demux, prg->i_number ) )
-        SetPIDFilter( p_demux, prg->i_pid_pcr, true ); /* Set demux filter */
+    if( ProgramIsSelected( p_sys, p_pmt->i_number ) )
+        SetPIDFilter( p_sys, PID(p_sys, p_pmt->i_pid_pcr), true ); /* Set demux filter */
 
     /* Parse PMT descriptors */
     ts_pmt_registration_type_t registration_type = TS_PMT_REGISTRATION_NONE;
@@ -4466,7 +5005,7 @@ static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt )
     if ( p_sys->arib.e_mode == ARIBMODE_AUTO )
     {
         int i_arib_flags = 0; /* Descriptors can be repeated */
-        for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
+        for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
         {
             switch(p_dr->i_tag)
             {
@@ -4486,18 +5025,18 @@ static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt )
                 break;
             }
         }
-        if ( i_arib_flags == 0b111 )
+        if ( i_arib_flags == 0x07 ) //0b111
             p_sys->arib.e_mode = ARIBMODE_ENABLED;
     }
 
-    for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
+    for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
     {
         /* special descriptors handling */
         switch(p_dr->i_tag)
         {
         case 0x1d: /* We have found an IOD descriptor */
             msg_Dbg( p_demux, " * PMT descriptor : IOD (0x1d)" );
-            prg->iod = IODNew( p_dr->i_length, p_dr->p_data );
+            p_pmt->iod = IODNew( VLC_OBJECT(p_demux), p_dr->i_length, p_dr->p_data );
             break;
 
         case 0x9:
@@ -4535,31 +5074,33 @@ static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt )
             msg_Dbg( p_demux, " * PMT descriptor : unknown (0x%x)", p_dr->i_tag );
         }
     }
-    dvbpsi_pmt_es_t      *p_es;
-    for( p_es = p_pmt->p_first_es; p_es != NULL; p_es = p_es->p_next )
+
+    dvbpsi_pmt_es_t      *p_dvbpsies;
+    for( p_dvbpsies = p_dvbpsipmt->p_first_es; p_dvbpsies != NULL; p_dvbpsies = p_dvbpsies->p_next )
     {
-        ts_pid_t tmp_pid, *old_pid = 0, *pid = &tmp_pid;
+        bool b_reusing_pid = false;
+        ts_pes_t *p_pes;
+
+        ts_pid_t *pespid = PID(p_sys, p_dvbpsies->i_pid);
+        if ( pespid->type == TYPE_PES && pespid->p_parent->u.p_pmt->i_number != p_pmt->i_number )
+        {
+            msg_Warn( p_demux, " * PMT wants to get a share or pid %d (unsupported)", pespid->i_pid );
+            continue;
+        }
 
         /* Find out if the PID was already declared */
-        for( int i = 0; i < i_clean; i++ )
+        for( int i = 0; i < old_es_rm.i_size; i++ )
         {
-            if( pp_clean[i] == &p_sys->pid[p_es->i_pid] )
+            if( old_es_rm.p_elems[i]->i_pid == p_dvbpsies->i_pid )
             {
-                old_pid = pp_clean[i];
+                b_reusing_pid = true;
                 break;
             }
         }
-        ValidateDVBMeta( p_demux, p_es->i_pid );
-
-        if( !old_pid && p_sys->pid[p_es->i_pid].b_valid )
-        {
-            msg_Warn( p_demux, " * PMT error: pid=%d already defined",
-                      p_es->i_pid );
-            continue;
-        }
+        ValidateDVBMeta( p_demux, p_dvbpsies->i_pid );
 
         char const * psz_typedesc = "";
-        switch(p_es->i_type)
+        switch(p_dvbpsies->i_type)
         {
         case 0x00:
             psz_typedesc = "ISO/IEC Reserved";
@@ -4607,336 +5148,507 @@ static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt )
             psz_typedesc = "ISO/IEC 13818-1 auxiliary";
             break;
         default:
-            if (p_es->i_type >= 0x0F && p_es->i_type <=0x7F)
+            if (p_dvbpsies->i_type >= 0x0F && p_dvbpsies->i_type <=0x7F)
                 psz_typedesc = "ISO/IEC 13818-1 Reserved";
             else
                 psz_typedesc = "User Private";
         }
 
         msg_Dbg( p_demux, "  * pid=%d type=0x%x %s",
-                 p_es->i_pid, p_es->i_type, psz_typedesc );
+                 p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
 
-        for( p_dr = p_es->p_first_descriptor; p_dr != NULL;
+        for( p_dr = p_dvbpsies->p_first_descriptor; p_dr != NULL;
              p_dr = p_dr->p_next )
         {
             msg_Dbg( p_demux, "    - descriptor tag 0x%x",
                      p_dr->i_tag );
         }
 
-        PIDInit( pid, false, pmt->psi );
-        PIDFillFormat( &pid->es->fmt, p_es->i_type );
-        pid->i_owner_number = prg->i_number;
-        pid->i_pid          = p_es->i_pid;
-        pid->b_seen         = p_sys->pid[p_es->i_pid].b_seen;
+        if ( !PIDSetup( p_demux, TYPE_PES, pespid, pmtpid ) )
+        {
+            msg_Warn( p_demux, "  * pid=%d type=0x%x %s (skipped)",
+                      p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
+            continue;
+        }
+        else
+        {
+            if( b_reusing_pid )
+            {
+                p_pes = ts_pes_New( p_demux );
+                if( !p_pes )
+                    continue;
+            }
+            else
+            {
+                p_pes = pespid->u.p_pes;
+            }
+        }
+
+        ARRAY_APPEND( p_pmt->e_streams, pespid );
 
+        PIDFillFormat( &p_pes->es.fmt, p_dvbpsies->i_type );
+
+        pespid->i_flags |= SEEN(PID(p_sys, p_dvbpsies->i_pid));
 
         bool b_registration_applied = false;
-        if ( p_es->i_type >= 0x80 ) /* non standard, extensions */
+        if ( p_dvbpsies->i_type >= 0x80 ) /* non standard, extensions */
         {
             if ( registration_type == TS_PMT_REGISTRATION_HDMV )
             {
-                if (( b_registration_applied = PMTSetupEsHDMV( p_demux, pid, p_es ) ))
+                if (( b_registration_applied = PMTSetupEsHDMV( p_demux, &p_pes->es, p_dvbpsies ) ))
                     msg_Dbg( p_demux, "    + HDMV registration applied to pid %d type 0x%x",
-                             p_es->i_pid, p_es->i_type );
+                             p_dvbpsies->i_pid, p_dvbpsies->i_type );
             }
             else
             {
-                if (( b_registration_applied = PMTSetupEsRegistration( p_demux, pid, p_es ) ))
+                if (( b_registration_applied = PMTSetupEsRegistration( p_demux, &p_pes->es, p_dvbpsies ) ))
                     msg_Dbg( p_demux, "    + registration applied to pid %d type 0x%x",
-                        p_es->i_pid, p_es->i_type );
+                        p_dvbpsies->i_pid, p_dvbpsies->i_type );
             }
         }
 
         if ( !b_registration_applied )
         {
-            switch( p_es->i_type )
+            switch( p_dvbpsies->i_type )
             {
             case 0x06:
                 /* Handle PES private data */
-                PMTSetupEs0x06( p_demux, pid, p_es );
+                PMTSetupEs0x06( p_demux, p_pes, p_dvbpsies );
                 break;
             /* All other private or reserved types */
             case 0x0f:
             case 0x10:
             case 0x11:
             case 0x12:
-                PMTSetupEsISO14496( p_demux, pid, prg, p_es );
+                PMTSetupEsISO14496( p_demux, &p_pes->es, p_pmt, p_dvbpsies );
                 break;
             case 0x83:
                 /* LPCM (audio) */
-                PMTSetupEs0x83( p_pmt, pid );
+                PMTSetupEs0x83( p_dvbpsipmt, &p_pes->es, p_dvbpsies->i_pid );
                 break;
             case 0xa0:
-                PMTSetupEs0xA0( p_demux, pid, p_es );
+                PMTSetupEs0xA0( p_demux, &p_pes->es, p_dvbpsies );
                 break;
             case 0xd1:
-                PMTSetupEs0xD1( p_demux, pid, p_es );
+                PMTSetupEs0xD1( p_demux, &p_pes->es, p_dvbpsies );
                 break;
             case 0xEA:
-                PMTSetupEs0xEA( p_demux, pid, p_es );
+                PMTSetupEs0xEA( p_demux, &p_pes->es, p_dvbpsies );
             default:
                 break;
             }
         }
 
-        if( pid->es->fmt.i_cat == AUDIO_ES ||
-            ( pid->es->fmt.i_cat == SPU_ES &&
-              pid->es->fmt.i_codec != VLC_CODEC_DVBS &&
-              pid->es->fmt.i_codec != VLC_CODEC_TELETEXT ) )
+        if( p_pes->es.fmt.i_cat == AUDIO_ES ||
+            ( p_pes->es.fmt.i_cat == SPU_ES &&
+              p_pes->es.fmt.i_codec != VLC_CODEC_DVBS &&
+              p_pes->es.fmt.i_codec != VLC_CODEC_TELETEXT ) )
         {
-            PMTParseEsIso639( p_demux, pid, p_es );
+            PMTParseEsIso639( p_demux, &p_pes->es, p_dvbpsies );
         }
 
-        switch( pid->es->fmt.i_codec )
+        switch( p_pes->es.fmt.i_codec )
         {
         case VLC_CODEC_SCTE_27:
-            pid->es->data_type = TS_ES_DATA_TABLE_SECTION;
+            p_pes->data_type = TS_ES_DATA_TABLE_SECTION;
             break;
         default:
             //pid->es->data_type = TS_ES_DATA_PES;
             break;
         }
 
-        pid->es->fmt.i_group = p_pmt->i_program_number;
-        for( int i = 0; i < pid->i_extra_es; i++ )
-            pid->extra_es[i]->fmt.i_group = p_pmt->i_program_number;
+        /* Set Groups / ID */
+        p_pes->es.fmt.i_group = p_dvbpsipmt->i_program_number;
+        if( p_sys->b_es_id_pid )
+            p_pes->es.fmt.i_id = p_dvbpsies->i_pid;
 
-        if( pid->es->fmt.i_cat == UNKNOWN_ES )
+        if( p_pes->es.fmt.i_cat == UNKNOWN_ES )
         {
             msg_Dbg( p_demux, "   => pid %d content is *unknown*",
-                     p_es->i_pid );
+                     p_dvbpsies->i_pid );
+            p_pes->es.fmt.psz_description = strdup( psz_typedesc );
         }
         else
         {
             msg_Dbg( p_demux, "   => pid %d has now es fcc=%4.4s",
-                     p_es->i_pid, (char*)&pid->es->fmt.i_codec );
-
-            if( p_sys->b_es_id_pid ) pid->es->fmt.i_id = p_es->i_pid;
+                     p_dvbpsies->i_pid, (char*)&p_pes->es.fmt.i_codec );
 
             /* Check if we can avoid restarting the ES */
-            if( old_pid &&
-                pid->es->fmt.i_codec == old_pid->es->fmt.i_codec &&
-                pid->es->fmt.i_extra == old_pid->es->fmt.i_extra &&
-                pid->es->fmt.i_extra == 0 &&
-                pid->i_extra_es == old_pid->i_extra_es &&
-                ( ( !pid->es->fmt.psz_language &&
-                    !old_pid->es->fmt.psz_language ) ||
-                  ( pid->es->fmt.psz_language &&
-                    old_pid->es->fmt.psz_language &&
-                    !strcmp( pid->es->fmt.psz_language,
-                             old_pid->es->fmt.psz_language ) ) ) )
+            if( b_reusing_pid )
             {
-                pid->i_cc = old_pid->i_cc;
-                ts_es_t *e = pid->es;
-                pid->es = old_pid->es;
-                old_pid->es = e;
-                for( int i = 0; i < pid->i_extra_es; i++ )
+                /* p_pes points to a tmp pes */
+                if( pespid->u.p_pes->es.fmt.i_codec != p_pes->es.fmt.i_codec ||
+                    pespid->u.p_pes->es.fmt.i_extra != p_pes->es.fmt.i_extra ||
+                    pespid->u.p_pes->es.fmt.i_extra != 0 ||
+                    pespid->u.p_pes->extra_es.i_size != p_pes->extra_es.i_size ||
+                    !( ( !pespid->u.p_pes->es.fmt.psz_language &&
+                        !p_pes->es.fmt.psz_language ) ||
+                      ( pespid->u.p_pes->es.fmt.psz_language &&
+                        p_pes->es.fmt.psz_language &&
+                        !strcmp( pespid->u.p_pes->es.fmt.psz_language,
+                                 p_pes->es.fmt.psz_language ) ) ) )
                 {
-                    e = pid->extra_es[i];
-                    pid->extra_es[i] = old_pid->extra_es[i];
-                    old_pid->extra_es[i] = e;
+                    /* Differs, swap then */
+                    ts_pes_t *e = pespid->u.p_pes;
+                    pespid->u.p_pes = p_pes;
+                    p_pes = e;
+
+                    /* p_pes still tmp, but now contains old config */
+                    pespid->u.p_pes->es.id = p_pes->es.id;
+                    if( pespid->u.p_pes->es.id )
+                    {
+                        p_pes->es.id = NULL;
+                        es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
+                                        pespid->u.p_pes->es.id, pespid->u.p_pes->es.fmt );
+                    }
+
+                    for( int i=0; i<pespid->u.p_pes->extra_es.i_size &&
+                                  i<p_pes->extra_es.i_size; i++ )
+                    {
+                        pespid->u.p_pes->extra_es.p_elems[i]->id = p_pes->extra_es.p_elems[i]->id;
+                        if( pespid->u.p_pes->extra_es.p_elems[i]->id )
+                        {
+                            es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
+                                            pespid->u.p_pes->extra_es.p_elems[i]->id,
+                                            pespid->u.p_pes->extra_es.p_elems[i]->fmt );
+                            p_pes->extra_es.p_elems[i]->id = NULL;
+                        }
+                    }
                 }
+
+                ts_pes_Del( p_demux, p_pes ); // delete temp
             }
             else
             {
-                pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
-                for( int i = 0; i < pid->i_extra_es; i++ )
-                {
-                    pid->extra_es[i]->id =
-                        es_out_Add( p_demux->out, &pid->extra_es[i]->fmt );
-                }
-                p_sys->i_pmt_es += 1 + pid->i_extra_es;
+                AddAndCreateES( p_demux, pespid, false );
             }
         }
 
-        /* Add ES to the list */
-        if( old_pid )
-        {
-            PIDClean( p_demux, old_pid );
-            TAB_REMOVE( i_clean, pp_clean, old_pid );
-        }
-        p_sys->pid[p_es->i_pid] = *pid;
-
-        p_dr = PMTEsFindDescriptor( p_es, 0x09 );
+        p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x09 );
         if( p_dr && p_dr->i_length >= 2 )
         {
             msg_Dbg( p_demux, "   * PMT descriptor : CA (0x9) SysID 0x%x",
                      (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
         }
-
-        if( ProgramIsSelected( p_demux, prg->i_number ) && pid->es->id != NULL )
-            SetPIDFilter( p_demux, p_es->i_pid, true ); /* Set demux filter */
     }
 
     /* Set CAM descrambling */
-    if( !ProgramIsSelected( p_demux, prg->i_number )
-     || stream_Control( p_demux->s, STREAM_SET_PRIVATE_ID_CA,
-                        p_pmt ) != VLC_SUCCESS )
-        dvbpsi_DeletePMT( p_pmt );
+    if( !ProgramIsSelected( p_sys, p_pmt->i_number ) )
+    {
+        dvbpsi_pmt_delete( p_dvbpsipmt );
+    }
+    else if( stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_CA,
+                             p_dvbpsipmt ) != VLC_SUCCESS )
+    {
+        if ( p_sys->arib.e_mode == ARIBMODE_ENABLED && !p_sys->arib.b25stream )
+        {
+            p_sys->arib.b25stream = stream_FilterNew( p_demux->s, "aribcam" );
+            p_sys->stream = ( p_sys->arib.b25stream ) ? p_sys->arib.b25stream : p_demux->s;
+            if (!p_sys->arib.b25stream)
+                dvbpsi_pmt_delete( p_dvbpsipmt );
+        } else dvbpsi_pmt_delete( p_dvbpsipmt );
+    }
+
+    /* Decref or clean now unused es */
+    for( int i = 0; i < old_es_rm.i_size; i++ )
+        PIDRelease( p_demux, old_es_rm.p_elems[i] );
+    ARRAY_RESET( old_es_rm );
+
+    UpdatePESFilters( p_demux, p_sys->b_es_all );
+
+    if( !p_sys->b_trust_pcr )
+    {
+        int i_cand = FindPCRCandidate( p_pmt );
+        p_pmt->i_pid_pcr = i_cand;
+        p_pmt->pcr.b_disable = true;
+        msg_Warn( p_demux, "PCR not trusted for program %d, set up workaround using pid %d",
+                  p_pmt->i_number, i_cand );
+    }
 
-    for( int i = 0; i < i_clean; i++ )
+    /* Probe Boundaries */
+    if( p_sys->b_canfastseek && p_pmt->i_last_dts == -1 )
     {
-        if( ProgramIsSelected( p_demux, prg->i_number ) )
-            SetPIDFilter( p_demux, pp_clean[i]->i_pid, false );
+        p_pmt->i_last_dts = 0;
+        ProbeStart( p_demux, p_pmt->i_number );
+        ProbeEnd( p_demux, p_pmt->i_number );
+    }
+}
 
-        PIDClean( p_demux, pp_clean[i] );
+static int PATCheck( demux_t *p_demux, dvbpsi_pat_t *p_pat )
+{
+    /* Some Dreambox streams have all PMT set to same pid */
+    int i_prev_pid = -1;
+    for( dvbpsi_pat_program_t * p_program = p_pat->p_first_program;
+         p_program != NULL;
+         p_program = p_program->p_next )
+    {
+        if( p_program->i_pid == i_prev_pid )
+        {
+            msg_Warn( p_demux, "PAT check failed: duplicate program pid %d", i_prev_pid );
+            return VLC_EGENERIC;
+        }
+        i_prev_pid = p_program->i_pid;
     }
-    if( i_clean )
-        free( pp_clean );
+    return VLC_SUCCESS;
 }
 
-static void PATCallBack( void *data, dvbpsi_pat_t *p_pat )
+static void PATCallBack( void *data, dvbpsi_pat_t *p_dvbpsipat )
 {
     demux_t              *p_demux = data;
     demux_sys_t          *p_sys = p_demux->p_sys;
     dvbpsi_pat_program_t *p_program;
-    ts_pid_t             *pat = &p_sys->pid[0];
+    ts_pid_t             *patpid = PID(p_sys, 0);
+    ts_pat_t             *p_pat = PID(p_sys, 0)->u.p_pat;
+
+    patpid->i_flags |= FLAG_SEEN;
 
     msg_Dbg( p_demux, "PATCallBack called" );
 
-    if( ( pat->psi->i_pat_version != -1 &&
-            ( !p_pat->b_current_next ||
-              p_pat->i_version == pat->psi->i_pat_version ) ) ||
-        p_sys->b_user_pmt )
+    if(unlikely( PID(p_sys, 0)->type != TYPE_PAT ))
+    {
+        msg_Warn( p_demux, "PATCallBack called on invalid pid" );
+        return;
+    }
+
+    if( ( p_pat->i_version != -1 &&
+            ( !p_dvbpsipat->b_current_next ||
+              p_dvbpsipat->i_version == p_pat->i_version ) ) ||
+        ( p_pat->i_ts_id != -1 && p_dvbpsipat->i_ts_id != p_pat->i_ts_id ) ||
+        p_sys->b_user_pmt || PATCheck( p_demux, p_dvbpsipat ) )
     {
-        dvbpsi_DeletePAT( p_pat );
+        dvbpsi_pat_delete( p_dvbpsipat );
         return;
     }
 
     msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
-             p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
+             p_dvbpsipat->i_ts_id, p_dvbpsipat->i_version, p_dvbpsipat->b_current_next );
+
+    /* Save old programs array */
+    DECL_ARRAY(ts_pid_t *) old_pmt_rm;
+    old_pmt_rm.i_alloc = p_pat->programs.i_alloc;
+    old_pmt_rm.i_size = p_pat->programs.i_size;
+    old_pmt_rm.p_elems = p_pat->programs.p_elems;
+    ARRAY_INIT(p_pat->programs);
 
-    /* Clean old */
-    if( p_sys->i_pmt > 0 )
+    /* now create programs */
+    for( p_program = p_dvbpsipat->p_first_program; p_program != NULL;
+         p_program = p_program->p_next )
     {
-        int      i_pmt_rm = 0;
-        ts_pid_t **pmt_rm = NULL;
+        msg_Dbg( p_demux, "  * number=%d pid=%d", p_program->i_number,
+                 p_program->i_pid );
+        if( p_program->i_number == 0 )
+            continue;
 
-        /* Search pmt to be deleted */
-        for( int i = 0; i < p_sys->i_pmt; i++ )
+        ts_pid_t *pmtpid = PID(p_sys, p_program->i_pid);
+
+        ValidateDVBMeta( p_demux, p_program->i_pid );
+
+        /* create or temporary incref pid */
+        if( !PIDSetup( p_demux, TYPE_PMT, pmtpid, patpid ) )
         {
-            ts_pid_t *pmt = p_sys->pmt[i];
-            bool b_keep = false;
+            msg_Warn( p_demux, "  * number=%d pid=%d (ignored)", p_program->i_number,
+                     p_program->i_pid );
+            continue;
+        }
 
-            for( p_program = p_pat->p_first_program; !b_keep && p_program;
-                 p_program = p_program->p_next )
-            {
-                if( p_program->i_pid != pmt->i_pid )
-                    continue;
+        pmtpid->u.p_pmt->i_number = p_program->i_number;
 
-                for( int i_prg = 0; !b_keep && i_prg < pmt->psi->i_prg; i_prg++ )
-                    if( p_program->i_number == pmt->psi->prg[i_prg]->i_number )
-                        b_keep = true;
-            }
+        if( !dvbpsi_pmt_attach( pmtpid->u.p_pmt->handle, p_program->i_number, PMTCallBack, p_demux ) )
+            msg_Err( p_demux, "PATCallback failed attaching PMTCallback to program %d",
+                     p_program->i_number );
 
-            if( b_keep )
-                continue;
+        ARRAY_APPEND( p_pat->programs, pmtpid );
+
+        /* Now select PID at access level */
+        if( p_sys->programs.i_size == 0 ||
+            ProgramIsSelected( p_sys, p_program->i_number ) )
+        {
+            if( p_sys->programs.i_size == 0 )
+            {
+                msg_Dbg( p_demux, "temporary receiving program %d", p_program->i_number );
+                p_sys->b_default_selection = true;
+                ARRAY_APPEND( p_sys->programs, p_program->i_number );
+            }
 
-            TAB_APPEND( i_pmt_rm, pmt_rm, pmt );
+            if( SetPIDFilter( p_sys, pmtpid, true ) )
+                p_sys->b_access_control = false;
+            else if ( p_sys->es_creation == DELAY_ES )
+                p_sys->es_creation = CREATE_ES;
         }
+    }
+    p_pat->i_version = p_dvbpsipat->i_version;
+    p_pat->i_ts_id = p_dvbpsipat->i_ts_id;
 
-        /* Delete all ES attached to thoses PMT */
-        for( int i = 2; i < 8192; i++ )
-        {
-            ts_pid_t *pid = &p_sys->pid[i];
+    for(int i=0; i<old_pmt_rm.i_size; i++)
+    {
+        /* decref current or release now unreferenced */
+        PIDRelease( p_demux, old_pmt_rm.p_elems[i] );
+    }
+    ARRAY_RESET(old_pmt_rm);
 
-            if( !pid->b_valid || pid->psi )
-                continue;
+    dvbpsi_pat_delete( p_dvbpsipat );
+}
 
-            for( int j = 0; j < i_pmt_rm && pid->b_valid; j++ )
-            {
-                for( int i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
-                {
-                    /* We only remove es that aren't defined by extra pmt */
-                    if( pid->p_owner->prg[i_prg]->i_pid_pmt != pmt_rm[j]->i_pid )
-                        continue;
+static inline bool handle_Init( demux_t *p_demux, dvbpsi_t **handle )
+{
+    *handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
+    if( !*handle )
+        return false;
+    (*handle)->p_sys = (void *) p_demux;
+    return true;
+}
 
-                    if( pid->es->id )
-                        SetPIDFilter( p_demux, i, false );
+static ts_pat_t *ts_pat_New( demux_t *p_demux )
+{
+    ts_pat_t *pat = malloc( sizeof( ts_pat_t ) );
+    if( !pat )
+        return NULL;
 
-                    PIDClean( p_demux, pid );
-                    break;
-                }
-            }
-        }
+    if( !handle_Init( p_demux, &pat->handle ) )
+    {
+        free( pat );
+        return NULL;
+    }
 
-        /* Delete PMT pid */
-        for( int i = 0; i < i_pmt_rm; i++ )
-        {
-            ts_pid_t *pid = pmt_rm[i];
-            SetPIDFilter( p_demux, pid->i_pid, false );
+    pat->i_version  = -1;
+    pat->i_ts_id    = -1;
+    ARRAY_INIT( pat->programs );
 
-            for( int i_prg = 0; i_prg < pid->psi->i_prg; i_prg++ )
-            {
-                const int i_number = pid->psi->prg[i_prg]->i_number;
-                es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, i_number );
-            }
+    return pat;
+}
 
-            PIDClean( p_demux, &p_sys->pid[pid->i_pid] );
-            TAB_REMOVE( p_sys->i_pmt, p_sys->pmt, pid );
-        }
+static void ts_pat_Del( demux_t *p_demux, ts_pat_t *pat )
+{
+    if( dvbpsi_decoder_present( pat->handle ) )
+        dvbpsi_pat_detach( pat->handle );
+    dvbpsi_delete( pat->handle );
+    for( int i=0; i<pat->programs.i_size; i++ )
+        PIDRelease( p_demux, pat->programs.p_elems[i] );
+    ARRAY_RESET( pat->programs );
+    free( pat );
+}
+
+static ts_pmt_t *ts_pmt_New( demux_t *p_demux )
+{
+    ts_pmt_t *pmt = malloc( sizeof( ts_pmt_t ) );
+    if( !pmt )
+        return NULL;
 
-        free( pmt_rm );
+    if( !handle_Init( p_demux, &pmt->handle ) )
+    {
+        free( pmt );
+        return NULL;
     }
 
-    /* now create programs */
-    for( p_program = p_pat->p_first_program; p_program != NULL;
-         p_program = p_program->p_next )
+    ARRAY_INIT( pmt->e_streams );
+
+    pmt->i_version  = -1;
+    pmt->i_number   = -1;
+    pmt->i_pid_pcr  = 0x1FFF;
+    pmt->iod        = NULL;
+
+    pmt->i_last_dts = -1;
+
+    pmt->pcr.i_current = -1;
+    pmt->pcr.i_first  = -1;
+    pmt->pcr.b_disable = false;
+    pmt->pcr.i_first_dts = VLC_TS_INVALID;
+    pmt->pcr.i_pcroffset = -1;
+
+    pmt->pcr.b_fix_done = false;
+
+    return pmt;
+}
+
+static void ts_pmt_Del( demux_t *p_demux, ts_pmt_t *pmt )
+{
+    if( dvbpsi_decoder_present( pmt->handle ) )
+        dvbpsi_pmt_detach( pmt->handle );
+    dvbpsi_delete( pmt->handle );
+    for( int i=0; i<pmt->e_streams.i_size; i++ )
+        PIDRelease( p_demux, pmt->e_streams.p_elems[i] );
+    ARRAY_RESET( pmt->e_streams );
+    if( pmt->iod )
+        IODFree( pmt->iod );
+    if( pmt->i_number > -1 )
+        es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, pmt->i_number );
+    free( pmt );
+}
+
+static ts_pes_t *ts_pes_New( demux_t *p_demux )
+{
+    VLC_UNUSED(p_demux);
+    ts_pes_t *pes = malloc( sizeof( ts_pes_t ) );
+    if( !pes )
+        return NULL;
+
+    pes->es.id = NULL;
+    pes->es.p_mpeg4desc = NULL;
+    es_format_Init( &pes->es.fmt, UNKNOWN_ES, 0 );
+    ARRAY_INIT( pes->extra_es );
+    pes->data_type = TS_ES_DATA_PES;
+    pes->i_data_size = 0;
+    pes->i_data_gathered = 0;
+    pes->p_data = NULL;
+    pes->pp_last = &pes->p_data;
+    pes->p_prepcr_outqueue = NULL;
+
+    return pes;
+}
+
+static void ts_pes_Del( demux_t *p_demux, ts_pes_t *pes )
+{
+    if( pes->es.id )
     {
-        msg_Dbg( p_demux, "  * number=%d pid=%d", p_program->i_number,
-                 p_program->i_pid );
-        if( p_program->i_number == 0 )
-            continue;
+        es_out_Del( p_demux->out, pes->es.id );
+        p_demux->p_sys->i_pmt_es--;
+    }
 
-        ts_pid_t *pmt = &p_sys->pid[p_program->i_pid];
+    if( pes->p_data )
+        block_ChainRelease( pes->p_data );
 
-        ValidateDVBMeta( p_demux, p_program->i_pid );
+    if( pes->p_prepcr_outqueue )
+        block_ChainRelease( pes->p_prepcr_outqueue );
 
-        if( pmt->b_valid )
-        {
-            bool b_add = true;
-            for( int i_prg = 0; b_add && i_prg < pmt->psi->i_prg; i_prg++ )
-                if( pmt->psi->prg[i_prg]->i_number == p_program->i_number )
-                    b_add = false;
+    es_format_Clean( &pes->es.fmt );
 
-            if( !b_add )
-                continue;
-        }
-        else
+    for( int i = 0; i < pes->extra_es.i_size; i++ )
+    {
+        if( pes->extra_es.p_elems[i]->id )
         {
-            TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
+            es_out_Del( p_demux->out, pes->extra_es.p_elems[i]->id );
+            p_demux->p_sys->i_pmt_es--;
         }
+        es_format_Clean( &pes->extra_es.p_elems[i]->fmt );
+        free( pes->extra_es.p_elems[i] );
+    }
+    ARRAY_RESET( pes->extra_es );
 
-        PIDInit( pmt, true, pat->psi );
-        ts_prg_psi_t *prg = pmt->psi->prg[pmt->psi->i_prg-1];
-#if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
-        prg->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
-        if( !prg->handle )
-        {
-            dvbpsi_DeletePAT( p_pat );
-            return;
-        }
-        prg->handle->p_sys = (void *) VLC_OBJECT(p_demux);
-        if( !dvbpsi_pmt_attach( prg->handle, p_program->i_number, PMTCallBack, p_demux ) )
-            msg_Err( p_demux, "PATCallback failed attaching PMTCallback to program %d",
-                     p_program->i_number );
-#else
-        prg->handle = dvbpsi_AttachPMT( p_program->i_number, PMTCallBack, p_demux );
-#endif
-        prg->i_number = p_program->i_number;
-        prg->i_pid_pmt = p_program->i_pid;
+    free( pes );
+}
 
-        /* Now select PID at access level */
-        if( ProgramIsSelected( p_demux, p_program->i_number ) )
-        {
-            if( p_sys->i_current_program == 0 )
-                p_sys->i_current_program = p_program->i_number;
+static ts_psi_t *ts_psi_New( demux_t *p_demux )
+{
+    ts_psi_t *psi = malloc( sizeof( ts_psi_t ) );
+    if( !psi )
+        return NULL;
 
-            if( SetPIDFilter( p_demux, p_program->i_pid, true ) )
-                p_sys->b_access_control = false;
-        }
+    if( !handle_Init( p_demux, &psi->handle ) )
+    {
+        free( psi );
+        return NULL;
     }
-    pat->psi->i_pat_version = p_pat->i_version;
 
-    dvbpsi_DeletePAT( p_pat );
+    psi->i_version  = -1;
+
+    return psi;
+}
+
+static void ts_psi_Del( demux_t *p_demux, ts_psi_t *psi )
+{
+    VLC_UNUSED(p_demux);
+    if( dvbpsi_decoder_present( psi->handle ) )
+        dvbpsi_DetachDemux( psi->handle );
+    dvbpsi_delete( psi->handle );
+    free( psi );
 }