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