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