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