]> git.sesse.net Git - vlc/blob - modules/demux/ts.c
4603f2d9b97436a4382439491f0653901f382c0b
[vlc] / modules / demux / ts.c
1 /*****************************************************************************
2  * ts.c: Transport Stream input module for VLC.
3  *****************************************************************************
4  * Copyright (C) 2004-2005 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Jean-Paul Saman <jpsaman #_at_# m2x.nl>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35
36 #include <assert.h>
37 #include <time.h>
38
39 #include <vlc_access.h>    /* DVB-specific things */
40 #include <vlc_demux.h>
41 #include <vlc_meta.h>
42 #include <vlc_epg.h>
43 #include <vlc_charset.h>   /* FromCharset, for EIT */
44 #include <vlc_bits.h>
45
46 #include "../mux/mpeg/csa.h"
47
48 /* Include dvbpsi headers */
49 # include <dvbpsi/dvbpsi.h>
50 # include <dvbpsi/demux.h>
51 # include <dvbpsi/descriptor.h>
52 # include <dvbpsi/pat.h>
53 # include <dvbpsi/pmt.h>
54 # include <dvbpsi/sdt.h>
55 # include <dvbpsi/dr.h>
56 # include <dvbpsi/psi.h>
57
58 /* EIT support */
59 # include <dvbpsi/eit.h>
60
61 /* TDT support */
62 # include <dvbpsi/tot.h>
63
64 #include "../mux/mpeg/dvbpsi_compat.h"
65 #include "../mux/mpeg/streams.h"
66 #include "../mux/mpeg/tsutil.h"
67 #include "../mux/mpeg/tables.h"
68
69 #include "../codec/opus_header.h"
70
71 #include "opus.h"
72
73 #undef TS_DEBUG
74 VLC_FORMAT(1, 2) static void ts_debug(const char *format, ...)
75 {
76 #ifdef TS_DEBUG
77     va_list ap;
78     va_start(ap, format);
79     vfprintf(stderr, format, ap);
80     va_end(ap);
81 #else
82     (void)format;
83 #endif
84 }
85
86 #ifdef HAVE_ARIBB24
87  #include <aribb24/aribb24.h>
88  #include <aribb24/decoder.h>
89 #endif
90
91 typedef enum arib_modes_e
92 {
93     ARIBMODE_AUTO = -1,
94     ARIBMODE_DISABLED = 0,
95     ARIBMODE_ENABLED = 1
96 } arib_modes_e;
97
98 /*****************************************************************************
99  * Module descriptor
100  *****************************************************************************/
101 static int  Open  ( vlc_object_t * );
102 static void Close ( vlc_object_t * );
103
104 /* TODO
105  * - Rename "extra pmt" to "user pmt"
106  * - Update extra pmt description
107  *      pmt_pid[:pmt_number][=pid_description[,pid_description]]
108  *      where pid_description could take 3 forms:
109  *          1. pid:pcr (to force the pcr pid)
110  *          2. pid:stream_type
111  *          3. pid:type=fourcc where type=(video|audio|spu)
112  */
113 #define PMT_TEXT N_("Extra PMT")
114 #define PMT_LONGTEXT N_( \
115   "Allows a user to specify an extra pmt (pmt_pid=pid:stream_type[,...])." )
116
117 #define PID_TEXT N_("Set id of ES to PID")
118 #define PID_LONGTEXT N_("Set the internal ID of each elementary stream" \
119                        " handled by VLC to the same value as the PID in" \
120                        " the TS stream, instead of 1, 2, 3, etc. Useful to" \
121                        " do \'#duplicate{..., select=\"es=<pid>\"}\'.")
122
123 #define CSA_TEXT N_("CSA Key")
124 #define CSA_LONGTEXT N_("CSA encryption key. This must be a " \
125   "16 char string (8 hexadecimal bytes).")
126
127 #define CSA2_TEXT N_("Second CSA Key")
128 #define CSA2_LONGTEXT N_("The even CSA encryption key. This must be a " \
129   "16 char string (8 hexadecimal bytes).")
130
131
132 #define CPKT_TEXT N_("Packet size in bytes to decrypt")
133 #define CPKT_LONGTEXT N_("Specify the size of the TS packet to decrypt. " \
134     "The decryption routines subtract the TS-header from the value before " \
135     "decrypting. " )
136
137 #define SPLIT_ES_TEXT N_("Separate sub-streams")
138 #define SPLIT_ES_LONGTEXT N_( \
139     "Separate teletex/dvbs pages into independent ES. " \
140     "It can be useful to turn off this option when using stream output." )
141
142 #define SEEK_PERCENT_TEXT N_("Seek based on percent not time")
143 #define SEEK_PERCENT_LONGTEXT N_( \
144     "Seek and position based on a percent byte position, not a PCR generated " \
145     "time position. If seeking doesn't work property, turn on this option." )
146
147 #define PCR_TEXT N_("Trust in-stream PCR")
148 #define PCR_LONGTEXT N_("Use the stream PCR as a reference.")
149
150 static const int const arib_mode_list[] =
151   { ARIBMODE_AUTO, ARIBMODE_ENABLED, ARIBMODE_DISABLED };
152 static const char *const arib_mode_list_text[] =
153   { N_("Auto"), N_("Enabled"), N_("Disabled") };
154
155 #define SUPPORT_ARIB_TEXT N_("ARIB STD-B24 mode")
156 #define SUPPORT_ARIB_LONGTEXT N_( \
157     "Forces ARIB STD-B24 mode for decoding characters." \
158     "This feature affects EPG information and subtitles." )
159
160 vlc_module_begin ()
161     set_description( N_("MPEG Transport Stream demuxer") )
162     set_shortname ( "MPEG-TS" )
163     set_category( CAT_INPUT )
164     set_subcategory( SUBCAT_INPUT_DEMUX )
165
166     add_string( "ts-extra-pmt", NULL, PMT_TEXT, PMT_LONGTEXT, true )
167     add_bool( "ts-trust-pcr", true, PCR_TEXT, PCR_LONGTEXT, true )
168         change_safe()
169     add_bool( "ts-es-id-pid", true, PID_TEXT, PID_LONGTEXT, true )
170         change_safe()
171     add_obsolete_string( "ts-out" ) /* since 2.2.0 */
172     add_obsolete_integer( "ts-out-mtu" ) /* since 2.2.0 */
173     add_string( "ts-csa-ck", NULL, CSA_TEXT, CSA_LONGTEXT, true )
174         change_safe()
175     add_string( "ts-csa2-ck", NULL, CSA2_TEXT, CSA2_LONGTEXT, true )
176         change_safe()
177     add_integer( "ts-csa-pkt", 188, CPKT_TEXT, CPKT_LONGTEXT, true )
178         change_safe()
179
180     add_bool( "ts-split-es", true, SPLIT_ES_TEXT, SPLIT_ES_LONGTEXT, false )
181     add_bool( "ts-seek-percent", false, SEEK_PERCENT_TEXT, SEEK_PERCENT_LONGTEXT, true )
182
183     add_integer( "ts-arib", ARIBMODE_AUTO, SUPPORT_ARIB_TEXT, SUPPORT_ARIB_LONGTEXT, false )
184         change_integer_list( arib_mode_list, arib_mode_list_text )
185
186     add_obsolete_bool( "ts-silent" );
187
188     set_capability( "demux", 10 )
189     set_callbacks( Open, Close )
190     add_shortcut( "ts" )
191 vlc_module_end ()
192
193 /*****************************************************************************
194  * Local prototypes
195  *****************************************************************************/
196 static const char *const ppsz_teletext_type[] = {
197  "",
198  N_("Teletext"),
199  N_("Teletext subtitles"),
200  N_("Teletext: additional information"),
201  N_("Teletext: program schedule"),
202  N_("Teletext subtitles: hearing impaired")
203 };
204
205 typedef struct
206 {
207     uint8_t                 i_objectTypeIndication;
208     uint8_t                 i_streamType;
209
210     int                     i_extra;
211     uint8_t                 *p_extra;
212
213 } decoder_config_descriptor_t;
214
215 typedef struct
216 {
217     bool                    b_ok;
218     uint16_t                i_es_id;
219
220     char                    *psz_url;
221
222     decoder_config_descriptor_t    dec_descr;
223
224 } es_mpeg4_descriptor_t;
225
226 #define ES_DESCRIPTOR_COUNT 255
227 typedef struct
228 {
229     /* IOD */
230     char                    *psz_url;
231
232     es_mpeg4_descriptor_t   es_descr[ES_DESCRIPTOR_COUNT];
233
234 } iod_descriptor_t;
235
236 typedef struct
237 {
238     dvbpsi_handle   handle;
239     int             i_version;
240     int             i_number;
241     int             i_pid_pcr;
242     int             i_pid_pmt;
243     /* IOD stuff (mpeg4) */
244     iod_descriptor_t *iod;
245
246     struct
247     {
248         mtime_t i_current;
249         mtime_t i_first; // seen <> != -1
250         /* broken PCR handling */
251         mtime_t i_first_dts;
252         mtime_t i_pcroffset;
253         bool    b_disable; /* ignore PCR field, use dts */
254     } pcr;
255
256     mtime_t i_last_dts;
257
258 } ts_prg_psi_t;
259
260 typedef struct
261 {
262     /* for special PAT/SDT case */
263     dvbpsi_handle   handle; /* PAT/SDT/EIT */
264     int             i_pat_version;
265     int             i_sdt_version;
266
267     /* For PMT */
268     int             i_prg;
269     ts_prg_psi_t    **prg;
270
271 } ts_psi_t;
272
273 typedef enum
274 {
275     TS_ES_DATA_PES,
276     TS_ES_DATA_TABLE_SECTION
277 } ts_es_data_type_t;
278
279 typedef enum
280 {
281     TS_PMT_REGISTRATION_NONE = 0,
282     TS_PMT_REGISTRATION_HDMV
283 } ts_pmt_registration_type_t;
284
285 typedef struct
286 {
287     es_format_t  fmt;
288     es_out_id_t *id;
289     ts_es_data_type_t data_type;
290     int         i_data_size;
291     int         i_data_gathered;
292     block_t     *p_data;
293     block_t     **pp_last;
294
295     es_mpeg4_descriptor_t *p_mpeg4desc;
296
297     block_t *   p_prepcr_outqueue;
298 } ts_es_t;
299
300 typedef struct
301 {
302     int         i_pid;
303
304     bool        b_seen;
305     bool        b_valid;
306     int         i_cc;   /* countinuity counter */
307     bool        b_scrambled;
308
309     /* PSI owner (ie PMT -> PAT, ES -> PMT */
310     ts_psi_t   *p_owner;
311     int         i_owner_number;
312
313     /* */
314     ts_psi_t    *psi;
315     ts_es_t     *es;
316
317     /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
318     ts_es_t     **extra_es;
319     int         i_extra_es;
320
321     struct
322     {
323         vlc_fourcc_t i_fourcc;
324         int i_type;
325         int i_pcr_count;
326     } probed;
327
328 } ts_pid_t;
329
330 typedef struct
331 {
332     int i_service;
333 } vdr_info_t;
334
335 #define MIN_ES_PID 4    /* Should be 32.. broken muxers */
336 #define MAX_ES_PID 8190
337
338 #define FROM_SCALE(x) (VLC_TS_0 + ((x) * 100 / 9))
339 #define TO_SCALE(x)   (((x) - VLC_TS_0) * 9 / 100)
340
341 struct demux_sys_t
342 {
343     stream_t   *stream;
344     bool        b_canseek;
345     bool        b_canfastseek;
346     vlc_mutex_t     csa_lock;
347
348     /* TS packet size (188, 192, 204) */
349     int         i_packet_size;
350
351     /* Additional TS packet header size (BluRay TS packets have 4-byte header before sync byte) */
352     int         i_packet_header_size;
353
354     /* how many TS packet we read at once */
355     int         i_ts_read;
356
357     bool        b_force_seek_per_percent;
358
359     struct
360     {
361         arib_modes_e e_mode;
362 #ifdef HAVE_ARIBB24
363         arib_instance_t *p_instance;
364 #endif
365         stream_t     *b25stream;
366     } arib;
367
368     /* All pid */
369     ts_pid_t    pid[8192];
370
371     /* All PMT */
372     bool        b_user_pmt;
373     int         i_pmt;
374     ts_pid_t    **pmt;
375     int         i_pmt_es;
376
377     enum
378     {
379         NO_ES, /* for preparse */
380         DELAY_ES,
381         CREATE_ES
382     } es_creation;
383     #define PREPARSING p_sys->es_creation == NO_ES
384
385     /* */
386     bool        b_es_id_pid;
387     csa_t       *csa;
388     int         i_csa_pkt_size;
389     bool        b_split_es;
390
391     bool        b_trust_pcr;
392
393     /* */
394     bool        b_access_control;
395     bool        b_end_preparse;
396
397     /* */
398     bool        b_dvb_meta;
399     int64_t     i_tdt_delta;
400     int64_t     i_dvb_start;
401     int64_t     i_dvb_length;
402     bool        b_broken_charset; /* True if broken encoding is used in EPG/SDT */
403
404     /* Selected programs */
405     DECL_ARRAY( int ) programs; /* List of selected/access-filtered programs */
406     bool        b_default_selection; /* True if set by default to first pmt seen (to get data from filtered access) */
407
408     struct
409     {
410         mtime_t i_first_dts;     /* first dts encountered for the stream */
411         int     i_timesourcepid; /* which pid we saved the dts from */
412         bool    b_pat_deadline;  /* set if we haven't seen PAT within 140ms */
413     } patfix;
414
415     vdr_info_t  vdr;
416
417     /* */
418     bool        b_start_record;
419 };
420
421 static int Demux    ( demux_t *p_demux );
422 static int Control( demux_t *p_demux, int i_query, va_list args );
423
424 static void PIDInit ( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner );
425 static void PIDClean( demux_t *, ts_pid_t *pid );
426 static void PIDFillFormat( es_format_t *fmt, int i_stream_type );
427
428 static void PATCallBack( void*, dvbpsi_pat_t * );
429 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt );
430 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
431 static void PSINewTableCallBack( dvbpsi_t *handle, uint8_t  i_table_id,
432                                  uint16_t i_extension, demux_t * );
433 #else
434 static void PSINewTableCallBack( demux_t *, dvbpsi_handle,
435                                  uint8_t  i_table_id, uint16_t i_extension );
436 #endif
437
438 static int ChangeKeyCallback( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
439
440
441 /* Helpers */
442 static ts_prg_psi_t * GetProgramByID( demux_sys_t *, int i_program );
443 static inline int PIDGet( block_t *p )
444 {
445     return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
446 }
447
448 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
449 static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid );
450 static void ProgramSetPCR( demux_t *p_demux, ts_prg_psi_t *p_prg, mtime_t i_pcr );
451
452 static block_t* ReadTSPacket( demux_t *p_demux );
453 static int ProbeStart( demux_t *p_demux, int i_program );
454 static int ProbeEnd( demux_t *p_demux, int i_program );
455 static int SeekToTime( demux_t *p_demux, ts_prg_psi_t *, int64_t time );
456 static void ReadyQueuesPostSeek( demux_sys_t *p_sys );
457 static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );
458 static void PCRFixHandle( demux_t *, ts_prg_psi_t *, block_t * );
459 static int64_t TimeStampWrapAround( ts_prg_psi_t *, int64_t );
460
461 static void              IODFree( iod_descriptor_t * );
462
463 #define TS_USER_PMT_NUMBER (0)
464 static int UserPmt( demux_t *p_demux, const char * );
465
466 static int  SetPIDFilter( demux_t *, int i_pid, bool b_selected );
467 static void SetPrgFilter( demux_t *, int i_prg, bool b_selected );
468
469 #define TS_PACKET_SIZE_188 188
470 #define TS_PACKET_SIZE_192 192
471 #define TS_PACKET_SIZE_204 204
472 #define TS_PACKET_SIZE_MAX 204
473 #define TS_HEADER_SIZE 4
474
475 static int DetectPacketSize( demux_t *p_demux, int *pi_header_size, int i_offset )
476 {
477     const uint8_t *p_peek;
478
479     if( stream_Peek( p_demux->s,
480                      &p_peek, i_offset + TS_PACKET_SIZE_MAX ) < i_offset + TS_PACKET_SIZE_MAX )
481         return -1;
482
483     for( int i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
484     {
485         if( p_peek[i_offset + i_sync] != 0x47 )
486             continue;
487
488         /* Check next 3 sync bytes */
489         int i_peek = i_offset + TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
490         if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
491         {
492             msg_Err( p_demux, "cannot peek" );
493             return -1;
494         }
495         if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_188] == 0x47 &&
496             p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
497             p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
498         {
499             return TS_PACKET_SIZE_188;
500         }
501         else if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_192] == 0x47 &&
502                  p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
503                  p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
504         {
505             if( i_sync == 4 )
506             {
507                 *pi_header_size = 4; /* BluRay TS packets have 4-byte header */
508             }
509             return TS_PACKET_SIZE_192;
510         }
511         else if( p_peek[i_offset + i_sync + 1 * TS_PACKET_SIZE_204] == 0x47 &&
512                  p_peek[i_offset + i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
513                  p_peek[i_offset + i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
514         {
515             return TS_PACKET_SIZE_204;
516         }
517     }
518
519     if( p_demux->b_force )
520     {
521         msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
522         return TS_PACKET_SIZE_188;
523     }
524     msg_Dbg( p_demux, "TS module discarded (lost sync)" );
525     return -1;
526 }
527
528 #define TOPFIELD_HEADER_SIZE 3712
529
530 static int DetectPVRHeadersAndHeaderSize( demux_t *p_demux, int *pi_header_size, vdr_info_t *p_vdr )
531 {
532     const uint8_t *p_peek;
533     *pi_header_size = 0;
534     int i_packet_size = -1;
535
536     if( stream_Peek( p_demux->s,
537                      &p_peek, TS_PACKET_SIZE_MAX ) < TS_PACKET_SIZE_MAX )
538         return -1;
539
540     if( memcmp( p_peek, "TFrc", 4 ) == 0 &&
541         p_peek[6] == 0 && memcmp( &p_peek[53], "\x80\x00\x00", 4 ) == 0 &&
542         stream_Peek( p_demux->s, &p_peek, TOPFIELD_HEADER_SIZE + TS_PACKET_SIZE_MAX )
543             == TOPFIELD_HEADER_SIZE + TS_PACKET_SIZE_MAX )
544     {
545         i_packet_size = DetectPacketSize( p_demux, pi_header_size, TOPFIELD_HEADER_SIZE );
546         if( i_packet_size != -1 )
547         {
548             msg_Dbg( p_demux, "this is a topfield file" );
549 #if 0
550             /* I used the TF5000PVR 2004 Firmware .doc header documentation,
551              * http://www.i-topfield.com/data/product/firmware/Structure%20of%20Recorded%20File%20in%20TF5000PVR%20(Feb%2021%202004).doc
552              * but after the filename the offsets seem to be incorrect.  - DJ */
553             int i_duration, i_name;
554             char *psz_name = xmalloc(25);
555             char *psz_event_name;
556             char *psz_event_text = xmalloc(130);
557             char *psz_ext_text = xmalloc(1025);
558
559             // 2 bytes version Uimsbf (4,5)
560             // 2 bytes reserved (6,7)
561             // 2 bytes duration in minutes Uimsbf (8,9(
562             i_duration = (int) (p_peek[8] << 8) | p_peek[9];
563             msg_Dbg( p_demux, "Topfield recording length: +/- %d minutes", i_duration);
564             // 2 bytes service number in channel list (10, 11)
565             // 2 bytes service type Bslbf 0=TV 1=Radio Bslb (12, 13)
566             // 4 bytes of reserved + tuner info (14,15,16,17)
567             // 2 bytes of Service ID  Bslbf (18,19)
568             // 2 bytes of PMT PID  Uimsbf (20,21)
569             // 2 bytes of PCR PID  Uimsbf (22,23)
570             // 2 bytes of Video PID  Uimsbf (24,25)
571             // 2 bytes of Audio PID  Uimsbf (26,27)
572             // 24 bytes filename Bslbf
573             memcpy( psz_name, &p_peek[28], 24 );
574             psz_name[24] = '\0';
575             msg_Dbg( p_demux, "recordingname=%s", psz_name );
576             // 1 byte of sat index Uimsbf  (52)
577             // 3 bytes (1 bit of polarity Bslbf +23 bits reserved)
578             // 4 bytes of freq. Uimsbf (56,57,58,59)
579             // 2 bytes of symbol rate Uimsbf (60,61)
580             // 2 bytes of TS stream ID Uimsbf (62,63)
581             // 4 bytes reserved
582             // 2 bytes reserved
583             // 2 bytes duration Uimsbf (70,71)
584             //i_duration = (int) (p_peek[70] << 8) | p_peek[71];
585             //msg_Dbg( p_demux, "Topfield 2nd duration field: +/- %d minutes", i_duration);
586             // 4 bytes EventID Uimsbf (72-75)
587             // 8 bytes of Start and End time info (76-83)
588             // 1 byte reserved (84)
589             // 1 byte event name length Uimsbf (89)
590             i_name = (int)(p_peek[89]&~0x81);
591             msg_Dbg( p_demux, "event name length = %d", i_name);
592             psz_event_name = xmalloc( i_name+1 );
593             // 1 byte parental rating (90)
594             // 129 bytes of event text
595             memcpy( psz_event_name, &p_peek[91], i_name );
596             psz_event_name[i_name] = '\0';
597             memcpy( psz_event_text, &p_peek[91+i_name], 129-i_name );
598             psz_event_text[129-i_name] = '\0';
599             msg_Dbg( p_demux, "event name=%s", psz_event_name );
600             msg_Dbg( p_demux, "event text=%s", psz_event_text );
601             // 12 bytes reserved (220)
602             // 6 bytes reserved
603             // 2 bytes Event Text Length Uimsbf
604             // 4 bytes EventID Uimsbf
605             // FIXME We just have 613 bytes. not enough for this entire text
606             // 1024 bytes Extended Event Text Bslbf
607             memcpy( psz_ext_text, p_peek+372, 1024 );
608             psz_ext_text[1024] = '\0';
609             msg_Dbg( p_demux, "extended event text=%s", psz_ext_text );
610             // 52 bytes reserved Bslbf
611 #endif
612             p_vdr->i_service = GetWBE(&p_peek[18]);
613
614             return i_packet_size;
615             //return TS_PACKET_SIZE_188;
616         }
617     }
618
619     return DetectPacketSize( p_demux, pi_header_size, 0 );
620 }
621
622 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
623 static void vlc_dvbpsi_reset( demux_t *p_demux )
624 {
625     demux_sys_t *p_sys = p_demux->p_sys;
626
627     ts_pid_t *pat = &p_sys->pid[0];
628     ts_pid_t *sdt = &p_sys->pid[0x11];
629     ts_pid_t *eit = &p_sys->pid[0x12];
630     ts_pid_t *tdt = &p_sys->pid[0x14];
631
632     if( pat->psi->handle )
633     {
634         if( dvbpsi_decoder_present( pat->psi->handle ) )
635             dvbpsi_pat_detach( pat->psi->handle );
636         dvbpsi_delete( pat->psi->handle );
637         pat->psi->handle = NULL;
638     }
639
640     if( sdt->psi->handle )
641     {
642         if( dvbpsi_decoder_present( sdt->psi->handle ) )
643             dvbpsi_DetachDemux( sdt->psi->handle );
644         dvbpsi_delete( sdt->psi->handle );
645         sdt->psi->handle = NULL;
646     }
647
648     if( eit->psi->handle )
649     {
650         if( dvbpsi_decoder_present( eit->psi->handle ) )
651             dvbpsi_DetachDemux( eit->psi->handle );
652         dvbpsi_delete( eit->psi->handle );
653         eit->psi->handle = NULL;
654     }
655
656     if( tdt->psi->handle )
657     {
658         if( dvbpsi_decoder_present( tdt->psi->handle ) )
659             dvbpsi_DetachDemux( tdt->psi->handle );
660         dvbpsi_delete( tdt->psi->handle );
661         tdt->psi->handle = NULL;
662     }
663 }
664 #endif
665
666 static inline mtime_t ExtractPESTimestamp( const uint8_t *p_data )
667 {
668     return ((mtime_t)(p_data[ 0]&0x0e ) << 29)|
669              (mtime_t)(p_data[1] << 22)|
670             ((mtime_t)(p_data[2]&0xfe) << 14)|
671              (mtime_t)(p_data[3] << 7)|
672              (mtime_t)(p_data[4] >> 1);
673 }
674
675 static void ProbePES( demux_t *p_demux, ts_pid_t *pid, const uint8_t *p_pesstart, size_t i_data, bool b_adaptfield )
676 {
677     demux_sys_t *p_sys = p_demux->p_sys;
678     const uint8_t *p_pes = p_pesstart;
679     pid->probed.i_type = -1;
680
681     if( b_adaptfield )
682     {
683         if ( i_data < 2 )
684             return;
685
686         uint8_t len = *p_pes;
687         p_pes++; i_data--;
688
689         if(len == 0)
690         {
691             p_pes++; i_data--;/* stuffing */
692         }
693         else
694         {
695             if( i_data < len )
696                 return;
697             if( len >= 7 && (p_pes[1] & 0x10) )
698                 pid->probed.i_pcr_count++;
699             p_pes += len;
700             i_data -= len;
701         }
702     }
703
704     if( i_data < 9 )
705         return;
706
707     if( p_pes[0] != 0 || p_pes[1] != 0 || p_pes[2] != 1 )
708         return;
709
710     size_t i_pesextoffset = 8;
711     mtime_t i_dts = -1;
712     if( p_pes[7] & 0x80 ) // PTS
713     {
714         i_pesextoffset += 5;
715         if ( i_data < i_pesextoffset )
716             return;
717         i_dts = ExtractPESTimestamp( &p_pes[9] );
718     }
719     if( p_pes[7] & 0x40 ) // DTS
720     {
721         i_pesextoffset += 5;
722         if ( i_data < i_pesextoffset )
723             return;
724         i_dts = ExtractPESTimestamp( &p_pes[14] );
725     }
726     if( p_pes[7] & 0x20 ) // ESCR
727         i_pesextoffset += 6;
728     if( p_pes[7] & 0x10 ) // ESrate
729         i_pesextoffset += 3;
730     if( p_pes[7] & 0x08 ) // DSM
731         i_pesextoffset += 1;
732     if( p_pes[7] & 0x04 ) // CopyInfo
733         i_pesextoffset += 1;
734     if( p_pes[7] & 0x02 ) // PESCRC
735         i_pesextoffset += 2;
736
737     if ( i_data < i_pesextoffset )
738         return;
739
740      /* HeaderdataLength */
741     const size_t i_payloadoffset = 8 + 1 + p_pes[8];
742     i_pesextoffset += 1;
743
744     if ( i_data < i_pesextoffset || i_data < i_payloadoffset )
745         return;
746
747     i_data -= 8 + 1 + p_pes[8];
748
749     if( p_pes[7] & 0x01 ) // PESExt
750     {
751         size_t i_extension2_offset = 1;
752         if ( p_pes[i_pesextoffset] & 0x80 ) // private data
753             i_extension2_offset += 16;
754         if ( p_pes[i_pesextoffset] & 0x40 ) // pack
755             i_extension2_offset += 1;
756         if ( p_pes[i_pesextoffset] & 0x20 ) // seq
757             i_extension2_offset += 2;
758         if ( p_pes[i_pesextoffset] & 0x10 ) // P-STD
759             i_extension2_offset += 2;
760         if ( p_pes[i_pesextoffset] & 0x01 ) // Extension 2
761         {
762             uint8_t i_len = p_pes[i_pesextoffset + i_extension2_offset] & 0x7F;
763             i_extension2_offset += i_len;
764         }
765         if( i_data < i_extension2_offset )
766             return;
767
768         i_data -= i_extension2_offset;
769     }
770     /* (i_payloadoffset - i_pesextoffset) 0xFF stuffing */
771
772     if ( i_data < 4 )
773         return;
774
775     const uint8_t *p_data = &p_pes[i_payloadoffset];
776     /* AUDIO STREAM */
777     if(p_pes[3] >= 0xC0 && p_pes[3] <= 0xDF)
778     {
779         if( !memcmp( p_data, "\x7F\xFE\x80\x01", 4 ) )
780         {
781             pid->probed.i_type = 0x06;
782             pid->probed.i_fourcc = VLC_CODEC_DTS;
783         }
784         else if( !memcmp( p_data, "\x0B\x77", 2 ) )
785         {
786             pid->probed.i_type = 0x06;
787             pid->probed.i_fourcc = VLC_CODEC_EAC3;
788         }
789         else if( p_data[0] == 0xFF && (p_data[1] & 0xE0) == 0xE0 )
790         {
791             switch(p_data[1] & 18)
792             {
793             /* 10 - MPEG Version 2 (ISO/IEC 13818-3)
794                11 - MPEG Version 1 (ISO/IEC 11172-3) */
795                 case 0x10:
796                     pid->probed.i_type = 0x04;
797                     break;
798                 case 0x18:
799                     pid->probed.i_type = 0x03;
800                 default:
801                     break;
802             }
803
804             switch(p_data[1] & 6)
805             {
806             /* 01 - Layer III
807                10 - Layer II
808                11 - Layer I */
809                 case 0x06:
810                     pid->probed.i_type = 0x04;
811                     pid->probed.i_fourcc = VLC_CODEC_MPGA;
812                     break;
813                 case 0x04:
814                     pid->probed.i_type = 0x04;
815                     pid->probed.i_fourcc = VLC_CODEC_MP2;
816                     break;
817                 case 0x02:
818                     pid->probed.i_type = 0x04;
819                     pid->probed.i_fourcc = VLC_CODEC_MP3;
820                 default:
821                     break;
822             }
823         }
824     }
825     /* VIDEO STREAM */
826     else if( p_pes[3] >= 0xE0 && p_pes[3] <= 0xEF )
827     {
828         if( !memcmp( p_data, "\x00\x00\x00", 4 ) )
829         {
830             pid->probed.i_type = 0x1b;
831             pid->probed.i_fourcc = VLC_CODEC_H264;
832         }
833         else if( !memcmp( p_data, "\x00\x00\x01", 4 ) )
834         {
835             pid->probed.i_type = 0x02;
836             pid->probed.i_fourcc = VLC_CODEC_MPGV;
837         }
838     }
839
840     /* Track timestamps and flag missing PAT */
841     if( !p_sys->patfix.i_timesourcepid && i_dts > -1 )
842     {
843         p_sys->patfix.i_first_dts = i_dts;
844         p_sys->patfix.i_timesourcepid = pid->i_pid;
845     }
846     else if( p_sys->patfix.i_timesourcepid == pid->i_pid && i_dts > -1 &&
847              !p_sys->patfix.b_pat_deadline )
848     {
849         if( i_dts - p_sys->patfix.i_first_dts > 9 * 140000 / 100 )
850             p_sys->patfix.b_pat_deadline = true;
851     }
852
853 }
854
855 static void BuildPATCallback( void *p_opaque, block_t *p_block )
856 {
857     ts_pid_t *pat_pid = (ts_pid_t *) p_opaque;
858     dvbpsi_PushPacket( pat_pid->psi->handle, p_block->p_buffer );
859 }
860
861 static void BuildPMTCallback( void *p_opaque, block_t *p_block )
862 {
863     ts_pid_t *program_pid = (ts_pid_t *) p_opaque;
864     while( p_block )
865     {
866         for( int i_prg = 0; i_prg < program_pid->psi->i_prg; i_prg++ )
867         {
868             dvbpsi_PushPacket( program_pid->psi->prg[i_prg]->handle,
869                                p_block->p_buffer );
870         }
871         p_block = p_block->p_next;
872     }
873 }
874
875 static void MissingPATPMTFixup( demux_t *p_demux )
876 {
877     demux_sys_t *p_sys = p_demux->p_sys;
878     int i_program_number = 1234;
879     int i_program_pid = 1337;
880     int i_pcr_pid = 0x1FFF;
881     int i_num_pes = 0;
882
883     if( p_sys->pid[i_program_pid].b_seen )
884     {
885         /* Find a free one */
886         for( i_program_pid = MIN_ES_PID;
887              i_program_pid <= MAX_ES_PID && p_sys->pid[i_program_pid].b_seen;
888              i_program_pid++ );
889     }
890
891     for( int i = MIN_ES_PID; i <= MAX_ES_PID; i++ )
892     {
893         if( !p_sys->pid[i].b_seen ||
894             p_sys->pid[i].probed.i_type == -1 )
895             continue;
896
897         if( i_pcr_pid == 0x1FFF && ( p_sys->pid[i].probed.i_type == 0x03 ||
898                                      p_sys->pid[i].probed.i_pcr_count ) )
899             i_pcr_pid = p_sys->pid[i].i_pid;
900
901         i_num_pes++;
902     }
903
904     if( i_num_pes == 0 )
905         return;
906
907     ts_stream_t patstream =
908     {
909         .i_pid = 0,
910         .i_continuity_counter = 0x10,
911         .b_discontinuity = false
912     };
913
914     ts_stream_t pmtprogramstream =
915     {
916         .i_pid = i_program_pid,
917         .i_continuity_counter = 0x0,
918         .b_discontinuity = false
919     };
920
921     BuildPAT( DVBPSI_HANDLE_PARAM(p_sys->pid[0].psi->handle)
922             &p_sys->pid[0], BuildPATCallback,
923             0, 1,
924             &patstream,
925             1, &pmtprogramstream, &i_program_number );
926
927     if( !p_sys->pid[i_program_pid].psi )
928     {
929         msg_Err( p_demux, "PAT creation failed" );
930         return;
931     }
932
933     struct esstreams_t
934     {
935         pes_stream_t pes;
936         ts_stream_t ts;
937     };
938     es_format_t esfmt = {0};
939     struct esstreams_t *esstreams = calloc( i_num_pes, sizeof(struct esstreams_t) );
940     pes_mapped_stream_t *mapped = calloc( i_num_pes, sizeof(pes_mapped_stream_t) );
941     if( esstreams && mapped )
942     {
943         int j=0;
944         for( int i = MIN_ES_PID; i <= MAX_ES_PID; i++ )
945         {
946             if( !p_sys->pid[i].b_seen ||
947                 p_sys->pid[i].probed.i_type == -1 )
948                 continue;
949
950             esstreams[j].pes.i_stream_type = p_sys->pid[i].probed.i_type;
951             esstreams[j].pes.i_stream_type = p_sys->pid[i].probed.i_type;
952             esstreams[j].ts.i_pid = p_sys->pid[i].i_pid;
953             mapped[j].pes = &esstreams[j].pes;
954             mapped[j].ts = &esstreams[j].ts;
955             mapped[j].fmt = &esfmt;
956             j++;
957         }
958
959         BuildPMT( DVBPSI_HANDLE_PARAM(p_sys->pid[0].psi->handle) VLC_OBJECT(p_demux),
960                 &p_sys->pid[i_program_pid], BuildPMTCallback,
961                 0, 1,
962                 i_pcr_pid,
963                 NULL,
964                 1, &pmtprogramstream, &i_program_number,
965                 i_num_pes, mapped );
966     }
967     free(esstreams);
968     free(mapped);
969 }
970
971 /*****************************************************************************
972  * Open
973  *****************************************************************************/
974 static int Open( vlc_object_t *p_this )
975 {
976     demux_t     *p_demux = (demux_t*)p_this;
977     demux_sys_t *p_sys;
978
979     int          i_packet_size, i_packet_header_size = 0;
980
981     ts_pid_t    *pat;
982     vdr_info_t   vdr = {0};
983
984     /* Search first sync byte */
985     i_packet_size = DetectPVRHeadersAndHeaderSize( p_demux, &i_packet_header_size, &vdr );
986     if( i_packet_size < 0 )
987         return VLC_EGENERIC;
988
989     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
990     if( !p_sys )
991         return VLC_ENOMEM;
992     memset( p_sys, 0, sizeof( demux_sys_t ) );
993     vlc_mutex_init( &p_sys->csa_lock );
994
995     p_demux->pf_demux = Demux;
996     p_demux->pf_control = Control;
997
998     /* Init p_sys field */
999     p_sys->b_dvb_meta = true;
1000     p_sys->b_access_control = true;
1001     p_sys->b_end_preparse = false;
1002     ARRAY_INIT( p_sys->programs );
1003     p_sys->b_default_selection = false;
1004     p_sys->i_tdt_delta = 0;
1005     p_sys->i_dvb_start = 0;
1006     p_sys->i_dvb_length = 0;
1007
1008     p_sys->vdr = vdr;
1009
1010     p_sys->arib.b25stream = NULL;
1011     p_sys->stream = p_demux->s;
1012
1013     p_sys->b_broken_charset = false;
1014
1015     for( int i = 0; i < 8192; i++ )
1016     {
1017         ts_pid_t *pid = &p_sys->pid[i];
1018         pid->i_pid      = i;
1019         pid->b_seen     = false;
1020         pid->b_valid    = false;
1021         pid->probed.i_fourcc = 0;
1022         pid->probed.i_type = 0;
1023     }
1024     /* PID 8191 is padding */
1025     p_sys->pid[8191].b_seen = true;
1026     p_sys->i_packet_size = i_packet_size;
1027     p_sys->i_packet_header_size = i_packet_header_size;
1028     p_sys->i_ts_read = 50;
1029     p_sys->csa = NULL;
1030     p_sys->b_start_record = false;
1031
1032 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1033 # define VLC_DVBPSI_DEMUX_TABLE_INIT(table,obj) \
1034     do { \
1035         (table)->psi->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG ); \
1036         if( ! (table)->psi->handle ) \
1037         { \
1038             vlc_mutex_destroy( &p_sys->csa_lock ); \
1039             free( p_sys ); \
1040             return VLC_ENOMEM; \
1041         } \
1042         (table)->psi->handle->p_sys = (void *) VLC_OBJECT(obj); \
1043         if( !dvbpsi_AttachDemux( (table)->psi->handle, (dvbpsi_demux_new_cb_t)PSINewTableCallBack, (obj) ) ) \
1044         { \
1045             vlc_dvbpsi_reset( obj ); \
1046             vlc_mutex_destroy( &p_sys->csa_lock ); \
1047             free( p_sys ); \
1048             return VLC_EGENERIC; \
1049         } \
1050     } while (0);
1051 #endif
1052
1053     /* Init PAT handler */
1054     pat = &p_sys->pid[0];
1055     PIDInit( pat, true, NULL );
1056 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1057     pat->psi->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
1058     if( !pat->psi->handle )
1059     {
1060         vlc_mutex_destroy( &p_sys->csa_lock );
1061         free( p_sys );
1062         return VLC_ENOMEM;
1063     }
1064     pat->psi->handle->p_sys = (void *) p_demux;
1065     if( !dvbpsi_pat_attach( pat->psi->handle, PATCallBack, p_demux ) )
1066     {
1067         vlc_dvbpsi_reset( p_demux );
1068         vlc_mutex_destroy( &p_sys->csa_lock );
1069         free( p_sys );
1070         return VLC_EGENERIC;
1071     }
1072 #else
1073     pat->psi->handle = dvbpsi_AttachPAT( PATCallBack, p_demux );
1074 #endif
1075     if( p_sys->b_dvb_meta )
1076     {
1077         ts_pid_t *sdt = &p_sys->pid[0x11];
1078         ts_pid_t *eit = &p_sys->pid[0x12];
1079
1080         PIDInit( sdt, true, NULL );
1081 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1082         VLC_DVBPSI_DEMUX_TABLE_INIT( sdt, p_demux )
1083 #else
1084         sdt->psi->handle =
1085             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
1086                                 p_demux );
1087 #endif
1088         PIDInit( eit, true, NULL );
1089 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1090         VLC_DVBPSI_DEMUX_TABLE_INIT( eit, p_demux )
1091 #else
1092         eit->psi->handle =
1093             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
1094                                 p_demux );
1095 #endif
1096         ts_pid_t *tdt = &p_sys->pid[0x14];
1097         PIDInit( tdt, true, NULL );
1098 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1099         VLC_DVBPSI_DEMUX_TABLE_INIT( tdt, p_demux )
1100 #else
1101         tdt->psi->handle =
1102             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
1103                                 p_demux );
1104 #endif
1105
1106         if( p_sys->b_access_control )
1107         {
1108             if( SetPIDFilter( p_demux, 0x11, true ) ||
1109                 SetPIDFilter( p_demux, 0x14, true ) ||
1110                 SetPIDFilter( p_demux, 0x12, true ) )
1111                 p_sys->b_access_control = false;
1112         }
1113     }
1114
1115 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1116 # undef VLC_DVBPSI_DEMUX_TABLE_INIT
1117 #endif
1118
1119     /* Init PMT array */
1120     TAB_INIT( p_sys->i_pmt, p_sys->pmt );
1121     p_sys->i_pmt_es = 0;
1122
1123     /* Read config */
1124     p_sys->b_es_id_pid = var_CreateGetBool( p_demux, "ts-es-id-pid" );
1125
1126     p_sys->b_trust_pcr = var_CreateGetBool( p_demux, "ts-trust-pcr" );
1127
1128     /* We handle description of an extra PMT */
1129     char* psz_string = var_CreateGetString( p_demux, "ts-extra-pmt" );
1130     p_sys->b_user_pmt = false;
1131     if( psz_string && *psz_string )
1132         UserPmt( p_demux, psz_string );
1133     free( psz_string );
1134
1135     psz_string = var_CreateGetStringCommand( p_demux, "ts-csa-ck" );
1136     if( psz_string && *psz_string )
1137     {
1138         int i_res;
1139         char* psz_csa2;
1140
1141         p_sys->csa = csa_New();
1142
1143         psz_csa2 = var_CreateGetStringCommand( p_demux, "ts-csa2-ck" );
1144         i_res = csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, true );
1145         if( i_res == VLC_SUCCESS && psz_csa2 && *psz_csa2 )
1146         {
1147             if( csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_csa2, false ) != VLC_SUCCESS )
1148             {
1149                 csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
1150             }
1151         }
1152         else if ( i_res == VLC_SUCCESS )
1153         {
1154             csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
1155         }
1156         else
1157         {
1158             csa_Delete( p_sys->csa );
1159             p_sys->csa = NULL;
1160         }
1161
1162         if( p_sys->csa )
1163         {
1164             var_AddCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, (void *)1 );
1165             var_AddCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
1166
1167             int i_pkt = var_CreateGetInteger( p_demux, "ts-csa-pkt" );
1168             if( i_pkt < 4 || i_pkt > 188 )
1169             {
1170                 msg_Err( p_demux, "wrong packet size %d specified.", i_pkt );
1171                 msg_Warn( p_demux, "using default packet size of 188 bytes" );
1172                 p_sys->i_csa_pkt_size = 188;
1173             }
1174             else
1175                 p_sys->i_csa_pkt_size = i_pkt;
1176             msg_Dbg( p_demux, "decrypting %d bytes of packet", p_sys->i_csa_pkt_size );
1177         }
1178         free( psz_csa2 );
1179     }
1180     free( psz_string );
1181
1182     p_sys->b_split_es = var_InheritBool( p_demux, "ts-split-es" );
1183
1184     p_sys->b_canseek = false;
1185     p_sys->b_canfastseek = false;
1186     p_sys->b_force_seek_per_percent = var_InheritBool( p_demux, "ts-seek-percent" );
1187
1188     p_sys->arib.e_mode = var_InheritInteger( p_demux, "ts-arib" );
1189
1190     stream_Control( p_sys->stream, STREAM_CAN_SEEK, &p_sys->b_canseek );
1191     stream_Control( p_sys->stream, STREAM_CAN_FASTSEEK, &p_sys->b_canfastseek );
1192
1193     /* Preparse time */
1194     if( p_sys->b_canseek )
1195     {
1196         p_sys->es_creation = NO_ES;
1197         while( !p_sys->i_pmt_es && !p_sys->b_end_preparse )
1198             if( Demux( p_demux ) != VLC_DEMUXER_SUCCESS )
1199                 break;
1200     }
1201
1202     p_sys->es_creation = ( p_sys->b_access_control ? CREATE_ES : DELAY_ES );
1203
1204     return VLC_SUCCESS;
1205 }
1206
1207 /*****************************************************************************
1208  * Close
1209  *****************************************************************************/
1210 static void Close( vlc_object_t *p_this )
1211 {
1212     demux_t     *p_demux = (demux_t*)p_this;
1213     demux_sys_t *p_sys = p_demux->p_sys;
1214
1215     msg_Dbg( p_demux, "pid list:" );
1216     for( int i = 0; i < 8192; i++ )
1217     {
1218         ts_pid_t *pid = &p_sys->pid[i];
1219
1220         if( pid->b_valid && pid->psi )
1221         {
1222             switch( pid->i_pid )
1223             {
1224             case 0: /* PAT */
1225 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1226                 if( dvbpsi_decoder_present( pid->psi->handle ) )
1227                     dvbpsi_pat_detach( pid->psi->handle );
1228                 dvbpsi_delete( pid->psi->handle );
1229                 pid->psi->handle = NULL;
1230 #else
1231                 dvbpsi_DetachPAT( pid->psi->handle );
1232 #endif
1233                 free( pid->psi );
1234                 break;
1235             case 1: /* CAT */
1236                 free( pid->psi );
1237                 break;
1238             default:
1239                 if( p_sys->b_dvb_meta && ( pid->i_pid == 0x11 || pid->i_pid == 0x12 || pid->i_pid == 0x14 ) )
1240                 {
1241                     /* SDT or EIT or TDT */
1242                     dvbpsi_DetachDemux( pid->psi->handle );
1243 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1244                     dvbpsi_delete( pid->psi->handle );
1245                     pid->psi->handle = NULL;
1246 #endif
1247                     free( pid->psi );
1248                 }
1249                 else
1250                 {
1251                     PIDClean( p_demux, pid );
1252                 }
1253                 break;
1254             }
1255         }
1256         else if( pid->b_valid && pid->es )
1257         {
1258             PIDClean( p_demux, pid );
1259         }
1260
1261         if( pid->b_seen )
1262         {
1263             msg_Dbg( p_demux, "  - pid[%d] seen", pid->i_pid );
1264         }
1265
1266         /* too much */
1267         if( pid->i_pid > 0 )
1268             SetPIDFilter( p_demux, pid->i_pid, false );
1269     }
1270
1271     vlc_mutex_lock( &p_sys->csa_lock );
1272     if( p_sys->csa )
1273     {
1274         var_DelCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, NULL );
1275         var_DelCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
1276         csa_Delete( p_sys->csa );
1277     }
1278     vlc_mutex_unlock( &p_sys->csa_lock );
1279
1280     TAB_CLEAN( p_sys->i_pmt, p_sys->pmt );
1281
1282     ARRAY_RESET( p_sys->programs );
1283
1284 #ifdef HAVE_ARIBB24
1285     if ( p_sys->arib.p_instance )
1286         arib_instance_destroy( p_sys->arib.p_instance );
1287 #endif
1288
1289     if ( p_sys->arib.b25stream )
1290     {
1291         p_sys->arib.b25stream->p_source = NULL; /* don't chain kill demuxer's source */
1292         stream_Delete( p_sys->arib.b25stream );
1293     }
1294
1295     vlc_mutex_destroy( &p_sys->csa_lock );
1296     free( p_sys );
1297 }
1298
1299 /*****************************************************************************
1300  * ChangeKeyCallback: called when changing the odd encryption key on the fly.
1301  *****************************************************************************/
1302 static int ChangeKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
1303                            vlc_value_t oldval, vlc_value_t newval,
1304                            void *p_data )
1305 {
1306     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
1307     demux_t     *p_demux = (demux_t*)p_this;
1308     demux_sys_t *p_sys = p_demux->p_sys;
1309     int         i_tmp = (intptr_t)p_data;
1310
1311     vlc_mutex_lock( &p_sys->csa_lock );
1312     if ( i_tmp )
1313         i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, true );
1314     else
1315         i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, false );
1316
1317     vlc_mutex_unlock( &p_sys->csa_lock );
1318     return i_tmp;
1319 }
1320
1321 /*****************************************************************************
1322  * Demux:
1323  *****************************************************************************/
1324 static int Demux( demux_t *p_demux )
1325 {
1326     demux_sys_t *p_sys = p_demux->p_sys;
1327     bool b_wait_es = p_sys->i_pmt_es <= 0;
1328
1329     /* If we had no PAT within 140ms, create PAT/PMT from probed streams */
1330     if( p_sys->i_pmt_es == 0 && !p_sys->pid[0].b_seen && p_sys->patfix.b_pat_deadline )
1331         MissingPATPMTFixup( p_demux );
1332
1333     /* We read at most 100 TS packet or until a frame is completed */
1334     for( int i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
1335     {
1336         bool         b_frame = false;
1337         block_t     *p_pkt;
1338         if( !(p_pkt = ReadTSPacket( p_demux )) )
1339         {
1340             return VLC_DEMUXER_EOF;
1341         }
1342
1343         if( p_sys->b_start_record )
1344         {
1345             /* Enable recording once synchronized */
1346             stream_Control( p_sys->stream, STREAM_SET_RECORD_STATE, true, "ts" );
1347             p_sys->b_start_record = false;
1348         }
1349
1350         /* Parse the TS packet */
1351         ts_pid_t *p_pid = &p_sys->pid[PIDGet( p_pkt )];
1352
1353         /* Probe streams to build PAT/PMT after 140ms in case we don't see any PAT */
1354         if( !p_sys->pid[0].b_seen &&
1355             (p_pid->probed.i_type == 0 || p_pid->i_pid == p_sys->patfix.i_timesourcepid) &&
1356             (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
1357             (p_pkt->p_buffer[3] & 0xD0) == 0x10 )  /* Has payload but is not encrypted */
1358         {
1359             ProbePES( p_demux, p_pid, p_pkt->p_buffer + TS_HEADER_SIZE,
1360                       p_pkt->i_buffer - TS_HEADER_SIZE, p_pkt->p_buffer[3] & 0x20 /* Adaptation field */);
1361         }
1362
1363         if( p_pid->b_valid )
1364         {
1365             if( p_pid->psi )
1366             {
1367                 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 ) ) )
1368                 {
1369                     dvbpsi_PushPacket( p_pid->psi->handle, p_pkt->p_buffer );
1370                 }
1371                 else
1372                 {
1373                     for( int i_prg = 0; i_prg < p_pid->psi->i_prg; i_prg++ )
1374                     {
1375                         dvbpsi_PushPacket( p_pid->psi->prg[i_prg]->handle,
1376                                            p_pkt->p_buffer );
1377                     }
1378                 }
1379                 block_Release( p_pkt );
1380             }
1381             else
1382             {
1383                 p_sys->b_end_preparse = true;
1384                 if( p_sys->es_creation == DELAY_ES ) /* No longer delay ES since that pid's program sends data */
1385                 {
1386                     AddAndCreateES( p_demux, NULL );
1387                 }
1388                 b_frame = GatherData( p_demux, p_pid, p_pkt );
1389
1390                 if( p_sys->b_default_selection )
1391                 {
1392                     p_sys->b_default_selection = false;
1393                     assert(p_sys->programs.i_size == 1);
1394                     if( p_sys->programs.p_elems[0] != p_pid->i_owner_number )
1395                     {
1396                         SetPrgFilter( p_demux, p_sys->programs.p_elems[0], false );
1397                         SetPrgFilter( p_demux, p_pid->i_owner_number, true );
1398                         p_sys->programs.p_elems[0] = p_pid->i_owner_number;
1399                     }
1400                 }
1401             }
1402         }
1403         else
1404         {
1405             if( !p_pid->b_seen )
1406             {
1407                 msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid );
1408             }
1409             /* We have to handle PCR if present */
1410             PCRHandle( p_demux, p_pid, p_pkt );
1411             block_Release( p_pkt );
1412         }
1413         p_pid->b_seen = true;
1414
1415         if( b_frame || ( b_wait_es && p_sys->i_pmt_es > 0 ) )
1416             break;
1417     }
1418
1419     demux_UpdateTitleFromStream( p_demux );
1420     return VLC_DEMUXER_SUCCESS;
1421 }
1422
1423 /*****************************************************************************
1424  * Control:
1425  *****************************************************************************/
1426 static int DVBEventInformation( demux_t *p_demux, int64_t *pi_time, int64_t *pi_length )
1427 {
1428     demux_sys_t *p_sys = p_demux->p_sys;
1429     if( pi_length )
1430         *pi_length = 0;
1431     if( pi_time )
1432         *pi_time = 0;
1433
1434     if( p_sys->i_dvb_length > 0 )
1435     {
1436         const int64_t t = mdate() + p_sys->i_tdt_delta;
1437
1438         if( p_sys->i_dvb_start <= t && t < p_sys->i_dvb_start + p_sys->i_dvb_length )
1439         {
1440             if( pi_length )
1441                 *pi_length = p_sys->i_dvb_length;
1442             if( pi_time )
1443                 *pi_time   = t - p_sys->i_dvb_start;
1444             return VLC_SUCCESS;
1445         }
1446     }
1447     return VLC_EGENERIC;
1448 }
1449
1450 static int Control( demux_t *p_demux, int i_query, va_list args )
1451 {
1452     demux_sys_t *p_sys = p_demux->p_sys;
1453     double f, *pf;
1454     bool b_bool, *pb_bool;
1455     int64_t i64;
1456     int64_t *pi64;
1457     int i_int;
1458     ts_prg_psi_t *p_prg;
1459     int i_first_program = ( p_sys->programs.i_size ) ? p_sys->programs.p_elems[0] : 0;
1460
1461     if( PREPARSING || !i_first_program || p_sys->b_default_selection )
1462     {
1463         /* Set default program for preparse time (no program has been selected) */
1464         for( int i=0; i<p_sys->i_pmt; i++ )
1465         {
1466             for( int j=0; j<p_sys->pmt[i]->psi->i_prg; j++ )
1467             {
1468                 p_prg = p_sys->pmt[i]->psi->prg[j];
1469                 if( ( p_prg->pcr.i_first > -1 || p_prg->pcr.i_first_dts > VLC_TS_INVALID ) && p_prg->i_last_dts > 0 )
1470                 {
1471                     i_first_program = p_prg->i_number;
1472                     break;
1473                 }
1474             }
1475         }
1476     }
1477
1478     switch( i_query )
1479     {
1480     case DEMUX_GET_POSITION:
1481         pf = (double*) va_arg( args, double* );
1482
1483         /* Access control test is because EPG for recordings is not relevant */
1484         if( p_sys->b_dvb_meta && p_sys->b_access_control )
1485         {
1486             int64_t i_time, i_length;
1487             if( !DVBEventInformation( p_demux, &i_time, &i_length ) && i_length > 0 )
1488             {
1489                 *pf = (double)i_time/(double)i_length;
1490                 return VLC_SUCCESS;
1491             }
1492         }
1493
1494         if( (p_prg = GetProgramByID( p_sys, i_first_program )) &&
1495              p_prg->pcr.i_first > -1 && p_prg->i_last_dts > VLC_TS_INVALID &&
1496              p_prg->pcr.i_current > -1 )
1497         {
1498             double i_length = TimeStampWrapAround( p_prg,
1499                                                    p_prg->i_last_dts ) - p_prg->pcr.i_first;
1500             i_length += p_prg->pcr.i_pcroffset;
1501             double i_pos = TimeStampWrapAround( p_prg,
1502                                                 p_prg->pcr.i_current ) - p_prg->pcr.i_first;
1503             *pf = i_pos / i_length;
1504             return VLC_SUCCESS;
1505         }
1506
1507         if( (i64 = stream_Size( p_sys->stream) ) > 0 )
1508         {
1509             int64_t offset = stream_Tell( p_sys->stream );
1510             *pf = (double)offset / (double)i64;
1511             return VLC_SUCCESS;
1512         }
1513         break;
1514
1515     case DEMUX_SET_POSITION:
1516         f = (double) va_arg( args, double );
1517
1518         if(!p_sys->b_canseek)
1519             break;
1520
1521         if( p_sys->b_dvb_meta && p_sys->b_access_control &&
1522            !p_sys->b_force_seek_per_percent &&
1523            (p_prg = GetProgramByID( p_sys, i_first_program )) )
1524         {
1525             int64_t i_time, i_length;
1526             if( !DVBEventInformation( p_demux, &i_time, &i_length ) &&
1527                  i_length > 0 && !SeekToTime( p_demux, p_prg, TO_SCALE(i_length) * f ) )
1528             {
1529                 ReadyQueuesPostSeek( p_sys );
1530                 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
1531                                 TO_SCALE(i_length) * f );
1532                 return VLC_SUCCESS;
1533             }
1534         }
1535
1536         if( !p_sys->b_force_seek_per_percent &&
1537             (p_prg = GetProgramByID( p_sys, i_first_program )) &&
1538              p_prg->pcr.i_first > -1 && p_prg->i_last_dts > VLC_TS_INVALID &&
1539              p_prg->pcr.i_current > -1 )
1540         {
1541             double i_length = TimeStampWrapAround( p_prg,
1542                                                    p_prg->i_last_dts ) - p_prg->pcr.i_first;
1543             if( !SeekToTime( p_demux, p_prg, p_prg->pcr.i_first + i_length * f ) )
1544             {
1545                 ReadyQueuesPostSeek( p_sys );
1546                 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
1547                                 FROM_SCALE(p_prg->pcr.i_first + i_length * f) );
1548                 return VLC_SUCCESS;
1549             }
1550         }
1551
1552         i64 = stream_Size( p_sys->stream );
1553         if( i64 > 0 &&
1554             stream_Seek( p_sys->stream, (int64_t)(i64 * f) ) == VLC_SUCCESS )
1555         {
1556             ReadyQueuesPostSeek( p_sys );
1557             return VLC_SUCCESS;
1558         }
1559         break;
1560
1561     case DEMUX_SET_TIME:
1562         i64 = (int64_t)va_arg( args, int64_t );
1563
1564         if( p_sys->b_canseek &&
1565            (p_prg = GetProgramByID( p_sys, i_first_program )) &&
1566             p_prg->pcr.i_first > -1 &&
1567            !SeekToTime( p_demux, p_prg, p_prg->pcr.i_first + TO_SCALE(i64) ) )
1568         {
1569             ReadyQueuesPostSeek( p_sys );
1570             es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
1571                             FROM_SCALE(p_prg->pcr.i_first) + i64 - VLC_TS_0 );
1572             return VLC_SUCCESS;
1573         }
1574         break;
1575
1576     case DEMUX_GET_TIME:
1577         pi64 = (int64_t*)va_arg( args, int64_t * );
1578
1579         if( p_sys->b_dvb_meta && p_sys->b_access_control )
1580         {
1581             if( !DVBEventInformation( p_demux, pi64, NULL ) )
1582                 return VLC_SUCCESS;
1583         }
1584
1585         if( (p_prg = GetProgramByID( p_sys, i_first_program )) &&
1586              p_prg->pcr.i_current > -1 && p_prg->pcr.i_first > -1 )
1587         {
1588             int64_t i_pcr = TimeStampWrapAround( p_prg, p_prg->pcr.i_current );
1589             *pi64 = FROM_SCALE(i_pcr - p_prg->pcr.i_first);
1590             return VLC_SUCCESS;
1591         }
1592         break;
1593
1594     case DEMUX_GET_LENGTH:
1595         pi64 = (int64_t*)va_arg( args, int64_t * );
1596
1597         if( p_sys->b_dvb_meta && p_sys->b_access_control )
1598         {
1599             if( !DVBEventInformation( p_demux, NULL, pi64 ) )
1600                 return VLC_SUCCESS;
1601         }
1602
1603         if( (p_prg = GetProgramByID( p_sys, i_first_program )) &&
1604            ( p_prg->pcr.i_first > -1 || p_prg->pcr.i_first_dts > VLC_TS_INVALID ) &&
1605              p_prg->i_last_dts > 0 )
1606         {
1607             int64_t i_start = (p_prg->pcr.i_first > -1) ? p_prg->pcr.i_first :
1608                               TO_SCALE(p_prg->pcr.i_first_dts);
1609             int64_t i_last = TimeStampWrapAround( p_prg, p_prg->i_last_dts );
1610             i_last += p_prg->pcr.i_pcroffset;
1611             *pi64 = FROM_SCALE(i_last - i_start);
1612             return VLC_SUCCESS;
1613         }
1614         break;
1615
1616     case DEMUX_SET_GROUP:
1617     {
1618         vlc_list_t *p_list;
1619
1620         i_int = (int)va_arg( args, int );
1621         p_list = (vlc_list_t *)va_arg( args, vlc_list_t * );
1622         msg_Dbg( p_demux, "DEMUX_SET_GROUP %d %p", i_int, p_list );
1623
1624         if( i_int != 0 ) /* If not default program */
1625         {
1626             /* Deselect/filter current ones */
1627             for( int i=0; i<p_sys->programs.i_size; i++ )
1628                 SetPrgFilter( p_demux, p_sys->programs.p_elems[i], false );
1629             ARRAY_RESET( p_sys->programs );
1630
1631             if( i_int != -1 )
1632             {
1633                 ARRAY_APPEND( p_sys->programs, i_int );
1634             }
1635             else if( likely( p_list != NULL ) )
1636             {
1637                 for( int i = 0; i < p_list->i_count; i++ )
1638                    ARRAY_APPEND( p_sys->programs, p_list->p_values[i].i_int );
1639             }
1640
1641             /* Select/filter current ones */
1642             for( int i=0; i<p_sys->programs.i_size; i++ )
1643             {
1644                 msg_Dbg( p_demux, "Program %d in new selection", p_sys->programs.p_elems[i] );
1645                 SetPrgFilter( p_demux, p_sys->programs.p_elems[i], true );
1646             }
1647
1648             p_sys->b_default_selection = false;
1649         }
1650
1651         return VLC_SUCCESS;
1652     }
1653
1654     case DEMUX_GET_TITLE_INFO:
1655     {
1656         struct input_title_t ***v = va_arg( args, struct input_title_t*** );
1657         int *c = va_arg( args, int * );
1658
1659         *va_arg( args, int* ) = 0; /* Title offset */
1660         *va_arg( args, int* ) = 0; /* Chapter offset */
1661         return stream_Control( p_sys->stream, STREAM_GET_TITLE_INFO, v, c );
1662     }
1663
1664     case DEMUX_SET_TITLE:
1665         return stream_vaControl( p_sys->stream, STREAM_SET_TITLE, args );
1666
1667     case DEMUX_SET_SEEKPOINT:
1668         return stream_vaControl( p_sys->stream, STREAM_SET_SEEKPOINT, args );
1669
1670     case DEMUX_GET_META:
1671         return stream_vaControl( p_sys->stream, STREAM_GET_META, args );
1672
1673     case DEMUX_CAN_RECORD:
1674         pb_bool = (bool*)va_arg( args, bool * );
1675         *pb_bool = true;
1676         return VLC_SUCCESS;
1677
1678     case DEMUX_SET_RECORD_STATE:
1679         b_bool = (bool)va_arg( args, int );
1680
1681         if( !b_bool )
1682             stream_Control( p_sys->stream, STREAM_SET_RECORD_STATE, false );
1683         p_sys->b_start_record = b_bool;
1684         return VLC_SUCCESS;
1685
1686     case DEMUX_GET_SIGNAL:
1687         return stream_vaControl( p_sys->stream, STREAM_GET_SIGNAL, args );
1688
1689     default:
1690         break;
1691     }
1692
1693     return VLC_EGENERIC;
1694 }
1695
1696 /*****************************************************************************
1697  *
1698  *****************************************************************************/
1699 static int UserPmt( demux_t *p_demux, const char *psz_fmt )
1700 {
1701     demux_sys_t *p_sys = p_demux->p_sys;
1702     char *psz_dup = strdup( psz_fmt );
1703     char *psz = psz_dup;
1704     int  i_pid;
1705     int  i_number;
1706     ts_prg_psi_t *prg = NULL;
1707
1708     if( !psz_dup )
1709         return VLC_ENOMEM;
1710
1711     /* Parse PID */
1712     i_pid = strtol( psz, &psz, 0 );
1713     if( i_pid < 2 || i_pid >= 8192 )
1714         goto error;
1715
1716     /* Parse optional program number */
1717     i_number = 0;
1718     if( *psz == ':' )
1719         i_number = strtol( &psz[1], &psz, 0 );
1720
1721     /* */
1722     ts_pid_t *pmt = &p_sys->pid[i_pid];
1723
1724     msg_Dbg( p_demux, "user pmt specified (pid=%d,number=%d)", i_pid, i_number );
1725     PIDInit( pmt, true, NULL );
1726
1727     /* Dummy PMT */
1728     prg = calloc( 1, sizeof( ts_prg_psi_t ) );
1729     if( !prg )
1730         goto error;
1731
1732     prg->i_pid_pcr  = -1;
1733     prg->i_pid_pmt  = -1;
1734     prg->i_version  = -1;
1735     prg->i_number   = i_number != 0 ? i_number : TS_USER_PMT_NUMBER;
1736 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1737     prg->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
1738     if( !prg->handle )
1739         goto error;
1740     prg->handle->p_sys = (void *) VLC_OBJECT(p_demux);
1741     if( !dvbpsi_pmt_attach( prg->handle,
1742                             ((i_number != TS_USER_PMT_NUMBER ? i_number : 1)),
1743                             PMTCallBack, p_demux ) )
1744     {
1745         dvbpsi_delete( prg->handle );
1746         prg->handle = NULL;
1747         goto error;
1748     }
1749 #else
1750     prg->handle     = dvbpsi_AttachPMT(
1751         ((i_number != TS_USER_PMT_NUMBER) ? i_number : 1),
1752         PMTCallBack, p_demux );
1753 #endif
1754     TAB_APPEND( pmt->psi->i_prg, pmt->psi->prg, prg );
1755
1756     psz = strchr( psz, '=' );
1757     if( psz )
1758         psz++;
1759     while( psz && *psz )
1760     {
1761         char *psz_next = strchr( psz, ',' );
1762         int i_pid;
1763
1764         if( psz_next )
1765             *psz_next++ = '\0';
1766
1767         i_pid = strtol( psz, &psz, 0 );
1768         if( *psz != ':' || i_pid < 2 || i_pid >= 8192 )
1769             goto next;
1770
1771         char *psz_opt = &psz[1];
1772         if( !strcmp( psz_opt, "pcr" ) )
1773         {
1774             prg->i_pid_pcr = i_pid;
1775         }
1776         else if( !p_sys->pid[i_pid].b_valid )
1777         {
1778             ts_pid_t *pid = &p_sys->pid[i_pid];
1779
1780             char *psz_arg = strchr( psz_opt, '=' );
1781             if( psz_arg )
1782                 *psz_arg++ = '\0';
1783
1784             PIDInit( pid, false, pmt->psi);
1785             if( prg->i_pid_pcr <= 0 )
1786                 prg->i_pid_pcr = i_pid;
1787
1788             if( psz_arg && strlen( psz_arg ) == 4 )
1789             {
1790                 const vlc_fourcc_t i_codec = VLC_FOURCC( psz_arg[0], psz_arg[1],
1791                                                          psz_arg[2], psz_arg[3] );
1792                 int i_cat = UNKNOWN_ES;
1793                 es_format_t *fmt = &pid->es->fmt;
1794
1795                 if( !strcmp( psz_opt, "video" ) )
1796                     i_cat = VIDEO_ES;
1797                 else if( !strcmp( psz_opt, "audio" ) )
1798                     i_cat = AUDIO_ES;
1799                 else if( !strcmp( psz_opt, "spu" ) )
1800                     i_cat = SPU_ES;
1801
1802                 es_format_Init( fmt, i_cat, i_codec );
1803                 fmt->b_packetized = false;
1804             }
1805             else
1806             {
1807                 const int i_stream_type = strtol( psz_opt, NULL, 0 );
1808                 PIDFillFormat( &pid->es->fmt, i_stream_type );
1809             }
1810             pid->es->fmt.i_group = i_number;
1811             if( p_sys->b_es_id_pid )
1812                 pid->es->fmt.i_id = i_pid;
1813
1814             if( pid->es->fmt.i_cat != UNKNOWN_ES )
1815             {
1816                 msg_Dbg( p_demux, "  * es pid=%d fcc=%4.4s", i_pid,
1817                          (char*)&pid->es->fmt.i_codec );
1818                 pid->es->id = es_out_Add( p_demux->out,
1819                                           &pid->es->fmt );
1820                 p_sys->i_pmt_es++;
1821             }
1822         }
1823
1824     next:
1825         psz = psz_next;
1826     }
1827
1828     p_sys->b_user_pmt = true;
1829     TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
1830     free( psz_dup );
1831     return VLC_SUCCESS;
1832
1833 error:
1834     free( prg );
1835     free( psz_dup );
1836     return VLC_EGENERIC;
1837 }
1838
1839 static int SetPIDFilter( demux_t *p_demux, int i_pid, bool b_selected )
1840 {
1841     demux_sys_t *p_sys = p_demux->p_sys;
1842
1843     if( !p_sys->b_access_control )
1844         return VLC_EGENERIC;
1845
1846     return stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_STATE,
1847                            i_pid, b_selected );
1848 }
1849
1850 static void SetPrgFilter( demux_t *p_demux, int i_prg_id, bool b_selected )
1851 {
1852     demux_sys_t *p_sys = p_demux->p_sys;
1853     ts_prg_psi_t *p_prg = NULL;
1854     int i_pmt_pid = -1;
1855
1856     /* Search pmt to be unselected */
1857     for( int i = 0; i < p_sys->i_pmt; i++ )
1858     {
1859         ts_pid_t *pmt = p_sys->pmt[i];
1860
1861         for( int i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
1862         {
1863             if( pmt->psi->prg[i_prg]->i_number == i_prg_id )
1864             {
1865                 i_pmt_pid = p_sys->pmt[i]->i_pid;
1866                 p_prg = p_sys->pmt[i]->psi->prg[i_prg];
1867                 break;
1868             }
1869         }
1870         if( i_pmt_pid > 0 )
1871             break;
1872     }
1873     if( i_pmt_pid <= 0 )
1874         return;
1875     assert( p_prg );
1876
1877     p_prg->pcr.b_disable = !p_sys->b_trust_pcr;
1878
1879     SetPIDFilter( p_demux, i_pmt_pid, b_selected );
1880     if( p_prg->i_pid_pcr > 0 )
1881         SetPIDFilter( p_demux, p_prg->i_pid_pcr, b_selected );
1882
1883     /* All ES */
1884     for( int i = 2; i < 8192; i++ )
1885     {
1886         ts_pid_t *pid = &p_sys->pid[i];
1887
1888         if( !pid->b_valid || pid->psi )
1889             continue;
1890
1891         for( int i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
1892         {
1893             if( pid->p_owner->prg[i_prg]->i_pid_pmt == i_pmt_pid && pid->es->id )
1894             {
1895                 /* We only remove/select es that aren't defined by extra pmt */
1896                 SetPIDFilter( p_demux, i, b_selected );
1897                 break;
1898             }
1899         }
1900     }
1901 }
1902
1903 static void PIDInit( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner )
1904 {
1905     bool b_old_valid = pid->b_valid;
1906
1907     pid->b_valid    = true;
1908     pid->i_cc       = 0xff;
1909     pid->b_scrambled = false;
1910     pid->p_owner    = p_owner;
1911     pid->i_owner_number = 0;
1912
1913     TAB_INIT( pid->i_extra_es, pid->extra_es );
1914
1915     if( b_psi )
1916     {
1917         pid->es  = NULL;
1918
1919         if( !b_old_valid )
1920         {
1921             pid->psi = xmalloc( sizeof( ts_psi_t ) );
1922             pid->psi->handle = NULL;
1923             TAB_INIT( pid->psi->i_prg, pid->psi->prg );
1924         }
1925         assert( pid->psi );
1926
1927         pid->psi->i_pat_version  = -1;
1928         pid->psi->i_sdt_version  = -1;
1929         if( p_owner )
1930         {
1931             ts_prg_psi_t *prg = malloc( sizeof( ts_prg_psi_t ) );
1932             if( !prg )
1933                 return;
1934             /* PMT */
1935             prg->i_version  = -1;
1936             prg->i_number   = -1;
1937             prg->i_pid_pcr  = -1;
1938             prg->i_pid_pmt  = -1;
1939             prg->iod        = NULL;
1940             prg->handle     = NULL;
1941
1942             prg->i_last_dts = -1;
1943
1944             prg->pcr.i_current = -1;
1945             prg->pcr.i_first  = -1;
1946             prg->pcr.b_disable = false;
1947             prg->pcr.i_first_dts = VLC_TS_INVALID;
1948             prg->pcr.i_pcroffset = -1;
1949             TAB_APPEND( pid->psi->i_prg, pid->psi->prg, prg );
1950         }
1951     }
1952     else
1953     {
1954         pid->psi = NULL;
1955         pid->es  = calloc( 1, sizeof( ts_es_t ) );
1956         if( !pid->es )
1957             return;
1958
1959         es_format_Init( &pid->es->fmt, UNKNOWN_ES, 0 );
1960         pid->es->data_type = TS_ES_DATA_PES;
1961         pid->es->pp_last = &pid->es->p_data;
1962     }
1963 }
1964
1965 static void PIDClean( demux_t *p_demux, ts_pid_t *pid )
1966 {
1967     demux_sys_t *p_sys = p_demux->p_sys;
1968     es_out_t *out = p_demux->out;
1969
1970     if( pid->psi )
1971     {
1972         if( pid->psi->handle )
1973         {
1974 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1975             if( dvbpsi_decoder_present( pid->psi->handle ) )
1976                 dvbpsi_pmt_detach( pid->psi->handle );
1977             dvbpsi_delete( pid->psi->handle );
1978             pid->psi->handle = NULL;
1979 #else
1980             dvbpsi_DetachPMT( pid->psi->handle );
1981 #endif
1982         }
1983         for( int i = 0; i < pid->psi->i_prg; i++ )
1984         {
1985             if( pid->psi->prg[i]->iod )
1986                 IODFree( pid->psi->prg[i]->iod );
1987             if( pid->psi->prg[i]->handle )
1988             {
1989 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1990                 if( dvbpsi_decoder_present( pid->psi->prg[i]->handle ) )
1991                     dvbpsi_pmt_detach( pid->psi->prg[i]->handle );
1992                 dvbpsi_delete( pid->psi->prg[i]->handle );
1993 #else
1994                 dvbpsi_DetachPMT( pid->psi->prg[i]->handle );
1995 #endif
1996             }
1997             free( pid->psi->prg[i] );
1998         }
1999         free( pid->psi->prg );
2000         free( pid->psi );
2001     }
2002     else
2003     {
2004         if( pid->es->id )
2005         {
2006             es_out_Del( out, pid->es->id );
2007             p_sys->i_pmt_es--;
2008         }
2009
2010         if( pid->es->p_data )
2011             block_ChainRelease( pid->es->p_data );
2012
2013         if( pid->es->p_prepcr_outqueue )
2014             block_ChainRelease( pid->es->p_prepcr_outqueue );
2015
2016         es_format_Clean( &pid->es->fmt );
2017
2018         free( pid->es );
2019
2020         for( int i = 0; i < pid->i_extra_es; i++ )
2021         {
2022             if( pid->extra_es[i]->id )
2023             {
2024                 es_out_Del( out, pid->extra_es[i]->id );
2025                 p_sys->i_pmt_es--;
2026             }
2027
2028             if( pid->extra_es[i]->p_data )
2029                 block_ChainRelease( pid->extra_es[i]->p_data );
2030
2031             es_format_Clean( &pid->extra_es[i]->fmt );
2032
2033             free( pid->extra_es[i] );
2034         }
2035         if( pid->i_extra_es )
2036             free( pid->extra_es );
2037     }
2038
2039     pid->b_valid = false;
2040 }
2041
2042 static int16_t read_opus_flag(uint8_t **buf, size_t *len)
2043 {
2044     if (*len < 2)
2045         return -1;
2046
2047     int16_t ret = ((*buf)[0] << 8) | (*buf)[1];
2048
2049     *len -= 2;
2050     *buf += 2;
2051
2052     if (ret & (3<<13))
2053         ret = -1;
2054
2055     return ret;
2056 }
2057
2058 static block_t *Opus_Parse(demux_t *demux, block_t *block)
2059 {
2060     block_t *out = NULL;
2061     block_t **last = NULL;
2062
2063     uint8_t *buf = block->p_buffer;
2064     size_t len = block->i_buffer;
2065
2066     while (len > 3 && ((buf[0] << 3) | (buf[1] >> 5)) == 0x3ff) {
2067         int16_t start_trim = 0, end_trim = 0;
2068         int start_trim_flag        = (buf[1] >> 4) & 1;
2069         int end_trim_flag          = (buf[1] >> 3) & 1;
2070         int control_extension_flag = (buf[1] >> 2) & 1;
2071
2072         len -= 2;
2073         buf += 2;
2074
2075         unsigned au_size = 0;
2076         while (len--) {
2077             int c = *buf++;
2078             au_size += c;
2079             if (c != 0xff)
2080                 break;
2081         }
2082
2083         if (start_trim_flag) {
2084             start_trim = read_opus_flag(&buf, &len);
2085             if (start_trim < 0) {
2086                 msg_Err(demux, "Invalid start trimming flag");
2087             }
2088         }
2089         if (end_trim_flag) {
2090             end_trim = read_opus_flag(&buf, &len);
2091             if (end_trim < 0) {
2092                 msg_Err(demux, "Invalid end trimming flag");
2093             }
2094         }
2095         if (control_extension_flag && len) {
2096             unsigned l = *buf++; len--;
2097             if (l > len) {
2098                 msg_Err(demux, "Invalid control extension length %d > %zu", l, len);
2099                 break;
2100             }
2101             buf += l;
2102             len -= l;
2103         }
2104
2105         if (!au_size || au_size > len) {
2106             msg_Err(demux, "Invalid Opus AU size %d (PES %zu)", au_size, len);
2107             break;
2108         }
2109
2110         block_t *au = block_Alloc(au_size);
2111         if (!au)
2112             break;
2113         memcpy(au->p_buffer, buf, au_size);
2114         block_CopyProperties(au, block);
2115         au->p_next = NULL;
2116
2117         if (!out)
2118             out = au;
2119         else
2120             *last = au;
2121         last = &au->p_next;
2122
2123         au->i_nb_samples = opus_frame_duration(buf, au_size);
2124         if (end_trim && end_trim <= au->i_nb_samples)
2125             au->i_length = end_trim; /* Blatant abuse of the i_length field. */
2126         else
2127             au->i_length = 0;
2128
2129         if (start_trim && start_trim < (au->i_nb_samples - au->i_length)) {
2130             au->i_nb_samples -= start_trim;
2131             if (au->i_nb_samples == 0)
2132                 au->i_flags |= BLOCK_FLAG_PREROLL;
2133         }
2134
2135         buf += au_size;
2136         len -= au_size;
2137     }
2138
2139     block_Release(block);
2140     return out;
2141 }
2142
2143 /****************************************************************************
2144  * gathering stuff
2145  ****************************************************************************/
2146 static int ParsePESHeader( demux_t *p_demux, const uint8_t *p_header, size_t i_header,
2147                            unsigned *pi_skip, mtime_t *pi_dts, mtime_t *pi_pts )
2148 {
2149     unsigned i_skip;
2150
2151     if ( i_header < 9 )
2152         return VLC_EGENERIC;
2153
2154     switch( p_header[3] )
2155     {
2156     case 0xBC:  /* Program stream map */
2157     case 0xBE:  /* Padding */
2158     case 0xBF:  /* Private stream 2 */
2159     case 0xF0:  /* ECM */
2160     case 0xF1:  /* EMM */
2161     case 0xFF:  /* Program stream directory */
2162     case 0xF2:  /* DSMCC stream */
2163     case 0xF8:  /* ITU-T H.222.1 type E stream */
2164         i_skip = 6;
2165         break;
2166     default:
2167         if( ( p_header[6]&0xC0 ) == 0x80 )
2168         {
2169             /* mpeg2 PES */
2170             i_skip = p_header[8] + 9;
2171             if( i_header < i_skip )
2172                 return VLC_EGENERIC;
2173
2174             if( p_header[7]&0x80 )    /* has pts */
2175             {
2176                 if( i_header < 9 + 5 )
2177                     return VLC_EGENERIC;
2178                 *pi_pts = ExtractPESTimestamp( &p_header[9] );
2179
2180                 if( p_header[7]&0x40 )    /* has dts */
2181                 {
2182                     if( i_header < 14 + 5 )
2183                         return VLC_EGENERIC;
2184                     *pi_dts = ExtractPESTimestamp( &p_header[14] );
2185                 }
2186             }
2187         }
2188         else
2189         {
2190             i_skip = 6;
2191             if( i_header < i_skip + 1 )
2192                 return VLC_EGENERIC;
2193             while( i_skip < 23 && p_header[i_skip] == 0xff )
2194             {
2195                 i_skip++;
2196                 if( i_header < i_skip + 1 )
2197                     return VLC_EGENERIC;
2198             }
2199             if( i_skip == 23 )
2200             {
2201                 msg_Err( p_demux, "too much MPEG-1 stuffing" );
2202                 return VLC_EGENERIC;
2203             }
2204             if( ( p_header[i_skip] & 0xC0 ) == 0x40 )
2205             {
2206                 i_skip += 2;
2207             }
2208
2209             if( i_header < i_skip + 1 )
2210                 return VLC_EGENERIC;
2211
2212             if(  p_header[i_skip]&0x20 )
2213             {
2214                 if( i_header < i_skip + 5 )
2215                     return VLC_EGENERIC;
2216                 *pi_pts = ExtractPESTimestamp( &p_header[i_skip] );
2217
2218                 if( p_header[i_skip]&0x10 )    /* has dts */
2219                 {
2220                     if( i_header < i_skip + 10 )
2221                         return VLC_EGENERIC;
2222                     *pi_dts = ExtractPESTimestamp( &p_header[i_skip+5] );
2223                     i_skip += 10;
2224                 }
2225                 else
2226                 {
2227                     i_skip += 5;
2228                 }
2229             }
2230             else
2231             {
2232                 i_skip += 1;
2233             }
2234         }
2235         break;
2236     }
2237
2238     if( i_header < i_skip )
2239         return VLC_EGENERIC;
2240
2241     *pi_skip = i_skip;
2242     return VLC_SUCCESS;
2243 }
2244
2245 static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
2246 {
2247     demux_sys_t *p_sys = p_demux->p_sys;
2248     uint8_t header[34];
2249     unsigned i_pes_size = 0;
2250     unsigned i_skip = 0;
2251     mtime_t i_dts = -1;
2252     mtime_t i_pts = -1;
2253     mtime_t i_length = 0;
2254
2255     const int i_max = block_ChainExtract( p_pes, header, 34 );
2256     if ( i_max < 4 )
2257     {
2258         block_ChainRelease( p_pes );
2259         return;
2260     }
2261
2262     if( pid->b_scrambled || header[0] != 0 || header[1] != 0 || header[2] != 1 )
2263     {
2264         if ( !pid->b_scrambled )
2265             msg_Warn( p_demux, "invalid header [0x%02x:%02x:%02x:%02x] (pid: %d)",
2266                         header[0], header[1],header[2],header[3], pid->i_pid );
2267         block_ChainRelease( p_pes );
2268         return;
2269     }
2270
2271     if( ParsePESHeader( p_demux, (uint8_t*)&header, i_max, &i_skip, &i_dts, &i_pts ) == VLC_EGENERIC )
2272     {
2273         block_ChainRelease( p_pes );
2274         return;
2275     }
2276     else
2277     {
2278         if( i_pts != -1 )
2279             i_pts = TimeStampWrapAround( GetProgramByID(p_sys, pid->i_owner_number), i_pts );
2280         if( i_dts != -1 )
2281             i_dts = TimeStampWrapAround( GetProgramByID(p_sys, pid->i_owner_number), i_dts );
2282     }
2283
2284     if( pid->es->fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
2285         pid->es->fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
2286     {
2287         i_skip += 4;
2288     }
2289     else if( pid->es->fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
2290              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
2291              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
2292     {
2293         i_skip += 1;
2294     }
2295     else if( pid->es->fmt.i_codec == VLC_CODEC_SUBT &&
2296              pid->es->p_mpeg4desc )
2297     {
2298         decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
2299
2300         if( dcd->i_extra > 2 &&
2301             dcd->p_extra[0] == 0x10 &&
2302             ( dcd->p_extra[1]&0x10 ) )
2303         {
2304             /* display length */
2305             if( p_pes->i_buffer + 2 <= i_skip )
2306                 i_length = GetWBE( &p_pes->p_buffer[i_skip] );
2307
2308             i_skip += 2;
2309         }
2310         if( p_pes->i_buffer + 2 <= i_skip )
2311             i_pes_size = GetWBE( &p_pes->p_buffer[i_skip] );
2312         /* */
2313         i_skip += 2;
2314     }
2315
2316     /* skip header */
2317     while( p_pes && i_skip > 0 )
2318     {
2319         if( p_pes->i_buffer <= i_skip )
2320         {
2321             block_t *p_next = p_pes->p_next;
2322
2323             i_skip -= p_pes->i_buffer;
2324             block_Release( p_pes );
2325             p_pes = p_next;
2326         }
2327         else
2328         {
2329             p_pes->i_buffer -= i_skip;
2330             p_pes->p_buffer += i_skip;
2331             break;
2332         }
2333     }
2334
2335     /* ISO/IEC 13818-1 2.7.5: if no pts and no dts, then dts == pts */
2336     if( i_pts >= 0 && i_dts < 0 )
2337         i_dts = i_pts;
2338
2339     if( p_pes )
2340     {
2341         block_t *p_block;
2342
2343         if( i_dts >= 0 )
2344             p_pes->i_dts = VLC_TS_0 + i_dts * 100 / 9;
2345
2346         if( i_pts >= 0 )
2347             p_pes->i_pts = VLC_TS_0 + i_pts * 100 / 9;
2348
2349         p_pes->i_length = i_length * 100 / 9;
2350
2351         p_block = block_ChainGather( p_pes );
2352         if( pid->es->fmt.i_codec == VLC_CODEC_SUBT )
2353         {
2354             if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
2355             {
2356                 p_block->i_buffer = i_pes_size;
2357             }
2358             /* Append a \0 */
2359             p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
2360             if( !p_block )
2361                 return;
2362             p_block->p_buffer[p_block->i_buffer -1] = '\0';
2363         }
2364         else if( pid->es->fmt.i_codec == VLC_CODEC_TELETEXT )
2365         {
2366             if( p_block->i_pts <= VLC_TS_INVALID )
2367             {
2368                 /* Teletext may have missing PTS (ETSI EN 300 472 Annexe A)
2369                  * In this case use the last PCR + 40ms */
2370                 for( int i = 0; pid->p_owner && i < pid->p_owner->i_prg; i++ )
2371                 {
2372                     if( pid->i_owner_number == pid->p_owner->prg[i]->i_number )
2373                     {
2374                         mtime_t i_pcr = pid->p_owner->prg[i]->pcr.i_current;
2375                         if( i_pcr > VLC_TS_INVALID )
2376                             p_block->i_pts = VLC_TS_0 + i_pcr * 100 / 9 + 40000;
2377                         break;
2378                     }
2379                 }
2380             }
2381         }
2382         else if( pid->es->fmt.i_codec == VLC_CODEC_ARIB_A ||
2383                  pid->es->fmt.i_codec == VLC_CODEC_ARIB_C )
2384         {
2385             if( p_block->i_pts <= VLC_TS_INVALID )
2386             {
2387                 if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
2388                 {
2389                     p_block->i_buffer = i_pes_size;
2390                 }
2391                 /* Append a \0 */
2392                 p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
2393                 if( !p_block )
2394                     return;
2395                 p_block->p_buffer[p_block->i_buffer -1] = '\0';
2396             }
2397         }
2398         else if( pid->es->fmt.i_codec == VLC_CODEC_OPUS)
2399         {
2400             p_block = Opus_Parse(p_demux, p_block);
2401         }
2402
2403         ts_prg_psi_t *p_program = GetProgramByID( p_sys, pid->i_owner_number );
2404
2405         while (p_block) {
2406             block_t *p_next = p_block->p_next;
2407             p_block->p_next = NULL;
2408
2409             if( p_program->pcr.i_first == -1 ) /* Not seen yet */
2410                 PCRFixHandle( p_demux, p_program, p_block );
2411
2412             if( p_program->pcr.i_current > -1 || p_program->pcr.b_disable )
2413             {
2414                 if( pid->es->p_prepcr_outqueue )
2415                 {
2416                     block_ChainAppend( &pid->es->p_prepcr_outqueue, p_block );
2417                     p_block = pid->es->p_prepcr_outqueue;
2418                     pid->es->p_prepcr_outqueue = NULL;
2419                 }
2420
2421                 if ( p_program->pcr.b_disable && p_block->i_dts > VLC_TS_INVALID &&
2422                      ( p_program->i_pid_pcr == pid->i_pid || p_program->i_pid_pcr == 0x1FFF ) )
2423                 {
2424                     ProgramSetPCR( p_demux, p_program, (p_block->i_dts - VLC_TS_0) * 9 / 100 - 120000 );
2425                 }
2426
2427                 /* Compute PCR/DTS offset if any */
2428                 if( p_program->pcr.i_pcroffset == -1 && p_block->i_dts > VLC_TS_INVALID &&
2429                     p_program->pcr.i_current > VLC_TS_INVALID )
2430                 {
2431                     int64_t i_dts27 = (p_block->i_dts - VLC_TS_0) * 9 / 100;
2432                     int64_t i_pcr = TimeStampWrapAround( p_program, p_program->pcr.i_current );
2433                     if( i_dts27 < i_pcr )
2434                     {
2435                         p_program->pcr.i_pcroffset = i_pcr - i_dts27 + 80000;
2436                         msg_Warn( p_demux, "Broken stream: pid %d sends packets with dts %"PRId64
2437                                            "us later than pcr, applying delay",
2438                                   pid->i_pid, p_program->pcr.i_pcroffset * 100 / 9 );
2439                     }
2440                     else p_program->pcr.i_pcroffset = 0;
2441                 }
2442
2443                 if( p_program->pcr.i_pcroffset != -1 )
2444                 {
2445                     if( p_block->i_dts > VLC_TS_INVALID )
2446                         p_block->i_dts += (p_program->pcr.i_pcroffset * 100 / 9);
2447                     if( p_block->i_pts > VLC_TS_INVALID )
2448                         p_block->i_pts += (p_program->pcr.i_pcroffset * 100 / 9);
2449                 }
2450
2451                 for( int i = 0; i < pid->i_extra_es; i++ )
2452                 {
2453                     es_out_Send( p_demux->out, pid->extra_es[i]->id,
2454                             block_Duplicate( p_block ) );
2455                 }
2456
2457                 es_out_Send( p_demux->out, pid->es->id, p_block );
2458             }
2459             else
2460             {
2461                 if( p_program->pcr.i_first == -1 ) /* Not seen yet */
2462                     PCRFixHandle( p_demux, p_program, p_block );
2463
2464                 block_ChainAppend( &pid->es->p_prepcr_outqueue, p_block );
2465             }
2466
2467             p_block = p_next;
2468         }
2469     }
2470     else
2471     {
2472         msg_Warn( p_demux, "empty pes" );
2473     }
2474 }
2475
2476 static void ParseTableSection( demux_t *p_demux, ts_pid_t *pid, block_t *p_data )
2477 {
2478     block_t *p_content = block_ChainGather( p_data );
2479     ts_prg_psi_t *p_program = NULL;
2480
2481     if ( pid->p_owner &&
2482          (p_program = GetProgramByID( p_demux->p_sys, pid->i_owner_number )) )
2483     {
2484         mtime_t i_date = p_program->pcr.i_current;
2485
2486         if( pid->es->fmt.i_codec == VLC_CODEC_SCTE_27 )
2487         {
2488             /* We need to extract the truncated pts stored inside the payload */
2489             if( p_content->i_buffer > 9 && p_content->p_buffer[0] == 0xc6 )
2490             {
2491                 int i_index = 0;
2492                 size_t i_offset = 4;
2493                 if( p_content->p_buffer[3] & 0x40 )
2494                 {
2495                     i_index = ((p_content->p_buffer[7] & 0x0f) << 8) |
2496                              p_content->p_buffer[8];
2497                     i_offset = 9;
2498                 }
2499                 if( i_index == 0 && p_content->i_buffer > i_offset + 8 )
2500                 {
2501                     bool is_immediate = p_content->p_buffer[i_offset + 3] & 0x40;
2502                     if( !is_immediate )
2503                     {
2504                         mtime_t i_display_in = GetDWBE( &p_content->p_buffer[i_offset + 4] );
2505                         if( i_display_in < i_date )
2506                             i_date = i_display_in + (1ll << 32);
2507                         else
2508                             i_date = i_display_in;
2509                     }
2510
2511                 }
2512             }
2513         }
2514
2515         p_content->i_dts = p_content->i_pts = VLC_TS_0 + i_date * 100 / 9;
2516         PCRFixHandle( p_demux, p_program, p_content );
2517     }
2518
2519     es_out_Send( p_demux->out, pid->es->id, p_content );
2520 }
2521
2522 static void ParseData( demux_t *p_demux, ts_pid_t *pid )
2523 {
2524     block_t *p_data = pid->es->p_data;
2525
2526     /* remove the pes from pid */
2527     pid->es->p_data = NULL;
2528     pid->es->i_data_size = 0;
2529     pid->es->i_data_gathered = 0;
2530     pid->es->pp_last = &pid->es->p_data;
2531
2532     if( pid->es->data_type == TS_ES_DATA_PES )
2533     {
2534         ParsePES( p_demux, pid, p_data );
2535     }
2536     else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
2537     {
2538         ParseTableSection( p_demux, pid, p_data );
2539     }
2540     else
2541     {
2542         block_ChainRelease( p_data );
2543     }
2544 }
2545
2546 static block_t* ReadTSPacket( demux_t *p_demux )
2547 {
2548     demux_sys_t *p_sys = p_demux->p_sys;
2549
2550     block_t     *p_pkt;
2551
2552     /* Get a new TS packet */
2553     if( !( p_pkt = stream_Block( p_sys->stream, p_sys->i_packet_size ) ) )
2554     {
2555         if( stream_Tell( p_sys->stream ) == stream_Size( p_sys->stream ) )
2556             msg_Dbg( p_demux, "EOF at %"PRId64, stream_Tell( p_sys->stream ) );
2557         else
2558             msg_Dbg( p_demux, "Can't read TS packet at %"PRId64, stream_Tell(p_sys->stream) );
2559         return NULL;
2560     }
2561
2562     if( p_pkt->i_buffer < TS_HEADER_SIZE + p_sys->i_packet_header_size )
2563     {
2564         block_Release( p_pkt );
2565         return NULL;
2566     }
2567
2568     /* Skip header (BluRay streams).
2569      * re-sync logic would do this (by adjusting packet start), but this would result in losing first and last ts packets.
2570      * First packet is usually PAT, and losing it means losing whole first GOP. This is fatal with still-image based menus.
2571      */
2572     p_pkt->p_buffer += p_sys->i_packet_header_size;
2573     p_pkt->i_buffer -= p_sys->i_packet_header_size;
2574
2575     /* Check sync byte and re-sync if needed */
2576     if( p_pkt->p_buffer[0] != 0x47 )
2577     {
2578         msg_Warn( p_demux, "lost synchro" );
2579         block_Release( p_pkt );
2580         for( ;; )
2581         {
2582             const uint8_t *p_peek;
2583             int i_peek, i_skip = 0;
2584
2585             i_peek = stream_Peek( p_sys->stream, &p_peek,
2586                     p_sys->i_packet_size * 10 );
2587             if( i_peek < p_sys->i_packet_size + 1 )
2588             {
2589                 msg_Dbg( p_demux, "eof ?" );
2590                 return NULL;
2591             }
2592
2593             while( i_skip < i_peek - p_sys->i_packet_size )
2594             {
2595                 if( p_peek[i_skip + p_sys->i_packet_header_size] == 0x47 &&
2596                         p_peek[i_skip + p_sys->i_packet_header_size + p_sys->i_packet_size] == 0x47 )
2597                 {
2598                     break;
2599                 }
2600                 i_skip++;
2601             }
2602             msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
2603             stream_Read( p_sys->stream, NULL, i_skip );
2604
2605             if( i_skip < i_peek - p_sys->i_packet_size )
2606             {
2607                 break;
2608             }
2609         }
2610         if( !( p_pkt = stream_Block( p_sys->stream, p_sys->i_packet_size ) ) )
2611         {
2612             msg_Dbg( p_demux, "eof ?" );
2613             return NULL;
2614         }
2615     }
2616     return p_pkt;
2617 }
2618
2619 static int64_t TimeStampWrapAround( ts_prg_psi_t *p_prg, int64_t i_time )
2620 {
2621     int64_t i_adjust = 0;
2622     if( p_prg && p_prg->pcr.i_first > 0x0FFFFFFFF && i_time < 0x0FFFFFFFF )
2623         i_adjust = 0x1FFFFFFFF;
2624
2625     return i_time + i_adjust;
2626 }
2627
2628 static mtime_t GetPCR( block_t *p_pkt )
2629 {
2630     const uint8_t *p = p_pkt->p_buffer;
2631
2632     mtime_t i_pcr = -1;
2633
2634     if( ( p[3]&0x20 ) && /* adaptation */
2635         ( p[5]&0x10 ) &&
2636         ( p[4] >= 7 ) )
2637     {
2638         /* PCR is 33 bits */
2639         i_pcr = ( (mtime_t)p[6] << 25 ) |
2640                 ( (mtime_t)p[7] << 17 ) |
2641                 ( (mtime_t)p[8] << 9 ) |
2642                 ( (mtime_t)p[9] << 1 ) |
2643                 ( (mtime_t)p[10] >> 7 );
2644     }
2645     return i_pcr;
2646 }
2647
2648 static inline void FlushESBuffer( ts_es_t *p_es )
2649 {
2650     if( p_es->p_data )
2651     {
2652         p_es->i_data_gathered = p_es->i_data_size = 0;
2653         block_ChainRelease( p_es->p_data );
2654         p_es->p_data = NULL;
2655         p_es->pp_last = &p_es->p_data;
2656     }
2657 }
2658
2659 static void ReadyQueuesPostSeek( demux_sys_t *p_sys )
2660 {
2661     for( int i=MIN_ES_PID; i<=MAX_ES_PID; i++ )
2662     {
2663         ts_pid_t *pid = &p_sys->pid[i];
2664
2665         if( !pid->es )
2666             continue;
2667
2668         pid->i_cc = 0xff;
2669
2670         if( pid->es->p_prepcr_outqueue )
2671         {
2672             block_ChainRelease( pid->es->p_prepcr_outqueue );
2673             pid->es->p_prepcr_outqueue = NULL;
2674         }
2675
2676         FlushESBuffer( pid->es );
2677
2678         for( int j = 0; j < pid->i_extra_es; j++ )
2679             FlushESBuffer( pid->extra_es[j] );
2680     }
2681
2682     for( int i=0; i<p_sys->i_pmt; i++ )
2683         for( int j=0; j<p_sys->pmt[i]->psi->i_prg; j++ )
2684             p_sys->pmt[i]->psi->prg[j]->pcr.i_current = -1;
2685 }
2686
2687 static int SeekToTime( demux_t *p_demux, ts_prg_psi_t *p_prg, int64_t i_scaledtime )
2688 {
2689     demux_sys_t *p_sys = p_demux->p_sys;
2690
2691     /* Deal with common but worst binary search case */
2692     if( p_prg->pcr.i_first == i_scaledtime && p_sys->b_canseek )
2693         return stream_Seek( p_sys->stream, 0 );
2694
2695     if( !p_sys->b_canfastseek )
2696         return VLC_EGENERIC;
2697
2698     int64_t i_initial_pos = stream_Tell( p_sys->stream );
2699
2700     /* Find the time position by using binary search algorithm. */
2701     int64_t i_head_pos = 0;
2702     int64_t i_tail_pos = stream_Size( p_sys->stream ) - p_sys->i_packet_size;
2703     if( i_head_pos >= i_tail_pos )
2704         return VLC_EGENERIC;
2705
2706     bool b_found = false;
2707     while( (i_head_pos + p_sys->i_packet_size) <= i_tail_pos && !b_found )
2708     {
2709         /* Round i_pos to a multiple of p_sys->i_packet_size */
2710         int64_t i_splitpos = i_head_pos + (i_tail_pos - i_head_pos) / 2;
2711         int64_t i_div = i_splitpos % p_sys->i_packet_size;
2712         i_splitpos -= i_div;
2713
2714         if ( stream_Seek( p_sys->stream, i_splitpos ) != VLC_SUCCESS )
2715             break;
2716
2717         int64_t i_pos = i_splitpos;
2718         while( i_pos > -1 && i_pos < i_tail_pos )
2719         {
2720             int64_t i_pcr = -1;
2721             block_t *p_pkt = ReadTSPacket( p_demux );
2722             if( !p_pkt )
2723             {
2724                 i_head_pos = i_tail_pos;
2725                 break;
2726             }
2727             else
2728                 i_pos = stream_Tell( p_sys->stream );
2729
2730             int i_pid = PIDGet( p_pkt );
2731             if( i_pid != 0x1FFF && p_sys->pid[i_pid].b_valid &&
2732                 p_sys->pid[i_pid].i_owner_number == p_prg->i_number &&
2733                (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
2734                (p_pkt->p_buffer[3] & 0xD0) == 0x10    /* Has payload but is not encrypted */
2735             )
2736             {
2737                 unsigned i_skip = 4;
2738                 if ( p_pkt->p_buffer[3] & 0x20 ) // adaptation field
2739                 {
2740                     if( p_pkt->i_buffer >= 4 + 2 + 5 )
2741                     {
2742                         i_pcr = GetPCR( p_pkt );
2743                         i_skip += 1 + p_pkt->p_buffer[4];
2744                     }
2745                 }
2746                 else
2747                 {
2748                     mtime_t i_dts = -1;
2749                     mtime_t i_pts = -1;
2750                     if ( VLC_SUCCESS == ParsePESHeader( p_demux, &p_pkt->p_buffer[i_skip],
2751                                                         p_pkt->i_buffer - i_skip, &i_skip, &i_dts, &i_pts ) )
2752                     {
2753                         if( i_dts > -1 )
2754                             i_pcr = i_dts;
2755                     }
2756                 }
2757             }
2758             block_Release( p_pkt );
2759
2760             if( i_pcr != -1 )
2761             {
2762                 int64_t i_diff = i_scaledtime - TimeStampWrapAround( p_prg, i_pcr );
2763                 if ( i_diff < 0 )
2764                     i_tail_pos = i_splitpos - p_sys->i_packet_size;
2765                 else if( i_diff < TO_SCALE(VLC_TS_0 + CLOCK_FREQ / 2) ) // 500ms
2766                     b_found = true;
2767                 else
2768                     i_head_pos = i_pos;
2769                 break;
2770             }
2771         }
2772
2773     }
2774
2775     if( !b_found )
2776     {
2777         msg_Dbg( p_demux, "Seek():cannot find a time position." );
2778         stream_Seek( p_sys->stream, i_initial_pos );
2779         return VLC_EGENERIC;
2780     }
2781     return VLC_SUCCESS;
2782 }
2783
2784 static ts_prg_psi_t * GetProgramByID( demux_sys_t *p_sys, int i_program )
2785 {
2786     for( int i = 0; i < p_sys->i_pmt; i++ )
2787     {
2788         for( int i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
2789         {
2790             ts_prg_psi_t *p_prg = p_sys->pmt[i]->psi->prg[i_prg];
2791             if( p_prg->i_number == i_program )
2792                 return p_prg;
2793         }
2794     }
2795     return NULL;
2796 }
2797
2798 #define PROBE_CHUNK_COUNT 250
2799
2800 static int ProbeChunk( demux_t *p_demux, int i_program, bool b_end, int64_t *pi_pcr, bool *pb_found )
2801 {
2802     demux_sys_t *p_sys = p_demux->p_sys;
2803     int i_count = 0;
2804     block_t *p_pkt = NULL;
2805     *pi_pcr = -1;
2806
2807     for( ;; )
2808     {
2809         if( i_count++ > PROBE_CHUNK_COUNT || !( p_pkt = ReadTSPacket( p_demux ) ) )
2810         {
2811             break;
2812         }
2813
2814         int i_pid = PIDGet( p_pkt );
2815         p_sys->pid[i_pid].b_seen = true;
2816
2817         if( i_pid != 0x1FFF && p_sys->pid[i_pid].b_valid && p_sys->pid[i_pid].p_owner &&
2818            (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
2819            (p_pkt->p_buffer[3] & 0xD0) == 0x10    /* Has payload but is not encrypted */
2820           )
2821         {
2822             bool b_pcrresult = true;
2823
2824             if( p_pkt->i_buffer >= 4 + 2 + 5 )
2825                 *pi_pcr = GetPCR( p_pkt );
2826
2827             if( *pi_pcr == -1 )
2828             {
2829                 b_pcrresult = false;
2830                 mtime_t i_dts = -1;
2831                 mtime_t i_pts = -1;
2832                 unsigned i_skip = 4;
2833                 if ( p_pkt->p_buffer[3] & 0x20 ) // adaptation field
2834                     i_skip += 1 + p_pkt->p_buffer[4];
2835
2836                 if ( VLC_SUCCESS == ParsePESHeader( p_demux, &p_pkt->p_buffer[i_skip],
2837                                                     p_pkt->i_buffer - i_skip,
2838                                                     &i_skip, &i_dts, &i_pts ) )
2839                 {
2840                     if( i_dts != -1 )
2841                         *pi_pcr = i_dts;
2842                     else if( i_pts != -1 )
2843                         *pi_pcr = i_pts;
2844                 }
2845             }
2846
2847             if( *pi_pcr != -1 )
2848             {
2849                 ts_psi_t *p_prg = p_sys->pid[i_pid].p_owner;
2850                 for(int i=0; i<p_prg->i_prg; i++)
2851                 {
2852                     if( i_program == 0 || i_program == p_prg->prg[i]->i_number )
2853                         *pb_found = true;
2854
2855                     if( b_end )
2856                     {
2857                         p_prg->prg[i]->i_last_dts = *pi_pcr;
2858                     }
2859                     /* Start, only keep first */
2860                     else if( b_pcrresult && p_prg->prg[i]->pcr.i_first == -1 )
2861                     {
2862                         p_prg->prg[i]->pcr.i_first = *pi_pcr;
2863                     }
2864                     else if( p_prg->prg[i]->pcr.i_first_dts < VLC_TS_0 )
2865                     {
2866                         p_prg->prg[i]->pcr.i_first_dts = VLC_TS_0 + *pi_pcr * 100 / 9;
2867                     }
2868                 }
2869             }
2870         }
2871
2872         block_Release( p_pkt );
2873     }
2874
2875     return i_count;
2876 }
2877
2878 static int ProbeStart( demux_t *p_demux, int i_program )
2879 {
2880     demux_sys_t *p_sys = p_demux->p_sys;
2881     const int64_t i_initial_pos = stream_Tell( p_sys->stream );
2882     int64_t i_stream_size = stream_Size( p_sys->stream );
2883
2884     int i_probe_count = 0;
2885     int64_t i_pos;
2886     mtime_t i_pcr = -1;
2887     bool b_found = false;
2888
2889     do
2890     {
2891         i_pos = p_sys->i_packet_size * i_probe_count;
2892         i_pos = __MIN( i_pos, i_stream_size );
2893
2894         if( stream_Seek( p_sys->stream, i_pos ) )
2895             return VLC_EGENERIC;
2896
2897         ProbeChunk( p_demux, i_program, false, &i_pcr, &b_found );
2898
2899         /* Go ahead one more chunk if end of file contained only stuffing packets */
2900         i_probe_count += PROBE_CHUNK_COUNT;
2901     } while( i_pos > 0 && (i_pcr == -1 || !b_found) && i_probe_count < (2 * PROBE_CHUNK_COUNT) );
2902
2903     stream_Seek( p_sys->stream, i_initial_pos );
2904
2905     return (b_found) ? VLC_SUCCESS : VLC_EGENERIC;
2906 }
2907
2908 static int ProbeEnd( demux_t *p_demux, int i_program )
2909 {
2910     demux_sys_t *p_sys = p_demux->p_sys;
2911     const int64_t i_initial_pos = stream_Tell( p_sys->stream );
2912     int64_t i_stream_size = stream_Size( p_sys->stream );
2913
2914     int i_probe_count = PROBE_CHUNK_COUNT;
2915     int64_t i_pos;
2916     mtime_t i_pcr = -1;
2917     bool b_found = false;
2918
2919     do
2920     {
2921         i_pos = i_stream_size - (p_sys->i_packet_size * i_probe_count);
2922         i_pos = __MAX( i_pos, 0 );
2923
2924         if( stream_Seek( p_sys->stream, i_pos ) )
2925             return VLC_EGENERIC;
2926
2927         ProbeChunk( p_demux, i_program, true, &i_pcr, &b_found );
2928
2929         /* Go ahead one more chunk if end of file contained only stuffing packets */
2930         i_probe_count += PROBE_CHUNK_COUNT;
2931     } while( i_pos > 0 && (i_pcr == -1 || !b_found) && i_probe_count < (6 * PROBE_CHUNK_COUNT) );
2932
2933     stream_Seek( p_sys->stream, i_initial_pos );
2934
2935     return (b_found) ? VLC_SUCCESS : VLC_EGENERIC;
2936 }
2937
2938 static void ProgramSetPCR( demux_t *p_demux, ts_prg_psi_t *p_prg, mtime_t i_pcr )
2939 {
2940     demux_sys_t *p_sys = p_demux->p_sys;
2941
2942     /* Check if we have enqueued blocks waiting the/before the
2943        PCR barrier, and then adapt pcr so they have valid PCR when dequeuing */
2944     if( p_prg->pcr.i_current == -1 )
2945     {
2946         mtime_t i_mindts = -1;
2947         for( int i=MIN_ES_PID; i<=MAX_ES_PID; i++ )
2948         {
2949             ts_pid_t *p_pid = &p_sys->pid[i];
2950             if( p_pid->b_valid && p_pid->i_owner_number == p_prg->i_number && p_pid->es )
2951             {
2952                 block_t *p_block = p_pid->es->p_prepcr_outqueue;
2953                 while( p_block && p_block->i_dts == VLC_TS_INVALID )
2954                     p_block = p_block->p_next;
2955
2956                 if( p_block )
2957                     msg_Warn( p_demux, "Program %ld %ld *******", i_mindts, p_block->i_dts );
2958
2959                 if( p_block && ( i_mindts == -1 || p_block->i_dts < i_mindts ) )
2960                 {
2961                     i_mindts = p_block->i_dts;
2962                     msg_Warn( p_demux, "Program %ld %ld *******", i_mindts, p_block->i_dts );
2963                 }
2964             }
2965         }
2966
2967         if( i_mindts > VLC_TS_INVALID )
2968         {
2969             msg_Dbg( p_demux, "Program %d PCR prequeue fixup %"PRId64"->%"PRId64,
2970                      p_prg->i_number, TO_SCALE(i_mindts), i_pcr );
2971             i_pcr = TO_SCALE(i_mindts);
2972         }
2973     }
2974
2975     p_prg->pcr.i_current = i_pcr;
2976     if( p_prg->pcr.i_first == -1 )
2977     {
2978         p_prg->pcr.i_first = i_pcr; // now seen
2979     }
2980
2981     if ( p_sys->i_pmt_es )
2982     {
2983         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
2984                         p_prg->i_number, VLC_TS_0 + i_pcr * 100 / 9 );
2985     }
2986 }
2987
2988 static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
2989 {
2990     demux_sys_t   *p_sys = p_demux->p_sys;
2991
2992     if( p_sys->i_pmt_es <= 0 )
2993         return;
2994
2995     mtime_t i_pcr = GetPCR( p_bk );
2996     if( i_pcr < 0 )
2997         return;
2998
2999     pid->probed.i_pcr_count++;
3000
3001     /* Search program and set the PCR */
3002     for( int i = 0; i < p_sys->i_pmt; i++ )
3003     {
3004         for( int i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
3005         {
3006             ts_prg_psi_t *p_prg = p_sys->pmt[i]->psi->prg[i_prg];
3007             mtime_t i_program_pcr = TimeStampWrapAround( p_prg, i_pcr );
3008
3009             if( p_prg->i_pid_pcr == 0x1FFF ) /* That program has no dedicated PCR pid ISO/IEC 13818-1 2.4.4.9 */
3010             {
3011                 if( pid->p_owner ) /* PCR shall be on pid itself */
3012                 {
3013                     /* ? update PCR for the whole group program ? */
3014                     ProgramSetPCR( p_demux, p_prg, i_program_pcr );
3015                 }
3016                 else
3017                 {
3018                     msg_Warn(p_demux, "discarding PCR update from pid %d which has no owner", pid->i_pid);
3019                 }
3020                 break;
3021             }
3022             else /* set PCR provided by current pid to program(s) referencing it */
3023             {
3024                 /* Can be dedicated PCR pid (no owned then) or another pid (owner == pmt) */
3025                 if( p_prg->i_pid_pcr == pid->i_pid ) /* If that program references current pid as PCR */
3026                 {
3027                     /* We've found a target group for update */
3028                     ProgramSetPCR( p_demux, p_prg, i_program_pcr );
3029                 }
3030             }
3031         }
3032     }
3033 }
3034
3035 static int FindPCRCandidate( demux_sys_t *p_sys, ts_prg_psi_t *p_prg )
3036 {
3037     ts_pid_t *p_cand = NULL;
3038     int i_previous = p_prg->i_pid_pcr;
3039     for( int i=MIN_ES_PID; i<=MAX_ES_PID; i++ )
3040     {
3041         ts_pid_t *p_pid = &p_sys->pid[i];
3042         if( p_pid->b_seen && p_pid->es && p_pid->es->id &&
3043             p_pid->i_owner_number == p_prg->i_number &&
3044             p_cand->i_pid != i_previous )
3045         {
3046             if( p_pid->probed.i_pcr_count ) /* check PCR frequency first */
3047             {
3048                 if( !p_cand || p_pid->probed.i_pcr_count > p_cand->probed.i_pcr_count )
3049                 {
3050                     p_cand = p_pid;
3051                     continue;
3052                 }
3053             }
3054
3055             if( p_pid->es->fmt.i_cat == AUDIO_ES )
3056             {
3057                 if( !p_cand )
3058                     p_cand = p_pid;
3059             }
3060             else if ( p_pid->es->fmt.i_cat == VIDEO_ES ) /* Otherwise prioritize video dts */
3061             {
3062                 if( !p_cand || p_cand->es->fmt.i_cat == AUDIO_ES )
3063                     p_cand = p_pid;
3064             }
3065         }
3066     }
3067
3068     if( p_cand )
3069         return p_cand->i_pid;
3070     else
3071         return 0x1FFF;
3072 }
3073
3074 static void PCRFixHandle( demux_t *p_demux, ts_prg_psi_t *p_prg, block_t *p_block )
3075 {
3076     if( p_prg->pcr.i_first > -1 || p_prg->pcr.b_disable )
3077         return;
3078
3079     /* Record the first data packet timestamp in case there wont be any PCR */
3080     if( !p_prg->pcr.i_first_dts )
3081     {
3082         p_prg->pcr.i_first_dts = p_block->i_dts;
3083     }
3084     else if( p_block->i_dts - p_prg->pcr.i_first_dts > CLOCK_FREQ / 2 ) /* "shall not exceed 100ms" */
3085     {
3086         int i_cand = FindPCRCandidate( p_demux->p_sys, p_prg );
3087         p_prg->i_pid_pcr = i_cand;
3088         p_prg->pcr.b_disable = true; /* So we do not wait packet PCR flag as there might be none on the pid */
3089         msg_Warn( p_demux, "No PCR received for program %d, set up workaround using pid %d",
3090                   p_prg->i_number, i_cand );
3091     }
3092 }
3093
3094 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
3095 {
3096     const uint8_t *p = p_bk->p_buffer;
3097     const bool b_unit_start = p[1]&0x40;
3098     const bool b_scrambled  = p[3]&0x80;
3099     const bool b_adaptation = p[3]&0x20;
3100     const bool b_payload    = p[3]&0x10;
3101     const int  i_cc         = p[3]&0x0f; /* continuity counter */
3102     bool       b_discontinuity = false;  /* discontinuity */
3103
3104     /* transport_scrambling_control is ignored */
3105     int         i_skip = 0;
3106     bool        i_ret  = false;
3107
3108 #if 0
3109     msg_Dbg( p_demux, "pid=%d unit_start=%d adaptation=%d payload=%d "
3110              "cc=0x%x", pid->i_pid, b_unit_start, b_adaptation,
3111              b_payload, i_cc );
3112 #endif
3113
3114     /* For now, ignore additional error correction
3115      * TODO: handle Reed-Solomon 204,188 error correction */
3116     p_bk->i_buffer = TS_PACKET_SIZE_188;
3117
3118     if( p[1]&0x80 )
3119     {
3120         msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
3121                  pid->i_pid );
3122         if( pid->es->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
3123             pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
3124     }
3125
3126     if( p_demux->p_sys->csa )
3127     {
3128         vlc_mutex_lock( &p_demux->p_sys->csa_lock );
3129         csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer, p_demux->p_sys->i_csa_pkt_size );
3130         vlc_mutex_unlock( &p_demux->p_sys->csa_lock );
3131     }
3132
3133     if( !b_adaptation )
3134     {
3135         /* We don't have any adaptation_field, so payload starts
3136          * immediately after the 4 byte TS header */
3137         i_skip = 4;
3138     }
3139     else
3140     {
3141         /* p[4] is adaptation_field_length minus one */
3142         i_skip = 5 + p[4];
3143         if( p[4] > 0 )
3144         {
3145             /* discontinuity indicator found in stream */
3146             b_discontinuity = (p[5]&0x80) ? true : false;
3147             if( b_discontinuity && pid->es->p_data )
3148             {
3149                 msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
3150                             pid->i_pid );
3151                 /* pid->es->p_data->i_flags |= BLOCK_FLAG_DISCONTINUITY; */
3152             }
3153 #if 0
3154             if( p[5]&0x40 )
3155                 msg_Dbg( p_demux, "random access indicator (pid=%d) ", pid->i_pid );
3156 #endif
3157         }
3158     }
3159
3160     /* Test continuity counter */
3161     /* continuous when (one of this):
3162         * diff == 1
3163         * diff == 0 and payload == 0
3164         * diff == 0 and duplicate packet (playload != 0) <- should we
3165         *   test the content ?
3166      */
3167     const int i_diff = ( i_cc - pid->i_cc )&0x0f;
3168     if( b_payload && i_diff == 1 )
3169     {
3170         pid->i_cc = ( pid->i_cc + 1 ) & 0xf;
3171     }
3172     else
3173     {
3174         if( pid->i_cc == 0xff )
3175         {
3176             msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
3177                       pid->i_pid, i_cc );
3178             pid->i_cc = i_cc;
3179         }
3180         else if( i_diff != 0 && !b_discontinuity )
3181         {
3182             msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x (pid=%d)",
3183                       i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );
3184
3185             pid->i_cc = i_cc;
3186             if( pid->es->p_data && pid->es->fmt.i_cat != VIDEO_ES &&
3187                 pid->es->fmt.i_cat != AUDIO_ES )
3188             {
3189                 /* Small audio/video artifacts are usually better than
3190                  * dropping full frames */
3191                 pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
3192             }
3193         }
3194     }
3195
3196     PCRHandle( p_demux, pid, p_bk );
3197
3198     if( i_skip >= 188 || pid->es->id == NULL )
3199     {
3200         block_Release( p_bk );
3201         return i_ret;
3202     }
3203
3204     /* */
3205     if( !pid->b_scrambled != !b_scrambled )
3206     {
3207         msg_Warn( p_demux, "scrambled state changed on pid %d (%d->%d)",
3208                   pid->i_pid, pid->b_scrambled, b_scrambled );
3209
3210         pid->b_scrambled = b_scrambled;
3211
3212         for( int i = 0; i < pid->i_extra_es; i++ )
3213         {
3214             es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
3215                             pid->extra_es[i]->id, b_scrambled );
3216         }
3217         es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
3218                         pid->es->id, b_scrambled );
3219     }
3220
3221     /* We have to gather it */
3222     p_bk->p_buffer += i_skip;
3223     p_bk->i_buffer -= i_skip;
3224
3225     if( b_unit_start )
3226     {
3227         if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
3228         {
3229             int i_pointer_field = __MIN( p_bk->p_buffer[0], p_bk->i_buffer - 1 );
3230             block_t *p = block_Duplicate( p_bk );
3231             if( p )
3232             {
3233                 p->i_buffer = i_pointer_field;
3234                 p->p_buffer++;
3235                 block_ChainLastAppend( &pid->es->pp_last, p );
3236             }
3237             p_bk->i_buffer -= 1 + i_pointer_field;
3238             p_bk->p_buffer += 1 + i_pointer_field;
3239         }
3240         if( pid->es->p_data )
3241         {
3242             ParseData( p_demux, pid );
3243             i_ret = true;
3244         }
3245
3246         block_ChainLastAppend( &pid->es->pp_last, p_bk );
3247         if( pid->es->data_type == TS_ES_DATA_PES )
3248         {
3249             if( p_bk->i_buffer > 6 )
3250             {
3251                 pid->es->i_data_size = GetWBE( &p_bk->p_buffer[4] );
3252                 if( pid->es->i_data_size > 0 )
3253                 {
3254                     pid->es->i_data_size += 6;
3255                 }
3256             }
3257         }
3258         else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
3259         {
3260             if( p_bk->i_buffer > 3 && p_bk->p_buffer[0] != 0xff )
3261             {
3262                 pid->es->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
3263             }
3264         }
3265         pid->es->i_data_gathered += p_bk->i_buffer;
3266         if( pid->es->i_data_size > 0 &&
3267             pid->es->i_data_gathered >= pid->es->i_data_size )
3268         {
3269             ParseData( p_demux, pid );
3270             i_ret = true;
3271         }
3272     }
3273     else
3274     {
3275         if( pid->es->p_data == NULL )
3276         {
3277             /* msg_Dbg( p_demux, "broken packet" ); */
3278             block_Release( p_bk );
3279         }
3280         else
3281         {
3282             block_ChainLastAppend( &pid->es->pp_last, p_bk );
3283             pid->es->i_data_gathered += p_bk->i_buffer;
3284
3285             if( pid->es->i_data_size > 0 &&
3286                 pid->es->i_data_gathered >= pid->es->i_data_size )
3287             {
3288                 ParseData( p_demux, pid );
3289                 i_ret = true;
3290             }
3291         }
3292     }
3293
3294     return i_ret;
3295 }
3296
3297 static void PIDFillFormat( es_format_t *fmt, int i_stream_type )
3298 {
3299     switch( i_stream_type )
3300     {
3301     case 0x01:  /* MPEG-1 video */
3302     case 0x02:  /* MPEG-2 video */
3303     case 0x80:  /* MPEG-2 MOTO video */
3304         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MPGV );
3305         break;
3306     case 0x03:  /* MPEG-1 audio */
3307     case 0x04:  /* MPEG-2 audio */
3308         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MPGA );
3309         break;
3310     case 0x11:  /* MPEG4 (audio) LATM */
3311     case 0x0f:  /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
3312     case 0x1c:  /* ISO/IEC 14496-3 Audio, without using any additional
3313                    transport syntax, such as DST, ALS and SLS */
3314         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MP4A );
3315         break;
3316     case 0x10:  /* MPEG4 (video) */
3317         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MP4V );
3318         break;
3319     case 0x1B:  /* H264 <- check transport syntax/needed descriptor */
3320         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_H264 );
3321         break;
3322     case 0x24:  /* HEVC */
3323         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_HEVC );
3324         break;
3325     case 0x42:  /* CAVS (Chinese AVS) */
3326         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_CAVS );
3327         break;
3328
3329     case 0x81:  /* A52 (audio) */
3330         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_A52 );
3331         break;
3332     case 0x82:  /* SCTE-27 (sub) */
3333         es_format_Init( fmt, SPU_ES, VLC_CODEC_SCTE_27 );
3334         break;
3335     case 0x84:  /* SDDS (audio) */
3336         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_SDDS );
3337         break;
3338     case 0x85:  /* DTS (audio) */
3339         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_DTS );
3340         break;
3341     case 0x87: /* E-AC3 */
3342         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_EAC3 );
3343         break;
3344
3345     case 0x91:  /* A52 vls (audio) */
3346         es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
3347         break;
3348     case 0x92:  /* DVD_SPU vls (sub) */
3349         es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
3350         break;
3351
3352     case 0x94:  /* SDDS (audio) */
3353         es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
3354         break;
3355
3356     case 0xa0:  /* MSCODEC vlc (video) (fixed later) */
3357         es_format_Init( fmt, UNKNOWN_ES, 0 );
3358         break;
3359
3360     case 0x06:  /* PES_PRIVATE  (fixed later) */
3361     case 0x12:  /* MPEG-4 generic (sub/scene/...) (fixed later) */
3362     case 0xEA:  /* Privately managed ES (VC-1) (fixed later */
3363     default:
3364         es_format_Init( fmt, UNKNOWN_ES, 0 );
3365         break;
3366     }
3367
3368     /* PES packets usually contain truncated frames */
3369     fmt->b_packetized = false;
3370 }
3371
3372 /*****************************************************************************
3373  * MP4 specific functions (IOD parser)
3374  *****************************************************************************/
3375 static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
3376 {
3377     unsigned int i_b;
3378     unsigned int i_len = 0;
3379     do
3380     {
3381         i_b = **pp_data;
3382         (*pp_data)++;
3383         (*pi_data)--;
3384         i_len = ( i_len << 7 ) + ( i_b&0x7f );
3385
3386     } while( i_b&0x80 && *pi_data > 0 );
3387
3388     if (i_len > *pi_data)
3389         i_len = *pi_data;
3390
3391     return i_len;
3392 }
3393
3394 static int IODGetBytes( int *pi_data, uint8_t **pp_data, size_t bytes )
3395 {
3396     uint32_t res = 0;
3397     while( *pi_data > 0 && bytes-- )
3398     {
3399         res <<= 8;
3400         res |= **pp_data;
3401         (*pp_data)++;
3402         (*pi_data)--;
3403     }
3404
3405     return res;
3406 }
3407
3408 static char* IODGetURL( int *pi_data, uint8_t **pp_data )
3409 {
3410     int len = IODGetBytes( pi_data, pp_data, 1 );
3411     if (len > *pi_data)
3412         len = *pi_data;
3413     char *url = strndup( (char*)*pp_data, len );
3414     *pp_data += len;
3415     *pi_data -= len;
3416     return url;
3417 }
3418
3419 static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
3420 {
3421     uint8_t i_iod_tag, i_iod_label, byte1, byte2, byte3;
3422
3423     iod_descriptor_t *p_iod = calloc( 1, sizeof( iod_descriptor_t ) );
3424     if( !p_iod )
3425         return NULL;
3426
3427     if( i_data < 3 )
3428     {
3429         return p_iod;
3430     }
3431
3432     byte1 = IODGetBytes( &i_data, &p_data, 1 );
3433     byte2 = IODGetBytes( &i_data, &p_data, 1 );
3434     byte3 = IODGetBytes( &i_data, &p_data, 1 );
3435     if( byte2 == 0x02 ) //old vlc's buggy implementation of the IOD_descriptor
3436     {
3437         i_iod_label = byte1;
3438         i_iod_tag = byte2;
3439     }
3440     else  //correct implementation of the IOD_descriptor
3441     {
3442         i_iod_label = byte2;
3443         i_iod_tag = byte3;
3444     }
3445
3446     ts_debug( "\n* iod label:%d tag:0x%x", i_iod_label, i_iod_tag );
3447
3448     if( i_iod_tag != 0x02 )
3449     {
3450         ts_debug( "\n ERR: tag %02x != 0x02", i_iod_tag );
3451         return p_iod;
3452     }
3453
3454     IODDescriptorLength( &i_data, &p_data );
3455
3456     uint16_t i_od_id = ( IODGetBytes( &i_data, &p_data, 1 ) << 2 );
3457     uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
3458     i_od_id |= i_flags >> 6;
3459     ts_debug( "\n* od_id:%d", i_od_id );
3460     ts_debug( "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
3461     if ((i_flags >> 5) & 0x01)
3462     {
3463         p_iod->psz_url = IODGetURL( &i_data, &p_data );
3464         ts_debug( "\n* url string:%s", p_iod->psz_url );
3465         ts_debug( "\n*****************************\n" );
3466         return p_iod;
3467     }
3468     else
3469     {
3470         p_iod->psz_url = NULL;
3471     }
3472
3473     /* Profile Level Indication */
3474     IODGetBytes( &i_data, &p_data, 1 ); /* OD */
3475     IODGetBytes( &i_data, &p_data, 1 ); /* scene */
3476     IODGetBytes( &i_data, &p_data, 1 ); /* audio */
3477     IODGetBytes( &i_data, &p_data, 1 ); /* visual */
3478     IODGetBytes( &i_data, &p_data, 1 ); /* graphics */
3479
3480     int i_length = 0;
3481     int i_data_sav = i_data;
3482     uint8_t *p_data_sav = p_data;
3483     for (int i = 0; i_data > 0 && i < ES_DESCRIPTOR_COUNT; i++)
3484     {
3485         es_mpeg4_descriptor_t *es_descr = &p_iod->es_descr[i];
3486
3487         p_data = p_data_sav + i_length;
3488         i_data = i_data_sav - i_length;
3489
3490         int i_tag = IODGetBytes( &i_data, &p_data, 1 );
3491         i_length = IODDescriptorLength( &i_data, &p_data );
3492
3493         i_data_sav = i_data;
3494         p_data_sav = p_data;
3495
3496         i_data = i_length;
3497
3498         if ( i_tag != 0x03 )
3499         {
3500             ts_debug( "\n* - OD tag:0x%x Unsupported", i_tag );
3501             continue;
3502         }
3503
3504         es_descr->i_es_id = IODGetBytes( &i_data, &p_data, 2 );
3505         int i_flags = IODGetBytes( &i_data, &p_data, 1 );
3506         bool b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
3507         if( b_streamDependenceFlag )
3508             IODGetBytes( &i_data, &p_data, 2 ); /* dependOn_es_id */
3509
3510         if( (i_flags >> 6) & 0x01 )
3511             es_descr->psz_url = IODGetURL( &i_data, &p_data );
3512
3513         bool b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
3514         if( b_OCRStreamFlag )
3515             IODGetBytes( &i_data, &p_data, 2 ); /* OCR_es_id */
3516
3517         if( IODGetBytes( &i_data, &p_data, 1 ) != 0x04 )
3518         {
3519             ts_debug( "\n* ERR missing DecoderConfigDescr" );
3520             continue;
3521         }
3522         int i_config_desc_length = IODDescriptorLength( &i_data, &p_data ); /* DecoderConfigDescr_length */
3523         decoder_config_descriptor_t *dec_descr = &es_descr->dec_descr;
3524         dec_descr->i_objectTypeIndication = IODGetBytes( &i_data, &p_data, 1 );
3525         i_flags = IODGetBytes( &i_data, &p_data, 1 );
3526         dec_descr->i_streamType = i_flags >> 2;
3527
3528         IODGetBytes( &i_data, &p_data, 3); /* bufferSizeDB */
3529         IODGetBytes( &i_data, &p_data, 4); /* maxBitrate */
3530         IODGetBytes( &i_data, &p_data, 4 ); /* avgBitrate */
3531
3532         if( i_config_desc_length > 13 && IODGetBytes( &i_data, &p_data, 1 ) == 0x05 )
3533         {
3534             dec_descr->i_extra = IODDescriptorLength( &i_data, &p_data );
3535             if( dec_descr->i_extra > 0 )
3536             {
3537                 dec_descr->p_extra = xmalloc( dec_descr->i_extra );
3538                 memcpy(dec_descr->p_extra, p_data, dec_descr->i_extra);
3539                 p_data += dec_descr->i_extra;
3540                 i_data -= dec_descr->i_extra;
3541             }
3542         }
3543         else
3544         {
3545             dec_descr->i_extra = 0;
3546             dec_descr->p_extra = NULL;
3547         }
3548
3549         if( IODGetBytes( &i_data, &p_data, 1 ) != 0x06 )
3550         {
3551             ts_debug( "\n* ERR missing SLConfigDescr" );
3552             continue;
3553         }
3554         IODDescriptorLength( &i_data, &p_data ); /* SLConfigDescr_length */
3555         switch( IODGetBytes( &i_data, &p_data, 1 ) /* predefined */ )
3556         {
3557         default:
3558             ts_debug( "\n* ERR unsupported SLConfigDescr predefined" );
3559         case 0x01:
3560             // FIXME
3561             break;
3562         }
3563         es_descr->b_ok = true;
3564     }
3565
3566     return p_iod;
3567 }
3568
3569 static void IODFree( iod_descriptor_t *p_iod )
3570 {
3571     if( p_iod->psz_url )
3572     {
3573         free( p_iod->psz_url );
3574         free( p_iod );
3575         return;
3576     }
3577
3578     for( int i = 0; i < 255; i++ )
3579     {
3580 #define es_descr p_iod->es_descr[i]
3581         if( es_descr.b_ok )
3582         {
3583             if( es_descr.psz_url )
3584                 free( es_descr.psz_url );
3585             else
3586                 free( es_descr.dec_descr.p_extra );
3587         }
3588 #undef  es_descr
3589     }
3590     free( p_iod );
3591 }
3592
3593 /****************************************************************************
3594  ****************************************************************************
3595  ** libdvbpsi callbacks
3596  ****************************************************************************
3597  ****************************************************************************/
3598 static bool ProgramIsSelected( demux_t *p_demux, uint16_t i_pgrm )
3599 {
3600     demux_sys_t          *p_sys = p_demux->p_sys;
3601
3602     for(int i=0; i<p_sys->programs.i_size; i++)
3603         if( p_sys->programs.p_elems[i] == i_pgrm )
3604             return true;
3605
3606     return false;
3607 }
3608
3609 static void ValidateDVBMeta( demux_t *p_demux, int i_pid )
3610 {
3611     demux_sys_t *p_sys = p_demux->p_sys;
3612
3613     if( !p_sys->b_dvb_meta || ( i_pid != 0x11 && i_pid != 0x12 && i_pid != 0x14 ) )
3614         return;
3615
3616     msg_Warn( p_demux, "Switching to non DVB mode" );
3617
3618     /* This doesn't look like a DVB stream so don't try
3619      * parsing the SDT/EDT/TDT */
3620
3621     for( int i = 0x11; i <= 0x14; i++ )
3622     {
3623         if( i == 0x13 ) continue;
3624         ts_pid_t *p_pid = &p_sys->pid[i];
3625         if( p_pid->psi )
3626         {
3627
3628 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
3629             if( dvbpsi_decoder_present( p_pid->psi->handle ))
3630                 dvbpsi_DetachDemux( p_pid->psi->handle );
3631             dvbpsi_delete( p_pid->psi->handle );
3632 #else
3633             dvbpsi_DetachDemux( p_pid->psi->handle );
3634 #endif
3635             free( p_pid->psi );
3636             p_pid->psi = NULL;
3637             p_pid->b_valid = false;
3638         }
3639         SetPIDFilter( p_demux, i, false );
3640     }
3641     p_sys->b_dvb_meta = false;
3642 }
3643
3644 #include "dvb-text.h"
3645
3646 static char *EITConvertToUTF8( demux_t *p_demux,
3647                                const unsigned char *psz_instring,
3648                                size_t i_length,
3649                                bool b_broken )
3650 {
3651     demux_sys_t *p_sys = p_demux->p_sys;
3652 #ifdef HAVE_ARIBB24
3653     if( p_sys->arib.e_mode == ARIBMODE_ENABLED )
3654     {
3655         if ( !p_sys->arib.p_instance )
3656             p_sys->arib.p_instance = arib_instance_new( p_demux );
3657         if ( !p_sys->arib.p_instance )
3658             return NULL;
3659         arib_decoder_t *p_decoder = arib_get_decoder( p_sys->arib.p_instance );
3660         if ( !p_decoder )
3661             return NULL;
3662
3663         char *psz_outstring = NULL;
3664         size_t i_out;
3665
3666         i_out = i_length * 4;
3667         psz_outstring = (char*) calloc( i_out + 1, sizeof(char) );
3668         if( !psz_outstring )
3669             return NULL;
3670
3671         arib_initialize_decoder( p_decoder );
3672         i_out = arib_decode_buffer( p_decoder, psz_instring, i_length,
3673                                     psz_outstring, i_out );
3674         arib_finalize_decoder( p_decoder );
3675
3676         return psz_outstring;
3677     }
3678 #else
3679     VLC_UNUSED(p_sys);
3680 #endif
3681     /* Deal with no longer broken providers (no switch byte
3682       but sending ISO_8859-1 instead of ISO_6937) without
3683       removing them from the broken providers table
3684       (keep the entry for correctly handling recorded TS).
3685     */
3686     b_broken = b_broken && i_length && *psz_instring > 0x20;
3687
3688     if( b_broken )
3689         return FromCharset( "ISO_8859-1", psz_instring, i_length );
3690     return vlc_from_EIT( psz_instring, i_length );
3691 }
3692
3693 static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
3694 {
3695     demux_sys_t          *p_sys = p_demux->p_sys;
3696     ts_pid_t             *sdt = &p_sys->pid[0x11];
3697     dvbpsi_sdt_service_t *p_srv;
3698
3699     msg_Dbg( p_demux, "SDTCallBack called" );
3700
3701     if( p_sys->es_creation != CREATE_ES ||
3702        !p_sdt->b_current_next ||
3703         p_sdt->i_version == sdt->psi->i_sdt_version )
3704     {
3705         dvbpsi_DeleteSDT( p_sdt );
3706         return;
3707     }
3708
3709     msg_Dbg( p_demux, "new SDT ts_id=%d version=%d current_next=%d "
3710              "network_id=%d",
3711 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
3712              p_sdt->i_extension,
3713 #else
3714              p_sdt->i_ts_id,
3715 #endif
3716              p_sdt->i_version, p_sdt->b_current_next,
3717              p_sdt->i_network_id );
3718
3719     p_sys->b_broken_charset = false;
3720
3721     for( p_srv = p_sdt->p_first_service; p_srv; p_srv = p_srv->p_next )
3722     {
3723         vlc_meta_t          *p_meta;
3724         dvbpsi_descriptor_t *p_dr;
3725
3726         const char *psz_type = NULL;
3727         const char *psz_status = NULL;
3728
3729         msg_Dbg( p_demux, "  * service id=%d eit schedule=%d present=%d "
3730                  "running=%d free_ca=%d",
3731                  p_srv->i_service_id, p_srv->b_eit_schedule,
3732                  p_srv->b_eit_present, p_srv->i_running_status,
3733                  p_srv->b_free_ca );
3734
3735         if( p_sys->vdr.i_service && p_srv->i_service_id != p_sys->vdr.i_service )
3736         {
3737             msg_Dbg( p_demux, "  * service id=%d skipped (not declared in vdr header)",
3738                      p_sys->vdr.i_service );
3739             continue;
3740         }
3741
3742         p_meta = vlc_meta_New();
3743         for( p_dr = p_srv->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3744         {
3745             if( p_dr->i_tag == 0x48 )
3746             {
3747                 static const char *ppsz_type[17] = {
3748                     "Reserved",
3749                     "Digital television service",
3750                     "Digital radio sound service",
3751                     "Teletext service",
3752                     "NVOD reference service",
3753                     "NVOD time-shifted service",
3754                     "Mosaic service",
3755                     "PAL coded signal",
3756                     "SECAM coded signal",
3757                     "D/D2-MAC",
3758                     "FM Radio",
3759                     "NTSC coded signal",
3760                     "Data broadcast service",
3761                     "Reserved for Common Interface Usage",
3762                     "RCS Map (see EN 301 790 [35])",
3763                     "RCS FLS (see EN 301 790 [35])",
3764                     "DVB MHP service"
3765                 };
3766                 dvbpsi_service_dr_t *pD = dvbpsi_DecodeServiceDr( p_dr );
3767                 char *str1 = NULL;
3768                 char *str2 = NULL;
3769
3770                 /* Workarounds for broadcasters with broken EPG */
3771
3772                 if( p_sdt->i_network_id == 133 )
3773                     p_sys->b_broken_charset = true;  /* SKY DE & BetaDigital use ISO8859-1 */
3774
3775                 /* List of providers using ISO8859-1 */
3776                 static const char ppsz_broken_providers[][8] = {
3777                     "CSAT",     /* CanalSat FR */
3778                     "GR1",      /* France televisions */
3779                     "MULTI4",   /* NT1 */
3780                     "MR5",      /* France 2/M6 HD */
3781                     ""
3782                 };
3783                 for( int i = 0; *ppsz_broken_providers[i]; i++ )
3784                 {
3785                     const size_t i_length = strlen(ppsz_broken_providers[i]);
3786                     if( pD->i_service_provider_name_length == i_length &&
3787                         !strncmp( (char *)pD->i_service_provider_name, ppsz_broken_providers[i], i_length ) )
3788                         p_sys->b_broken_charset = true;
3789                 }
3790
3791                 /* FIXME: Digital+ ES also uses ISO8859-1 */
3792
3793                 str1 = EITConvertToUTF8(p_demux,
3794                                         pD->i_service_provider_name,
3795                                         pD->i_service_provider_name_length,
3796                                         p_sys->b_broken_charset );
3797                 str2 = EITConvertToUTF8(p_demux,
3798                                         pD->i_service_name,
3799                                         pD->i_service_name_length,
3800                                         p_sys->b_broken_charset );
3801
3802                 msg_Dbg( p_demux, "    - type=%d provider=%s name=%s",
3803                          pD->i_service_type, str1, str2 );
3804
3805                 vlc_meta_SetTitle( p_meta, str2 );
3806                 vlc_meta_SetPublisher( p_meta, str1 );
3807                 if( pD->i_service_type >= 0x01 && pD->i_service_type <= 0x10 )
3808                     psz_type = ppsz_type[pD->i_service_type];
3809                 free( str1 );
3810                 free( str2 );
3811             }
3812         }
3813
3814         if( p_srv->i_running_status >= 0x01 && p_srv->i_running_status <= 0x04 )
3815         {
3816             static const char *ppsz_status[5] = {
3817                 "Unknown",
3818                 "Not running",
3819                 "Starts in a few seconds",
3820                 "Pausing",
3821                 "Running"
3822             };
3823             psz_status = ppsz_status[p_srv->i_running_status];
3824         }
3825
3826         if( psz_type )
3827             vlc_meta_AddExtra( p_meta, "Type", psz_type );
3828         if( psz_status )
3829             vlc_meta_AddExtra( p_meta, "Status", psz_status );
3830
3831         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_META,
3832                         p_srv->i_service_id, p_meta );
3833         vlc_meta_Delete( p_meta );
3834     }
3835
3836     sdt->psi->i_sdt_version = p_sdt->i_version;
3837     dvbpsi_DeleteSDT( p_sdt );
3838 }
3839
3840 /* i_year: year - 1900  i_month: 0-11  i_mday: 1-31 i_hour: 0-23 i_minute: 0-59 i_second: 0-59 */
3841 static int64_t vlc_timegm( int i_year, int i_month, int i_mday, int i_hour, int i_minute, int i_second )
3842 {
3843     static const int pn_day[12+1] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
3844     int64_t i_day;
3845
3846     if( i_year < 70 ||
3847         i_month < 0 || i_month > 11 || i_mday < 1 || i_mday > 31 ||
3848         i_hour < 0 || i_hour > 23 || i_minute < 0 || i_minute > 59 || i_second < 0 || i_second > 59 )
3849         return -1;
3850
3851     /* Count the number of days */
3852     i_day = 365 * (i_year-70) + pn_day[i_month] + i_mday - 1;
3853 #define LEAP(y) ( ((y)%4) == 0 && (((y)%100) != 0 || ((y)%400) == 0) ? 1 : 0)
3854     for( int i = 70; i < i_year; i++ )
3855         i_day += LEAP(1900+i);
3856     if( i_month > 1 )
3857         i_day += LEAP(1900+i_year);
3858 #undef LEAP
3859     /**/
3860     return ((24*i_day + i_hour)*60 + i_minute)*60 + i_second;
3861 }
3862
3863 static void EITDecodeMjd( int i_mjd, int *p_y, int *p_m, int *p_d )
3864 {
3865     const int yp = (int)( ( (double)i_mjd - 15078.2)/365.25 );
3866     const int mp = (int)( ((double)i_mjd - 14956.1 - (int)(yp * 365.25)) / 30.6001 );
3867     const int c = ( mp == 14 || mp == 15 ) ? 1 : 0;
3868
3869     *p_y = 1900 + yp + c*1;
3870     *p_m = mp - 1 - c*12;
3871     *p_d = i_mjd - 14956 - (int)(yp*365.25) - (int)(mp*30.6001);
3872 }
3873 #define CVT_FROM_BCD(v) ((((v) >> 4)&0xf)*10 + ((v)&0xf))
3874 static int64_t EITConvertStartTime( uint64_t i_date )
3875 {
3876     const int i_mjd = i_date >> 24;
3877     const int i_hour   = CVT_FROM_BCD(i_date >> 16);
3878     const int i_minute = CVT_FROM_BCD(i_date >>  8);
3879     const int i_second = CVT_FROM_BCD(i_date      );
3880     int i_year;
3881     int i_month;
3882     int i_day;
3883
3884     /* if all 40 bits are 1, the start is unknown */
3885     if( i_date == UINT64_C(0xffffffffff) )
3886         return -1;
3887
3888     EITDecodeMjd( i_mjd, &i_year, &i_month, &i_day );
3889     return vlc_timegm( i_year - 1900, i_month - 1, i_day, i_hour, i_minute, i_second );
3890 }
3891 static int EITConvertDuration( uint32_t i_duration )
3892 {
3893     return CVT_FROM_BCD(i_duration >> 16) * 3600 +
3894            CVT_FROM_BCD(i_duration >> 8 ) * 60 +
3895            CVT_FROM_BCD(i_duration      );
3896 }
3897 #undef CVT_FROM_BCD
3898
3899 static void TDTCallBack( demux_t *p_demux, dvbpsi_tot_t *p_tdt )
3900 {
3901     demux_sys_t        *p_sys = p_demux->p_sys;
3902
3903     p_sys->i_tdt_delta = CLOCK_FREQ * EITConvertStartTime( p_tdt->i_utc_time )
3904                          - mdate();
3905     dvbpsi_DeleteTOT(p_tdt);
3906 }
3907
3908
3909 static void EITCallBack( demux_t *p_demux,
3910                          dvbpsi_eit_t *p_eit, bool b_current_following )
3911 {
3912     demux_sys_t        *p_sys = p_demux->p_sys;
3913     dvbpsi_eit_event_t *p_evt;
3914     vlc_epg_t *p_epg;
3915
3916     msg_Dbg( p_demux, "EITCallBack called" );
3917     if( !p_eit->b_current_next )
3918     {
3919         dvbpsi_DeleteEIT( p_eit );
3920         return;
3921     }
3922
3923     msg_Dbg( p_demux, "new EIT service_id=%d version=%d current_next=%d "
3924              "ts_id=%d network_id=%d segment_last_section_number=%d "
3925              "last_table_id=%d",
3926 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
3927              p_eit->i_extension,
3928 #else
3929              p_eit->i_service_id,
3930 #endif
3931              p_eit->i_version, p_eit->b_current_next,
3932              p_eit->i_ts_id, p_eit->i_network_id,
3933              p_eit->i_segment_last_section_number, p_eit->i_last_table_id );
3934
3935     p_epg = vlc_epg_New( NULL );
3936     for( p_evt = p_eit->p_first_event; p_evt; p_evt = p_evt->p_next )
3937     {
3938         dvbpsi_descriptor_t *p_dr;
3939         char                *psz_name = NULL;
3940         char                *psz_text = NULL;
3941         char                *psz_extra = strdup("");
3942         int64_t i_start;
3943         int i_duration;
3944         int i_min_age = 0;
3945         int64_t i_tot_time = 0;
3946
3947         i_start = EITConvertStartTime( p_evt->i_start_time );
3948         i_duration = EITConvertDuration( p_evt->i_duration );
3949
3950         if( p_sys->arib.e_mode == ARIBMODE_ENABLED )
3951         {
3952             if( p_sys->i_tdt_delta == 0 )
3953                 p_sys->i_tdt_delta = CLOCK_FREQ * (i_start + i_duration - 5) - mdate();
3954
3955             i_tot_time = (mdate() + p_sys->i_tdt_delta) / CLOCK_FREQ;
3956
3957             tzset(); // JST -> UTC
3958             i_start += timezone; // FIXME: what about DST?
3959             i_tot_time += timezone;
3960
3961             if( p_evt->i_running_status == 0x00 &&
3962                 (i_start - 5 < i_tot_time &&
3963                  i_tot_time < i_start + i_duration + 5) )
3964             {
3965                 p_evt->i_running_status = 0x04;
3966                 msg_Dbg( p_demux, "  EIT running status 0x00 -> 0x04" );
3967             }
3968         }
3969
3970         msg_Dbg( p_demux, "  * event id=%d start_time:%d duration=%d "
3971                           "running=%d free_ca=%d",
3972                  p_evt->i_event_id, (int)i_start, (int)i_duration,
3973                  p_evt->i_running_status, p_evt->b_free_ca );
3974
3975         for( p_dr = p_evt->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3976         {
3977             switch(p_dr->i_tag)
3978             {
3979             case 0x4d:
3980             {
3981                 dvbpsi_short_event_dr_t *pE = dvbpsi_DecodeShortEventDr( p_dr );
3982
3983                 /* Only take first description, as we don't handle language-info
3984                    for epg atm*/
3985                 if( pE && psz_name == NULL )
3986                 {
3987                     psz_name = EITConvertToUTF8( p_demux,
3988                                                  pE->i_event_name, pE->i_event_name_length,
3989                                                  p_sys->b_broken_charset );
3990                     free( psz_text );
3991                     psz_text = EITConvertToUTF8( p_demux,
3992                                                  pE->i_text, pE->i_text_length,
3993                                                  p_sys->b_broken_charset );
3994                     msg_Dbg( p_demux, "    - short event lang=%3.3s '%s' : '%s'",
3995                              pE->i_iso_639_code, psz_name, psz_text );
3996                 }
3997             }
3998                 break;
3999
4000             case 0x4e:
4001             {
4002                 dvbpsi_extended_event_dr_t *pE = dvbpsi_DecodeExtendedEventDr( p_dr );
4003                 if( pE )
4004                 {
4005                     msg_Dbg( p_demux, "    - extended event lang=%3.3s [%d/%d]",
4006                              pE->i_iso_639_code,
4007                              pE->i_descriptor_number, pE->i_last_descriptor_number );
4008
4009                     if( pE->i_text_length > 0 )
4010                     {
4011                         char *psz_text = EITConvertToUTF8( p_demux,
4012                                                            pE->i_text, pE->i_text_length,
4013                                                            p_sys->b_broken_charset );
4014                         if( psz_text )
4015                         {
4016                             msg_Dbg( p_demux, "       - text='%s'", psz_text );
4017
4018                             psz_extra = xrealloc( psz_extra,
4019                                    strlen(psz_extra) + strlen(psz_text) + 1 );
4020                             strcat( psz_extra, psz_text );
4021                             free( psz_text );
4022                         }
4023                     }
4024
4025                     for( int i = 0; i < pE->i_entry_count; i++ )
4026                     {
4027                         char *psz_dsc = EITConvertToUTF8( p_demux,
4028                                                           pE->i_item_description[i],
4029                                                           pE->i_item_description_length[i],
4030                                                           p_sys->b_broken_charset );
4031                         char *psz_itm = EITConvertToUTF8( p_demux,
4032                                                           pE->i_item[i], pE->i_item_length[i],
4033                                                           p_sys->b_broken_charset );
4034
4035                         if( psz_dsc && psz_itm )
4036                         {
4037                             msg_Dbg( p_demux, "       - desc='%s' item='%s'", psz_dsc, psz_itm );
4038 #if 0
4039                             psz_extra = xrealloc( psz_extra,
4040                                          strlen(psz_extra) + strlen(psz_dsc) +
4041                                          strlen(psz_itm) + 3 + 1 );
4042                             strcat( psz_extra, "(" );
4043                             strcat( psz_extra, psz_dsc );
4044                             strcat( psz_extra, " " );
4045                             strcat( psz_extra, psz_itm );
4046                             strcat( psz_extra, ")" );
4047 #endif
4048                         }
4049                         free( psz_dsc );
4050                         free( psz_itm );
4051                     }
4052                 }
4053             }
4054                 break;
4055
4056             case 0x55:
4057             {
4058                 dvbpsi_parental_rating_dr_t *pR = dvbpsi_DecodeParentalRatingDr( p_dr );
4059                 if ( pR )
4060                 {
4061                     for ( int i = 0; i < pR->i_ratings_number; i++ )
4062                     {
4063                         const dvbpsi_parental_rating_t *p_rating = & pR->p_parental_rating[ i ];
4064                         if ( p_rating->i_rating > 0x00 && p_rating->i_rating <= 0x0F )
4065                         {
4066                             if ( p_rating->i_rating + 3 > i_min_age )
4067                                 i_min_age = p_rating->i_rating + 3;
4068                             msg_Dbg( p_demux, "    - parental control set to %d years",
4069                                      i_min_age );
4070                         }
4071                     }
4072                 }
4073             }
4074                 break;
4075
4076             default:
4077                 msg_Dbg( p_demux, "    - event unknown dr 0x%x(%d)", p_dr->i_tag, p_dr->i_tag );
4078                 break;
4079             }
4080         }
4081
4082         /* */
4083         if( i_start > 0 && psz_name && psz_text)
4084             vlc_epg_AddEvent( p_epg, i_start, i_duration, psz_name, psz_text,
4085                               *psz_extra ? psz_extra : NULL, i_min_age );
4086
4087         /* Update "now playing" field */
4088         if( p_evt->i_running_status == 0x04 && i_start > 0  && psz_name && psz_text )
4089             vlc_epg_SetCurrent( p_epg, i_start );
4090
4091         free( psz_name );
4092         free( psz_text );
4093
4094         free( psz_extra );
4095     }
4096     if( p_epg->i_event > 0 )
4097     {
4098         if( b_current_following &&
4099             (  p_sys->programs.i_size == 0 ||
4100                p_sys->programs.p_elems[0] ==
4101 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
4102                     p_eit->i_extension
4103 #else
4104                     p_eit->i_service_id
4105 #endif
4106                 ) )
4107         {
4108             p_sys->i_dvb_length = 0;
4109             p_sys->i_dvb_start = 0;
4110
4111             if( p_epg->p_current )
4112             {
4113                 p_sys->i_dvb_start = CLOCK_FREQ * p_epg->p_current->i_start;
4114                 p_sys->i_dvb_length = CLOCK_FREQ * p_epg->p_current->i_duration;
4115             }
4116         }
4117         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_EPG,
4118 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
4119                         p_eit->i_extension,
4120 #else
4121                         p_eit->i_service_id,
4122 #endif
4123                         p_epg );
4124     }
4125     vlc_epg_Delete( p_epg );
4126
4127     dvbpsi_DeleteEIT( p_eit );
4128 }
4129 static void EITCallBackCurrentFollowing( demux_t *p_demux, dvbpsi_eit_t *p_eit )
4130 {
4131     EITCallBack( p_demux, p_eit, true );
4132 }
4133 static void EITCallBackSchedule( demux_t *p_demux, dvbpsi_eit_t *p_eit )
4134 {
4135     EITCallBack( p_demux, p_eit, false );
4136 }
4137
4138 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
4139 static void PSINewTableCallBack( dvbpsi_t *h, uint8_t i_table_id,
4140                                  uint16_t i_extension, demux_t *p_demux )
4141 #else
4142 static void PSINewTableCallBack( demux_t *p_demux, dvbpsi_handle h,
4143                                  uint8_t  i_table_id, uint16_t i_extension )
4144 #endif
4145 {
4146     assert( h );
4147 #if 0
4148     msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4149              i_table_id, i_table_id, i_extension, i_extension );
4150 #endif
4151     if( p_demux->p_sys->pid[0].psi->i_pat_version != -1 && i_table_id == 0x42 )
4152     {
4153         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4154                  i_table_id, i_table_id, i_extension, i_extension );
4155 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
4156         if( !dvbpsi_sdt_attach( h, i_table_id, i_extension, (dvbpsi_sdt_callback)SDTCallBack, p_demux ) )
4157             msg_Err( p_demux, "PSINewTableCallback: failed attaching SDTCallback" );
4158 #else
4159         dvbpsi_AttachSDT( h, i_table_id, i_extension,
4160                           (dvbpsi_sdt_callback)SDTCallBack, p_demux );
4161 #endif
4162     }
4163     else if( p_demux->p_sys->pid[0x11].psi->i_sdt_version != -1 &&
4164              ( i_table_id == 0x4e || /* Current/Following */
4165                (i_table_id >= 0x50 && i_table_id <= 0x5f) ) ) /* Schedule */
4166     {
4167         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4168                  i_table_id, i_table_id, i_extension, i_extension );
4169
4170         dvbpsi_eit_callback cb = i_table_id == 0x4e ?
4171                                     (dvbpsi_eit_callback)EITCallBackCurrentFollowing :
4172                                     (dvbpsi_eit_callback)EITCallBackSchedule;
4173 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
4174         if( !dvbpsi_eit_attach( h, i_table_id, i_extension, cb, p_demux ) )
4175             msg_Err( p_demux, "PSINewTableCallback: failed attaching EITCallback" );
4176 #else
4177         dvbpsi_AttachEIT( h, i_table_id, i_extension, cb, p_demux );
4178 #endif
4179     }
4180     else if( p_demux->p_sys->pid[0x11].psi->i_sdt_version != -1 &&
4181             (i_table_id == 0x70 /* TDT */ || i_table_id == 0x73 /* TOT */) )
4182     {
4183          msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4184                  i_table_id, i_table_id, i_extension, i_extension );
4185 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
4186         if( !dvbpsi_tot_attach( h, i_table_id, i_extension, (dvbpsi_tot_callback)TDTCallBack, p_demux ) )
4187             msg_Err( p_demux, "PSINewTableCallback: failed attaching TDTCallback" );
4188 #else
4189          dvbpsi_AttachTOT( h, i_table_id, i_extension,
4190                            (dvbpsi_tot_callback)TDTCallBack, p_demux);
4191 #endif
4192     }
4193 }
4194
4195 /*****************************************************************************
4196  * PMT callback and helpers
4197  *****************************************************************************/
4198 static dvbpsi_descriptor_t *PMTEsFindDescriptor( const dvbpsi_pmt_es_t *p_es,
4199                                                  int i_tag )
4200 {
4201     dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
4202     while( p_dr && ( p_dr->i_tag != i_tag ) )
4203         p_dr = p_dr->p_next;
4204     return p_dr;
4205 }
4206 static bool PMTEsHasRegistration( demux_t *p_demux,
4207                                   const dvbpsi_pmt_es_t *p_es,
4208                                   const char *psz_tag )
4209 {
4210     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x05 );
4211     if( !p_dr )
4212         return false;
4213
4214     if( p_dr->i_length < 4 )
4215     {
4216         msg_Warn( p_demux, "invalid Registration Descriptor" );
4217         return false;
4218     }
4219
4220     assert( strlen(psz_tag) == 4 );
4221     return !memcmp( p_dr->p_data, psz_tag, 4 );
4222 }
4223
4224 static bool PMTEsHasComponentTag( const dvbpsi_pmt_es_t *p_es,
4225                                   int i_component_tag )
4226 {
4227     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x52 );
4228     if( !p_dr )
4229         return false;
4230     dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4231     if( !p_si )
4232         return false;
4233
4234     return p_si->i_component_tag == i_component_tag;
4235 }
4236
4237 static void PMTSetupEsISO14496( demux_t *p_demux, ts_pid_t *pid,
4238                                 const ts_prg_psi_t *prg, const dvbpsi_pmt_es_t *p_es )
4239 {
4240     es_format_t *p_fmt = &pid->es->fmt;
4241
4242     /* MPEG-4 stream: search FMC_DESCRIPTOR (SL Packetized stream) */
4243     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x1f );
4244
4245     if( p_dr && p_dr->i_length == 2 )
4246     {
4247         const int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
4248
4249         msg_Dbg( p_demux, "found FMC_descriptor declaring sl packetization on es_id=%d", i_es_id );
4250
4251         pid->es->p_mpeg4desc = NULL;
4252
4253         for( int i = 0; i < ES_DESCRIPTOR_COUNT; i++ )
4254         {
4255             iod_descriptor_t *iod = prg->iod;
4256             if( iod->es_descr[i].i_es_id == i_es_id )
4257             {
4258                 if ( iod->es_descr[i].b_ok )
4259                     pid->es->p_mpeg4desc = &iod->es_descr[i];
4260                 else
4261                     msg_Dbg( p_demux, "MPEG-4 descriptor not yet available on es_id=%d", i_es_id );
4262                 break;
4263             }
4264         }
4265     }
4266     if( !pid->es->p_mpeg4desc )
4267     {
4268         switch( p_es->i_type )
4269         {
4270         /* non fatal, set by packetizer */
4271         case 0x0f: /* ADTS */
4272         case 0x11: /* LOAS */
4273             msg_Info( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4274                       pid->i_pid, p_es->i_type );
4275             break;
4276         default:
4277             msg_Err( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4278                      pid->i_pid, p_es->i_type );
4279             break;
4280         }
4281         return;
4282     }
4283
4284     const decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
4285     if( dcd->i_streamType == 0x04 )    /* VisualStream */
4286     {
4287         p_fmt->i_cat = VIDEO_ES;
4288         switch( dcd->i_objectTypeIndication )
4289         {
4290         case 0x0B: /* mpeg4 sub */
4291             p_fmt->i_cat = SPU_ES;
4292             p_fmt->i_codec = VLC_CODEC_SUBT;
4293             break;
4294
4295         case 0x20: /* mpeg4 */
4296             p_fmt->i_codec = VLC_CODEC_MP4V;
4297             break;
4298         case 0x21: /* h264 */
4299             p_fmt->i_codec = VLC_CODEC_H264;
4300             break;
4301         case 0x60:
4302         case 0x61:
4303         case 0x62:
4304         case 0x63:
4305         case 0x64:
4306         case 0x65: /* mpeg2 */
4307             p_fmt->i_codec = VLC_CODEC_MPGV;
4308             break;
4309         case 0x6a: /* mpeg1 */
4310             p_fmt->i_codec = VLC_CODEC_MPGV;
4311             break;
4312         case 0x6c: /* mpeg1 */
4313             p_fmt->i_codec = VLC_CODEC_JPEG;
4314             break;
4315         default:
4316             p_fmt->i_cat = UNKNOWN_ES;
4317             break;
4318         }
4319     }
4320     else if( dcd->i_streamType == 0x05 )    /* AudioStream */
4321     {
4322         p_fmt->i_cat = AUDIO_ES;
4323         switch( dcd->i_objectTypeIndication )
4324         {
4325         case 0x40: /* mpeg4 */
4326             p_fmt->i_codec = VLC_CODEC_MP4A;
4327             break;
4328         case 0x66:
4329         case 0x67:
4330         case 0x68: /* mpeg2 aac */
4331             p_fmt->i_codec = VLC_CODEC_MP4A;
4332             break;
4333         case 0x69: /* mpeg2 */
4334             p_fmt->i_codec = VLC_CODEC_MPGA;
4335             break;
4336         case 0x6b: /* mpeg1 */
4337             p_fmt->i_codec = VLC_CODEC_MPGA;
4338             break;
4339         default:
4340             p_fmt->i_cat = UNKNOWN_ES;
4341             break;
4342         }
4343     }
4344     else
4345     {
4346         p_fmt->i_cat = UNKNOWN_ES;
4347     }
4348
4349     if( p_fmt->i_cat != UNKNOWN_ES )
4350     {
4351         p_fmt->i_extra = dcd->i_extra;
4352         if( p_fmt->i_extra > 0 )
4353         {
4354             p_fmt->p_extra = malloc( p_fmt->i_extra );
4355             if( p_fmt->p_extra )
4356                 memcpy( p_fmt->p_extra, dcd->p_extra, p_fmt->i_extra );
4357             else
4358                 p_fmt->i_extra = 0;
4359         }
4360     }
4361 }
4362
4363 typedef struct
4364 {
4365     int  i_type;
4366     int  i_magazine;
4367     int  i_page;
4368     char p_iso639[3];
4369 } ts_teletext_page_t;
4370
4371 static void PMTSetupEsTeletext( demux_t *p_demux, ts_pid_t *pid,
4372                                 const dvbpsi_pmt_es_t *p_es )
4373 {
4374     es_format_t *p_fmt = &pid->es->fmt;
4375
4376     ts_teletext_page_t p_page[2 * 64 + 20];
4377     unsigned i_page = 0;
4378
4379     /* Gather pages information */
4380 #if defined _DVBPSI_DR_56_H_ && \
4381     defined DVBPSI_VERSION && DVBPSI_VERSION_INT > DVBPSI_VERSION_WANTED(0,1,5)
4382     for( unsigned i_tag_idx = 0; i_tag_idx < 2; i_tag_idx++ )
4383     {
4384         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, i_tag_idx == 0 ? 0x46 : 0x56 );
4385         if( !p_dr )
4386             continue;
4387
4388         dvbpsi_teletext_dr_t *p_sub = dvbpsi_DecodeTeletextDr( p_dr );
4389         if( !p_sub )
4390             continue;
4391
4392         for( int i = 0; i < p_sub->i_pages_number; i++ )
4393         {
4394             const dvbpsi_teletextpage_t *p_src = &p_sub->p_pages[i];
4395
4396             if( p_src->i_teletext_type >= 0x06 )
4397                 continue;
4398
4399             assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4400
4401             ts_teletext_page_t *p_dst = &p_page[i_page++];
4402
4403             p_dst->i_type = p_src->i_teletext_type;
4404             p_dst->i_magazine = p_src->i_teletext_magazine_number
4405                 ? p_src->i_teletext_magazine_number : 8;
4406             p_dst->i_page = p_src->i_teletext_page_number;
4407             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4408         }
4409     }
4410 #endif
4411
4412     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
4413     if( p_dr )
4414     {
4415         dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4416         for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4417         {
4418             dvbpsi_subtitle_t *p_src = &p_sub->p_subtitle[i];
4419
4420             if( p_src->i_subtitling_type < 0x01 || p_src->i_subtitling_type > 0x03 )
4421                 continue;
4422
4423             assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4424
4425             ts_teletext_page_t *p_dst = &p_page[i_page++];
4426
4427             switch( p_src->i_subtitling_type )
4428             {
4429             case 0x01:
4430                 p_dst->i_type = 0x02;
4431                 break;
4432             default:
4433                 p_dst->i_type = 0x03;
4434                 break;
4435             }
4436             /* FIXME check if it is the right split */
4437             p_dst->i_magazine = (p_src->i_composition_page_id >> 8)
4438                 ? (p_src->i_composition_page_id >> 8) : 8;
4439             p_dst->i_page = p_src->i_composition_page_id & 0xff;
4440             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4441         }
4442     }
4443
4444     /* */
4445     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_TELETEXT );
4446
4447     if( !p_demux->p_sys->b_split_es || i_page <= 0 )
4448     {
4449         p_fmt->subs.teletext.i_magazine = -1;
4450         p_fmt->subs.teletext.i_page = 0;
4451         p_fmt->psz_description = strdup( vlc_gettext(ppsz_teletext_type[1]) );
4452
4453         dvbpsi_descriptor_t *p_dr;
4454         p_dr = PMTEsFindDescriptor( p_es, 0x46 );
4455         if( !p_dr )
4456             p_dr = PMTEsFindDescriptor( p_es, 0x56 );
4457
4458         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4459         {
4460             /* Descriptor pass-through */
4461             p_fmt->p_extra = malloc( p_dr->i_length );
4462             if( p_fmt->p_extra )
4463             {
4464                 p_fmt->i_extra = p_dr->i_length;
4465                 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4466             }
4467         }
4468     }
4469     else
4470     {
4471         for( unsigned i = 0; i < i_page; i++ )
4472         {
4473             ts_es_t *p_es;
4474
4475             /* */
4476             if( i == 0 )
4477             {
4478                 p_es = pid->es;
4479             }
4480             else
4481             {
4482                 p_es = malloc( sizeof(*p_es) );
4483                 if( !p_es )
4484                     break;
4485
4486                 es_format_Copy( &p_es->fmt, &pid->es->fmt );
4487                 free( p_es->fmt.psz_language );
4488                 free( p_es->fmt.psz_description );
4489                 p_es->fmt.psz_language = NULL;
4490                 p_es->fmt.psz_description = NULL;
4491
4492                 p_es->id      = NULL;
4493                 p_es->p_data  = NULL;
4494                 p_es->i_data_size = 0;
4495                 p_es->i_data_gathered = 0;
4496                 p_es->pp_last = &p_es->p_data;
4497                 p_es->data_type = TS_ES_DATA_PES;
4498                 p_es->p_mpeg4desc = NULL;
4499
4500                 TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
4501             }
4502
4503             /* */
4504             const ts_teletext_page_t *p = &p_page[i];
4505             p_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ?
4506                       ES_PRIORITY_SELECTABLE_MIN : ES_PRIORITY_NOT_DEFAULTABLE;
4507             p_es->fmt.psz_language = strndup( p->p_iso639, 3 );
4508             p_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
4509             p_es->fmt.subs.teletext.i_magazine = p->i_magazine;
4510             p_es->fmt.subs.teletext.i_page = p->i_page;
4511
4512             msg_Dbg( p_demux,
4513                          "    * ttxt type=%s lan=%s page=%d%02x",
4514                          p_es->fmt.psz_description,
4515                          p_es->fmt.psz_language,
4516                          p->i_magazine, p->i_page );
4517         }
4518     }
4519 }
4520 static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pid_t *pid,
4521                                    const dvbpsi_pmt_es_t *p_es )
4522 {
4523     es_format_t *p_fmt = &pid->es->fmt;
4524
4525     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_DVBS );
4526
4527     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
4528     int i_page = 0;
4529     dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4530     for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4531     {
4532         const int i_type = p_sub->p_subtitle[i].i_subtitling_type;
4533         if( ( i_type >= 0x10 && i_type <= 0x14 ) ||
4534             ( i_type >= 0x20 && i_type <= 0x24 ) )
4535             i_page++;
4536     }
4537
4538     if( !p_demux->p_sys->b_split_es  || i_page <= 0 )
4539     {
4540         p_fmt->subs.dvb.i_id = -1;
4541         p_fmt->psz_description = strdup( _("DVB subtitles") );
4542
4543         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4544         {
4545             /* Descriptor pass-through */
4546             p_fmt->p_extra = malloc( p_dr->i_length );
4547             if( p_fmt->p_extra )
4548             {
4549                 p_fmt->i_extra = p_dr->i_length;
4550                 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4551             }
4552         }
4553     }
4554     else
4555     {
4556         for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4557         {
4558             ts_es_t *p_es;
4559
4560             /* */
4561             if( i == 0 )
4562             {
4563                 p_es = pid->es;
4564             }
4565             else
4566             {
4567                 p_es = malloc( sizeof(*p_es) );
4568                 if( !p_es )
4569                     break;
4570
4571                 es_format_Copy( &p_es->fmt, &pid->es->fmt );
4572                 free( p_es->fmt.psz_language );
4573                 free( p_es->fmt.psz_description );
4574                 p_es->fmt.psz_language = NULL;
4575                 p_es->fmt.psz_description = NULL;
4576
4577                 p_es->id      = NULL;
4578                 p_es->p_data   = NULL;
4579                 p_es->i_data_size = 0;
4580                 p_es->i_data_gathered = 0;
4581                 p_es->pp_last = &p_es->p_data;
4582                 p_es->data_type = TS_ES_DATA_PES;
4583                 p_es->p_mpeg4desc = NULL;
4584
4585                 TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
4586             }
4587
4588             /* */
4589             const dvbpsi_subtitle_t *p = &p_sub->p_subtitle[i];
4590             p_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
4591             switch( p->i_subtitling_type )
4592             {
4593             case 0x10: /* unspec. */
4594             case 0x11: /* 4:3 */
4595             case 0x12: /* 16:9 */
4596             case 0x13: /* 2.21:1 */
4597             case 0x14: /* HD monitor */
4598                 p_es->fmt.psz_description = strdup( _("DVB subtitles") );
4599                 break;
4600             case 0x20: /* Hearing impaired unspec. */
4601             case 0x21: /* h.i. 4:3 */
4602             case 0x22: /* h.i. 16:9 */
4603             case 0x23: /* h.i. 2.21:1 */
4604             case 0x24: /* h.i. HD monitor */
4605                 p_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
4606                 break;
4607             default:
4608                 break;
4609             }
4610
4611             /* Hack, FIXME */
4612             p_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id <<  0 ) |
4613                                       ( p->i_ancillary_page_id   << 16 );
4614         }
4615     }
4616 }
4617
4618 static int vlc_ceil_log2( const unsigned int val )
4619 {
4620     int n = 31 - clz(val);
4621     if ((1U << n) != val)
4622         n++;
4623
4624     return n;
4625 }
4626
4627 static void OpusSetup(demux_t *demux, uint8_t *p, size_t len, es_format_t *p_fmt)
4628 {
4629     OpusHeader h;
4630
4631     /* default mapping */
4632     static const unsigned char map[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
4633     memcpy(h.stream_map, map, sizeof(map));
4634
4635     int csc, mapping;
4636     int channels = 0;
4637     int stream_count = 0;
4638     int ccc = p[1]; // channel_config_code
4639     if (ccc <= 8) {
4640         channels = ccc;
4641         if (channels)
4642             mapping = channels > 2;
4643         else {
4644             mapping = 255;
4645             channels = 2; // dual mono
4646         }
4647         static const uint8_t p_csc[8] = { 0, 1, 1, 2, 2, 2, 3, 3 };
4648         csc = p_csc[channels - 1];
4649         stream_count = channels - csc;
4650
4651         static const uint8_t map[6][7] = {
4652             { 2,1 },
4653             { 1,2,3 },
4654             { 4,1,2,3 },
4655             { 4,1,2,3,5 },
4656             { 4,1,2,3,5,6 },
4657             { 6,1,2,3,4,5,7 },
4658         };
4659         if (channels > 2)
4660             memcpy(&h.stream_map[1], map[channels-3], channels - 1);
4661     } else if (ccc == 0x81) {
4662         if (len < 4)
4663             goto explicit_config_too_short;
4664
4665         channels = p[2];
4666         mapping = p[3];
4667         csc = 0;
4668         if (mapping) {
4669             bs_t s;
4670             bs_init(&s, &p[4], len - 4);
4671             stream_count = 1;
4672             if (channels) {
4673                 int bits = vlc_ceil_log2(channels);
4674                 if (s.i_left < bits)
4675                     goto explicit_config_too_short;
4676                 stream_count = bs_read(&s, bits) + 1;
4677                 bits = vlc_ceil_log2(stream_count + 1);
4678                 if (s.i_left < bits)
4679                     goto explicit_config_too_short;
4680                 csc = bs_read(&s, bits);
4681             }
4682             int channel_bits = vlc_ceil_log2(stream_count + csc + 1);
4683             if (s.i_left < channels * channel_bits)
4684                 goto explicit_config_too_short;
4685
4686             unsigned char silence = (1U << (stream_count + csc + 1)) - 1;
4687             for (int i = 0; i < channels; i++) {
4688                 unsigned char m = bs_read(&s, channel_bits);
4689                 if (m == silence)
4690                     m = 0xff;
4691                 h.stream_map[i] = m;
4692             }
4693         }
4694     } else if (ccc >= 0x80 && ccc <= 0x88) {
4695         channels = ccc - 0x80;
4696         if (channels)
4697             mapping = 1;
4698         else {
4699             mapping = 255;
4700             channels = 2; // dual mono
4701         }
4702         csc = 0;
4703         stream_count = channels;
4704     } else {
4705         msg_Err(demux, "Opus channel configuration 0x%.2x is reserved", ccc);
4706     }
4707
4708     if (!channels) {
4709         msg_Err(demux, "Opus channel configuration 0x%.2x not supported yet", p[1]);
4710         return;
4711     }
4712
4713     opus_prepare_header(channels, 0, &h);
4714     h.preskip = 0;
4715     h.input_sample_rate = 48000;
4716     h.nb_coupled = csc;
4717     h.nb_streams = channels - csc;
4718     h.channel_mapping = mapping;
4719
4720     if (h.channels) {
4721         opus_write_header((uint8_t**)&p_fmt->p_extra, &p_fmt->i_extra, &h, NULL /* FIXME */);
4722         if (p_fmt->p_extra) {
4723             p_fmt->i_cat = AUDIO_ES;
4724             p_fmt->i_codec = VLC_CODEC_OPUS;
4725             p_fmt->audio.i_channels = h.channels;
4726             p_fmt->audio.i_rate = 48000;
4727         }
4728     }
4729
4730     return;
4731
4732 explicit_config_too_short:
4733     msg_Err(demux, "Opus descriptor too short");
4734 }
4735
4736 static void PMTSetupEs0x06( demux_t *p_demux, ts_pid_t *pid,
4737                             const dvbpsi_pmt_es_t *p_es )
4738 {
4739     es_format_t *p_fmt = &pid->es->fmt;
4740     dvbpsi_descriptor_t *p_subs_dr = PMTEsFindDescriptor( p_es, 0x59 );
4741     dvbpsi_descriptor_t *desc;
4742
4743     if( PMTEsHasRegistration( p_demux, p_es, "AC-3" ) ||
4744         PMTEsFindDescriptor( p_es, 0x6a ) ||
4745         PMTEsFindDescriptor( p_es, 0x81 ) )
4746     {
4747         p_fmt->i_cat = AUDIO_ES;
4748         p_fmt->i_codec = VLC_CODEC_A52;
4749     }
4750     else if( (desc = PMTEsFindDescriptor( p_es, 0x7f ) ) && desc->i_length >= 2 &&
4751               PMTEsHasRegistration(p_demux, p_es, "Opus"))
4752     {
4753         OpusSetup(p_demux, desc->p_data, desc->i_length, p_fmt);
4754     }
4755     else if( PMTEsFindDescriptor( p_es, 0x7a ) )
4756     {
4757         /* DVB with stream_type 0x06 (ETS EN 300 468) */
4758         p_fmt->i_cat = AUDIO_ES;
4759         p_fmt->i_codec = VLC_CODEC_EAC3;
4760     }
4761     else if( PMTEsHasRegistration( p_demux, p_es, "DTS1" ) ||
4762              PMTEsHasRegistration( p_demux, p_es, "DTS2" ) ||
4763              PMTEsHasRegistration( p_demux, p_es, "DTS3" ) ||
4764              PMTEsFindDescriptor( p_es, 0x73 ) )
4765     {
4766         /*registration descriptor(ETSI TS 101 154 Annex F)*/
4767         p_fmt->i_cat = AUDIO_ES;
4768         p_fmt->i_codec = VLC_CODEC_DTS;
4769     }
4770     else if( PMTEsHasRegistration( p_demux, p_es, "BSSD" ) && !p_subs_dr )
4771     {
4772         /* BSSD is AES3 DATA, but could also be subtitles
4773          * we need to check for secondary descriptor then s*/
4774         p_fmt->i_cat = AUDIO_ES;
4775         p_fmt->b_packetized = true;
4776         p_fmt->i_codec = VLC_CODEC_302M;
4777     }
4778     else if( PMTEsHasRegistration( p_demux, p_es, "HEVC" ) )
4779     {
4780         p_fmt->i_cat = VIDEO_ES;
4781         p_fmt->i_codec = VLC_CODEC_HEVC;
4782     }
4783     else if ( p_demux->p_sys->arib.e_mode == ARIBMODE_ENABLED )
4784     {
4785         /* Lookup our data component descriptor first ARIB STD B10 6.4 */
4786         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0xFD );
4787         /* and check that it maps to something ARIB STD B14 Table 5.1/5.2 */
4788         if ( p_dr && p_dr->i_length >= 2 )
4789         {
4790             if( !memcmp( p_dr->p_data, "\x00\x08", 2 ) &&  (
4791                     PMTEsHasComponentTag( p_es, 0x30 ) ||
4792                     PMTEsHasComponentTag( p_es, 0x31 ) ||
4793                     PMTEsHasComponentTag( p_es, 0x32 ) ||
4794                     PMTEsHasComponentTag( p_es, 0x33 ) ||
4795                     PMTEsHasComponentTag( p_es, 0x34 ) ||
4796                     PMTEsHasComponentTag( p_es, 0x35 ) ||
4797                     PMTEsHasComponentTag( p_es, 0x36 ) ||
4798                     PMTEsHasComponentTag( p_es, 0x37 ) ) )
4799             {
4800                 es_format_Init( &pid->es->fmt, SPU_ES, VLC_CODEC_ARIB_A );
4801                 p_fmt->psz_language = strndup ( "jpn", 3 );
4802                 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4803             }
4804             else if( !memcmp( p_dr->p_data, "\x00\x12", 2 ) && (
4805                      PMTEsHasComponentTag( p_es, 0x87 ) ||
4806                      PMTEsHasComponentTag( p_es, 0x88 ) ) )
4807             {
4808                 es_format_Init( &pid->es->fmt, SPU_ES, VLC_CODEC_ARIB_C );
4809                 p_fmt->psz_language = strndup ( "jpn", 3 );
4810                 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4811             }
4812         }
4813     }
4814     else
4815     {
4816         /* Subtitle/Teletext/VBI fallbacks */
4817         dvbpsi_subtitling_dr_t *p_sub;
4818         if( p_subs_dr && ( p_sub = dvbpsi_DecodeSubtitlingDr( p_subs_dr ) ) )
4819         {
4820             for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4821             {
4822                 if( p_fmt->i_cat != UNKNOWN_ES )
4823                     break;
4824
4825                 switch( p_sub->p_subtitle[i].i_subtitling_type )
4826                 {
4827                 case 0x01: /* EBU Teletext subtitles */
4828                 case 0x02: /* Associated EBU Teletext */
4829                 case 0x03: /* VBI data */
4830                     PMTSetupEsTeletext( p_demux, pid, p_es );
4831                     break;
4832                 case 0x10: /* DVB Subtitle (normal) with no monitor AR critical */
4833                 case 0x11: /*                 ...   on 4:3 AR monitor */
4834                 case 0x12: /*                 ...   on 16:9 AR monitor */
4835                 case 0x13: /*                 ...   on 2.21:1 AR monitor */
4836                 case 0x14: /*                 ...   for display on a high definition monitor */
4837                 case 0x20: /* DVB Subtitle (impaired) with no monitor AR critical */
4838                 case 0x21: /*                 ...   on 4:3 AR monitor */
4839                 case 0x22: /*                 ...   on 16:9 AR monitor */
4840                 case 0x23: /*                 ...   on 2.21:1 AR monitor */
4841                 case 0x24: /*                 ...   for display on a high definition monitor */
4842                     PMTSetupEsDvbSubtitle( p_demux, pid, p_es );
4843                     break;
4844                 default:
4845                     msg_Err( p_demux, "Unrecognized DVB subtitle type (0x%x)",
4846                              p_sub->p_subtitle[i].i_subtitling_type );
4847                     break;
4848                 }
4849             }
4850         }
4851
4852         if( p_fmt->i_cat == UNKNOWN_ES &&
4853             ( PMTEsFindDescriptor( p_es, 0x45 ) ||  /* VBI Data descriptor */
4854               PMTEsFindDescriptor( p_es, 0x46 ) ||  /* VBI Teletext descriptor */
4855               PMTEsFindDescriptor( p_es, 0x56 ) ) ) /* EBU Teletext descriptor */
4856         {
4857             /* Teletext/VBI */
4858             PMTSetupEsTeletext( p_demux, pid, p_es );
4859         }
4860     }
4861
4862     /* FIXME is it useful ? */
4863     if( PMTEsFindDescriptor( p_es, 0x52 ) )
4864     {
4865         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x52 );
4866         dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4867
4868         msg_Dbg( p_demux, "    * Stream Component Identifier: %d", p_si->i_component_tag );
4869     }
4870 }
4871
4872 static void PMTSetupEs0xEA( demux_t *p_demux, ts_pid_t *pid,
4873                            const dvbpsi_pmt_es_t *p_es )
4874 {
4875     /* Registration Descriptor */
4876     if( !PMTEsHasRegistration( p_demux, p_es, "VC-1" ) )
4877     {
4878         msg_Err( p_demux, "Registration descriptor not found or invalid" );
4879         return;
4880     }
4881
4882     es_format_t *p_fmt = &pid->es->fmt;
4883
4884     /* registration descriptor for VC-1 (SMPTE rp227) */
4885     p_fmt->i_cat = VIDEO_ES;
4886     p_fmt->i_codec = VLC_CODEC_VC1;
4887
4888     /* XXX With Simple and Main profile the SEQUENCE
4889      * header is modified: video width and height are
4890      * inserted just after the start code as 2 int16_t
4891      * The packetizer will take care of that. */
4892 }
4893
4894 static void PMTSetupEs0xD1( demux_t *p_demux, ts_pid_t *pid,
4895                            const dvbpsi_pmt_es_t *p_es )
4896 {
4897     /* Registration Descriptor */
4898     if( !PMTEsHasRegistration( p_demux, p_es, "drac" ) )
4899     {
4900         msg_Err( p_demux, "Registration descriptor not found or invalid" );
4901         return;
4902     }
4903
4904     es_format_t *p_fmt = &pid->es->fmt;
4905
4906     /* registration descriptor for Dirac
4907      * (backwards compatable with VC-2 (SMPTE Sxxxx:2008)) */
4908     p_fmt->i_cat = VIDEO_ES;
4909     p_fmt->i_codec = VLC_CODEC_DIRAC;
4910 }
4911
4912 static void PMTSetupEs0xA0( demux_t *p_demux, ts_pid_t *pid,
4913                            const dvbpsi_pmt_es_t *p_es )
4914 {
4915     /* MSCODEC sent by vlc */
4916     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0xa0 );
4917     if( !p_dr || p_dr->i_length < 10 )
4918     {
4919         msg_Warn( p_demux,
4920                   "private MSCODEC (vlc) without bih private descriptor" );
4921         return;
4922     }
4923
4924     es_format_t *p_fmt = &pid->es->fmt;
4925     p_fmt->i_cat = VIDEO_ES;
4926     p_fmt->i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
4927                                  p_dr->p_data[2], p_dr->p_data[3] );
4928     p_fmt->video.i_width = GetWBE( &p_dr->p_data[4] );
4929     p_fmt->video.i_height = GetWBE( &p_dr->p_data[6] );
4930     p_fmt->i_extra = GetWBE( &p_dr->p_data[8] );
4931
4932     if( p_fmt->i_extra > 0 )
4933     {
4934         p_fmt->p_extra = malloc( p_fmt->i_extra );
4935         if( p_fmt->p_extra )
4936             memcpy( p_fmt->p_extra, &p_dr->p_data[10],
4937                     __MIN( p_fmt->i_extra, p_dr->i_length - 10 ) );
4938         else
4939             p_fmt->i_extra = 0;
4940     }
4941     /* For such stream we will gather them ourself and don't launch a
4942      * packetizer.
4943      * Yes it's ugly but it's the only way to have DIV3 working */
4944     p_fmt->b_packetized = true;
4945 }
4946
4947 static void PMTSetupEs0x83( const dvbpsi_pmt_t *p_pmt, ts_pid_t *pid )
4948 {
4949     /* WiDi broadcasts without registration on PMT 0x1, PCR 0x1000 and
4950      * with audio track pid being 0x1100..0x11FF */
4951     if ( p_pmt->i_program_number == 0x1 &&
4952          p_pmt->i_pcr_pid == 0x1000 &&
4953         ( pid->i_pid >> 8 ) == 0x11 )
4954     {
4955         /* Not enough ? might contain 0x83 private descriptor, 2 bytes 0x473F */
4956         es_format_Init( &pid->es->fmt, AUDIO_ES, VLC_CODEC_WIDI_LPCM );
4957     }
4958     else
4959         es_format_Init( &pid->es->fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
4960 }
4961
4962 static bool PMTSetupEsHDMV( demux_t *p_demux, ts_pid_t *pid,
4963                             const dvbpsi_pmt_es_t *p_es )
4964 {
4965     es_format_t *p_fmt = &pid->es->fmt;
4966
4967     /* Blu-Ray mapping */
4968     switch( p_es->i_type )
4969     {
4970     case 0x80:
4971         p_fmt->i_cat = AUDIO_ES;
4972         p_fmt->i_codec = VLC_CODEC_BD_LPCM;
4973         break;
4974     case 0x81:
4975         p_fmt->i_cat = AUDIO_ES;
4976         p_fmt->i_codec = VLC_CODEC_A52;
4977         break;
4978     case 0x82:
4979     case 0x85: /* DTS-HD High resolution audio */
4980     case 0x86: /* DTS-HD Master audio */
4981     case 0xA2: /* Secondary DTS audio */
4982         p_fmt->i_cat = AUDIO_ES;
4983         p_fmt->i_codec = VLC_CODEC_DTS;
4984         break;
4985
4986     case 0x83: /* TrueHD AC3 */
4987         p_fmt->i_cat = AUDIO_ES;
4988         p_fmt->i_codec = VLC_CODEC_TRUEHD;
4989         break;
4990
4991     case 0x84: /* E-AC3 */
4992     case 0xA1: /* Secondary E-AC3 */
4993         p_fmt->i_cat = AUDIO_ES;
4994         p_fmt->i_codec = VLC_CODEC_EAC3;
4995         break;
4996     case 0x90: /* Presentation graphics */
4997         p_fmt->i_cat = SPU_ES;
4998         p_fmt->i_codec = VLC_CODEC_BD_PG;
4999         break;
5000     case 0x91: /* Interactive graphics */
5001     case 0x92: /* Subtitle */
5002         return false;
5003     case 0xEA:
5004         p_fmt->i_cat = VIDEO_ES;
5005         p_fmt->i_codec = VLC_CODEC_VC1;
5006         break;
5007     default:
5008         msg_Info( p_demux, "HDMV registration not implemented for pid 0x%x type 0x%x",
5009                   p_es->i_pid, p_es->i_type );
5010         return false;
5011         break;
5012     }
5013     return true;
5014 }
5015
5016 static bool PMTSetupEsRegistration( demux_t *p_demux, ts_pid_t *pid,
5017                                     const dvbpsi_pmt_es_t *p_es )
5018 {
5019     static const struct
5020     {
5021         char         psz_tag[5];
5022         int          i_cat;
5023         vlc_fourcc_t i_codec;
5024     } p_regs[] = {
5025         { "AC-3", AUDIO_ES, VLC_CODEC_A52   },
5026         { "DTS1", AUDIO_ES, VLC_CODEC_DTS   },
5027         { "DTS2", AUDIO_ES, VLC_CODEC_DTS   },
5028         { "DTS3", AUDIO_ES, VLC_CODEC_DTS   },
5029         { "BSSD", AUDIO_ES, VLC_CODEC_302M  },
5030         { "VC-1", VIDEO_ES, VLC_CODEC_VC1   },
5031         { "drac", VIDEO_ES, VLC_CODEC_DIRAC },
5032         { "", UNKNOWN_ES, 0 }
5033     };
5034     es_format_t *p_fmt = &pid->es->fmt;
5035
5036     for( int i = 0; p_regs[i].i_cat != UNKNOWN_ES; i++ )
5037     {
5038         if( PMTEsHasRegistration( p_demux, p_es, p_regs[i].psz_tag ) )
5039         {
5040             p_fmt->i_cat   = p_regs[i].i_cat;
5041             p_fmt->i_codec = p_regs[i].i_codec;
5042             if (p_es->i_type == 0x87)
5043                 p_fmt->i_codec = VLC_CODEC_EAC3;
5044             return true;
5045         }
5046     }
5047     return false;
5048 }
5049
5050 static char *GetAudioTypeDesc(demux_t *p_demux, int type)
5051 {
5052     static const char *audio_type[] = {
5053         NULL,
5054         N_("clean effects"),
5055         N_("hearing impaired"),
5056         N_("visual impaired commentary"),
5057     };
5058
5059     if (type < 0 || type > 3)
5060         msg_Dbg( p_demux, "unknown audio type: %d", type);
5061     else if (type > 0)
5062         return strdup(audio_type[type]);
5063
5064     return NULL;
5065 }
5066 static void PMTParseEsIso639( demux_t *p_demux, ts_pid_t *pid,
5067                               const dvbpsi_pmt_es_t *p_es )
5068 {
5069     /* get language descriptor */
5070     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x0a );
5071
5072     if( !p_dr )
5073         return;
5074
5075     dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
5076     if( !p_decoded )
5077     {
5078         msg_Err( p_demux, "Failed to decode a ISO 639 descriptor" );
5079         return;
5080     }
5081
5082 #if defined(DR_0A_API_VER) && (DR_0A_API_VER >= 2)
5083     pid->es->fmt.psz_language = malloc( 4 );
5084     if( pid->es->fmt.psz_language )
5085     {
5086         memcpy( pid->es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
5087         pid->es->fmt.psz_language[3] = 0;
5088         msg_Dbg( p_demux, "found language: %s", pid->es->fmt.psz_language);
5089     }
5090     int type = p_decoded->code[0].i_audio_type;
5091     pid->es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
5092     if (type == 0)
5093         pid->es->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1; // prioritize normal audio tracks
5094
5095     pid->es->fmt.i_extra_languages = p_decoded->i_code_count-1;
5096     if( pid->es->fmt.i_extra_languages > 0 )
5097         pid->es->fmt.p_extra_languages =
5098             malloc( sizeof(*pid->es->fmt.p_extra_languages) *
5099                     pid->es->fmt.i_extra_languages );
5100     if( pid->es->fmt.p_extra_languages )
5101     {
5102         for( unsigned i = 0; i < pid->es->fmt.i_extra_languages; i++ )
5103         {
5104             pid->es->fmt.p_extra_languages[i].psz_language = malloc(4);
5105             if( pid->es->fmt.p_extra_languages[i].psz_language )
5106             {
5107                 memcpy( pid->es->fmt.p_extra_languages[i].psz_language,
5108                     p_decoded->code[i+1].iso_639_code, 3 );
5109                 pid->es->fmt.p_extra_languages[i].psz_language[3] = '\0';
5110             }
5111             int type = p_decoded->code[i].i_audio_type;
5112             pid->es->fmt.p_extra_languages[i].psz_description = GetAudioTypeDesc(p_demux, type);
5113         }
5114     }
5115 #else
5116     pid->es->fmt.psz_language = malloc( 4 );
5117     if( pid->es->fmt.psz_language )
5118     {
5119         memcpy( pid->es->fmt.psz_language,
5120                 p_decoded->i_iso_639_code, 3 );
5121         pid->es->fmt.psz_language[3] = 0;
5122     }
5123 #endif
5124 }
5125
5126 static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid )
5127 {
5128     demux_sys_t  *p_sys = p_demux->p_sys;
5129     bool b_create_delayed = false;
5130
5131     if( pid )
5132     {
5133         if( pid->b_seen && p_sys->es_creation == DELAY_ES )
5134         {
5135             p_sys->es_creation = CREATE_ES;
5136             b_create_delayed = true;
5137         }
5138
5139         if( p_sys->es_creation == CREATE_ES )
5140         {
5141             pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
5142             for( int i = 0; i < pid->i_extra_es; i++ )
5143             {
5144                 pid->extra_es[i]->id =
5145                     es_out_Add( p_demux->out, &pid->extra_es[i]->fmt );
5146             }
5147             p_sys->i_pmt_es += 1 + pid->i_extra_es;
5148         }
5149     }
5150     else if( p_sys->es_creation == DELAY_ES )
5151     {
5152         p_sys->es_creation = CREATE_ES;
5153         b_create_delayed = true;
5154     }
5155
5156     if( b_create_delayed )
5157     {
5158         for(int i=MIN_ES_PID; i<=MAX_ES_PID; i++)
5159         {
5160             pid = &p_sys->pid[i];
5161             if(!pid->es || pid->es->id)
5162                 continue;
5163             pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
5164             for( int j = 0; j < pid->i_extra_es; j++ )
5165             {
5166                 pid->extra_es[j]->id =
5167                     es_out_Add( p_demux->out, &pid->extra_es[j]->fmt );
5168             }
5169             p_sys->i_pmt_es += 1 + pid->i_extra_es;
5170
5171             if( pid->es->id != NULL && ProgramIsSelected( p_demux, pid->i_owner_number ) )
5172                 SetPIDFilter( p_demux, pid->i_pid, true );
5173         }
5174     }
5175 }
5176
5177 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt )
5178 {
5179     demux_t      *p_demux = data;
5180     demux_sys_t  *p_sys = p_demux->p_sys;
5181
5182     ts_pid_t     *pmt = NULL;
5183     ts_prg_psi_t *prg;
5184
5185     msg_Dbg( p_demux, "PMTCallBack called" );
5186
5187     /* First find this PMT declared in PAT */
5188     for( int i = 0; !pmt && i < p_sys->i_pmt; i++ )
5189         for( int i_prg = 0; !pmt && i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
5190         {
5191             const int i_pmt_number = p_sys->pmt[i]->psi->prg[i_prg]->i_number;
5192             if( i_pmt_number != TS_USER_PMT_NUMBER &&
5193                 i_pmt_number == p_pmt->i_program_number )
5194             {
5195                 pmt = p_sys->pmt[i];
5196                 prg = p_sys->pmt[i]->psi->prg[i_prg];
5197             }
5198         }
5199
5200     if( pmt == NULL )
5201     {
5202         msg_Warn( p_demux, "unreferenced program (broken stream)" );
5203         dvbpsi_DeletePMT(p_pmt);
5204         return;
5205     }
5206
5207
5208     if( prg->i_version != -1 &&
5209         ( !p_pmt->b_current_next || prg->i_version == p_pmt->i_version ) )
5210     {
5211         dvbpsi_DeletePMT( p_pmt );
5212         return;
5213     }
5214
5215     ts_pid_t **pp_clean = NULL;
5216     int      i_clean = 0;
5217     /* Clean this program (remove all es) */
5218     for( int i = 0; i < 8192; i++ )
5219     {
5220         ts_pid_t *pid = &p_sys->pid[i];
5221
5222         if( pid->b_valid && pid->p_owner == pmt->psi &&
5223             pid->i_owner_number == prg->i_number && pid->psi == NULL )
5224         {
5225             TAB_APPEND( i_clean, pp_clean, pid );
5226         }
5227     }
5228     if( prg->iod )
5229     {
5230         IODFree( prg->iod );
5231         prg->iod = NULL;
5232     }
5233
5234     msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
5235              p_pmt->i_program_number, p_pmt->i_version, p_pmt->i_pcr_pid );
5236     prg->i_pid_pcr = p_pmt->i_pcr_pid;
5237     prg->i_version = p_pmt->i_version;
5238
5239     ValidateDVBMeta( p_demux, prg->i_pid_pcr );
5240     if( ProgramIsSelected( p_demux, prg->i_number ) )
5241         SetPIDFilter( p_demux, prg->i_pid_pcr, true ); /* Set demux filter */
5242
5243     /* Parse PMT descriptors */
5244     ts_pmt_registration_type_t registration_type = TS_PMT_REGISTRATION_NONE;
5245     dvbpsi_descriptor_t  *p_dr;
5246
5247     /* First pass for standard detection */
5248     if ( p_sys->arib.e_mode == ARIBMODE_AUTO )
5249     {
5250         int i_arib_flags = 0; /* Descriptors can be repeated */
5251         for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5252         {
5253             switch(p_dr->i_tag)
5254             {
5255             case 0x09:
5256             {
5257                 dvbpsi_ca_dr_t *p_cadr = dvbpsi_DecodeCADr( p_dr );
5258                 i_arib_flags |= (p_cadr->i_ca_system_id == 0x05);
5259             }
5260                 break;
5261             case 0xF6:
5262                 i_arib_flags |= 1 << 1;
5263                 break;
5264             case 0xC1:
5265                 i_arib_flags |= 1 << 2;
5266                 break;
5267             default:
5268                 break;
5269             }
5270         }
5271         if ( i_arib_flags == 0x07 ) //0b111
5272             p_sys->arib.e_mode = ARIBMODE_ENABLED;
5273     }
5274
5275     for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5276     {
5277         /* special descriptors handling */
5278         switch(p_dr->i_tag)
5279         {
5280         case 0x1d: /* We have found an IOD descriptor */
5281             msg_Dbg( p_demux, " * PMT descriptor : IOD (0x1d)" );
5282             prg->iod = IODNew( p_dr->i_length, p_dr->p_data );
5283             break;
5284
5285         case 0x9:
5286             msg_Dbg( p_demux, " * PMT descriptor : CA (0x9) SysID 0x%x",
5287                     (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5288             break;
5289
5290         case 0x5: /* Registration Descriptor */
5291             if( p_dr->i_length != 4 )
5292             {
5293                 msg_Warn( p_demux, " * PMT invalid Registration Descriptor" );
5294             }
5295             else
5296             {
5297                 msg_Dbg( p_demux, " * PMT descriptor : registration %4.4s", p_dr->p_data );
5298                 if( !memcmp( p_dr->p_data, "HDMV", 4 ) || !memcmp( p_dr->p_data, "HDPR", 4 ) )
5299                     registration_type = TS_PMT_REGISTRATION_HDMV; /* Blu-Ray */
5300             }
5301             break;
5302
5303         case 0x0f:
5304             msg_Dbg( p_demux, " * PMT descriptor : Private Data (0x0f)" );
5305             break;
5306
5307         case 0xC1:
5308             msg_Dbg( p_demux, " * PMT descriptor : Digital copy control (0xC1)" );
5309             break;
5310
5311         case 0x88: /* EACEM Simulcast HD Logical channels ordering */
5312             msg_Dbg( p_demux, " * descriptor : EACEM Simulcast HD" );
5313             /* TODO: apply visibility flags */
5314             break;
5315
5316         default:
5317             msg_Dbg( p_demux, " * PMT descriptor : unknown (0x%x)", p_dr->i_tag );
5318         }
5319     }
5320     dvbpsi_pmt_es_t      *p_es;
5321     for( p_es = p_pmt->p_first_es; p_es != NULL; p_es = p_es->p_next )
5322     {
5323         ts_pid_t tmp_pid = {0}, *old_pid = {0}, *pid = &tmp_pid;
5324
5325         /* Find out if the PID was already declared */
5326         for( int i = 0; i < i_clean; i++ )
5327         {
5328             if( pp_clean[i] == &p_sys->pid[p_es->i_pid] )
5329             {
5330                 old_pid = pp_clean[i];
5331                 break;
5332             }
5333         }
5334         ValidateDVBMeta( p_demux, p_es->i_pid );
5335
5336         if( !old_pid && p_sys->pid[p_es->i_pid].b_valid )
5337         {
5338             msg_Warn( p_demux, " * PMT error: pid=%d already defined",
5339                       p_es->i_pid );
5340             continue;
5341         }
5342
5343         char const * psz_typedesc = "";
5344         switch(p_es->i_type)
5345         {
5346         case 0x00:
5347             psz_typedesc = "ISO/IEC Reserved";
5348             break;
5349         case 0x01:
5350             psz_typedesc = "ISO/IEC 11172 Video";
5351             break;
5352         case 0x02:
5353             psz_typedesc = "ISO/IEC 13818-2 Video or ISO/IEC 11172-2 constrained parameter video stream";
5354             break;
5355         case 0x03:
5356             psz_typedesc = "ISO/IEC 11172 Audio";
5357             break;
5358         case 0x04:
5359             psz_typedesc = "ISO/IEC 13818-3 Audio";
5360             break;
5361         case 0x05:
5362             psz_typedesc = "ISO/IEC 13818-1 private_sections";
5363             break;
5364         case 0x06:
5365             psz_typedesc = "ISO/IEC 13818-1 PES packets containing private data";
5366             break;
5367         case 0x07:
5368             psz_typedesc = "ISO/IEC 13522 MHEG";
5369             break;
5370         case 0x08:
5371             psz_typedesc = "ISO/IEC 13818-1 Annex A DSM CC";
5372             break;
5373         case 0x09:
5374             psz_typedesc = "ITU-T Rec. H.222.1";
5375             break;
5376         case 0x0A:
5377             psz_typedesc = "ISO/IEC 13818-6 type A";
5378             break;
5379         case 0x0B:
5380             psz_typedesc = "ISO/IEC 13818-6 type B";
5381             break;
5382         case 0x0C:
5383             psz_typedesc = "ISO/IEC 13818-6 type C";
5384             break;
5385         case 0x0D:
5386             psz_typedesc = "ISO/IEC 13818-6 type D";
5387             break;
5388         case 0x0E:
5389             psz_typedesc = "ISO/IEC 13818-1 auxiliary";
5390             break;
5391         default:
5392             if (p_es->i_type >= 0x0F && p_es->i_type <=0x7F)
5393                 psz_typedesc = "ISO/IEC 13818-1 Reserved";
5394             else
5395                 psz_typedesc = "User Private";
5396         }
5397
5398         msg_Dbg( p_demux, "  * pid=%d type=0x%x %s",
5399                  p_es->i_pid, p_es->i_type, psz_typedesc );
5400
5401         for( p_dr = p_es->p_first_descriptor; p_dr != NULL;
5402              p_dr = p_dr->p_next )
5403         {
5404             msg_Dbg( p_demux, "    - descriptor tag 0x%x",
5405                      p_dr->i_tag );
5406         }
5407
5408         PIDInit( pid, false, pmt->psi );
5409         PIDFillFormat( &pid->es->fmt, p_es->i_type );
5410         pid->i_owner_number = prg->i_number;
5411         pid->i_pid          = p_es->i_pid;
5412         pid->b_seen         = p_sys->pid[p_es->i_pid].b_seen;
5413
5414
5415         bool b_registration_applied = false;
5416         if ( p_es->i_type >= 0x80 ) /* non standard, extensions */
5417         {
5418             if ( registration_type == TS_PMT_REGISTRATION_HDMV )
5419             {
5420                 if (( b_registration_applied = PMTSetupEsHDMV( p_demux, pid, p_es ) ))
5421                     msg_Dbg( p_demux, "    + HDMV registration applied to pid %d type 0x%x",
5422                              p_es->i_pid, p_es->i_type );
5423             }
5424             else
5425             {
5426                 if (( b_registration_applied = PMTSetupEsRegistration( p_demux, pid, p_es ) ))
5427                     msg_Dbg( p_demux, "    + registration applied to pid %d type 0x%x",
5428                         p_es->i_pid, p_es->i_type );
5429             }
5430         }
5431
5432         if ( !b_registration_applied )
5433         {
5434             switch( p_es->i_type )
5435             {
5436             case 0x06:
5437                 /* Handle PES private data */
5438                 PMTSetupEs0x06( p_demux, pid, p_es );
5439                 break;
5440             /* All other private or reserved types */
5441             case 0x0f:
5442             case 0x10:
5443             case 0x11:
5444             case 0x12:
5445                 PMTSetupEsISO14496( p_demux, pid, prg, p_es );
5446                 break;
5447             case 0x83:
5448                 /* LPCM (audio) */
5449                 PMTSetupEs0x83( p_pmt, pid );
5450                 break;
5451             case 0xa0:
5452                 PMTSetupEs0xA0( p_demux, pid, p_es );
5453                 break;
5454             case 0xd1:
5455                 PMTSetupEs0xD1( p_demux, pid, p_es );
5456                 break;
5457             case 0xEA:
5458                 PMTSetupEs0xEA( p_demux, pid, p_es );
5459             default:
5460                 break;
5461             }
5462         }
5463
5464         if( pid->es->fmt.i_cat == AUDIO_ES ||
5465             ( pid->es->fmt.i_cat == SPU_ES &&
5466               pid->es->fmt.i_codec != VLC_CODEC_DVBS &&
5467               pid->es->fmt.i_codec != VLC_CODEC_TELETEXT ) )
5468         {
5469             PMTParseEsIso639( p_demux, pid, p_es );
5470         }
5471
5472         switch( pid->es->fmt.i_codec )
5473         {
5474         case VLC_CODEC_SCTE_27:
5475             pid->es->data_type = TS_ES_DATA_TABLE_SECTION;
5476             break;
5477         default:
5478             //pid->es->data_type = TS_ES_DATA_PES;
5479             break;
5480         }
5481
5482         pid->es->fmt.i_group = p_pmt->i_program_number;
5483         for( int i = 0; i < pid->i_extra_es; i++ )
5484             pid->extra_es[i]->fmt.i_group = p_pmt->i_program_number;
5485
5486         if( pid->es->fmt.i_cat == UNKNOWN_ES )
5487         {
5488             msg_Dbg( p_demux, "   => pid %d content is *unknown*",
5489                      p_es->i_pid );
5490         }
5491         else
5492         {
5493             msg_Dbg( p_demux, "   => pid %d has now es fcc=%4.4s",
5494                      p_es->i_pid, (char*)&pid->es->fmt.i_codec );
5495
5496             if( p_sys->b_es_id_pid ) pid->es->fmt.i_id = p_es->i_pid;
5497
5498             /* Check if we can avoid restarting the ES */
5499             if( old_pid &&
5500                 pid->es->fmt.i_codec == old_pid->es->fmt.i_codec &&
5501                 pid->es->fmt.i_extra == old_pid->es->fmt.i_extra &&
5502                 pid->es->fmt.i_extra == 0 &&
5503                 pid->i_extra_es == old_pid->i_extra_es &&
5504                 ( ( !pid->es->fmt.psz_language &&
5505                     !old_pid->es->fmt.psz_language ) ||
5506                   ( pid->es->fmt.psz_language &&
5507                     old_pid->es->fmt.psz_language &&
5508                     !strcmp( pid->es->fmt.psz_language,
5509                              old_pid->es->fmt.psz_language ) ) ) )
5510             {
5511                 pid->i_cc = old_pid->i_cc;
5512                 ts_es_t *e = pid->es;
5513                 pid->es = old_pid->es;
5514                 old_pid->es = e;
5515                 for( int i = 0; i < pid->i_extra_es; i++ )
5516                 {
5517                     e = pid->extra_es[i];
5518                     pid->extra_es[i] = old_pid->extra_es[i];
5519                     old_pid->extra_es[i] = e;
5520                 }
5521             }
5522             else
5523             {
5524                 AddAndCreateES( p_demux, pid );
5525             }
5526         }
5527
5528         /* Add ES to the list */
5529         if( old_pid )
5530         {
5531             PIDClean( p_demux, old_pid );
5532             TAB_REMOVE( i_clean, pp_clean, old_pid );
5533         }
5534         p_sys->pid[p_es->i_pid] = *pid;
5535
5536         p_dr = PMTEsFindDescriptor( p_es, 0x09 );
5537         if( p_dr && p_dr->i_length >= 2 )
5538         {
5539             msg_Dbg( p_demux, "   * PMT descriptor : CA (0x9) SysID 0x%x",
5540                      (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5541         }
5542
5543         if( ProgramIsSelected( p_demux, prg->i_number ) && pid->es->id != NULL )
5544             SetPIDFilter( p_demux, p_es->i_pid, true ); /* Set demux filter */
5545     }
5546
5547     /* Set CAM descrambling */
5548     if( !ProgramIsSelected( p_demux, prg->i_number ) )
5549     {
5550         dvbpsi_DeletePMT( p_pmt );
5551     }
5552     else if( stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_CA,
5553                              p_pmt ) != VLC_SUCCESS )
5554     {
5555         if ( p_sys->arib.e_mode == ARIBMODE_ENABLED )
5556         {
5557             p_sys->arib.b25stream = stream_FilterNew( p_demux->s, "aribcam" );
5558             p_sys->stream = ( p_sys->arib.b25stream ) ? p_sys->arib.b25stream : p_demux->s;
5559             if (!p_sys->arib.b25stream)
5560                 dvbpsi_DeletePMT( p_pmt );
5561         } else dvbpsi_DeletePMT( p_pmt );
5562     }
5563
5564     for( int i = 0; i < i_clean; i++ )
5565     {
5566         if( ProgramIsSelected( p_demux, prg->i_number ) )
5567             SetPIDFilter( p_demux, pp_clean[i]->i_pid, false );
5568
5569         PIDClean( p_demux, pp_clean[i] );
5570     }
5571     if( i_clean )
5572         free( pp_clean );
5573
5574     if( !p_sys->b_trust_pcr )
5575     {
5576         int i_cand = FindPCRCandidate( p_demux->p_sys, prg );
5577         prg->i_pid_pcr = i_cand;
5578         prg->pcr.b_disable = true;
5579         msg_Warn( p_demux, "PCR not trusted for program %d, set up workaround using pid %d",
5580                   prg->i_number, i_cand );
5581     }
5582
5583     /* Probe Boundaries */
5584     if( p_sys->b_canfastseek && prg->i_last_dts == -1 )
5585     {
5586         prg->i_last_dts = 0;
5587         ProbeStart( p_demux, prg->i_number );
5588         ProbeEnd( p_demux, prg->i_number );
5589     }
5590 }
5591
5592 static int PATCheck( demux_t *p_demux, dvbpsi_pat_t *p_pat )
5593 {
5594     /* Some Dreambox streams have all PMT set to same pid */
5595     int i_prev_pid = -1;
5596     for( dvbpsi_pat_program_t * p_program = p_pat->p_first_program;
5597          p_program != NULL;
5598          p_program = p_program->p_next )
5599     {
5600         if( p_program->i_pid == i_prev_pid )
5601         {
5602             msg_Warn( p_demux, "PAT check failed: duplicate program pid %d", i_prev_pid );
5603             return VLC_EGENERIC;
5604         }
5605         i_prev_pid = p_program->i_pid;
5606     }
5607     return VLC_SUCCESS;
5608 }
5609
5610 static void PATCallBack( void *data, dvbpsi_pat_t *p_pat )
5611 {
5612     demux_t              *p_demux = data;
5613     demux_sys_t          *p_sys = p_demux->p_sys;
5614     dvbpsi_pat_program_t *p_program;
5615     ts_pid_t             *pat = &p_sys->pid[0];
5616
5617     msg_Dbg( p_demux, "PATCallBack called" );
5618
5619     if( ( pat->psi->i_pat_version != -1 &&
5620             ( !p_pat->b_current_next ||
5621               p_pat->i_version == pat->psi->i_pat_version ) ) ||
5622         p_sys->b_user_pmt || PATCheck( p_demux, p_pat ) )
5623     {
5624         dvbpsi_DeletePAT( p_pat );
5625         return;
5626     }
5627
5628     msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
5629              p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
5630
5631     /* Clean old */
5632     if( p_sys->i_pmt > 0 )
5633     {
5634         int      i_pmt_rm = 0;
5635         ts_pid_t **pmt_rm = NULL;
5636
5637         /* Search pmt to be deleted */
5638         for( int i = 0; i < p_sys->i_pmt; i++ )
5639         {
5640             ts_pid_t *pmt = p_sys->pmt[i];
5641             bool b_keep = false;
5642
5643             for( p_program = p_pat->p_first_program; !b_keep && p_program;
5644                  p_program = p_program->p_next )
5645             {
5646                 if( p_program->i_pid != pmt->i_pid )
5647                     continue;
5648
5649                 for( int i_prg = 0; !b_keep && i_prg < pmt->psi->i_prg; i_prg++ )
5650                     if( p_program->i_number == pmt->psi->prg[i_prg]->i_number )
5651                         b_keep = true;
5652             }
5653
5654             if( b_keep )
5655                 continue;
5656
5657             TAB_APPEND( i_pmt_rm, pmt_rm, pmt );
5658         }
5659
5660         /* Delete all ES attached to thoses PMT */
5661         for( int i = 2; i < 8192; i++ )
5662         {
5663             ts_pid_t *pid = &p_sys->pid[i];
5664
5665             if( !pid->b_valid || pid->psi )
5666                 continue;
5667
5668             for( int j = 0; j < i_pmt_rm && pid->b_valid; j++ )
5669             {
5670                 for( int i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
5671                 {
5672                     /* We only remove es that aren't defined by extra pmt */
5673                     if( pid->p_owner->prg[i_prg]->i_pid_pmt != pmt_rm[j]->i_pid )
5674                         continue;
5675
5676                     if( pid->es->id )
5677                         SetPIDFilter( p_demux, i, false );
5678
5679                     PIDClean( p_demux, pid );
5680                     break;
5681                 }
5682             }
5683         }
5684
5685         /* Delete PMT pid */
5686         for( int i = 0; i < i_pmt_rm; i++ )
5687         {
5688             ts_pid_t *pid = pmt_rm[i];
5689             SetPIDFilter( p_demux, pid->i_pid, false );
5690
5691             for( int i_prg = 0; i_prg < pid->psi->i_prg; i_prg++ )
5692             {
5693                 const int i_number = pid->psi->prg[i_prg]->i_number;
5694                 es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, i_number );
5695             }
5696
5697             PIDClean( p_demux, &p_sys->pid[pid->i_pid] );
5698             TAB_REMOVE( p_sys->i_pmt, p_sys->pmt, pid );
5699         }
5700
5701         free( pmt_rm );
5702     }
5703
5704     /* now create programs */
5705     for( p_program = p_pat->p_first_program; p_program != NULL;
5706          p_program = p_program->p_next )
5707     {
5708         msg_Dbg( p_demux, "  * number=%d pid=%d", p_program->i_number,
5709                  p_program->i_pid );
5710         if( p_program->i_number == 0 )
5711             continue;
5712
5713         ts_pid_t *pmt = &p_sys->pid[p_program->i_pid];
5714
5715         ValidateDVBMeta( p_demux, p_program->i_pid );
5716
5717         if( pmt->b_valid )
5718         {
5719             bool b_add = true;
5720             for( int i_prg = 0; b_add && i_prg < pmt->psi->i_prg; i_prg++ )
5721                 if( pmt->psi->prg[i_prg]->i_number == p_program->i_number )
5722                     b_add = false;
5723
5724             if( !b_add )
5725                 continue;
5726         }
5727         else
5728         {
5729             TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
5730         }
5731
5732         PIDInit( pmt, true, pat->psi );
5733         ts_prg_psi_t *prg = pmt->psi->prg[pmt->psi->i_prg-1];
5734 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
5735         prg->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
5736         if( !prg->handle )
5737         {
5738             dvbpsi_DeletePAT( p_pat );
5739             return;
5740         }
5741         prg->handle->p_sys = (void *) VLC_OBJECT(p_demux);
5742         if( !dvbpsi_pmt_attach( prg->handle, p_program->i_number, PMTCallBack, p_demux ) )
5743             msg_Err( p_demux, "PATCallback failed attaching PMTCallback to program %d",
5744                      p_program->i_number );
5745 #else
5746         prg->handle = dvbpsi_AttachPMT( p_program->i_number, PMTCallBack, p_demux );
5747 #endif
5748         prg->i_number = p_program->i_number;
5749         prg->i_pid_pmt = p_program->i_pid;
5750
5751         /* Now select PID at access level */
5752         if( p_sys->programs.i_size == 0 ||
5753             ProgramIsSelected( p_demux, p_program->i_number ) )
5754         {
5755             if( p_sys->programs.i_size == 0 )
5756             {
5757                 p_sys->b_default_selection = true;
5758                 ARRAY_APPEND( p_sys->programs, p_program->i_number );
5759             }
5760
5761             if( SetPIDFilter( p_demux, p_program->i_pid, true ) )
5762                 p_sys->b_access_control = false;
5763             else if ( p_sys->es_creation == DELAY_ES )
5764                 p_sys->es_creation = CREATE_ES;
5765         }
5766     }
5767     pat->psi->i_pat_version = p_pat->i_version;
5768
5769     dvbpsi_DeletePAT( p_pat );
5770 }