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