]> git.sesse.net Git - vlc/blob - modules/demux/ts.c
demux: ts: only set self pcr to its program
[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 == p_pat->programs.p_elems[i] ) /* 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         }
2992         else /* set PCR provided by current pid to program(s) referencing it */
2993         {
2994             /* Can be dedicated PCR pid (no owned then) or another pid (owner == pmt) */
2995             if( p_pmt->i_pid_pcr == pid->i_pid ) /* If that program references current pid as PCR */
2996             {
2997                 /* We've found a target group for update */
2998                 ProgramSetPCR( p_demux, p_pmt, i_program_pcr );
2999             }
3000         }
3001
3002     }
3003 }
3004
3005 static int FindPCRCandidate( ts_pmt_t *p_pmt )
3006 {
3007     ts_pid_t *p_cand = NULL;
3008     int i_previous = p_pmt->i_pid_pcr;
3009
3010     for( int i=0; i<p_pmt->e_streams.i_size; i++ )
3011     {
3012         ts_pid_t *p_pid = p_pmt->e_streams.p_elems[i];
3013         if( SEEN(*p_pid) &&
3014             (!p_cand || p_cand->i_pid != i_previous) )
3015         {
3016             if( p_pid->probed.i_pcr_count ) /* check PCR frequency first */
3017             {
3018                 if( !p_cand || p_pid->probed.i_pcr_count > p_cand->probed.i_pcr_count )
3019                 {
3020                     p_cand = p_pid;
3021                     continue;
3022                 }
3023             }
3024
3025             if( p_pid->u.p_pes->es.fmt.i_cat == AUDIO_ES )
3026             {
3027                 if( !p_cand )
3028                     p_cand = p_pid;
3029             }
3030             else if ( p_pid->u.p_pes->es.fmt.i_cat == VIDEO_ES ) /* Otherwise prioritize video dts */
3031             {
3032                 if( !p_cand || p_cand->u.p_pes->es.fmt.i_cat == AUDIO_ES )
3033                     p_cand = p_pid;
3034             }
3035         }
3036     }
3037
3038     if( p_cand )
3039         return p_cand->i_pid;
3040     else
3041         return 0x1FFF;
3042 }
3043
3044 static void PCRFixHandle( demux_t *p_demux, ts_pmt_t *p_pmt, block_t *p_block )
3045 {
3046     if( p_pmt->pcr.i_first > -1 || p_pmt->pcr.b_disable )
3047         return;
3048
3049     /* Record the first data packet timestamp in case there wont be any PCR */
3050     if( !p_pmt->pcr.i_first_dts )
3051     {
3052         p_pmt->pcr.i_first_dts = p_block->i_dts;
3053     }
3054     else if( p_block->i_dts - p_pmt->pcr.i_first_dts > CLOCK_FREQ / 2 ) /* "shall not exceed 100ms" */
3055     {
3056         int i_cand = FindPCRCandidate( p_pmt );
3057         p_pmt->i_pid_pcr = i_cand;
3058         p_pmt->pcr.b_disable = true; /* So we do not wait packet PCR flag as there might be none on the pid */
3059         msg_Warn( p_demux, "No PCR received for program %d, set up workaround using pid %d",
3060                   p_pmt->i_number, i_cand );
3061         UpdatePESFilters( p_demux, p_demux->p_sys->b_es_all );
3062     }
3063 }
3064
3065 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
3066 {
3067     const uint8_t *p = p_bk->p_buffer;
3068     const bool b_unit_start = p[1]&0x40;
3069     const bool b_adaptation = p[3]&0x20;
3070     const bool b_payload    = p[3]&0x10;
3071     const int  i_cc         = p[3]&0x0f; /* continuity counter */
3072     bool       b_discontinuity = false;  /* discontinuity */
3073
3074     /* transport_scrambling_control is ignored */
3075     int         i_skip = 0;
3076     bool        i_ret  = false;
3077
3078 #if 0
3079     msg_Dbg( p_demux, "pid=%d unit_start=%d adaptation=%d payload=%d "
3080              "cc=0x%x", pid->i_pid, b_unit_start, b_adaptation,
3081              b_payload, i_cc );
3082 #endif
3083
3084     /* For now, ignore additional error correction
3085      * TODO: handle Reed-Solomon 204,188 error correction */
3086     p_bk->i_buffer = TS_PACKET_SIZE_188;
3087
3088     if( p[1]&0x80 )
3089     {
3090         msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
3091                  pid->i_pid );
3092         if( pid->u.p_pes->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
3093             pid->u.p_pes->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
3094     }
3095
3096     if( p_demux->p_sys->csa )
3097     {
3098         vlc_mutex_lock( &p_demux->p_sys->csa_lock );
3099         csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer, p_demux->p_sys->i_csa_pkt_size );
3100         vlc_mutex_unlock( &p_demux->p_sys->csa_lock );
3101     }
3102
3103     if( !b_adaptation )
3104     {
3105         /* We don't have any adaptation_field, so payload starts
3106          * immediately after the 4 byte TS header */
3107         i_skip = 4;
3108     }
3109     else
3110     {
3111         /* p[4] is adaptation_field_length minus one */
3112         i_skip = 5 + p[4];
3113         if( p[4] > 0 )
3114         {
3115             /* discontinuity indicator found in stream */
3116             b_discontinuity = (p[5]&0x80) ? true : false;
3117             if( b_discontinuity && pid->u.p_pes->p_data )
3118             {
3119                 msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
3120                             pid->i_pid );
3121                 /* pid->es->p_data->i_flags |= BLOCK_FLAG_DISCONTINUITY; */
3122             }
3123 #if 0
3124             if( p[5]&0x40 )
3125                 msg_Dbg( p_demux, "random access indicator (pid=%d) ", pid->i_pid );
3126 #endif
3127         }
3128     }
3129
3130     /* Test continuity counter */
3131     /* continuous when (one of this):
3132         * diff == 1
3133         * diff == 0 and payload == 0
3134         * diff == 0 and duplicate packet (playload != 0) <- should we
3135         *   test the content ?
3136      */
3137     const int i_diff = ( i_cc - pid->i_cc )&0x0f;
3138     if( b_payload && i_diff == 1 )
3139     {
3140         pid->i_cc = ( pid->i_cc + 1 ) & 0xf;
3141     }
3142     else
3143     {
3144         if( pid->i_cc == 0xff )
3145         {
3146             msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
3147                       pid->i_pid, i_cc );
3148             pid->i_cc = i_cc;
3149         }
3150         else if( i_diff != 0 && !b_discontinuity )
3151         {
3152             msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x (pid=%d)",
3153                       i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );
3154
3155             pid->i_cc = i_cc;
3156             if( pid->u.p_pes->p_data && pid->u.p_pes->es.fmt.i_cat != VIDEO_ES &&
3157                 pid->u.p_pes->es.fmt.i_cat != AUDIO_ES )
3158             {
3159                 /* Small audio/video artifacts are usually better than
3160                  * dropping full frames */
3161                 pid->u.p_pes->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
3162             }
3163         }
3164     }
3165
3166     PCRHandle( p_demux, pid, p_bk );
3167
3168     if( i_skip >= 188 || pid->u.p_pes->es.id == NULL )
3169     {
3170         block_Release( p_bk );
3171         return i_ret;
3172     }
3173
3174     /* We have to gather it */
3175     p_bk->p_buffer += i_skip;
3176     p_bk->i_buffer -= i_skip;
3177
3178     if( b_unit_start )
3179     {
3180         if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
3181         {
3182             int i_pointer_field = __MIN( p_bk->p_buffer[0], p_bk->i_buffer - 1 );
3183             block_t *p = block_Duplicate( p_bk );
3184             if( p )
3185             {
3186                 p->i_buffer = i_pointer_field;
3187                 p->p_buffer++;
3188                 block_ChainLastAppend( &pid->u.p_pes->pp_last, p );
3189             }
3190             p_bk->i_buffer -= 1 + i_pointer_field;
3191             p_bk->p_buffer += 1 + i_pointer_field;
3192         }
3193         if( pid->u.p_pes->p_data )
3194         {
3195             ParseData( p_demux, pid );
3196             i_ret = true;
3197         }
3198
3199         block_ChainLastAppend( &pid->u.p_pes->pp_last, p_bk );
3200         if( pid->u.p_pes->data_type == TS_ES_DATA_PES )
3201         {
3202             if( p_bk->i_buffer > 6 )
3203             {
3204                 pid->u.p_pes->i_data_size = GetWBE( &p_bk->p_buffer[4] );
3205                 if( pid->u.p_pes->i_data_size > 0 )
3206                 {
3207                     pid->u.p_pes->i_data_size += 6;
3208                 }
3209             }
3210         }
3211         else if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION )
3212         {
3213             if( p_bk->i_buffer > 3 && p_bk->p_buffer[0] != 0xff )
3214             {
3215                 pid->u.p_pes->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
3216             }
3217         }
3218         pid->u.p_pes->i_data_gathered += p_bk->i_buffer;
3219         if( pid->u.p_pes->i_data_size > 0 &&
3220             pid->u.p_pes->i_data_gathered >= pid->u.p_pes->i_data_size )
3221         {
3222             ParseData( p_demux, pid );
3223             i_ret = true;
3224         }
3225     }
3226     else
3227     {
3228         if( pid->u.p_pes->p_data == NULL )
3229         {
3230             /* msg_Dbg( p_demux, "broken packet" ); */
3231             block_Release( p_bk );
3232         }
3233         else
3234         {
3235             block_ChainLastAppend( &pid->u.p_pes->pp_last, p_bk );
3236             pid->u.p_pes->i_data_gathered += p_bk->i_buffer;
3237
3238             if( pid->u.p_pes->i_data_size > 0 &&
3239                 pid->u.p_pes->i_data_gathered >= pid->u.p_pes->i_data_size )
3240             {
3241                 ParseData( p_demux, pid );
3242                 i_ret = true;
3243             }
3244         }
3245     }
3246
3247     return i_ret;
3248 }
3249
3250 static void PIDFillFormat( es_format_t *fmt, int i_stream_type )
3251 {
3252     switch( i_stream_type )
3253     {
3254     case 0x01:  /* MPEG-1 video */
3255     case 0x02:  /* MPEG-2 video */
3256     case 0x80:  /* MPEG-2 MOTO video */
3257         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MPGV );
3258         break;
3259     case 0x03:  /* MPEG-1 audio */
3260     case 0x04:  /* MPEG-2 audio */
3261         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MPGA );
3262         break;
3263     case 0x11:  /* MPEG4 (audio) LATM */
3264     case 0x0f:  /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
3265     case 0x1c:  /* ISO/IEC 14496-3 Audio, without using any additional
3266                    transport syntax, such as DST, ALS and SLS */
3267         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MP4A );
3268         break;
3269     case 0x10:  /* MPEG4 (video) */
3270         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MP4V );
3271         break;
3272     case 0x1B:  /* H264 <- check transport syntax/needed descriptor */
3273         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_H264 );
3274         break;
3275     case 0x24:  /* HEVC */
3276         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_HEVC );
3277         break;
3278     case 0x42:  /* CAVS (Chinese AVS) */
3279         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_CAVS );
3280         break;
3281
3282     case 0x81:  /* A52 (audio) */
3283         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_A52 );
3284         break;
3285     case 0x82:  /* SCTE-27 (sub) */
3286         es_format_Init( fmt, SPU_ES, VLC_CODEC_SCTE_27 );
3287         break;
3288     case 0x84:  /* SDDS (audio) */
3289         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_SDDS );
3290         break;
3291     case 0x85:  /* DTS (audio) */
3292         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_DTS );
3293         break;
3294     case 0x87: /* E-AC3 */
3295         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_EAC3 );
3296         break;
3297
3298     case 0x91:  /* A52 vls (audio) */
3299         es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
3300         break;
3301     case 0x92:  /* DVD_SPU vls (sub) */
3302         es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
3303         break;
3304
3305     case 0x94:  /* SDDS (audio) */
3306         es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
3307         break;
3308
3309     case 0xa0:  /* MSCODEC vlc (video) (fixed later) */
3310         es_format_Init( fmt, UNKNOWN_ES, 0 );
3311         break;
3312
3313     case 0x06:  /* PES_PRIVATE  (fixed later) */
3314     case 0x12:  /* MPEG-4 generic (sub/scene/...) (fixed later) */
3315     case 0xEA:  /* Privately managed ES (VC-1) (fixed later */
3316     default:
3317         es_format_Init( fmt, UNKNOWN_ES, 0 );
3318         break;
3319     }
3320
3321     /* PES packets usually contain truncated frames */
3322     fmt->b_packetized = false;
3323 }
3324
3325 /*****************************************************************************
3326  * MP4 specific functions (IOD parser)
3327  *****************************************************************************/
3328 static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
3329 {
3330     unsigned int i_b;
3331     unsigned int i_len = 0;
3332     do
3333     {
3334         i_b = **pp_data;
3335         (*pp_data)++;
3336         (*pi_data)--;
3337         i_len = ( i_len << 7 ) + ( i_b&0x7f );
3338
3339     } while( i_b&0x80 && *pi_data > 0 );
3340
3341     if (i_len > *pi_data)
3342         i_len = *pi_data;
3343
3344     return i_len;
3345 }
3346
3347 static int IODGetBytes( int *pi_data, uint8_t **pp_data, size_t bytes )
3348 {
3349     uint32_t res = 0;
3350     while( *pi_data > 0 && bytes-- )
3351     {
3352         res <<= 8;
3353         res |= **pp_data;
3354         (*pp_data)++;
3355         (*pi_data)--;
3356     }
3357
3358     return res;
3359 }
3360
3361 static char* IODGetURL( int *pi_data, uint8_t **pp_data )
3362 {
3363     int len = IODGetBytes( pi_data, pp_data, 1 );
3364     if (len > *pi_data)
3365         len = *pi_data;
3366     char *url = strndup( (char*)*pp_data, len );
3367     *pp_data += len;
3368     *pi_data -= len;
3369     return url;
3370 }
3371
3372 static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
3373 {
3374     uint8_t i_iod_tag, i_iod_label, byte1, byte2, byte3;
3375
3376     iod_descriptor_t *p_iod = calloc( 1, sizeof( iod_descriptor_t ) );
3377     if( !p_iod )
3378         return NULL;
3379
3380     if( i_data < 3 )
3381     {
3382         return p_iod;
3383     }
3384
3385     byte1 = IODGetBytes( &i_data, &p_data, 1 );
3386     byte2 = IODGetBytes( &i_data, &p_data, 1 );
3387     byte3 = IODGetBytes( &i_data, &p_data, 1 );
3388     if( byte2 == 0x02 ) //old vlc's buggy implementation of the IOD_descriptor
3389     {
3390         i_iod_label = byte1;
3391         i_iod_tag = byte2;
3392     }
3393     else  //correct implementation of the IOD_descriptor
3394     {
3395         i_iod_label = byte2;
3396         i_iod_tag = byte3;
3397     }
3398
3399     ts_debug( "\n* iod label:%d tag:0x%x", i_iod_label, i_iod_tag );
3400
3401     if( i_iod_tag != 0x02 )
3402     {
3403         ts_debug( "\n ERR: tag %02x != 0x02", i_iod_tag );
3404         return p_iod;
3405     }
3406
3407     IODDescriptorLength( &i_data, &p_data );
3408
3409     uint16_t i_od_id = ( IODGetBytes( &i_data, &p_data, 1 ) << 2 );
3410     uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
3411     i_od_id |= i_flags >> 6;
3412     ts_debug( "\n* od_id:%d", i_od_id );
3413     ts_debug( "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
3414     if ((i_flags >> 5) & 0x01)
3415     {
3416         p_iod->psz_url = IODGetURL( &i_data, &p_data );
3417         ts_debug( "\n* url string:%s", p_iod->psz_url );
3418         ts_debug( "\n*****************************\n" );
3419         return p_iod;
3420     }
3421     else
3422     {
3423         p_iod->psz_url = NULL;
3424     }
3425
3426     /* Profile Level Indication */
3427     IODGetBytes( &i_data, &p_data, 1 ); /* OD */
3428     IODGetBytes( &i_data, &p_data, 1 ); /* scene */
3429     IODGetBytes( &i_data, &p_data, 1 ); /* audio */
3430     IODGetBytes( &i_data, &p_data, 1 ); /* visual */
3431     IODGetBytes( &i_data, &p_data, 1 ); /* graphics */
3432
3433     int i_length = 0;
3434     int i_data_sav = i_data;
3435     uint8_t *p_data_sav = p_data;
3436     for (int i = 0; i_data > 0 && i < ES_DESCRIPTOR_COUNT; i++)
3437     {
3438         es_mpeg4_descriptor_t *es_descr = &p_iod->es_descr[i];
3439
3440         p_data = p_data_sav + i_length;
3441         i_data = i_data_sav - i_length;
3442
3443         int i_tag = IODGetBytes( &i_data, &p_data, 1 );
3444         i_length = IODDescriptorLength( &i_data, &p_data );
3445
3446         i_data_sav = i_data;
3447         p_data_sav = p_data;
3448
3449         i_data = i_length;
3450
3451         if ( i_tag != 0x03 )
3452         {
3453             ts_debug( "\n* - OD tag:0x%x Unsupported", i_tag );
3454             continue;
3455         }
3456
3457         es_descr->i_es_id = IODGetBytes( &i_data, &p_data, 2 );
3458         int i_flags = IODGetBytes( &i_data, &p_data, 1 );
3459         bool b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
3460         if( b_streamDependenceFlag )
3461             IODGetBytes( &i_data, &p_data, 2 ); /* dependOn_es_id */
3462
3463         if( (i_flags >> 6) & 0x01 )
3464             es_descr->psz_url = IODGetURL( &i_data, &p_data );
3465
3466         bool b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
3467         if( b_OCRStreamFlag )
3468             IODGetBytes( &i_data, &p_data, 2 ); /* OCR_es_id */
3469
3470         if( IODGetBytes( &i_data, &p_data, 1 ) != 0x04 )
3471         {
3472             ts_debug( "\n* ERR missing DecoderConfigDescr" );
3473             continue;
3474         }
3475         int i_config_desc_length = IODDescriptorLength( &i_data, &p_data ); /* DecoderConfigDescr_length */
3476         decoder_config_descriptor_t *dec_descr = &es_descr->dec_descr;
3477         dec_descr->i_objectTypeIndication = IODGetBytes( &i_data, &p_data, 1 );
3478         i_flags = IODGetBytes( &i_data, &p_data, 1 );
3479         dec_descr->i_streamType = i_flags >> 2;
3480
3481         IODGetBytes( &i_data, &p_data, 3); /* bufferSizeDB */
3482         IODGetBytes( &i_data, &p_data, 4); /* maxBitrate */
3483         IODGetBytes( &i_data, &p_data, 4 ); /* avgBitrate */
3484
3485         if( i_config_desc_length > 13 && IODGetBytes( &i_data, &p_data, 1 ) == 0x05 )
3486         {
3487             dec_descr->i_extra = IODDescriptorLength( &i_data, &p_data );
3488             if( dec_descr->i_extra > 0 )
3489             {
3490                 dec_descr->p_extra = xmalloc( dec_descr->i_extra );
3491                 memcpy(dec_descr->p_extra, p_data, dec_descr->i_extra);
3492                 p_data += dec_descr->i_extra;
3493                 i_data -= dec_descr->i_extra;
3494             }
3495         }
3496         else
3497         {
3498             dec_descr->i_extra = 0;
3499             dec_descr->p_extra = NULL;
3500         }
3501
3502         if( IODGetBytes( &i_data, &p_data, 1 ) != 0x06 )
3503         {
3504             ts_debug( "\n* ERR missing SLConfigDescr" );
3505             continue;
3506         }
3507         IODDescriptorLength( &i_data, &p_data ); /* SLConfigDescr_length */
3508         switch( IODGetBytes( &i_data, &p_data, 1 ) /* predefined */ )
3509         {
3510         default:
3511             ts_debug( "\n* ERR unsupported SLConfigDescr predefined" );
3512         case 0x01:
3513             // FIXME
3514             break;
3515         }
3516         es_descr->b_ok = true;
3517     }
3518
3519     return p_iod;
3520 }
3521
3522 static void IODFree( iod_descriptor_t *p_iod )
3523 {
3524     if( p_iod->psz_url )
3525     {
3526         free( p_iod->psz_url );
3527         free( p_iod );
3528         return;
3529     }
3530
3531     for( int i = 0; i < 255; i++ )
3532     {
3533 #define es_descr p_iod->es_descr[i]
3534         if( es_descr.b_ok )
3535         {
3536             if( es_descr.psz_url )
3537                 free( es_descr.psz_url );
3538             else
3539                 free( es_descr.dec_descr.p_extra );
3540         }
3541 #undef  es_descr
3542     }
3543     free( p_iod );
3544 }
3545
3546 /****************************************************************************
3547  ****************************************************************************
3548  ** libdvbpsi callbacks
3549  ****************************************************************************
3550  ****************************************************************************/
3551 static bool ProgramIsSelected( demux_sys_t *p_sys, uint16_t i_pgrm )
3552 {
3553     for(int i=0; i<p_sys->programs.i_size; i++)
3554         if( p_sys->programs.p_elems[i] == i_pgrm )
3555             return true;
3556
3557     return false;
3558 }
3559
3560 static void ValidateDVBMeta( demux_t *p_demux, int i_pid )
3561 {
3562     demux_sys_t *p_sys = p_demux->p_sys;
3563
3564     if( !p_sys->b_dvb_meta || ( i_pid != 0x11 && i_pid != 0x12 && i_pid != 0x14 ) )
3565         return;
3566
3567     msg_Warn( p_demux, "Switching to non DVB mode" );
3568
3569     /* This doesn't look like a DVB stream so don't try
3570      * parsing the SDT/EDT/TDT */
3571
3572     PIDRelease( p_demux, &p_sys->pid[0x11] );
3573     PIDRelease( p_demux, &p_sys->pid[0x12] );
3574     PIDRelease( p_demux, &p_sys->pid[0x14] );
3575     p_sys->b_dvb_meta = false;
3576 }
3577
3578 #include "dvb-text.h"
3579
3580 static char *EITConvertToUTF8( demux_t *p_demux,
3581                                const unsigned char *psz_instring,
3582                                size_t i_length,
3583                                bool b_broken )
3584 {
3585     demux_sys_t *p_sys = p_demux->p_sys;
3586 #ifdef HAVE_ARIBB24
3587     if( p_sys->arib.e_mode == ARIBMODE_ENABLED )
3588     {
3589         if ( !p_sys->arib.p_instance )
3590             p_sys->arib.p_instance = arib_instance_new( p_demux );
3591         if ( !p_sys->arib.p_instance )
3592             return NULL;
3593         arib_decoder_t *p_decoder = arib_get_decoder( p_sys->arib.p_instance );
3594         if ( !p_decoder )
3595             return NULL;
3596
3597         char *psz_outstring = NULL;
3598         size_t i_out;
3599
3600         i_out = i_length * 4;
3601         psz_outstring = (char*) calloc( i_out + 1, sizeof(char) );
3602         if( !psz_outstring )
3603             return NULL;
3604
3605         arib_initialize_decoder( p_decoder );
3606         i_out = arib_decode_buffer( p_decoder, psz_instring, i_length,
3607                                     psz_outstring, i_out );
3608         arib_finalize_decoder( p_decoder );
3609
3610         return psz_outstring;
3611     }
3612 #else
3613     VLC_UNUSED(p_sys);
3614 #endif
3615     /* Deal with no longer broken providers (no switch byte
3616       but sending ISO_8859-1 instead of ISO_6937) without
3617       removing them from the broken providers table
3618       (keep the entry for correctly handling recorded TS).
3619     */
3620     b_broken = b_broken && i_length && *psz_instring > 0x20;
3621
3622     if( b_broken )
3623         return FromCharset( "ISO_8859-1", psz_instring, i_length );
3624     return vlc_from_EIT( psz_instring, i_length );
3625 }
3626
3627 static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
3628 {
3629     demux_sys_t          *p_sys = p_demux->p_sys;
3630     ts_pid_t             *sdt = &p_sys->pid[0x11];
3631     dvbpsi_sdt_service_t *p_srv;
3632
3633     msg_Dbg( p_demux, "SDTCallBack called" );
3634
3635     if( p_sys->es_creation != CREATE_ES ||
3636        !p_sdt->b_current_next ||
3637         p_sdt->i_version == sdt->u.p_psi->i_version )
3638     {
3639         dvbpsi_sdt_delete( p_sdt );
3640         return;
3641     }
3642
3643     msg_Dbg( p_demux, "new SDT ts_id=%d version=%d current_next=%d "
3644              "network_id=%d",
3645              p_sdt->i_extension,
3646              p_sdt->i_version, p_sdt->b_current_next,
3647              p_sdt->i_network_id );
3648
3649     p_sys->b_broken_charset = false;
3650
3651     for( p_srv = p_sdt->p_first_service; p_srv; p_srv = p_srv->p_next )
3652     {
3653         vlc_meta_t          *p_meta;
3654         dvbpsi_descriptor_t *p_dr;
3655
3656         const char *psz_type = NULL;
3657         const char *psz_status = NULL;
3658
3659         msg_Dbg( p_demux, "  * service id=%d eit schedule=%d present=%d "
3660                  "running=%d free_ca=%d",
3661                  p_srv->i_service_id, p_srv->b_eit_schedule,
3662                  p_srv->b_eit_present, p_srv->i_running_status,
3663                  p_srv->b_free_ca );
3664
3665         if( p_sys->vdr.i_service && p_srv->i_service_id != p_sys->vdr.i_service )
3666         {
3667             msg_Dbg( p_demux, "  * service id=%d skipped (not declared in vdr header)",
3668                      p_sys->vdr.i_service );
3669             continue;
3670         }
3671
3672         p_meta = vlc_meta_New();
3673         for( p_dr = p_srv->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3674         {
3675             if( p_dr->i_tag == 0x48 )
3676             {
3677                 static const char *ppsz_type[17] = {
3678                     "Reserved",
3679                     "Digital television service",
3680                     "Digital radio sound service",
3681                     "Teletext service",
3682                     "NVOD reference service",
3683                     "NVOD time-shifted service",
3684                     "Mosaic service",
3685                     "PAL coded signal",
3686                     "SECAM coded signal",
3687                     "D/D2-MAC",
3688                     "FM Radio",
3689                     "NTSC coded signal",
3690                     "Data broadcast service",
3691                     "Reserved for Common Interface Usage",
3692                     "RCS Map (see EN 301 790 [35])",
3693                     "RCS FLS (see EN 301 790 [35])",
3694                     "DVB MHP service"
3695                 };
3696                 dvbpsi_service_dr_t *pD = dvbpsi_DecodeServiceDr( p_dr );
3697                 char *str1 = NULL;
3698                 char *str2 = NULL;
3699
3700                 /* Workarounds for broadcasters with broken EPG */
3701
3702                 if( p_sdt->i_network_id == 133 )
3703                     p_sys->b_broken_charset = true;  /* SKY DE & BetaDigital use ISO8859-1 */
3704
3705                 /* List of providers using ISO8859-1 */
3706                 static const char ppsz_broken_providers[][8] = {
3707                     "CSAT",     /* CanalSat FR */
3708                     "GR1",      /* France televisions */
3709                     "MULTI4",   /* NT1 */
3710                     "MR5",      /* France 2/M6 HD */
3711                     ""
3712                 };
3713                 for( int i = 0; *ppsz_broken_providers[i]; i++ )
3714                 {
3715                     const size_t i_length = strlen(ppsz_broken_providers[i]);
3716                     if( pD->i_service_provider_name_length == i_length &&
3717                         !strncmp( (char *)pD->i_service_provider_name, ppsz_broken_providers[i], i_length ) )
3718                         p_sys->b_broken_charset = true;
3719                 }
3720
3721                 /* FIXME: Digital+ ES also uses ISO8859-1 */
3722
3723                 str1 = EITConvertToUTF8(p_demux,
3724                                         pD->i_service_provider_name,
3725                                         pD->i_service_provider_name_length,
3726                                         p_sys->b_broken_charset );
3727                 str2 = EITConvertToUTF8(p_demux,
3728                                         pD->i_service_name,
3729                                         pD->i_service_name_length,
3730                                         p_sys->b_broken_charset );
3731
3732                 msg_Dbg( p_demux, "    - type=%d provider=%s name=%s",
3733                          pD->i_service_type, str1, str2 );
3734
3735                 vlc_meta_SetTitle( p_meta, str2 );
3736                 vlc_meta_SetPublisher( p_meta, str1 );
3737                 if( pD->i_service_type >= 0x01 && pD->i_service_type <= 0x10 )
3738                     psz_type = ppsz_type[pD->i_service_type];
3739                 free( str1 );
3740                 free( str2 );
3741             }
3742         }
3743
3744         if( p_srv->i_running_status >= 0x01 && p_srv->i_running_status <= 0x04 )
3745         {
3746             static const char *ppsz_status[5] = {
3747                 "Unknown",
3748                 "Not running",
3749                 "Starts in a few seconds",
3750                 "Pausing",
3751                 "Running"
3752             };
3753             psz_status = ppsz_status[p_srv->i_running_status];
3754         }
3755
3756         if( psz_type )
3757             vlc_meta_AddExtra( p_meta, "Type", psz_type );
3758         if( psz_status )
3759             vlc_meta_AddExtra( p_meta, "Status", psz_status );
3760
3761         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_META,
3762                         p_srv->i_service_id, p_meta );
3763         vlc_meta_Delete( p_meta );
3764     }
3765
3766     sdt->u.p_psi->i_version = p_sdt->i_version;
3767     dvbpsi_sdt_delete( p_sdt );
3768 }
3769
3770 /* i_year: year - 1900  i_month: 0-11  i_mday: 1-31 i_hour: 0-23 i_minute: 0-59 i_second: 0-59 */
3771 static int64_t vlc_timegm( int i_year, int i_month, int i_mday, int i_hour, int i_minute, int i_second )
3772 {
3773     static const int pn_day[12+1] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
3774     int64_t i_day;
3775
3776     if( i_year < 70 ||
3777         i_month < 0 || i_month > 11 || i_mday < 1 || i_mday > 31 ||
3778         i_hour < 0 || i_hour > 23 || i_minute < 0 || i_minute > 59 || i_second < 0 || i_second > 59 )
3779         return -1;
3780
3781     /* Count the number of days */
3782     i_day = 365 * (i_year-70) + pn_day[i_month] + i_mday - 1;
3783 #define LEAP(y) ( ((y)%4) == 0 && (((y)%100) != 0 || ((y)%400) == 0) ? 1 : 0)
3784     for( int i = 70; i < i_year; i++ )
3785         i_day += LEAP(1900+i);
3786     if( i_month > 1 )
3787         i_day += LEAP(1900+i_year);
3788 #undef LEAP
3789     /**/
3790     return ((24*i_day + i_hour)*60 + i_minute)*60 + i_second;
3791 }
3792
3793 static void EITDecodeMjd( int i_mjd, int *p_y, int *p_m, int *p_d )
3794 {
3795     const int yp = (int)( ( (double)i_mjd - 15078.2)/365.25 );
3796     const int mp = (int)( ((double)i_mjd - 14956.1 - (int)(yp * 365.25)) / 30.6001 );
3797     const int c = ( mp == 14 || mp == 15 ) ? 1 : 0;
3798
3799     *p_y = 1900 + yp + c*1;
3800     *p_m = mp - 1 - c*12;
3801     *p_d = i_mjd - 14956 - (int)(yp*365.25) - (int)(mp*30.6001);
3802 }
3803 #define CVT_FROM_BCD(v) ((((v) >> 4)&0xf)*10 + ((v)&0xf))
3804 static int64_t EITConvertStartTime( uint64_t i_date )
3805 {
3806     const int i_mjd = i_date >> 24;
3807     const int i_hour   = CVT_FROM_BCD(i_date >> 16);
3808     const int i_minute = CVT_FROM_BCD(i_date >>  8);
3809     const int i_second = CVT_FROM_BCD(i_date      );
3810     int i_year;
3811     int i_month;
3812     int i_day;
3813
3814     /* if all 40 bits are 1, the start is unknown */
3815     if( i_date == UINT64_C(0xffffffffff) )
3816         return -1;
3817
3818     EITDecodeMjd( i_mjd, &i_year, &i_month, &i_day );
3819     return vlc_timegm( i_year - 1900, i_month - 1, i_day, i_hour, i_minute, i_second );
3820 }
3821 static int EITConvertDuration( uint32_t i_duration )
3822 {
3823     return CVT_FROM_BCD(i_duration >> 16) * 3600 +
3824            CVT_FROM_BCD(i_duration >> 8 ) * 60 +
3825            CVT_FROM_BCD(i_duration      );
3826 }
3827 #undef CVT_FROM_BCD
3828
3829 static void TDTCallBack( demux_t *p_demux, dvbpsi_tot_t *p_tdt )
3830 {
3831     demux_sys_t        *p_sys = p_demux->p_sys;
3832
3833     p_sys->i_tdt_delta = CLOCK_FREQ * EITConvertStartTime( p_tdt->i_utc_time )
3834                          - mdate();
3835     dvbpsi_tot_delete(p_tdt);
3836 }
3837
3838
3839 static void EITCallBack( demux_t *p_demux,
3840                          dvbpsi_eit_t *p_eit, bool b_current_following )
3841 {
3842     demux_sys_t        *p_sys = p_demux->p_sys;
3843     dvbpsi_eit_event_t *p_evt;
3844     vlc_epg_t *p_epg;
3845
3846     msg_Dbg( p_demux, "EITCallBack called" );
3847     if( !p_eit->b_current_next )
3848     {
3849         dvbpsi_eit_delete( p_eit );
3850         return;
3851     }
3852
3853     msg_Dbg( p_demux, "new EIT service_id=%d version=%d current_next=%d "
3854              "ts_id=%d network_id=%d segment_last_section_number=%d "
3855              "last_table_id=%d",
3856              p_eit->i_extension,
3857              p_eit->i_version, p_eit->b_current_next,
3858              p_eit->i_ts_id, p_eit->i_network_id,
3859              p_eit->i_segment_last_section_number, p_eit->i_last_table_id );
3860
3861     p_epg = vlc_epg_New( NULL );
3862     for( p_evt = p_eit->p_first_event; p_evt; p_evt = p_evt->p_next )
3863     {
3864         dvbpsi_descriptor_t *p_dr;
3865         char                *psz_name = NULL;
3866         char                *psz_text = NULL;
3867         char                *psz_extra = strdup("");
3868         int64_t i_start;
3869         int i_duration;
3870         int i_min_age = 0;
3871         int64_t i_tot_time = 0;
3872
3873         i_start = EITConvertStartTime( p_evt->i_start_time );
3874         i_duration = EITConvertDuration( p_evt->i_duration );
3875
3876         if( p_sys->arib.e_mode == ARIBMODE_ENABLED )
3877         {
3878             if( p_sys->i_tdt_delta == 0 )
3879                 p_sys->i_tdt_delta = CLOCK_FREQ * (i_start + i_duration - 5) - mdate();
3880
3881             i_tot_time = (mdate() + p_sys->i_tdt_delta) / CLOCK_FREQ;
3882
3883             tzset(); // JST -> UTC
3884             i_start += timezone; // FIXME: what about DST?
3885             i_tot_time += timezone;
3886
3887             if( p_evt->i_running_status == 0x00 &&
3888                 (i_start - 5 < i_tot_time &&
3889                  i_tot_time < i_start + i_duration + 5) )
3890             {
3891                 p_evt->i_running_status = 0x04;
3892                 msg_Dbg( p_demux, "  EIT running status 0x00 -> 0x04" );
3893             }
3894         }
3895
3896         msg_Dbg( p_demux, "  * event id=%d start_time:%d duration=%d "
3897                           "running=%d free_ca=%d",
3898                  p_evt->i_event_id, (int)i_start, (int)i_duration,
3899                  p_evt->i_running_status, p_evt->b_free_ca );
3900
3901         for( p_dr = p_evt->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3902         {
3903             switch(p_dr->i_tag)
3904             {
3905             case 0x4d:
3906             {
3907                 dvbpsi_short_event_dr_t *pE = dvbpsi_DecodeShortEventDr( p_dr );
3908
3909                 /* Only take first description, as we don't handle language-info
3910                    for epg atm*/
3911                 if( pE && psz_name == NULL )
3912                 {
3913                     psz_name = EITConvertToUTF8( p_demux,
3914                                                  pE->i_event_name, pE->i_event_name_length,
3915                                                  p_sys->b_broken_charset );
3916                     free( psz_text );
3917                     psz_text = EITConvertToUTF8( p_demux,
3918                                                  pE->i_text, pE->i_text_length,
3919                                                  p_sys->b_broken_charset );
3920                     msg_Dbg( p_demux, "    - short event lang=%3.3s '%s' : '%s'",
3921                              pE->i_iso_639_code, psz_name, psz_text );
3922                 }
3923             }
3924                 break;
3925
3926             case 0x4e:
3927             {
3928                 dvbpsi_extended_event_dr_t *pE = dvbpsi_DecodeExtendedEventDr( p_dr );
3929                 if( pE )
3930                 {
3931                     msg_Dbg( p_demux, "    - extended event lang=%3.3s [%d/%d]",
3932                              pE->i_iso_639_code,
3933                              pE->i_descriptor_number, pE->i_last_descriptor_number );
3934
3935                     if( pE->i_text_length > 0 )
3936                     {
3937                         char *psz_text = EITConvertToUTF8( p_demux,
3938                                                            pE->i_text, pE->i_text_length,
3939                                                            p_sys->b_broken_charset );
3940                         if( psz_text )
3941                         {
3942                             msg_Dbg( p_demux, "       - text='%s'", psz_text );
3943
3944                             psz_extra = xrealloc( psz_extra,
3945                                    strlen(psz_extra) + strlen(psz_text) + 1 );
3946                             strcat( psz_extra, psz_text );
3947                             free( psz_text );
3948                         }
3949                     }
3950
3951                     for( int i = 0; i < pE->i_entry_count; i++ )
3952                     {
3953                         char *psz_dsc = EITConvertToUTF8( p_demux,
3954                                                           pE->i_item_description[i],
3955                                                           pE->i_item_description_length[i],
3956                                                           p_sys->b_broken_charset );
3957                         char *psz_itm = EITConvertToUTF8( p_demux,
3958                                                           pE->i_item[i], pE->i_item_length[i],
3959                                                           p_sys->b_broken_charset );
3960
3961                         if( psz_dsc && psz_itm )
3962                         {
3963                             msg_Dbg( p_demux, "       - desc='%s' item='%s'", psz_dsc, psz_itm );
3964 #if 0
3965                             psz_extra = xrealloc( psz_extra,
3966                                          strlen(psz_extra) + strlen(psz_dsc) +
3967                                          strlen(psz_itm) + 3 + 1 );
3968                             strcat( psz_extra, "(" );
3969                             strcat( psz_extra, psz_dsc );
3970                             strcat( psz_extra, " " );
3971                             strcat( psz_extra, psz_itm );
3972                             strcat( psz_extra, ")" );
3973 #endif
3974                         }
3975                         free( psz_dsc );
3976                         free( psz_itm );
3977                     }
3978                 }
3979             }
3980                 break;
3981
3982             case 0x55:
3983             {
3984                 dvbpsi_parental_rating_dr_t *pR = dvbpsi_DecodeParentalRatingDr( p_dr );
3985                 if ( pR )
3986                 {
3987                     for ( int i = 0; i < pR->i_ratings_number; i++ )
3988                     {
3989                         const dvbpsi_parental_rating_t *p_rating = & pR->p_parental_rating[ i ];
3990                         if ( p_rating->i_rating > 0x00 && p_rating->i_rating <= 0x0F )
3991                         {
3992                             if ( p_rating->i_rating + 3 > i_min_age )
3993                                 i_min_age = p_rating->i_rating + 3;
3994                             msg_Dbg( p_demux, "    - parental control set to %d years",
3995                                      i_min_age );
3996                         }
3997                     }
3998                 }
3999             }
4000                 break;
4001
4002             default:
4003                 msg_Dbg( p_demux, "    - event unknown dr 0x%x(%d)", p_dr->i_tag, p_dr->i_tag );
4004                 break;
4005             }
4006         }
4007
4008         /* */
4009         if( i_start > 0 && psz_name && psz_text)
4010             vlc_epg_AddEvent( p_epg, i_start, i_duration, psz_name, psz_text,
4011                               *psz_extra ? psz_extra : NULL, i_min_age );
4012
4013         /* Update "now playing" field */
4014         if( p_evt->i_running_status == 0x04 && i_start > 0  && psz_name && psz_text )
4015             vlc_epg_SetCurrent( p_epg, i_start );
4016
4017         free( psz_name );
4018         free( psz_text );
4019
4020         free( psz_extra );
4021     }
4022     if( p_epg->i_event > 0 )
4023     {
4024         if( b_current_following &&
4025             (  p_sys->programs.i_size == 0 ||
4026                p_sys->programs.p_elems[0] ==
4027                     p_eit->i_extension
4028                 ) )
4029         {
4030             p_sys->i_dvb_length = 0;
4031             p_sys->i_dvb_start = 0;
4032
4033             if( p_epg->p_current )
4034             {
4035                 p_sys->i_dvb_start = CLOCK_FREQ * p_epg->p_current->i_start;
4036                 p_sys->i_dvb_length = CLOCK_FREQ * p_epg->p_current->i_duration;
4037             }
4038         }
4039         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_EPG,
4040                         p_eit->i_extension,
4041                         p_epg );
4042     }
4043     vlc_epg_Delete( p_epg );
4044
4045     dvbpsi_eit_delete( p_eit );
4046 }
4047 static void EITCallBackCurrentFollowing( demux_t *p_demux, dvbpsi_eit_t *p_eit )
4048 {
4049     EITCallBack( p_demux, p_eit, true );
4050 }
4051 static void EITCallBackSchedule( demux_t *p_demux, dvbpsi_eit_t *p_eit )
4052 {
4053     EITCallBack( p_demux, p_eit, false );
4054 }
4055
4056 static void PSINewTableCallBack( dvbpsi_t *h, uint8_t i_table_id,
4057                                  uint16_t i_extension, demux_t *p_demux )
4058 {
4059     demux_sys_t *p_sys = p_demux->p_sys;
4060     assert( h );
4061 #if 0
4062     msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4063              i_table_id, i_table_id, i_extension, i_extension );
4064 #endif
4065     if( p_sys->pid[0].u.p_pat->i_version != -1 && i_table_id == 0x42 )
4066     {
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
4070         if( !dvbpsi_sdt_attach( h, i_table_id, i_extension, (dvbpsi_sdt_callback)SDTCallBack, p_demux ) )
4071             msg_Err( p_demux, "PSINewTableCallback: failed attaching SDTCallback" );
4072     }
4073     else if( p_sys->pid[0x11].u.p_psi->i_version != -1 &&
4074              ( i_table_id == 0x4e || /* Current/Following */
4075                (i_table_id >= 0x50 && i_table_id <= 0x5f) ) ) /* Schedule */
4076     {
4077         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4078                  i_table_id, i_table_id, i_extension, i_extension );
4079
4080         dvbpsi_eit_callback cb = i_table_id == 0x4e ?
4081                                     (dvbpsi_eit_callback)EITCallBackCurrentFollowing :
4082                                     (dvbpsi_eit_callback)EITCallBackSchedule;
4083
4084         if( !dvbpsi_eit_attach( h, i_table_id, i_extension, cb, p_demux ) )
4085             msg_Err( p_demux, "PSINewTableCallback: failed attaching EITCallback" );
4086     }
4087     else if( p_demux->p_sys->pid[0x11].u.p_psi->i_version != -1 &&
4088             (i_table_id == 0x70 /* TDT */ || i_table_id == 0x73 /* TOT */) )
4089     {
4090          msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4091                  i_table_id, i_table_id, i_extension, i_extension );
4092
4093         if( !dvbpsi_tot_attach( h, i_table_id, i_extension, (dvbpsi_tot_callback)TDTCallBack, p_demux ) )
4094             msg_Err( p_demux, "PSINewTableCallback: failed attaching TDTCallback" );
4095     }
4096 }
4097
4098 /*****************************************************************************
4099  * PMT callback and helpers
4100  *****************************************************************************/
4101 static dvbpsi_descriptor_t *PMTEsFindDescriptor( const dvbpsi_pmt_es_t *p_es,
4102                                                  int i_tag )
4103 {
4104     dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
4105     while( p_dr && ( p_dr->i_tag != i_tag ) )
4106         p_dr = p_dr->p_next;
4107     return p_dr;
4108 }
4109 static bool PMTEsHasRegistration( demux_t *p_demux,
4110                                   const dvbpsi_pmt_es_t *p_es,
4111                                   const char *psz_tag )
4112 {
4113     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x05 );
4114     if( !p_dr )
4115         return false;
4116
4117     if( p_dr->i_length < 4 )
4118     {
4119         msg_Warn( p_demux, "invalid Registration Descriptor" );
4120         return false;
4121     }
4122
4123     assert( strlen(psz_tag) == 4 );
4124     return !memcmp( p_dr->p_data, psz_tag, 4 );
4125 }
4126
4127 static bool PMTEsHasComponentTag( const dvbpsi_pmt_es_t *p_es,
4128                                   int i_component_tag )
4129 {
4130     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x52 );
4131     if( !p_dr )
4132         return false;
4133     dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4134     if( !p_si )
4135         return false;
4136
4137     return p_si->i_component_tag == i_component_tag;
4138 }
4139
4140 static void PMTSetupEsISO14496( demux_t *p_demux, ts_pes_es_t *p_es,
4141                                 const ts_pmt_t *p_pmt, const dvbpsi_pmt_es_t *p_dvbpsies )
4142 {
4143     es_format_t *p_fmt = &p_es->fmt;
4144
4145     /* MPEG-4 stream: search FMC_DESCRIPTOR (SL Packetized stream) */
4146     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x1f );
4147
4148     if( p_dr && p_dr->i_length == 2 )
4149     {
4150         const int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
4151
4152         msg_Dbg( p_demux, "found FMC_descriptor declaring sl packetization on es_id=%d", i_es_id );
4153
4154         p_es->p_mpeg4desc = NULL;
4155
4156         for( int i = 0; i < ES_DESCRIPTOR_COUNT; i++ )
4157         {
4158             iod_descriptor_t *iod = p_pmt->iod;
4159             if( iod->es_descr[i].i_es_id == i_es_id )
4160             {
4161                 if ( iod->es_descr[i].b_ok )
4162                     p_es->p_mpeg4desc = &iod->es_descr[i];
4163                 else
4164                     msg_Dbg( p_demux, "MPEG-4 descriptor not yet available on es_id=%d", i_es_id );
4165                 break;
4166             }
4167         }
4168     }
4169     if( !p_es->p_mpeg4desc )
4170     {
4171         switch( p_dvbpsies->i_type )
4172         {
4173         /* non fatal, set by packetizer */
4174         case 0x0f: /* ADTS */
4175         case 0x11: /* LOAS */
4176             msg_Info( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4177                       p_dvbpsies->i_pid, p_dvbpsies->i_type );
4178             break;
4179         default:
4180             msg_Err( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4181                      p_dvbpsies->i_pid, p_dvbpsies->i_type );
4182             break;
4183         }
4184         return;
4185     }
4186
4187     const decoder_config_descriptor_t *dcd = &p_es->p_mpeg4desc->dec_descr;
4188     if( dcd->i_streamType == 0x04 )    /* VisualStream */
4189     {
4190         p_fmt->i_cat = VIDEO_ES;
4191         switch( dcd->i_objectTypeIndication )
4192         {
4193         case 0x0B: /* mpeg4 sub */
4194             p_fmt->i_cat = SPU_ES;
4195             p_fmt->i_codec = VLC_CODEC_SUBT;
4196             break;
4197
4198         case 0x20: /* mpeg4 */
4199             p_fmt->i_codec = VLC_CODEC_MP4V;
4200             break;
4201         case 0x21: /* h264 */
4202             p_fmt->i_codec = VLC_CODEC_H264;
4203             break;
4204         case 0x60:
4205         case 0x61:
4206         case 0x62:
4207         case 0x63:
4208         case 0x64:
4209         case 0x65: /* mpeg2 */
4210             p_fmt->i_codec = VLC_CODEC_MPGV;
4211             break;
4212         case 0x6a: /* mpeg1 */
4213             p_fmt->i_codec = VLC_CODEC_MPGV;
4214             break;
4215         case 0x6c: /* mpeg1 */
4216             p_fmt->i_codec = VLC_CODEC_JPEG;
4217             break;
4218         default:
4219             p_fmt->i_cat = UNKNOWN_ES;
4220             break;
4221         }
4222     }
4223     else if( dcd->i_streamType == 0x05 )    /* AudioStream */
4224     {
4225         p_fmt->i_cat = AUDIO_ES;
4226         switch( dcd->i_objectTypeIndication )
4227         {
4228         case 0x40: /* mpeg4 */
4229             p_fmt->i_codec = VLC_CODEC_MP4A;
4230             break;
4231         case 0x66:
4232         case 0x67:
4233         case 0x68: /* mpeg2 aac */
4234             p_fmt->i_codec = VLC_CODEC_MP4A;
4235             break;
4236         case 0x69: /* mpeg2 */
4237             p_fmt->i_codec = VLC_CODEC_MPGA;
4238             break;
4239         case 0x6b: /* mpeg1 */
4240             p_fmt->i_codec = VLC_CODEC_MPGA;
4241             break;
4242         default:
4243             p_fmt->i_cat = UNKNOWN_ES;
4244             break;
4245         }
4246     }
4247     else
4248     {
4249         p_fmt->i_cat = UNKNOWN_ES;
4250     }
4251
4252     if( p_fmt->i_cat != UNKNOWN_ES )
4253     {
4254         p_fmt->i_extra = dcd->i_extra;
4255         if( p_fmt->i_extra > 0 )
4256         {
4257             p_fmt->p_extra = malloc( p_fmt->i_extra );
4258             if( p_fmt->p_extra )
4259                 memcpy( p_fmt->p_extra, dcd->p_extra, p_fmt->i_extra );
4260             else
4261                 p_fmt->i_extra = 0;
4262         }
4263     }
4264 }
4265
4266 typedef struct
4267 {
4268     int  i_type;
4269     int  i_magazine;
4270     int  i_page;
4271     char p_iso639[3];
4272 } ts_teletext_page_t;
4273
4274 static void PMTSetupEsTeletext( demux_t *p_demux, ts_pes_t *p_pes,
4275                                 const dvbpsi_pmt_es_t *p_dvbpsies )
4276 {
4277     es_format_t *p_fmt = &p_pes->es.fmt;
4278
4279     ts_teletext_page_t p_page[2 * 64 + 20];
4280     unsigned i_page = 0;
4281
4282     /* Gather pages information */
4283     for( unsigned i_tag_idx = 0; i_tag_idx < 2; i_tag_idx++ )
4284     {
4285         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, i_tag_idx == 0 ? 0x46 : 0x56 );
4286         if( !p_dr )
4287             continue;
4288
4289         dvbpsi_teletext_dr_t *p_sub = dvbpsi_DecodeTeletextDr( p_dr );
4290         if( !p_sub )
4291             continue;
4292
4293         for( int i = 0; i < p_sub->i_pages_number; i++ )
4294         {
4295             const dvbpsi_teletextpage_t *p_src = &p_sub->p_pages[i];
4296
4297             if( p_src->i_teletext_type >= 0x06 )
4298                 continue;
4299
4300             assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4301
4302             ts_teletext_page_t *p_dst = &p_page[i_page++];
4303
4304             p_dst->i_type = p_src->i_teletext_type;
4305             p_dst->i_magazine = p_src->i_teletext_magazine_number
4306                 ? p_src->i_teletext_magazine_number : 8;
4307             p_dst->i_page = p_src->i_teletext_page_number;
4308             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4309         }
4310     }
4311
4312     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4313     if( p_dr )
4314     {
4315         dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4316         for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4317         {
4318             dvbpsi_subtitle_t *p_src = &p_sub->p_subtitle[i];
4319
4320             if( p_src->i_subtitling_type < 0x01 || p_src->i_subtitling_type > 0x03 )
4321                 continue;
4322
4323             assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4324
4325             ts_teletext_page_t *p_dst = &p_page[i_page++];
4326
4327             switch( p_src->i_subtitling_type )
4328             {
4329             case 0x01:
4330                 p_dst->i_type = 0x02;
4331                 break;
4332             default:
4333                 p_dst->i_type = 0x03;
4334                 break;
4335             }
4336             /* FIXME check if it is the right split */
4337             p_dst->i_magazine = (p_src->i_composition_page_id >> 8)
4338                 ? (p_src->i_composition_page_id >> 8) : 8;
4339             p_dst->i_page = p_src->i_composition_page_id & 0xff;
4340             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4341         }
4342     }
4343
4344     /* */
4345     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_TELETEXT );
4346
4347     if( !p_demux->p_sys->b_split_es || i_page <= 0 )
4348     {
4349         p_fmt->subs.teletext.i_magazine = -1;
4350         p_fmt->subs.teletext.i_page = 0;
4351         p_fmt->psz_description = strdup( vlc_gettext(ppsz_teletext_type[1]) );
4352
4353         dvbpsi_descriptor_t *p_dr;
4354         p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x46 );
4355         if( !p_dr )
4356             p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x56 );
4357
4358         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4359         {
4360             /* Descriptor pass-through */
4361             p_fmt->p_extra = malloc( p_dr->i_length );
4362             if( p_fmt->p_extra )
4363             {
4364                 p_fmt->i_extra = p_dr->i_length;
4365                 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4366             }
4367         }
4368     }
4369     else
4370     {
4371         for( unsigned i = 0; i < i_page; i++ )
4372         {
4373             ts_pes_es_t *p_page_es;
4374
4375             /* */
4376             if( i == 0 )
4377             {
4378                 p_page_es = &p_pes->es;
4379             }
4380             else
4381             {
4382                 p_page_es = malloc( sizeof(*p_page_es) );
4383                 if( !p_page_es )
4384                     break;
4385
4386                 es_format_Copy( &p_page_es->fmt, p_fmt );
4387                 free( p_page_es->fmt.psz_language );
4388                 free( p_page_es->fmt.psz_description );
4389                 p_page_es->fmt.psz_language = NULL;
4390                 p_page_es->fmt.psz_description = NULL;
4391
4392                 ARRAY_APPEND( p_pes->extra_es, p_page_es );
4393             }
4394
4395             /* */
4396             const ts_teletext_page_t *p = &p_page[i];
4397             p_page_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ?
4398                       ES_PRIORITY_SELECTABLE_MIN : ES_PRIORITY_NOT_DEFAULTABLE;
4399             p_page_es->fmt.psz_language = strndup( p->p_iso639, 3 );
4400             p_page_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
4401             p_page_es->fmt.subs.teletext.i_magazine = p->i_magazine;
4402             p_page_es->fmt.subs.teletext.i_page = p->i_page;
4403
4404             msg_Dbg( p_demux,
4405                          "    * ttxt type=%s lan=%s page=%d%02x",
4406                          p_page_es->fmt.psz_description,
4407                          p_page_es->fmt.psz_language,
4408                          p->i_magazine, p->i_page );
4409         }
4410     }
4411 }
4412 static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pes_t *p_pes,
4413                                    const dvbpsi_pmt_es_t *p_dvbpsies )
4414 {
4415     es_format_t *p_fmt = &p_pes->es.fmt;
4416
4417     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_DVBS );
4418
4419     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4420     int i_page = 0;
4421     dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4422     for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4423     {
4424         const int i_type = p_sub->p_subtitle[i].i_subtitling_type;
4425         if( ( i_type >= 0x10 && i_type <= 0x14 ) ||
4426             ( i_type >= 0x20 && i_type <= 0x24 ) )
4427             i_page++;
4428     }
4429
4430     if( !p_demux->p_sys->b_split_es  || i_page <= 0 )
4431     {
4432         p_fmt->subs.dvb.i_id = -1;
4433         p_fmt->psz_description = strdup( _("DVB subtitles") );
4434
4435         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4436         {
4437             /* Descriptor pass-through */
4438             p_fmt->p_extra = malloc( p_dr->i_length );
4439             if( p_fmt->p_extra )
4440             {
4441                 p_fmt->i_extra = p_dr->i_length;
4442                 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4443             }
4444         }
4445     }
4446     else
4447     {
4448         for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4449         {
4450             ts_pes_es_t *p_subs_es;
4451
4452             /* */
4453             if( i == 0 )
4454             {
4455                 p_subs_es = &p_pes->es;
4456             }
4457             else
4458             {
4459                 p_subs_es = malloc( sizeof(*p_subs_es) );
4460                 if( !p_subs_es )
4461                     break;
4462
4463                 es_format_Copy( &p_subs_es->fmt, p_fmt );
4464                 free( p_subs_es->fmt.psz_language );
4465                 free( p_subs_es->fmt.psz_description );
4466                 p_subs_es->fmt.psz_language = NULL;
4467                 p_subs_es->fmt.psz_description = NULL;
4468
4469                 ARRAY_APPEND( p_pes->extra_es, p_subs_es );
4470             }
4471
4472             /* */
4473             const dvbpsi_subtitle_t *p = &p_sub->p_subtitle[i];
4474             p_subs_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
4475             switch( p->i_subtitling_type )
4476             {
4477             case 0x10: /* unspec. */
4478             case 0x11: /* 4:3 */
4479             case 0x12: /* 16:9 */
4480             case 0x13: /* 2.21:1 */
4481             case 0x14: /* HD monitor */
4482                 p_subs_es->fmt.psz_description = strdup( _("DVB subtitles") );
4483                 break;
4484             case 0x20: /* Hearing impaired unspec. */
4485             case 0x21: /* h.i. 4:3 */
4486             case 0x22: /* h.i. 16:9 */
4487             case 0x23: /* h.i. 2.21:1 */
4488             case 0x24: /* h.i. HD monitor */
4489                 p_subs_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
4490                 break;
4491             default:
4492                 break;
4493             }
4494
4495             /* Hack, FIXME */
4496             p_subs_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id <<  0 ) |
4497                                       ( p->i_ancillary_page_id   << 16 );
4498         }
4499     }
4500 }
4501
4502 static int vlc_ceil_log2( const unsigned int val )
4503 {
4504     int n = 31 - clz(val);
4505     if ((1U << n) != val)
4506         n++;
4507
4508     return n;
4509 }
4510
4511 static void OpusSetup(demux_t *demux, uint8_t *p, size_t len, es_format_t *p_fmt)
4512 {
4513     OpusHeader h;
4514
4515     /* default mapping */
4516     static const unsigned char map[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
4517     memcpy(h.stream_map, map, sizeof(map));
4518
4519     int csc, mapping;
4520     int channels = 0;
4521     int stream_count = 0;
4522     int ccc = p[1]; // channel_config_code
4523     if (ccc <= 8) {
4524         channels = ccc;
4525         if (channels)
4526             mapping = channels > 2;
4527         else {
4528             mapping = 255;
4529             channels = 2; // dual mono
4530         }
4531         static const uint8_t p_csc[8] = { 0, 1, 1, 2, 2, 2, 3, 3 };
4532         csc = p_csc[channels - 1];
4533         stream_count = channels - csc;
4534
4535         static const uint8_t map[6][7] = {
4536             { 2,1 },
4537             { 1,2,3 },
4538             { 4,1,2,3 },
4539             { 4,1,2,3,5 },
4540             { 4,1,2,3,5,6 },
4541             { 6,1,2,3,4,5,7 },
4542         };
4543         if (channels > 2)
4544             memcpy(&h.stream_map[1], map[channels-3], channels - 1);
4545     } else if (ccc == 0x81) {
4546         if (len < 4)
4547             goto explicit_config_too_short;
4548
4549         channels = p[2];
4550         mapping = p[3];
4551         csc = 0;
4552         if (mapping) {
4553             bs_t s;
4554             bs_init(&s, &p[4], len - 4);
4555             stream_count = 1;
4556             if (channels) {
4557                 int bits = vlc_ceil_log2(channels);
4558                 if (s.i_left < bits)
4559                     goto explicit_config_too_short;
4560                 stream_count = bs_read(&s, bits) + 1;
4561                 bits = vlc_ceil_log2(stream_count + 1);
4562                 if (s.i_left < bits)
4563                     goto explicit_config_too_short;
4564                 csc = bs_read(&s, bits);
4565             }
4566             int channel_bits = vlc_ceil_log2(stream_count + csc + 1);
4567             if (s.i_left < channels * channel_bits)
4568                 goto explicit_config_too_short;
4569
4570             unsigned char silence = (1U << (stream_count + csc + 1)) - 1;
4571             for (int i = 0; i < channels; i++) {
4572                 unsigned char m = bs_read(&s, channel_bits);
4573                 if (m == silence)
4574                     m = 0xff;
4575                 h.stream_map[i] = m;
4576             }
4577         }
4578     } else if (ccc >= 0x80 && ccc <= 0x88) {
4579         channels = ccc - 0x80;
4580         if (channels)
4581             mapping = 1;
4582         else {
4583             mapping = 255;
4584             channels = 2; // dual mono
4585         }
4586         csc = 0;
4587         stream_count = channels;
4588     } else {
4589         msg_Err(demux, "Opus channel configuration 0x%.2x is reserved", ccc);
4590     }
4591
4592     if (!channels) {
4593         msg_Err(demux, "Opus channel configuration 0x%.2x not supported yet", p[1]);
4594         return;
4595     }
4596
4597     opus_prepare_header(channels, 0, &h);
4598     h.preskip = 0;
4599     h.input_sample_rate = 48000;
4600     h.nb_coupled = csc;
4601     h.nb_streams = channels - csc;
4602     h.channel_mapping = mapping;
4603
4604     if (h.channels) {
4605         opus_write_header((uint8_t**)&p_fmt->p_extra, &p_fmt->i_extra, &h, NULL /* FIXME */);
4606         if (p_fmt->p_extra) {
4607             p_fmt->i_cat = AUDIO_ES;
4608             p_fmt->i_codec = VLC_CODEC_OPUS;
4609             p_fmt->audio.i_channels = h.channels;
4610             p_fmt->audio.i_rate = 48000;
4611         }
4612     }
4613
4614     return;
4615
4616 explicit_config_too_short:
4617     msg_Err(demux, "Opus descriptor too short");
4618 }
4619
4620 static void PMTSetupEs0x06( demux_t *p_demux, ts_pes_t *p_pes,
4621                             const dvbpsi_pmt_es_t *p_dvbpsies )
4622 {
4623     es_format_t *p_fmt = &p_pes->es.fmt;
4624     dvbpsi_descriptor_t *p_subs_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4625     dvbpsi_descriptor_t *desc;
4626
4627     if( PMTEsHasRegistration( p_demux, p_dvbpsies, "AC-3" ) ||
4628         PMTEsFindDescriptor( p_dvbpsies, 0x6a ) ||
4629         PMTEsFindDescriptor( p_dvbpsies, 0x81 ) )
4630     {
4631         p_fmt->i_cat = AUDIO_ES;
4632         p_fmt->i_codec = VLC_CODEC_A52;
4633     }
4634     else if( (desc = PMTEsFindDescriptor( p_dvbpsies, 0x7f ) ) && desc->i_length >= 2 &&
4635               PMTEsHasRegistration(p_demux, p_dvbpsies, "Opus"))
4636     {
4637         OpusSetup(p_demux, desc->p_data, desc->i_length, p_fmt);
4638     }
4639     else if( PMTEsFindDescriptor( p_dvbpsies, 0x7a ) )
4640     {
4641         /* DVB with stream_type 0x06 (ETS EN 300 468) */
4642         p_fmt->i_cat = AUDIO_ES;
4643         p_fmt->i_codec = VLC_CODEC_EAC3;
4644     }
4645     else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS1" ) ||
4646              PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS2" ) ||
4647              PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS3" ) ||
4648              PMTEsFindDescriptor( p_dvbpsies, 0x73 ) )
4649     {
4650         /*registration descriptor(ETSI TS 101 154 Annex F)*/
4651         p_fmt->i_cat = AUDIO_ES;
4652         p_fmt->i_codec = VLC_CODEC_DTS;
4653     }
4654     else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "BSSD" ) && !p_subs_dr )
4655     {
4656         /* BSSD is AES3 DATA, but could also be subtitles
4657          * we need to check for secondary descriptor then s*/
4658         p_fmt->i_cat = AUDIO_ES;
4659         p_fmt->b_packetized = true;
4660         p_fmt->i_codec = VLC_CODEC_302M;
4661     }
4662     else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "HEVC" ) )
4663     {
4664         p_fmt->i_cat = VIDEO_ES;
4665         p_fmt->i_codec = VLC_CODEC_HEVC;
4666     }
4667     else if ( p_demux->p_sys->arib.e_mode == ARIBMODE_ENABLED )
4668     {
4669         /* Lookup our data component descriptor first ARIB STD B10 6.4 */
4670         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xFD );
4671         /* and check that it maps to something ARIB STD B14 Table 5.1/5.2 */
4672         if ( p_dr && p_dr->i_length >= 2 )
4673         {
4674             if( !memcmp( p_dr->p_data, "\x00\x08", 2 ) &&  (
4675                     PMTEsHasComponentTag( p_dvbpsies, 0x30 ) ||
4676                     PMTEsHasComponentTag( p_dvbpsies, 0x31 ) ||
4677                     PMTEsHasComponentTag( p_dvbpsies, 0x32 ) ||
4678                     PMTEsHasComponentTag( p_dvbpsies, 0x33 ) ||
4679                     PMTEsHasComponentTag( p_dvbpsies, 0x34 ) ||
4680                     PMTEsHasComponentTag( p_dvbpsies, 0x35 ) ||
4681                     PMTEsHasComponentTag( p_dvbpsies, 0x36 ) ||
4682                     PMTEsHasComponentTag( p_dvbpsies, 0x37 ) ) )
4683             {
4684                 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_A );
4685                 p_fmt->psz_language = strndup ( "jpn", 3 );
4686                 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4687             }
4688             else if( !memcmp( p_dr->p_data, "\x00\x12", 2 ) && (
4689                      PMTEsHasComponentTag( p_dvbpsies, 0x87 ) ||
4690                      PMTEsHasComponentTag( p_dvbpsies, 0x88 ) ) )
4691             {
4692                 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_C );
4693                 p_fmt->psz_language = strndup ( "jpn", 3 );
4694                 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4695             }
4696         }
4697     }
4698     else
4699     {
4700         /* Subtitle/Teletext/VBI fallbacks */
4701         dvbpsi_subtitling_dr_t *p_sub;
4702         if( p_subs_dr && ( p_sub = dvbpsi_DecodeSubtitlingDr( p_subs_dr ) ) )
4703         {
4704             for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4705             {
4706                 if( p_fmt->i_cat != UNKNOWN_ES )
4707                     break;
4708
4709                 switch( p_sub->p_subtitle[i].i_subtitling_type )
4710                 {
4711                 case 0x01: /* EBU Teletext subtitles */
4712                 case 0x02: /* Associated EBU Teletext */
4713                 case 0x03: /* VBI data */
4714                     PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
4715                     break;
4716                 case 0x10: /* DVB Subtitle (normal) with no monitor AR critical */
4717                 case 0x11: /*                 ...   on 4:3 AR monitor */
4718                 case 0x12: /*                 ...   on 16:9 AR monitor */
4719                 case 0x13: /*                 ...   on 2.21:1 AR monitor */
4720                 case 0x14: /*                 ...   for display on a high definition monitor */
4721                 case 0x20: /* DVB Subtitle (impaired) with no monitor AR critical */
4722                 case 0x21: /*                 ...   on 4:3 AR monitor */
4723                 case 0x22: /*                 ...   on 16:9 AR monitor */
4724                 case 0x23: /*                 ...   on 2.21:1 AR monitor */
4725                 case 0x24: /*                 ...   for display on a high definition monitor */
4726                     PMTSetupEsDvbSubtitle( p_demux, p_pes, p_dvbpsies );
4727                     break;
4728                 default:
4729                     msg_Err( p_demux, "Unrecognized DVB subtitle type (0x%x)",
4730                              p_sub->p_subtitle[i].i_subtitling_type );
4731                     break;
4732                 }
4733             }
4734         }
4735
4736         if( p_fmt->i_cat == UNKNOWN_ES &&
4737             ( PMTEsFindDescriptor( p_dvbpsies, 0x45 ) ||  /* VBI Data descriptor */
4738               PMTEsFindDescriptor( p_dvbpsies, 0x46 ) ||  /* VBI Teletext descriptor */
4739               PMTEsFindDescriptor( p_dvbpsies, 0x56 ) ) ) /* EBU Teletext descriptor */
4740         {
4741             /* Teletext/VBI */
4742             PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
4743         }
4744     }
4745
4746     /* FIXME is it useful ? */
4747     if( PMTEsFindDescriptor( p_dvbpsies, 0x52 ) )
4748     {
4749         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x52 );
4750         dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4751
4752         msg_Dbg( p_demux, "    * Stream Component Identifier: %d", p_si->i_component_tag );
4753     }
4754 }
4755
4756 static void PMTSetupEs0xEA( demux_t *p_demux, ts_pes_es_t *p_es,
4757                            const dvbpsi_pmt_es_t *p_dvbpsies )
4758 {
4759     /* Registration Descriptor */
4760     if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "VC-1" ) )
4761     {
4762         msg_Err( p_demux, "Registration descriptor not found or invalid" );
4763         return;
4764     }
4765
4766     es_format_t *p_fmt = &p_es->fmt;
4767
4768     /* registration descriptor for VC-1 (SMPTE rp227) */
4769     p_fmt->i_cat = VIDEO_ES;
4770     p_fmt->i_codec = VLC_CODEC_VC1;
4771
4772     /* XXX With Simple and Main profile the SEQUENCE
4773      * header is modified: video width and height are
4774      * inserted just after the start code as 2 int16_t
4775      * The packetizer will take care of that. */
4776 }
4777
4778 static void PMTSetupEs0xD1( demux_t *p_demux, ts_pes_es_t *p_es,
4779                            const dvbpsi_pmt_es_t *p_dvbpsies )
4780 {
4781     /* Registration Descriptor */
4782     if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "drac" ) )
4783     {
4784         msg_Err( p_demux, "Registration descriptor not found or invalid" );
4785         return;
4786     }
4787
4788     es_format_t *p_fmt = &p_es->fmt;
4789
4790     /* registration descriptor for Dirac
4791      * (backwards compatable with VC-2 (SMPTE Sxxxx:2008)) */
4792     p_fmt->i_cat = VIDEO_ES;
4793     p_fmt->i_codec = VLC_CODEC_DIRAC;
4794 }
4795
4796 static void PMTSetupEs0xA0( demux_t *p_demux, ts_pes_es_t *p_es,
4797                            const dvbpsi_pmt_es_t *p_dvbpsies )
4798 {
4799     /* MSCODEC sent by vlc */
4800     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xa0 );
4801     if( !p_dr || p_dr->i_length < 10 )
4802     {
4803         msg_Warn( p_demux,
4804                   "private MSCODEC (vlc) without bih private descriptor" );
4805         return;
4806     }
4807
4808     es_format_t *p_fmt = &p_es->fmt;
4809     p_fmt->i_cat = VIDEO_ES;
4810     p_fmt->i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
4811                                  p_dr->p_data[2], p_dr->p_data[3] );
4812     p_fmt->video.i_width = GetWBE( &p_dr->p_data[4] );
4813     p_fmt->video.i_height = GetWBE( &p_dr->p_data[6] );
4814     p_fmt->i_extra = GetWBE( &p_dr->p_data[8] );
4815
4816     if( p_fmt->i_extra > 0 )
4817     {
4818         p_fmt->p_extra = malloc( p_fmt->i_extra );
4819         if( p_fmt->p_extra )
4820             memcpy( p_fmt->p_extra, &p_dr->p_data[10],
4821                     __MIN( p_fmt->i_extra, p_dr->i_length - 10 ) );
4822         else
4823             p_fmt->i_extra = 0;
4824     }
4825     /* For such stream we will gather them ourself and don't launch a
4826      * packetizer.
4827      * Yes it's ugly but it's the only way to have DIV3 working */
4828     p_fmt->b_packetized = true;
4829 }
4830
4831 static void PMTSetupEs0x83( const dvbpsi_pmt_t *p_pmt, ts_pes_es_t *p_es, int i_pid )
4832 {
4833     /* WiDi broadcasts without registration on PMT 0x1, PCR 0x1000 and
4834      * with audio track pid being 0x1100..0x11FF */
4835     if ( p_pmt->i_program_number == 0x1 &&
4836          p_pmt->i_pcr_pid == 0x1000 &&
4837         ( i_pid >> 8 ) == 0x11 )
4838     {
4839         /* Not enough ? might contain 0x83 private descriptor, 2 bytes 0x473F */
4840         es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_WIDI_LPCM );
4841     }
4842     else
4843         es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
4844 }
4845
4846 static bool PMTSetupEsHDMV( demux_t *p_demux, ts_pes_es_t *p_es,
4847                             const dvbpsi_pmt_es_t *p_dvbpsies )
4848 {
4849     es_format_t *p_fmt = &p_es->fmt;
4850
4851     /* Blu-Ray mapping */
4852     switch( p_dvbpsies->i_type )
4853     {
4854     case 0x80:
4855         p_fmt->i_cat = AUDIO_ES;
4856         p_fmt->i_codec = VLC_CODEC_BD_LPCM;
4857         break;
4858     case 0x81:
4859         p_fmt->i_cat = AUDIO_ES;
4860         p_fmt->i_codec = VLC_CODEC_A52;
4861         break;
4862     case 0x82:
4863     case 0x85: /* DTS-HD High resolution audio */
4864     case 0x86: /* DTS-HD Master audio */
4865     case 0xA2: /* Secondary DTS audio */
4866         p_fmt->i_cat = AUDIO_ES;
4867         p_fmt->i_codec = VLC_CODEC_DTS;
4868         break;
4869
4870     case 0x83: /* TrueHD AC3 */
4871         p_fmt->i_cat = AUDIO_ES;
4872         p_fmt->i_codec = VLC_CODEC_TRUEHD;
4873         break;
4874
4875     case 0x84: /* E-AC3 */
4876     case 0xA1: /* Secondary E-AC3 */
4877         p_fmt->i_cat = AUDIO_ES;
4878         p_fmt->i_codec = VLC_CODEC_EAC3;
4879         break;
4880     case 0x90: /* Presentation graphics */
4881         p_fmt->i_cat = SPU_ES;
4882         p_fmt->i_codec = VLC_CODEC_BD_PG;
4883         break;
4884     case 0x91: /* Interactive graphics */
4885     case 0x92: /* Subtitle */
4886         return false;
4887     case 0xEA:
4888         p_fmt->i_cat = VIDEO_ES;
4889         p_fmt->i_codec = VLC_CODEC_VC1;
4890         break;
4891     default:
4892         msg_Info( p_demux, "HDMV registration not implemented for pid 0x%x type 0x%x",
4893                   p_dvbpsies->i_pid, p_dvbpsies->i_type );
4894         return false;
4895         break;
4896     }
4897     return true;
4898 }
4899
4900 static bool PMTSetupEsRegistration( demux_t *p_demux, ts_pes_es_t *p_es,
4901                                     const dvbpsi_pmt_es_t *p_dvbpsies )
4902 {
4903     static const struct
4904     {
4905         char         psz_tag[5];
4906         int          i_cat;
4907         vlc_fourcc_t i_codec;
4908     } p_regs[] = {
4909         { "AC-3", AUDIO_ES, VLC_CODEC_A52   },
4910         { "DTS1", AUDIO_ES, VLC_CODEC_DTS   },
4911         { "DTS2", AUDIO_ES, VLC_CODEC_DTS   },
4912         { "DTS3", AUDIO_ES, VLC_CODEC_DTS   },
4913         { "BSSD", AUDIO_ES, VLC_CODEC_302M  },
4914         { "VC-1", VIDEO_ES, VLC_CODEC_VC1   },
4915         { "drac", VIDEO_ES, VLC_CODEC_DIRAC },
4916         { "", UNKNOWN_ES, 0 }
4917     };
4918     es_format_t *p_fmt = &p_es->fmt;
4919
4920     for( int i = 0; p_regs[i].i_cat != UNKNOWN_ES; i++ )
4921     {
4922         if( PMTEsHasRegistration( p_demux, p_dvbpsies, p_regs[i].psz_tag ) )
4923         {
4924             p_fmt->i_cat   = p_regs[i].i_cat;
4925             p_fmt->i_codec = p_regs[i].i_codec;
4926             if (p_dvbpsies->i_type == 0x87)
4927                 p_fmt->i_codec = VLC_CODEC_EAC3;
4928             return true;
4929         }
4930     }
4931     return false;
4932 }
4933
4934 static char *GetAudioTypeDesc(demux_t *p_demux, int type)
4935 {
4936     static const char *audio_type[] = {
4937         NULL,
4938         N_("clean effects"),
4939         N_("hearing impaired"),
4940         N_("visual impaired commentary"),
4941     };
4942
4943     if (type < 0 || type > 3)
4944         msg_Dbg( p_demux, "unknown audio type: %d", type);
4945     else if (type > 0)
4946         return strdup(audio_type[type]);
4947
4948     return NULL;
4949 }
4950 static void PMTParseEsIso639( demux_t *p_demux, ts_pes_es_t *p_es,
4951                               const dvbpsi_pmt_es_t *p_dvbpsies )
4952 {
4953     /* get language descriptor */
4954     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x0a );
4955
4956     if( !p_dr )
4957         return;
4958
4959     dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
4960     if( !p_decoded )
4961     {
4962         msg_Err( p_demux, "Failed to decode a ISO 639 descriptor" );
4963         return;
4964     }
4965
4966 #if defined(DR_0A_API_VER) && (DR_0A_API_VER >= 2)
4967     p_es->fmt.psz_language = malloc( 4 );
4968     if( p_es->fmt.psz_language )
4969     {
4970         memcpy( p_es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
4971         p_es->fmt.psz_language[3] = 0;
4972         msg_Dbg( p_demux, "found language: %s", p_es->fmt.psz_language);
4973     }
4974     int type = p_decoded->code[0].i_audio_type;
4975     p_es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
4976     if (type == 0)
4977         p_es->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1; // prioritize normal audio tracks
4978
4979     p_es->fmt.i_extra_languages = p_decoded->i_code_count-1;
4980     if( p_es->fmt.i_extra_languages > 0 )
4981         p_es->fmt.p_extra_languages =
4982             malloc( sizeof(*p_es->fmt.p_extra_languages) *
4983                     p_es->fmt.i_extra_languages );
4984     if( p_es->fmt.p_extra_languages )
4985     {
4986         for( unsigned i = 0; i < p_es->fmt.i_extra_languages; i++ )
4987         {
4988             p_es->fmt.p_extra_languages[i].psz_language = malloc(4);
4989             if( p_es->fmt.p_extra_languages[i].psz_language )
4990             {
4991                 memcpy( p_es->fmt.p_extra_languages[i].psz_language,
4992                     p_decoded->code[i+1].iso_639_code, 3 );
4993                 p_es->fmt.p_extra_languages[i].psz_language[3] = '\0';
4994             }
4995             int type = p_decoded->code[i].i_audio_type;
4996             p_es->fmt.p_extra_languages[i].psz_description = GetAudioTypeDesc(p_demux, type);
4997         }
4998     }
4999 #else
5000     p_es->fmt.psz_language = malloc( 4 );
5001     if( p_es->fmt.psz_language )
5002     {
5003         memcpy( p_es->fmt.psz_language,
5004                 p_decoded->i_iso_639_code, 3 );
5005         p_es->fmt.psz_language[3] = 0;
5006     }
5007 #endif
5008 }
5009
5010 static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid, bool b_create_delayed )
5011 {
5012     demux_sys_t  *p_sys = p_demux->p_sys;
5013
5014     if( b_create_delayed )
5015         p_sys->es_creation = CREATE_ES;
5016
5017     if( pid && p_sys->es_creation == CREATE_ES )
5018     {
5019         /* FIXME: other owners / shared pid */
5020         pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
5021         for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
5022         {
5023             pid->u.p_pes->extra_es.p_elems[i]->id =
5024                     es_out_Add( p_demux->out, &pid->u.p_pes->extra_es.p_elems[i]->fmt );
5025         }
5026         p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
5027
5028         /* Update the default program == first created ES group */
5029         if( p_sys->b_default_selection )
5030         {
5031             p_sys->b_default_selection = false;
5032             assert(p_sys->programs.i_size == 1);
5033             if( p_sys->programs.p_elems[0] != pid->p_parent->u.p_pmt->i_number )
5034                 p_sys->programs.p_elems[0] = pid->p_parent->u.p_pmt->i_number;
5035             msg_Dbg( p_demux, "Default program is %d", pid->p_parent->u.p_pmt->i_number );
5036         }
5037     }
5038
5039     if( b_create_delayed )
5040     {
5041         ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
5042         for( int i=0; i< p_pat->programs.i_size; i++ )
5043         {
5044             ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
5045             for( int j=0; j<p_pmt->e_streams.i_size; j++ )
5046             {
5047                 ts_pid_t *pid = p_pmt->e_streams.p_elems[j];
5048                 if( pid->u.p_pes->es.id )
5049                     continue;
5050
5051                 pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
5052                 for( int k = 0; k < pid->u.p_pes->extra_es.i_size; k++ )
5053                 {
5054                     pid->u.p_pes->extra_es.p_elems[k]->id =
5055                         es_out_Add( p_demux->out, &pid->u.p_pes->extra_es.p_elems[k]->fmt );
5056                 }
5057                 p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
5058             }
5059         }
5060     }
5061
5062     UpdatePESFilters( p_demux, p_sys->b_es_all );
5063 }
5064
5065 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_dvbpsipmt )
5066 {
5067     demux_t      *p_demux = data;
5068     demux_sys_t  *p_sys = p_demux->p_sys;
5069
5070     ts_pid_t     *pmtpid = NULL;
5071     ts_pmt_t     *p_pmt = NULL;
5072
5073     msg_Dbg( p_demux, "PMTCallBack called" );
5074
5075     if (unlikely(p_sys->pid[0].type != TYPE_PAT))
5076     {
5077         assert(p_sys->pid[0].type == TYPE_PAT);
5078         dvbpsi_pmt_delete(p_dvbpsipmt);
5079     }
5080
5081     const ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
5082
5083     /* First find this PMT declared in PAT */
5084     for( int i = 0; !pmtpid && i < p_pat->programs.i_size; i++ )
5085     {
5086         const int i_pmt_prgnumber = p_pat->programs.p_elems[i]->u.p_pmt->i_number;
5087         if( i_pmt_prgnumber != TS_USER_PMT_NUMBER &&
5088             i_pmt_prgnumber == p_dvbpsipmt->i_program_number )
5089         {
5090             pmtpid = p_pat->programs.p_elems[i];
5091             assert(pmtpid->type == TYPE_PMT);
5092             p_pmt = pmtpid->u.p_pmt;
5093         }
5094     }
5095
5096     if( pmtpid == NULL )
5097     {
5098         msg_Warn( p_demux, "unreferenced program (broken stream)" );
5099         dvbpsi_pmt_delete(p_dvbpsipmt);
5100         return;
5101     }
5102
5103     pmtpid->i_flags |= FLAG_SEEN;
5104
5105     if( p_pmt->i_version != -1 &&
5106         ( !p_dvbpsipmt->b_current_next || p_pmt->i_version == p_dvbpsipmt->i_version ) )
5107     {
5108         dvbpsi_pmt_delete( p_dvbpsipmt );
5109         return;
5110     }
5111
5112     /* Save old es array */
5113     DECL_ARRAY(ts_pid_t *) old_es_rm;
5114     old_es_rm.i_alloc = p_pmt->e_streams.i_alloc;
5115     old_es_rm.i_size = p_pmt->e_streams.i_size;
5116     old_es_rm.p_elems = p_pmt->e_streams.p_elems;
5117     ARRAY_INIT(p_pmt->e_streams);
5118
5119     if( p_pmt->iod )
5120     {
5121         IODFree( p_pmt->iod );
5122         p_pmt->iod = NULL;
5123     }
5124
5125     msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
5126              p_dvbpsipmt->i_program_number, p_dvbpsipmt->i_version, p_dvbpsipmt->i_pcr_pid );
5127     p_pmt->i_pid_pcr = p_dvbpsipmt->i_pcr_pid;
5128     p_pmt->i_version = p_dvbpsipmt->i_version;
5129
5130     ValidateDVBMeta( p_demux, p_pmt->i_pid_pcr );
5131
5132     if( ProgramIsSelected( p_sys, p_pmt->i_number ) )
5133         SetPIDFilter( p_sys, &p_sys->pid[p_pmt->i_pid_pcr], true ); /* Set demux filter */
5134
5135     /* Parse PMT descriptors */
5136     ts_pmt_registration_type_t registration_type = TS_PMT_REGISTRATION_NONE;
5137     dvbpsi_descriptor_t  *p_dr;
5138
5139     /* First pass for standard detection */
5140     if ( p_sys->arib.e_mode == ARIBMODE_AUTO )
5141     {
5142         int i_arib_flags = 0; /* Descriptors can be repeated */
5143         for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5144         {
5145             switch(p_dr->i_tag)
5146             {
5147             case 0x09:
5148             {
5149                 dvbpsi_ca_dr_t *p_cadr = dvbpsi_DecodeCADr( p_dr );
5150                 i_arib_flags |= (p_cadr->i_ca_system_id == 0x05);
5151             }
5152                 break;
5153             case 0xF6:
5154                 i_arib_flags |= 1 << 1;
5155                 break;
5156             case 0xC1:
5157                 i_arib_flags |= 1 << 2;
5158                 break;
5159             default:
5160                 break;
5161             }
5162         }
5163         if ( i_arib_flags == 0x07 ) //0b111
5164             p_sys->arib.e_mode = ARIBMODE_ENABLED;
5165     }
5166
5167     for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5168     {
5169         /* special descriptors handling */
5170         switch(p_dr->i_tag)
5171         {
5172         case 0x1d: /* We have found an IOD descriptor */
5173             msg_Dbg( p_demux, " * PMT descriptor : IOD (0x1d)" );
5174             p_pmt->iod = IODNew( p_dr->i_length, p_dr->p_data );
5175             break;
5176
5177         case 0x9:
5178             msg_Dbg( p_demux, " * PMT descriptor : CA (0x9) SysID 0x%x",
5179                     (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5180             break;
5181
5182         case 0x5: /* Registration Descriptor */
5183             if( p_dr->i_length != 4 )
5184             {
5185                 msg_Warn( p_demux, " * PMT invalid Registration Descriptor" );
5186             }
5187             else
5188             {
5189                 msg_Dbg( p_demux, " * PMT descriptor : registration %4.4s", p_dr->p_data );
5190                 if( !memcmp( p_dr->p_data, "HDMV", 4 ) || !memcmp( p_dr->p_data, "HDPR", 4 ) )
5191                     registration_type = TS_PMT_REGISTRATION_HDMV; /* Blu-Ray */
5192             }
5193             break;
5194
5195         case 0x0f:
5196             msg_Dbg( p_demux, " * PMT descriptor : Private Data (0x0f)" );
5197             break;
5198
5199         case 0xC1:
5200             msg_Dbg( p_demux, " * PMT descriptor : Digital copy control (0xC1)" );
5201             break;
5202
5203         case 0x88: /* EACEM Simulcast HD Logical channels ordering */
5204             msg_Dbg( p_demux, " * descriptor : EACEM Simulcast HD" );
5205             /* TODO: apply visibility flags */
5206             break;
5207
5208         default:
5209             msg_Dbg( p_demux, " * PMT descriptor : unknown (0x%x)", p_dr->i_tag );
5210         }
5211     }
5212
5213     dvbpsi_pmt_es_t      *p_dvbpsies;
5214     for( p_dvbpsies = p_dvbpsipmt->p_first_es; p_dvbpsies != NULL; p_dvbpsies = p_dvbpsies->p_next )
5215     {
5216         bool b_reusing_pid = false;
5217         ts_pes_t *p_pes;
5218
5219         ts_pid_t *pespid = &p_sys->pid[p_dvbpsies->i_pid];
5220         if ( pespid->type == TYPE_PES && pespid->p_parent->u.p_pmt->i_number != p_pmt->i_number )
5221         {
5222             msg_Warn( p_demux, " * PMT wants to get a share or pid %d (unsupported)", pespid->i_pid );
5223             continue;
5224         }
5225
5226         /* Find out if the PID was already declared */
5227         for( int i = 0; i < old_es_rm.i_size; i++ )
5228         {
5229             if( old_es_rm.p_elems[i]->i_pid == p_dvbpsies->i_pid )
5230             {
5231                 b_reusing_pid = true;
5232                 break;
5233             }
5234         }
5235         ValidateDVBMeta( p_demux, p_dvbpsies->i_pid );
5236
5237         char const * psz_typedesc = "";
5238         switch(p_dvbpsies->i_type)
5239         {
5240         case 0x00:
5241             psz_typedesc = "ISO/IEC Reserved";
5242             break;
5243         case 0x01:
5244             psz_typedesc = "ISO/IEC 11172 Video";
5245             break;
5246         case 0x02:
5247             psz_typedesc = "ISO/IEC 13818-2 Video or ISO/IEC 11172-2 constrained parameter video stream";
5248             break;
5249         case 0x03:
5250             psz_typedesc = "ISO/IEC 11172 Audio";
5251             break;
5252         case 0x04:
5253             psz_typedesc = "ISO/IEC 13818-3 Audio";
5254             break;
5255         case 0x05:
5256             psz_typedesc = "ISO/IEC 13818-1 private_sections";
5257             break;
5258         case 0x06:
5259             psz_typedesc = "ISO/IEC 13818-1 PES packets containing private data";
5260             break;
5261         case 0x07:
5262             psz_typedesc = "ISO/IEC 13522 MHEG";
5263             break;
5264         case 0x08:
5265             psz_typedesc = "ISO/IEC 13818-1 Annex A DSM CC";
5266             break;
5267         case 0x09:
5268             psz_typedesc = "ITU-T Rec. H.222.1";
5269             break;
5270         case 0x0A:
5271             psz_typedesc = "ISO/IEC 13818-6 type A";
5272             break;
5273         case 0x0B:
5274             psz_typedesc = "ISO/IEC 13818-6 type B";
5275             break;
5276         case 0x0C:
5277             psz_typedesc = "ISO/IEC 13818-6 type C";
5278             break;
5279         case 0x0D:
5280             psz_typedesc = "ISO/IEC 13818-6 type D";
5281             break;
5282         case 0x0E:
5283             psz_typedesc = "ISO/IEC 13818-1 auxiliary";
5284             break;
5285         default:
5286             if (p_dvbpsies->i_type >= 0x0F && p_dvbpsies->i_type <=0x7F)
5287                 psz_typedesc = "ISO/IEC 13818-1 Reserved";
5288             else
5289                 psz_typedesc = "User Private";
5290         }
5291
5292         msg_Dbg( p_demux, "  * pid=%d type=0x%x %s",
5293                  p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
5294
5295         for( p_dr = p_dvbpsies->p_first_descriptor; p_dr != NULL;
5296              p_dr = p_dr->p_next )
5297         {
5298             msg_Dbg( p_demux, "    - descriptor tag 0x%x",
5299                      p_dr->i_tag );
5300         }
5301
5302         if ( !PIDSetup( p_demux, TYPE_PES, pespid, pmtpid ) )
5303         {
5304             msg_Warn( p_demux, "  * pid=%d type=0x%x %s (skipped)",
5305                       p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
5306             continue;
5307         }
5308         else
5309         {
5310             if( b_reusing_pid )
5311             {
5312                 p_pes = ts_pes_New( p_demux );
5313                 if( !p_pes )
5314                     continue;
5315             }
5316             else
5317             {
5318                 p_pes = pespid->u.p_pes;
5319             }
5320         }
5321
5322         ARRAY_APPEND( p_pmt->e_streams, pespid );
5323
5324         PIDFillFormat( &p_pes->es.fmt, p_dvbpsies->i_type );
5325
5326         pespid->i_flags |= SEEN(p_sys->pid[p_dvbpsies->i_pid]);
5327
5328         bool b_registration_applied = false;
5329         if ( p_dvbpsies->i_type >= 0x80 ) /* non standard, extensions */
5330         {
5331             if ( registration_type == TS_PMT_REGISTRATION_HDMV )
5332             {
5333                 if (( b_registration_applied = PMTSetupEsHDMV( p_demux, &p_pes->es, p_dvbpsies ) ))
5334                     msg_Dbg( p_demux, "    + HDMV registration applied to pid %d type 0x%x",
5335                              p_dvbpsies->i_pid, p_dvbpsies->i_type );
5336             }
5337             else
5338             {
5339                 if (( b_registration_applied = PMTSetupEsRegistration( p_demux, &p_pes->es, p_dvbpsies ) ))
5340                     msg_Dbg( p_demux, "    + registration applied to pid %d type 0x%x",
5341                         p_dvbpsies->i_pid, p_dvbpsies->i_type );
5342             }
5343         }
5344
5345         if ( !b_registration_applied )
5346         {
5347             switch( p_dvbpsies->i_type )
5348             {
5349             case 0x06:
5350                 /* Handle PES private data */
5351                 PMTSetupEs0x06( p_demux, p_pes, p_dvbpsies );
5352                 break;
5353             /* All other private or reserved types */
5354             case 0x0f:
5355             case 0x10:
5356             case 0x11:
5357             case 0x12:
5358                 PMTSetupEsISO14496( p_demux, &p_pes->es, p_pmt, p_dvbpsies );
5359                 break;
5360             case 0x83:
5361                 /* LPCM (audio) */
5362                 PMTSetupEs0x83( p_dvbpsipmt, &p_pes->es, p_dvbpsies->i_pid );
5363                 break;
5364             case 0xa0:
5365                 PMTSetupEs0xA0( p_demux, &p_pes->es, p_dvbpsies );
5366                 break;
5367             case 0xd1:
5368                 PMTSetupEs0xD1( p_demux, &p_pes->es, p_dvbpsies );
5369                 break;
5370             case 0xEA:
5371                 PMTSetupEs0xEA( p_demux, &p_pes->es, p_dvbpsies );
5372             default:
5373                 break;
5374             }
5375         }
5376
5377         if( p_pes->es.fmt.i_cat == AUDIO_ES ||
5378             ( p_pes->es.fmt.i_cat == SPU_ES &&
5379               p_pes->es.fmt.i_codec != VLC_CODEC_DVBS &&
5380               p_pes->es.fmt.i_codec != VLC_CODEC_TELETEXT ) )
5381         {
5382             PMTParseEsIso639( p_demux, &p_pes->es, p_dvbpsies );
5383         }
5384
5385         switch( p_pes->es.fmt.i_codec )
5386         {
5387         case VLC_CODEC_SCTE_27:
5388             p_pes->data_type = TS_ES_DATA_TABLE_SECTION;
5389             break;
5390         default:
5391             //pid->es->data_type = TS_ES_DATA_PES;
5392             break;
5393         }
5394
5395         p_pes->es.fmt.i_group = p_dvbpsipmt->i_program_number;
5396         for( int i = 0; i < p_pes->extra_es.i_size; i++ )
5397             p_pes->extra_es.p_elems[i]->fmt.i_group = p_dvbpsipmt->i_program_number;
5398
5399         if( p_pes->es.fmt.i_cat == UNKNOWN_ES )
5400         {
5401             msg_Dbg( p_demux, "   => pid %d content is *unknown*",
5402                      p_dvbpsies->i_pid );
5403             p_pes->es.fmt.psz_description = strdup( psz_typedesc );
5404         }
5405         else
5406         {
5407             msg_Dbg( p_demux, "   => pid %d has now es fcc=%4.4s",
5408                      p_dvbpsies->i_pid, (char*)&p_pes->es.fmt.i_codec );
5409
5410             if( p_sys->b_es_id_pid ) p_pes->es.fmt.i_id = p_dvbpsies->i_pid;
5411
5412             /* Check if we can avoid restarting the ES */
5413             if( b_reusing_pid )
5414             {
5415                 /* p_pes points to a tmp pes */
5416                 if( pespid->u.p_pes->es.fmt.i_codec != p_pes->es.fmt.i_codec ||
5417                     pespid->u.p_pes->es.fmt.i_extra != p_pes->es.fmt.i_extra ||
5418                     pespid->u.p_pes->es.fmt.i_extra != 0 ||
5419                     pespid->u.p_pes->extra_es.i_size != p_pes->extra_es.i_size ||
5420                     !( ( !pespid->u.p_pes->es.fmt.psz_language &&
5421                         !p_pes->es.fmt.psz_language ) ||
5422                       ( pespid->u.p_pes->es.fmt.psz_language &&
5423                         p_pes->es.fmt.psz_language &&
5424                         !strcmp( pespid->u.p_pes->es.fmt.psz_language,
5425                                  p_pes->es.fmt.psz_language ) ) ) )
5426                 {
5427                     /* Differs, swap then */
5428                     ts_pes_t *e = pespid->u.p_pes;
5429                     pespid->u.p_pes = p_pes;
5430                     p_pes = e;
5431
5432                     /* p_pes still tmp, but now contains old config */
5433                     pespid->u.p_pes->es.id = p_pes->es.id;
5434                     if( pespid->u.p_pes->es.id )
5435                     {
5436                         p_pes->es.id = NULL;
5437                         es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
5438                                         pespid->u.p_pes->es.id, pespid->u.p_pes->es.fmt );
5439                     }
5440
5441                     for( int i=0; i<pespid->u.p_pes->extra_es.i_size &&
5442                                   i<p_pes->extra_es.i_size; i++ )
5443                     {
5444                         pespid->u.p_pes->extra_es.p_elems[i]->id = p_pes->extra_es.p_elems[i]->id;
5445                         if( pespid->u.p_pes->extra_es.p_elems[i]->id )
5446                         {
5447                             es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
5448                                             pespid->u.p_pes->extra_es.p_elems[i]->id,
5449                                             pespid->u.p_pes->extra_es.p_elems[i]->fmt );
5450                             p_pes->extra_es.p_elems[i]->id = NULL;
5451                         }
5452                     }
5453                 }
5454
5455                 ts_pes_Del( p_demux, p_pes ); // delete temp
5456             }
5457             else
5458             {
5459                 AddAndCreateES( p_demux, pespid, false );
5460             }
5461         }
5462
5463         p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x09 );
5464         if( p_dr && p_dr->i_length >= 2 )
5465         {
5466             msg_Dbg( p_demux, "   * PMT descriptor : CA (0x9) SysID 0x%x",
5467                      (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5468         }
5469     }
5470
5471     /* Set CAM descrambling */
5472     if( !ProgramIsSelected( p_sys, p_pmt->i_number ) )
5473     {
5474         dvbpsi_pmt_delete( p_dvbpsipmt );
5475     }
5476     else if( stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_CA,
5477                              p_dvbpsipmt ) != VLC_SUCCESS )
5478     {
5479         if ( p_sys->arib.e_mode == ARIBMODE_ENABLED && !p_sys->arib.b25stream )
5480         {
5481             p_sys->arib.b25stream = stream_FilterNew( p_demux->s, "aribcam" );
5482             p_sys->stream = ( p_sys->arib.b25stream ) ? p_sys->arib.b25stream : p_demux->s;
5483             if (!p_sys->arib.b25stream)
5484                 dvbpsi_pmt_delete( p_dvbpsipmt );
5485         } else dvbpsi_pmt_delete( p_dvbpsipmt );
5486     }
5487
5488     /* Decref or clean now unused es */
5489     for( int i = 0; i < old_es_rm.i_size; i++ )
5490         PIDRelease( p_demux, old_es_rm.p_elems[i] );
5491     ARRAY_RESET( old_es_rm );
5492
5493     UpdatePESFilters( p_demux, p_sys->b_es_all );
5494
5495     if( !p_sys->b_trust_pcr )
5496     {
5497         int i_cand = FindPCRCandidate( p_pmt );
5498         p_pmt->i_pid_pcr = i_cand;
5499         p_pmt->pcr.b_disable = true;
5500         msg_Warn( p_demux, "PCR not trusted for program %d, set up workaround using pid %d",
5501                   p_pmt->i_number, i_cand );
5502     }
5503
5504     /* Probe Boundaries */
5505     if( p_sys->b_canfastseek && p_pmt->i_last_dts == -1 )
5506     {
5507         p_pmt->i_last_dts = 0;
5508         ProbeStart( p_demux, p_pmt->i_number );
5509         ProbeEnd( p_demux, p_pmt->i_number );
5510     }
5511 }
5512
5513 static int PATCheck( demux_t *p_demux, dvbpsi_pat_t *p_pat )
5514 {
5515     /* Some Dreambox streams have all PMT set to same pid */
5516     int i_prev_pid = -1;
5517     for( dvbpsi_pat_program_t * p_program = p_pat->p_first_program;
5518          p_program != NULL;
5519          p_program = p_program->p_next )
5520     {
5521         if( p_program->i_pid == i_prev_pid )
5522         {
5523             msg_Warn( p_demux, "PAT check failed: duplicate program pid %d", i_prev_pid );
5524             return VLC_EGENERIC;
5525         }
5526         i_prev_pid = p_program->i_pid;
5527     }
5528     return VLC_SUCCESS;
5529 }
5530
5531 static void PATCallBack( void *data, dvbpsi_pat_t *p_dvbpsipat )
5532 {
5533     demux_t              *p_demux = data;
5534     demux_sys_t          *p_sys = p_demux->p_sys;
5535     dvbpsi_pat_program_t *p_program;
5536     ts_pid_t             *patpid = &p_sys->pid[0];
5537     ts_pat_t             *p_pat = p_sys->pid[0].u.p_pat;
5538
5539     patpid->i_flags |= FLAG_SEEN;
5540
5541     msg_Dbg( p_demux, "PATCallBack called" );
5542
5543     if(unlikely( p_sys->pid[0].type != TYPE_PAT ))
5544     {
5545         msg_Warn( p_demux, "PATCallBack called on invalid pid" );
5546         return;
5547     }
5548
5549     if( ( p_pat->i_version != -1 &&
5550             ( !p_dvbpsipat->b_current_next ||
5551               p_dvbpsipat->i_version == p_pat->i_version ) ) ||
5552         ( p_pat->i_ts_id != -1 && p_dvbpsipat->i_ts_id != p_pat->i_ts_id ) ||
5553         p_sys->b_user_pmt || PATCheck( p_demux, p_dvbpsipat ) )
5554     {
5555         dvbpsi_pat_delete( p_dvbpsipat );
5556         return;
5557     }
5558
5559     msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
5560              p_dvbpsipat->i_ts_id, p_dvbpsipat->i_version, p_dvbpsipat->b_current_next );
5561
5562     /* Save old programs array */
5563     DECL_ARRAY(ts_pid_t *) old_pmt_rm;
5564     old_pmt_rm.i_alloc = p_pat->programs.i_alloc;
5565     old_pmt_rm.i_size = p_pat->programs.i_size;
5566     old_pmt_rm.p_elems = p_pat->programs.p_elems;
5567     ARRAY_INIT(p_pat->programs);
5568
5569     /* now create programs */
5570     for( p_program = p_dvbpsipat->p_first_program; p_program != NULL;
5571          p_program = p_program->p_next )
5572     {
5573         msg_Dbg( p_demux, "  * number=%d pid=%d", p_program->i_number,
5574                  p_program->i_pid );
5575         if( p_program->i_number == 0 )
5576             continue;
5577
5578         ts_pid_t *pmtpid = &p_sys->pid[p_program->i_pid];
5579
5580         ValidateDVBMeta( p_demux, p_program->i_pid );
5581
5582         /* create or temporary incref pid */
5583         if( !PIDSetup( p_demux, TYPE_PMT, pmtpid, patpid ) )
5584         {
5585             msg_Warn( p_demux, "  * number=%d pid=%d (ignored)", p_program->i_number,
5586                      p_program->i_pid );
5587             continue;
5588         }
5589
5590         pmtpid->u.p_pmt->i_number = p_program->i_number;
5591
5592         if( !dvbpsi_pmt_attach( pmtpid->u.p_pmt->handle, p_program->i_number, PMTCallBack, p_demux ) )
5593             msg_Err( p_demux, "PATCallback failed attaching PMTCallback to program %d",
5594                      p_program->i_number );
5595
5596         ARRAY_APPEND( p_pat->programs, pmtpid );
5597
5598         /* Now select PID at access level */
5599         if( p_sys->programs.i_size == 0 ||
5600             ProgramIsSelected( p_sys, p_program->i_number ) )
5601         {
5602             if( p_sys->programs.i_size == 0 )
5603             {
5604                 msg_Dbg( p_demux, "temporary receiving program %d", p_program->i_number );
5605                 p_sys->b_default_selection = true;
5606                 ARRAY_APPEND( p_sys->programs, p_program->i_number );
5607             }
5608
5609             if( SetPIDFilter( p_sys, pmtpid, true ) )
5610                 p_sys->b_access_control = false;
5611             else if ( p_sys->es_creation == DELAY_ES )
5612                 p_sys->es_creation = CREATE_ES;
5613         }
5614     }
5615     p_pat->i_version = p_dvbpsipat->i_version;
5616     p_pat->i_ts_id = p_dvbpsipat->i_ts_id;
5617
5618     for(int i=0; i<old_pmt_rm.i_size; i++)
5619     {
5620         /* decref current or release now unreferenced */
5621         PIDRelease( p_demux, old_pmt_rm.p_elems[i] );
5622     }
5623     ARRAY_RESET(old_pmt_rm);
5624
5625     dvbpsi_pat_delete( p_dvbpsipat );
5626 }
5627
5628 static inline bool handle_Init( demux_t *p_demux, dvbpsi_t **handle )
5629 {
5630     *handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
5631     if( !*handle )
5632         return false;
5633     (*handle)->p_sys = (void *) p_demux;
5634     return true;
5635 }
5636
5637 static ts_pat_t *ts_pat_New( demux_t *p_demux )
5638 {
5639     ts_pat_t *pat = malloc( sizeof( ts_pat_t ) );
5640     if( !pat )
5641         return NULL;
5642
5643     if( !handle_Init( p_demux, &pat->handle ) )
5644     {
5645         free( pat );
5646         return NULL;
5647     }
5648
5649     pat->i_version  = -1;
5650     pat->i_ts_id    = -1;
5651     ARRAY_INIT( pat->programs );
5652
5653     return pat;
5654 }
5655
5656 static void ts_pat_Del( demux_t *p_demux, ts_pat_t *pat )
5657 {
5658     if( dvbpsi_decoder_present( pat->handle ) )
5659         dvbpsi_pat_detach( pat->handle );
5660     dvbpsi_delete( pat->handle );
5661     for( int i=0; i<pat->programs.i_size; i++ )
5662         PIDRelease( p_demux, pat->programs.p_elems[i] );
5663     ARRAY_RESET( pat->programs );
5664     free( pat );
5665 }
5666
5667 static ts_pmt_t *ts_pmt_New( demux_t *p_demux )
5668 {
5669     ts_pmt_t *pmt = malloc( sizeof( ts_pmt_t ) );
5670     if( !pmt )
5671         return NULL;
5672
5673     if( !handle_Init( p_demux, &pmt->handle ) )
5674     {
5675         free( pmt );
5676         return NULL;
5677     }
5678
5679     ARRAY_INIT( pmt->e_streams );
5680
5681     pmt->i_version  = -1;
5682     pmt->i_number   = -1;
5683     pmt->i_pid_pcr  = 0x1FFF;
5684     pmt->iod        = NULL;
5685
5686     pmt->i_last_dts = -1;
5687
5688     pmt->pcr.i_current = -1;
5689     pmt->pcr.i_first  = -1;
5690     pmt->pcr.b_disable = false;
5691     pmt->pcr.i_first_dts = VLC_TS_INVALID;
5692     pmt->pcr.i_pcroffset = -1;
5693
5694     return pmt;
5695 }
5696
5697 static void ts_pmt_Del( demux_t *p_demux, ts_pmt_t *pmt )
5698 {
5699     if( dvbpsi_decoder_present( pmt->handle ) )
5700         dvbpsi_pmt_detach( pmt->handle );
5701     dvbpsi_delete( pmt->handle );
5702     for( int i=0; i<pmt->e_streams.i_size; i++ )
5703         PIDRelease( p_demux, pmt->e_streams.p_elems[i] );
5704     ARRAY_RESET( pmt->e_streams );
5705     if( pmt->iod )
5706         IODFree( pmt->iod );
5707     if( pmt->i_number > -1 )
5708         es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, pmt->i_number );
5709     free( pmt );
5710 }
5711
5712 static ts_pes_t *ts_pes_New( demux_t *p_demux )
5713 {
5714     VLC_UNUSED(p_demux);
5715     ts_pes_t *pes = malloc( sizeof( ts_pes_t ) );
5716     if( !pes )
5717         return NULL;
5718
5719     pes->es.id = NULL;
5720     pes->es.p_mpeg4desc = NULL;
5721     es_format_Init( &pes->es.fmt, UNKNOWN_ES, 0 );
5722     ARRAY_INIT( pes->extra_es );
5723     pes->data_type = TS_ES_DATA_PES;
5724     pes->i_data_size = 0;
5725     pes->i_data_gathered = 0;
5726     pes->p_data = NULL;
5727     pes->pp_last = &pes->p_data;
5728     pes->p_prepcr_outqueue = NULL;
5729
5730     return pes;
5731 }
5732
5733 static void ts_pes_Del( demux_t *p_demux, ts_pes_t *pes )
5734 {
5735     if( pes->es.id )
5736     {
5737         es_out_Del( p_demux->out, pes->es.id );
5738         p_demux->p_sys->i_pmt_es--;
5739     }
5740
5741     if( pes->p_data )
5742         block_ChainRelease( pes->p_data );
5743
5744     if( pes->p_prepcr_outqueue )
5745         block_ChainRelease( pes->p_prepcr_outqueue );
5746
5747     es_format_Clean( &pes->es.fmt );
5748     free( pes->es.p_mpeg4desc );
5749
5750     for( int i = 0; i < pes->extra_es.i_size; i++ )
5751     {
5752         if( pes->extra_es.p_elems[i]->id )
5753         {
5754             es_out_Del( p_demux->out, pes->extra_es.p_elems[i]->id );
5755             p_demux->p_sys->i_pmt_es--;
5756         }
5757         es_format_Clean( &pes->extra_es.p_elems[i]->fmt );
5758         free( pes->extra_es.p_elems[i] );
5759     }
5760     ARRAY_RESET( pes->extra_es );
5761
5762     free( pes );
5763 }
5764
5765 static ts_psi_t *ts_psi_New( demux_t *p_demux )
5766 {
5767     ts_psi_t *psi = malloc( sizeof( ts_psi_t ) );
5768     if( !psi )
5769         return NULL;
5770
5771     if( !handle_Init( p_demux, &psi->handle ) )
5772     {
5773         free( psi );
5774         return NULL;
5775     }
5776
5777     psi->i_version  = -1;
5778
5779     return psi;
5780 }
5781
5782 static void ts_psi_Del( demux_t *p_demux, ts_psi_t *psi )
5783 {
5784     VLC_UNUSED(p_demux);
5785     if( dvbpsi_decoder_present( psi->handle ) )
5786         dvbpsi_DetachDemux( psi->handle );
5787     dvbpsi_delete( psi->handle );
5788     free( psi );
5789 }