]> git.sesse.net Git - vlc/blob - modules/demux/ts.c
demux: ts: SetPIDFilter: pass by pid
[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_sys_t *, ts_pid_t *, 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_sys, &p_sys->pid[0x11], true ) ||
1082                     SetPIDFilter( p_sys, &p_sys->pid[0x14], true ) ||
1083                     SetPIDFilter( p_sys, &p_sys->pid[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_sys_t *p_sys, ts_pid_t *p_pid, bool b_selected )
1758 {
1759     if( !p_sys->b_access_control )
1760         return VLC_EGENERIC;
1761
1762     return stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_STATE,
1763                            p_pid->i_pid, b_selected );
1764 }
1765
1766 static void SetPrgFilter( demux_t *p_demux, int i_prg_id, bool b_selected )
1767 {
1768     demux_sys_t *p_sys = p_demux->p_sys;
1769     ts_pmt_t *p_pmt = NULL;
1770     ts_pid_t *pid = NULL;
1771
1772     /* Search pmt to be unselected */
1773     if(unlikely(p_sys->pid[0].type != TYPE_PAT))
1774         return;
1775
1776     ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
1777     for( int i = 0; i < p_pat->programs.i_size; i++ )
1778     {
1779         ts_pid_t *pmtpid = p_pat->programs.p_elems[i];
1780         assert(pmtpid->type == TYPE_PMT);
1781
1782         if( pmtpid->u.p_pmt->i_number == i_prg_id )
1783         {
1784             pid = pmtpid;
1785             p_pmt = pid->u.p_pmt;
1786             break;
1787         }
1788     }
1789     if( !pid )
1790         return;
1791
1792     p_pmt->pcr.b_disable = !p_sys->b_trust_pcr;
1793
1794     SetPIDFilter( p_sys, pid, b_selected );
1795     if( p_pmt->i_pid_pcr > 0 )
1796         SetPIDFilter( p_sys, &p_sys->pid[p_pmt->i_pid_pcr], b_selected );
1797
1798     /* All ES */
1799     for( int i = 0; i < p_pmt->e_streams.i_size; i++ )
1800     {
1801         ts_pid_t *pespid = p_pmt->e_streams.p_elems[i];
1802         assert( pespid->type == TYPE_PES );
1803         /* We only remove/select es that aren't defined by extra pmt */
1804         if( pespid->u.p_pes->es.id || !b_selected )
1805             SetPIDFilter( p_sys, pespid, b_selected );
1806     }
1807 }
1808
1809 static void PIDReset( ts_pid_t *pid )
1810 {
1811     assert(pid->i_refcount == 0);
1812     pid->i_cc       = 0xff;
1813     pid->i_flags    &= ~FLAG_SCRAMBLED;
1814     pid->p_parent    = NULL;
1815     pid->type = TYPE_FREE;
1816 }
1817
1818 static bool PIDSetup( demux_t *p_demux, ts_pid_type_t i_type, ts_pid_t *pid, ts_pid_t *p_parent )
1819 {
1820     if( pid == p_parent || pid->i_pid == 0x1FFF )
1821         return false;
1822
1823     if( pid->i_refcount == 0 )
1824     {
1825         assert( pid->type == TYPE_FREE );
1826         switch( i_type )
1827         {
1828         case TYPE_FREE: /* nonsense ?*/
1829             PIDReset( pid );
1830             return true;
1831
1832         case TYPE_PAT:
1833             PIDReset( pid );
1834             pid->u.p_pat = ts_pat_New( p_demux );
1835             if( !pid->u.p_pat )
1836                 return false;
1837             break;
1838
1839         case TYPE_PMT:
1840             PIDReset( pid );
1841             pid->u.p_pmt = ts_pmt_New( p_demux );
1842             if( !pid->u.p_pmt )
1843                 return false;
1844             break;
1845
1846         case TYPE_PES:
1847             PIDReset( pid );
1848             pid->u.p_pes = ts_pes_New( p_demux );
1849             if( !pid->u.p_pes )
1850                 return false;
1851             break;
1852
1853         case TYPE_SDT:
1854         case TYPE_TDT:
1855         case TYPE_EIT:
1856             PIDReset( pid );
1857             pid->u.p_psi = ts_psi_New( p_demux );
1858             if( !pid->u.p_psi )
1859                 return false;
1860             break;
1861
1862         default:
1863             assert(false);
1864             break;
1865         }
1866
1867         pid->i_refcount++;
1868         pid->type = i_type;
1869         pid->p_parent = p_parent;
1870     }
1871     else if( pid->type == i_type && pid->i_refcount < UINT8_MAX )
1872     {
1873         pid->i_refcount++;
1874     }
1875     else
1876     {
1877         if( pid->type != TYPE_FREE )
1878             msg_Warn( p_demux, "Tried to redeclare pid %d with another type", pid->i_pid );
1879         return false;
1880     }
1881
1882     return true;
1883 }
1884
1885 static void PIDRelease( demux_t *p_demux, ts_pid_t *pid )
1886 {
1887     if( pid->i_refcount == 0 )
1888     {
1889         assert( pid->type == TYPE_FREE );
1890         return;
1891     }
1892     else if( pid->i_refcount == 1 )
1893     {
1894         pid->i_refcount--;
1895     }
1896     else if( pid->i_refcount > 1 )
1897     {
1898         assert( pid->type != TYPE_FREE && pid->type != TYPE_PAT );
1899         pid->i_refcount--;
1900     }
1901
1902     if( pid->i_refcount == 0 )
1903     {
1904         switch( pid->type )
1905         {
1906         default:
1907         case TYPE_FREE: /* nonsense ?*/
1908             assert( pid->type != TYPE_FREE );
1909             break;
1910
1911         case TYPE_PAT:
1912             ts_pat_Del( p_demux, pid->u.p_pat );
1913             pid->u.p_pat = NULL;
1914             break;
1915
1916         case TYPE_PMT:
1917             ts_pmt_Del( p_demux, pid->u.p_pmt );
1918             pid->u.p_pmt = NULL;
1919             break;
1920
1921         case TYPE_PES:
1922             ts_pes_Del( p_demux, pid->u.p_pes );
1923             pid->u.p_pes = NULL;
1924             break;
1925
1926         case TYPE_SDT:
1927         case TYPE_TDT:
1928         case TYPE_EIT:
1929             ts_psi_Del( p_demux, pid->u.p_psi );
1930             pid->u.p_psi = NULL;
1931             break;
1932
1933         }
1934
1935         SetPIDFilter( p_demux->p_sys, pid, false );
1936         PIDReset( pid );
1937     }
1938 }
1939
1940 static int16_t read_opus_flag(uint8_t **buf, size_t *len)
1941 {
1942     if (*len < 2)
1943         return -1;
1944
1945     int16_t ret = ((*buf)[0] << 8) | (*buf)[1];
1946
1947     *len -= 2;
1948     *buf += 2;
1949
1950     if (ret & (3<<13))
1951         ret = -1;
1952
1953     return ret;
1954 }
1955
1956 static block_t *Opus_Parse(demux_t *demux, block_t *block)
1957 {
1958     block_t *out = NULL;
1959     block_t **last = NULL;
1960
1961     uint8_t *buf = block->p_buffer;
1962     size_t len = block->i_buffer;
1963
1964     while (len > 3 && ((buf[0] << 3) | (buf[1] >> 5)) == 0x3ff) {
1965         int16_t start_trim = 0, end_trim = 0;
1966         int start_trim_flag        = (buf[1] >> 4) & 1;
1967         int end_trim_flag          = (buf[1] >> 3) & 1;
1968         int control_extension_flag = (buf[1] >> 2) & 1;
1969
1970         len -= 2;
1971         buf += 2;
1972
1973         unsigned au_size = 0;
1974         while (len--) {
1975             int c = *buf++;
1976             au_size += c;
1977             if (c != 0xff)
1978                 break;
1979         }
1980
1981         if (start_trim_flag) {
1982             start_trim = read_opus_flag(&buf, &len);
1983             if (start_trim < 0) {
1984                 msg_Err(demux, "Invalid start trimming flag");
1985             }
1986         }
1987         if (end_trim_flag) {
1988             end_trim = read_opus_flag(&buf, &len);
1989             if (end_trim < 0) {
1990                 msg_Err(demux, "Invalid end trimming flag");
1991             }
1992         }
1993         if (control_extension_flag && len) {
1994             unsigned l = *buf++; len--;
1995             if (l > len) {
1996                 msg_Err(demux, "Invalid control extension length %d > %zu", l, len);
1997                 break;
1998             }
1999             buf += l;
2000             len -= l;
2001         }
2002
2003         if (!au_size || au_size > len) {
2004             msg_Err(demux, "Invalid Opus AU size %d (PES %zu)", au_size, len);
2005             break;
2006         }
2007
2008         block_t *au = block_Alloc(au_size);
2009         if (!au)
2010             break;
2011         memcpy(au->p_buffer, buf, au_size);
2012         block_CopyProperties(au, block);
2013         au->p_next = NULL;
2014
2015         if (!out)
2016             out = au;
2017         else
2018             *last = au;
2019         last = &au->p_next;
2020
2021         au->i_nb_samples = opus_frame_duration(buf, au_size);
2022         if (end_trim && end_trim <= au->i_nb_samples)
2023             au->i_length = end_trim; /* Blatant abuse of the i_length field. */
2024         else
2025             au->i_length = 0;
2026
2027         if (start_trim && start_trim < (au->i_nb_samples - au->i_length)) {
2028             au->i_nb_samples -= start_trim;
2029             if (au->i_nb_samples == 0)
2030                 au->i_flags |= BLOCK_FLAG_PREROLL;
2031         }
2032
2033         buf += au_size;
2034         len -= au_size;
2035     }
2036
2037     block_Release(block);
2038     return out;
2039 }
2040
2041 /****************************************************************************
2042  * gathering stuff
2043  ****************************************************************************/
2044 static int ParsePESHeader( demux_t *p_demux, const uint8_t *p_header, size_t i_header,
2045                            unsigned *pi_skip, mtime_t *pi_dts, mtime_t *pi_pts )
2046 {
2047     unsigned i_skip;
2048
2049     if ( i_header < 9 )
2050         return VLC_EGENERIC;
2051
2052     switch( p_header[3] )
2053     {
2054     case 0xBC:  /* Program stream map */
2055     case 0xBE:  /* Padding */
2056     case 0xBF:  /* Private stream 2 */
2057     case 0xF0:  /* ECM */
2058     case 0xF1:  /* EMM */
2059     case 0xFF:  /* Program stream directory */
2060     case 0xF2:  /* DSMCC stream */
2061     case 0xF8:  /* ITU-T H.222.1 type E stream */
2062         i_skip = 6;
2063         break;
2064     default:
2065         if( ( p_header[6]&0xC0 ) == 0x80 )
2066         {
2067             /* mpeg2 PES */
2068             i_skip = p_header[8] + 9;
2069             if( i_header < i_skip )
2070                 return VLC_EGENERIC;
2071
2072             if( p_header[7]&0x80 )    /* has pts */
2073             {
2074                 if( i_header < 9 + 5 )
2075                     return VLC_EGENERIC;
2076                 *pi_pts = ExtractPESTimestamp( &p_header[9] );
2077
2078                 if( p_header[7]&0x40 )    /* has dts */
2079                 {
2080                     if( i_header < 14 + 5 )
2081                         return VLC_EGENERIC;
2082                     *pi_dts = ExtractPESTimestamp( &p_header[14] );
2083                 }
2084             }
2085         }
2086         else
2087         {
2088             i_skip = 6;
2089             if( i_header < i_skip + 1 )
2090                 return VLC_EGENERIC;
2091             while( i_skip < 23 && p_header[i_skip] == 0xff )
2092             {
2093                 i_skip++;
2094                 if( i_header < i_skip + 1 )
2095                     return VLC_EGENERIC;
2096             }
2097             if( i_skip == 23 )
2098             {
2099                 msg_Err( p_demux, "too much MPEG-1 stuffing" );
2100                 return VLC_EGENERIC;
2101             }
2102             if( ( p_header[i_skip] & 0xC0 ) == 0x40 )
2103             {
2104                 i_skip += 2;
2105             }
2106
2107             if( i_header < i_skip + 1 )
2108                 return VLC_EGENERIC;
2109
2110             if(  p_header[i_skip]&0x20 )
2111             {
2112                 if( i_header < i_skip + 5 )
2113                     return VLC_EGENERIC;
2114                 *pi_pts = ExtractPESTimestamp( &p_header[i_skip] );
2115
2116                 if( p_header[i_skip]&0x10 )    /* has dts */
2117                 {
2118                     if( i_header < i_skip + 10 )
2119                         return VLC_EGENERIC;
2120                     *pi_dts = ExtractPESTimestamp( &p_header[i_skip+5] );
2121                     i_skip += 10;
2122                 }
2123                 else
2124                 {
2125                     i_skip += 5;
2126                 }
2127             }
2128             else
2129             {
2130                 i_skip += 1;
2131             }
2132         }
2133         break;
2134     }
2135
2136     if( i_header < i_skip )
2137         return VLC_EGENERIC;
2138
2139     *pi_skip = i_skip;
2140     return VLC_SUCCESS;
2141 }
2142
2143 static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
2144 {
2145     uint8_t header[34];
2146     unsigned i_pes_size = 0;
2147     unsigned i_skip = 0;
2148     mtime_t i_dts = -1;
2149     mtime_t i_pts = -1;
2150     mtime_t i_length = 0;
2151
2152     assert(pid->type == TYPE_PES);
2153     assert(pid->p_parent && pid->p_parent->type == TYPE_PMT);
2154
2155     const int i_max = block_ChainExtract( p_pes, header, 34 );
2156     if ( i_max < 4 )
2157     {
2158         block_ChainRelease( p_pes );
2159         return;
2160     }
2161
2162     if( SCRAMBLED(*pid) || header[0] != 0 || header[1] != 0 || header[2] != 1 )
2163     {
2164         if ( !SCRAMBLED(*pid) )
2165             msg_Warn( p_demux, "invalid header [0x%02x:%02x:%02x:%02x] (pid: %d)",
2166                         header[0], header[1],header[2],header[3], pid->i_pid );
2167         block_ChainRelease( p_pes );
2168         return;
2169     }
2170
2171     if( ParsePESHeader( p_demux, (uint8_t*)&header, i_max, &i_skip, &i_dts, &i_pts ) == VLC_EGENERIC )
2172     {
2173         block_ChainRelease( p_pes );
2174         return;
2175     }
2176     else
2177     {
2178         if( i_pts != -1 )
2179             i_pts = TimeStampWrapAround( pid->p_parent->u.p_pmt, i_pts );
2180         if( i_dts != -1 )
2181             i_dts = TimeStampWrapAround( pid->p_parent->u.p_pmt, i_dts );
2182     }
2183
2184     if( pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
2185         pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
2186     {
2187         i_skip += 4;
2188     }
2189     else if( pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
2190              pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
2191              pid->u.p_pes->es.fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
2192     {
2193         i_skip += 1;
2194     }
2195     else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SUBT &&
2196              pid->u.p_pes->es.p_mpeg4desc )
2197     {
2198         decoder_config_descriptor_t *dcd = &pid->u.p_pes->es.p_mpeg4desc->dec_descr;
2199
2200         if( dcd->i_extra > 2 &&
2201             dcd->p_extra[0] == 0x10 &&
2202             ( dcd->p_extra[1]&0x10 ) )
2203         {
2204             /* display length */
2205             if( p_pes->i_buffer + 2 <= i_skip )
2206                 i_length = GetWBE( &p_pes->p_buffer[i_skip] );
2207
2208             i_skip += 2;
2209         }
2210         if( p_pes->i_buffer + 2 <= i_skip )
2211             i_pes_size = GetWBE( &p_pes->p_buffer[i_skip] );
2212         /* */
2213         i_skip += 2;
2214     }
2215
2216     /* skip header */
2217     while( p_pes && i_skip > 0 )
2218     {
2219         if( p_pes->i_buffer <= i_skip )
2220         {
2221             block_t *p_next = p_pes->p_next;
2222
2223             i_skip -= p_pes->i_buffer;
2224             block_Release( p_pes );
2225             p_pes = p_next;
2226         }
2227         else
2228         {
2229             p_pes->i_buffer -= i_skip;
2230             p_pes->p_buffer += i_skip;
2231             break;
2232         }
2233     }
2234
2235     /* ISO/IEC 13818-1 2.7.5: if no pts and no dts, then dts == pts */
2236     if( i_pts >= 0 && i_dts < 0 )
2237         i_dts = i_pts;
2238
2239     if( p_pes )
2240     {
2241         block_t *p_block;
2242
2243         if( i_dts >= 0 )
2244             p_pes->i_dts = VLC_TS_0 + i_dts * 100 / 9;
2245
2246         if( i_pts >= 0 )
2247             p_pes->i_pts = VLC_TS_0 + i_pts * 100 / 9;
2248
2249         p_pes->i_length = i_length * 100 / 9;
2250
2251         p_block = block_ChainGather( p_pes );
2252         if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SUBT )
2253         {
2254             if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
2255             {
2256                 p_block->i_buffer = i_pes_size;
2257             }
2258             /* Append a \0 */
2259             p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
2260             if( !p_block )
2261                 return;
2262             p_block->p_buffer[p_block->i_buffer -1] = '\0';
2263         }
2264         else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_TELETEXT )
2265         {
2266             if( p_block->i_pts <= VLC_TS_INVALID && pid->p_parent )
2267             {
2268                 /* Teletext may have missing PTS (ETSI EN 300 472 Annexe A)
2269                  * In this case use the last PCR + 40ms */
2270                 assert( pid->p_parent->type == TYPE_PMT );
2271                 if( likely(pid->p_parent->type == TYPE_PMT) )
2272                 {
2273                     mtime_t i_pcr = pid->p_parent->u.p_pmt->pcr.i_current;
2274                     if( i_pcr > VLC_TS_INVALID )
2275                         p_block->i_pts = VLC_TS_0 + i_pcr * 100 / 9 + 40000;
2276                 }
2277             }
2278         }
2279         else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_ARIB_A ||
2280                  pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_ARIB_C )
2281         {
2282             if( p_block->i_pts <= VLC_TS_INVALID )
2283             {
2284                 if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
2285                 {
2286                     p_block->i_buffer = i_pes_size;
2287                 }
2288                 /* Append a \0 */
2289                 p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
2290                 if( !p_block )
2291                     return;
2292                 p_block->p_buffer[p_block->i_buffer -1] = '\0';
2293             }
2294         }
2295         else if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_OPUS)
2296         {
2297             p_block = Opus_Parse(p_demux, p_block);
2298         }
2299
2300         if( !pid->p_parent || pid->p_parent->type != TYPE_PMT )
2301         {
2302             block_Release( p_block );
2303             return;
2304         }
2305
2306         ts_pmt_t *p_pmt = pid->p_parent->u.p_pmt;
2307
2308         while (p_block) {
2309             block_t *p_next = p_block->p_next;
2310             p_block->p_next = NULL;
2311
2312             if( p_pmt->pcr.i_first == -1 ) /* Not seen yet */
2313                 PCRFixHandle( p_demux, p_pmt, p_block );
2314
2315             if( p_pmt->pcr.i_current > -1 || p_pmt->pcr.b_disable )
2316             {
2317                 if( pid->u.p_pes->p_prepcr_outqueue )
2318                 {
2319                     block_ChainAppend( &pid->u.p_pes->p_prepcr_outqueue, p_block );
2320                     p_block = pid->u.p_pes->p_prepcr_outqueue;
2321                     pid->u.p_pes->p_prepcr_outqueue = NULL;
2322                 }
2323
2324                 if ( p_pmt->pcr.b_disable && p_block->i_dts > VLC_TS_INVALID &&
2325                      ( p_pmt->i_pid_pcr == pid->i_pid || p_pmt->i_pid_pcr == 0x1FFF ) )
2326                 {
2327                     ProgramSetPCR( p_demux, p_pmt, (p_block->i_dts - VLC_TS_0) * 9 / 100 - 120000 );
2328                 }
2329
2330                 /* Compute PCR/DTS offset if any */
2331                 if( p_pmt->pcr.i_pcroffset == -1 && p_block->i_dts > VLC_TS_INVALID &&
2332                     p_pmt->pcr.i_current > VLC_TS_INVALID )
2333                 {
2334                     int64_t i_dts27 = (p_block->i_dts - VLC_TS_0) * 9 / 100;
2335                     int64_t i_pcr = TimeStampWrapAround( p_pmt, p_pmt->pcr.i_current );
2336                     if( i_dts27 < i_pcr )
2337                     {
2338                         p_pmt->pcr.i_pcroffset = i_pcr - i_dts27 + 80000;
2339                         msg_Warn( p_demux, "Broken stream: pid %d sends packets with dts %"PRId64
2340                                            "us later than pcr, applying delay",
2341                                   pid->i_pid, p_pmt->pcr.i_pcroffset * 100 / 9 );
2342                     }
2343                     else p_pmt->pcr.i_pcroffset = 0;
2344                 }
2345
2346                 if( p_pmt->pcr.i_pcroffset != -1 )
2347                 {
2348                     if( p_block->i_dts > VLC_TS_INVALID )
2349                         p_block->i_dts += (p_pmt->pcr.i_pcroffset * 100 / 9);
2350                     if( p_block->i_pts > VLC_TS_INVALID )
2351                         p_block->i_pts += (p_pmt->pcr.i_pcroffset * 100 / 9);
2352                 }
2353
2354                 for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
2355                 {
2356                     es_out_Send( p_demux->out, pid->u.p_pes->extra_es.p_elems[i]->id,
2357                             block_Duplicate( p_block ) );
2358                 }
2359
2360                 es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_block );
2361             }
2362             else
2363             {
2364                 if( p_pmt->pcr.i_first == -1 ) /* Not seen yet */
2365                     PCRFixHandle( p_demux, p_pmt, p_block );
2366
2367                 block_ChainAppend( &pid->u.p_pes->p_prepcr_outqueue, p_block );
2368             }
2369
2370             p_block = p_next;
2371         }
2372     }
2373     else
2374     {
2375         msg_Warn( p_demux, "empty pes" );
2376     }
2377 }
2378
2379 static void ParseTableSection( demux_t *p_demux, ts_pid_t *pid, block_t *p_data )
2380 {
2381     block_t *p_content = block_ChainGather( p_data );
2382
2383     if ( pid->p_parent && pid->p_parent->type == TYPE_PMT )
2384     {
2385         ts_pmt_t *p_pmt = pid->p_parent->u.p_pmt;
2386         mtime_t i_date = p_pmt->pcr.i_current;
2387
2388         if( pid->u.p_pes->es.fmt.i_codec == VLC_CODEC_SCTE_27 )
2389         {
2390             /* We need to extract the truncated pts stored inside the payload */
2391             if( p_content->i_buffer > 9 && p_content->p_buffer[0] == 0xc6 )
2392             {
2393                 int i_index = 0;
2394                 size_t i_offset = 4;
2395                 if( p_content->p_buffer[3] & 0x40 )
2396                 {
2397                     i_index = ((p_content->p_buffer[7] & 0x0f) << 8) |
2398                              p_content->p_buffer[8];
2399                     i_offset = 9;
2400                 }
2401                 if( i_index == 0 && p_content->i_buffer > i_offset + 8 )
2402                 {
2403                     bool is_immediate = p_content->p_buffer[i_offset + 3] & 0x40;
2404                     if( !is_immediate )
2405                     {
2406                         mtime_t i_display_in = GetDWBE( &p_content->p_buffer[i_offset + 4] );
2407                         if( i_display_in < i_date )
2408                             i_date = i_display_in + (1ll << 32);
2409                         else
2410                             i_date = i_display_in;
2411                     }
2412
2413                 }
2414             }
2415         }
2416
2417         p_content->i_dts = p_content->i_pts = VLC_TS_0 + i_date * 100 / 9;
2418         PCRFixHandle( p_demux, p_pmt, p_content );
2419     }
2420
2421     es_out_Send( p_demux->out, pid->u.p_pes->es.id, p_content );
2422 }
2423
2424 static void ParseData( demux_t *p_demux, ts_pid_t *pid )
2425 {
2426     block_t *p_data = pid->u.p_pes->p_data;
2427     assert(p_data);
2428     if(!p_data)
2429         return;
2430
2431     /* remove the pes from pid */
2432     pid->u.p_pes->p_data = NULL;
2433     pid->u.p_pes->i_data_size = 0;
2434     pid->u.p_pes->i_data_gathered = 0;
2435     pid->u.p_pes->pp_last = &pid->u.p_pes->p_data;
2436
2437     if( pid->u.p_pes->data_type == TS_ES_DATA_PES )
2438     {
2439         ParsePES( p_demux, pid, p_data );
2440     }
2441     else if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION )
2442     {
2443         ParseTableSection( p_demux, pid, p_data );
2444     }
2445     else
2446     {
2447         block_ChainRelease( p_data );
2448     }
2449 }
2450
2451 static block_t* ReadTSPacket( demux_t *p_demux )
2452 {
2453     demux_sys_t *p_sys = p_demux->p_sys;
2454
2455     block_t     *p_pkt;
2456
2457     /* Get a new TS packet */
2458     if( !( p_pkt = stream_Block( p_sys->stream, p_sys->i_packet_size ) ) )
2459     {
2460         if( stream_Tell( p_sys->stream ) == stream_Size( p_sys->stream ) )
2461             msg_Dbg( p_demux, "EOF at %"PRId64, stream_Tell( p_sys->stream ) );
2462         else
2463             msg_Dbg( p_demux, "Can't read TS packet at %"PRId64, stream_Tell(p_sys->stream) );
2464         return NULL;
2465     }
2466
2467     if( p_pkt->i_buffer < TS_HEADER_SIZE + p_sys->i_packet_header_size )
2468     {
2469         block_Release( p_pkt );
2470         return NULL;
2471     }
2472
2473     /* Skip header (BluRay streams).
2474      * re-sync logic would do this (by adjusting packet start), but this would result in losing first and last ts packets.
2475      * First packet is usually PAT, and losing it means losing whole first GOP. This is fatal with still-image based menus.
2476      */
2477     p_pkt->p_buffer += p_sys->i_packet_header_size;
2478     p_pkt->i_buffer -= p_sys->i_packet_header_size;
2479
2480     /* Check sync byte and re-sync if needed */
2481     if( p_pkt->p_buffer[0] != 0x47 )
2482     {
2483         msg_Warn( p_demux, "lost synchro" );
2484         block_Release( p_pkt );
2485         for( ;; )
2486         {
2487             const uint8_t *p_peek;
2488             int i_peek, i_skip = 0;
2489
2490             i_peek = stream_Peek( p_sys->stream, &p_peek,
2491                     p_sys->i_packet_size * 10 );
2492             if( i_peek < p_sys->i_packet_size + 1 )
2493             {
2494                 msg_Dbg( p_demux, "eof ?" );
2495                 return NULL;
2496             }
2497
2498             while( i_skip < i_peek - p_sys->i_packet_size )
2499             {
2500                 if( p_peek[i_skip + p_sys->i_packet_header_size] == 0x47 &&
2501                         p_peek[i_skip + p_sys->i_packet_header_size + p_sys->i_packet_size] == 0x47 )
2502                 {
2503                     break;
2504                 }
2505                 i_skip++;
2506             }
2507             msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
2508             stream_Read( p_sys->stream, NULL, i_skip );
2509
2510             if( i_skip < i_peek - p_sys->i_packet_size )
2511             {
2512                 break;
2513             }
2514         }
2515         if( !( p_pkt = stream_Block( p_sys->stream, p_sys->i_packet_size ) ) )
2516         {
2517             msg_Dbg( p_demux, "eof ?" );
2518             return NULL;
2519         }
2520     }
2521     return p_pkt;
2522 }
2523
2524 static int64_t TimeStampWrapAround( ts_pmt_t *p_pmt, int64_t i_time )
2525 {
2526     int64_t i_adjust = 0;
2527     if( p_pmt && p_pmt->pcr.i_first > 0x0FFFFFFFF && i_time < 0x0FFFFFFFF )
2528         i_adjust = 0x1FFFFFFFF;
2529
2530     return i_time + i_adjust;
2531 }
2532
2533 static mtime_t GetPCR( block_t *p_pkt )
2534 {
2535     const uint8_t *p = p_pkt->p_buffer;
2536
2537     mtime_t i_pcr = -1;
2538
2539     if( ( p[3]&0x20 ) && /* adaptation */
2540         ( p[5]&0x10 ) &&
2541         ( p[4] >= 7 ) )
2542     {
2543         /* PCR is 33 bits */
2544         i_pcr = ( (mtime_t)p[6] << 25 ) |
2545                 ( (mtime_t)p[7] << 17 ) |
2546                 ( (mtime_t)p[8] << 9 ) |
2547                 ( (mtime_t)p[9] << 1 ) |
2548                 ( (mtime_t)p[10] >> 7 );
2549     }
2550     return i_pcr;
2551 }
2552
2553 static inline void FlushESBuffer( ts_pes_t *p_pes )
2554 {
2555     if( p_pes->p_data )
2556     {
2557         p_pes->i_data_gathered = p_pes->i_data_size = 0;
2558         block_ChainRelease( p_pes->p_data );
2559         p_pes->p_data = NULL;
2560         p_pes->pp_last = &p_pes->p_data;
2561     }
2562 }
2563
2564 static void ReadyQueuesPostSeek( demux_sys_t *p_sys )
2565 {
2566     ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
2567     for( int i=0; i< p_pat->programs.i_size; i++ )
2568     {
2569         ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2570         for( int j=0; j<p_pmt->e_streams.i_size; j++ )
2571         {
2572             ts_pid_t *pid = p_pmt->e_streams.p_elems[j];
2573
2574             if( pid->type != TYPE_PES )
2575                 continue;
2576
2577             pid->i_cc = 0xff;
2578
2579             if( pid->u.p_pes->p_prepcr_outqueue )
2580             {
2581                 block_ChainRelease( pid->u.p_pes->p_prepcr_outqueue );
2582                 pid->u.p_pes->p_prepcr_outqueue = NULL;
2583             }
2584
2585             FlushESBuffer( pid->u.p_pes );
2586         }
2587         p_pmt->pcr.i_current = -1;
2588     }
2589 }
2590
2591 static int SeekToTime( demux_t *p_demux, ts_pmt_t *p_pmt, int64_t i_scaledtime )
2592 {
2593     demux_sys_t *p_sys = p_demux->p_sys;
2594
2595     /* Deal with common but worst binary search case */
2596     if( p_pmt->pcr.i_first == i_scaledtime && p_sys->b_canseek )
2597         return stream_Seek( p_sys->stream, 0 );
2598
2599     if( !p_sys->b_canfastseek )
2600         return VLC_EGENERIC;
2601
2602     int64_t i_initial_pos = stream_Tell( p_sys->stream );
2603
2604     /* Find the time position by using binary search algorithm. */
2605     int64_t i_head_pos = 0;
2606     int64_t i_tail_pos = stream_Size( p_sys->stream ) - p_sys->i_packet_size;
2607     if( i_head_pos >= i_tail_pos )
2608         return VLC_EGENERIC;
2609
2610     bool b_found = false;
2611     while( (i_head_pos + p_sys->i_packet_size) <= i_tail_pos && !b_found )
2612     {
2613         /* Round i_pos to a multiple of p_sys->i_packet_size */
2614         int64_t i_splitpos = i_head_pos + (i_tail_pos - i_head_pos) / 2;
2615         int64_t i_div = i_splitpos % p_sys->i_packet_size;
2616         i_splitpos -= i_div;
2617
2618         if ( stream_Seek( p_sys->stream, i_splitpos ) != VLC_SUCCESS )
2619             break;
2620
2621         int64_t i_pos = i_splitpos;
2622         while( i_pos > -1 && i_pos < i_tail_pos )
2623         {
2624             int64_t i_pcr = -1;
2625             block_t *p_pkt = ReadTSPacket( p_demux );
2626             if( !p_pkt )
2627             {
2628                 i_head_pos = i_tail_pos;
2629                 break;
2630             }
2631             else
2632                 i_pos = stream_Tell( p_sys->stream );
2633
2634             int i_pid = PIDGet( p_pkt );
2635             if( i_pid != 0x1FFF && p_sys->pid[i_pid].type == TYPE_PES &&
2636                 p_sys->pid[i_pid].p_parent->u.p_pmt == p_pmt &&
2637                (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
2638                (p_pkt->p_buffer[3] & 0xD0) == 0x10    /* Has payload but is not encrypted */
2639             )
2640             {
2641                 unsigned i_skip = 4;
2642                 if ( p_pkt->p_buffer[3] & 0x20 ) // adaptation field
2643                 {
2644                     if( p_pkt->i_buffer >= 4 + 2 + 5 )
2645                     {
2646                         i_pcr = GetPCR( p_pkt );
2647                         i_skip += 1 + p_pkt->p_buffer[4];
2648                     }
2649                 }
2650                 else
2651                 {
2652                     mtime_t i_dts = -1;
2653                     mtime_t i_pts = -1;
2654                     if ( VLC_SUCCESS == ParsePESHeader( p_demux, &p_pkt->p_buffer[i_skip],
2655                                                         p_pkt->i_buffer - i_skip, &i_skip, &i_dts, &i_pts ) )
2656                     {
2657                         if( i_dts > -1 )
2658                             i_pcr = i_dts;
2659                     }
2660                 }
2661             }
2662             block_Release( p_pkt );
2663
2664             if( i_pcr != -1 )
2665             {
2666                 int64_t i_diff = i_scaledtime - TimeStampWrapAround( p_pmt, i_pcr );
2667                 if ( i_diff < 0 )
2668                     i_tail_pos = i_splitpos - p_sys->i_packet_size;
2669                 else if( i_diff < TO_SCALE(VLC_TS_0 + CLOCK_FREQ / 2) ) // 500ms
2670                     b_found = true;
2671                 else
2672                     i_head_pos = i_pos;
2673                 break;
2674             }
2675         }
2676
2677         if ( !b_found && i_pos > i_tail_pos - p_sys->i_packet_size )
2678             i_tail_pos = i_splitpos - p_sys->i_packet_size;
2679     }
2680
2681     if( !b_found )
2682     {
2683         msg_Dbg( p_demux, "Seek():cannot find a time position." );
2684         stream_Seek( p_sys->stream, i_initial_pos );
2685         return VLC_EGENERIC;
2686     }
2687     return VLC_SUCCESS;
2688 }
2689
2690 static ts_pmt_t * GetProgramByID( demux_sys_t *p_sys, int i_program )
2691 {
2692     if(unlikely(p_sys->pid[0].type != TYPE_PAT))
2693         return NULL;
2694
2695     ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
2696     for( int i = 0; i < p_pat->programs.i_size; i++ )
2697     {
2698         assert(p_pat->programs.p_elems[i]->type == TYPE_PMT);
2699         ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2700         if( p_pmt->i_number == i_program )
2701             return p_pmt;
2702     }
2703     return NULL;
2704 }
2705
2706 #define PROBE_CHUNK_COUNT 250
2707
2708 static int ProbeChunk( demux_t *p_demux, int i_program, bool b_end, int64_t *pi_pcr, bool *pb_found )
2709 {
2710     demux_sys_t *p_sys = p_demux->p_sys;
2711     int i_count = 0;
2712     block_t *p_pkt = NULL;
2713     *pi_pcr = -1;
2714
2715     for( ;; )
2716     {
2717         if( i_count++ > PROBE_CHUNK_COUNT || !( p_pkt = ReadTSPacket( p_demux ) ) )
2718         {
2719             break;
2720         }
2721
2722         int i_pid = PIDGet( p_pkt );
2723         p_sys->pid[i_pid].i_flags = FLAG_SEEN;
2724
2725         if( i_pid != 0x1FFF && p_sys->pid[i_pid].type == TYPE_PES &&
2726            (p_pkt->p_buffer[1] & 0xC0) == 0x40 && /* Payload start but not corrupt */
2727            (p_pkt->p_buffer[3] & 0xD0) == 0x10    /* Has payload but is not encrypted */
2728           )
2729         {
2730             bool b_pcrresult = true;
2731
2732             if( p_pkt->i_buffer >= 4 + 2 + 5 )
2733                 *pi_pcr = GetPCR( p_pkt );
2734
2735             if( *pi_pcr == -1 )
2736             {
2737                 b_pcrresult = false;
2738                 mtime_t i_dts = -1;
2739                 mtime_t i_pts = -1;
2740                 unsigned i_skip = 4;
2741                 if ( p_pkt->p_buffer[3] & 0x20 ) // adaptation field
2742                     i_skip += 1 + p_pkt->p_buffer[4];
2743
2744                 if ( VLC_SUCCESS == ParsePESHeader( p_demux, &p_pkt->p_buffer[i_skip],
2745                                                     p_pkt->i_buffer - i_skip,
2746                                                     &i_skip, &i_dts, &i_pts ) )
2747                 {
2748                     if( i_dts != -1 )
2749                         *pi_pcr = i_dts;
2750                     else if( i_pts != -1 )
2751                         *pi_pcr = i_pts;
2752                 }
2753             }
2754
2755             if( *pi_pcr != -1 ) // TODO: non ES PCR
2756             {
2757                 ts_pid_t *pmtpid = p_sys->pid[i_pid].p_parent;
2758                 assert(pmtpid->type == TYPE_PMT);
2759
2760                 if( i_program == 0 || i_program == pmtpid->u.p_pmt->i_number )
2761                 {
2762                     if( b_end )
2763                     {
2764                         pmtpid->u.p_pmt->i_last_dts = *pi_pcr;
2765                     }
2766                     /* Start, only keep first */
2767                     else if( b_pcrresult && pmtpid->u.p_pmt->pcr.i_first == -1 )
2768                     {
2769                         pmtpid->u.p_pmt->pcr.i_first = *pi_pcr;
2770                     }
2771                     else if( pmtpid->u.p_pmt->pcr.i_first_dts < VLC_TS_0 )
2772                     {
2773                         pmtpid->u.p_pmt->pcr.i_first_dts = VLC_TS_0 + *pi_pcr * 100 / 9;
2774                     }
2775                     *pb_found = true;
2776                 }
2777             }
2778         }
2779
2780         block_Release( p_pkt );
2781     }
2782
2783     return i_count;
2784 }
2785
2786 static int ProbeStart( demux_t *p_demux, int i_program )
2787 {
2788     demux_sys_t *p_sys = p_demux->p_sys;
2789     const int64_t i_initial_pos = stream_Tell( p_sys->stream );
2790     int64_t i_stream_size = stream_Size( p_sys->stream );
2791
2792     int i_probe_count = 0;
2793     int64_t i_pos;
2794     mtime_t i_pcr = -1;
2795     bool b_found = false;
2796
2797     do
2798     {
2799         i_pos = p_sys->i_packet_size * i_probe_count;
2800         i_pos = __MIN( i_pos, i_stream_size );
2801
2802         if( stream_Seek( p_sys->stream, i_pos ) )
2803             return VLC_EGENERIC;
2804
2805         ProbeChunk( p_demux, i_program, false, &i_pcr, &b_found );
2806
2807         /* Go ahead one more chunk if end of file contained only stuffing packets */
2808         i_probe_count += PROBE_CHUNK_COUNT;
2809     } while( i_pos > 0 && (i_pcr == -1 || !b_found) && i_probe_count < (2 * PROBE_CHUNK_COUNT) );
2810
2811     stream_Seek( p_sys->stream, i_initial_pos );
2812
2813     return (b_found) ? VLC_SUCCESS : VLC_EGENERIC;
2814 }
2815
2816 static int ProbeEnd( demux_t *p_demux, int i_program )
2817 {
2818     demux_sys_t *p_sys = p_demux->p_sys;
2819     const int64_t i_initial_pos = stream_Tell( p_sys->stream );
2820     int64_t i_stream_size = stream_Size( p_sys->stream );
2821
2822     int i_probe_count = PROBE_CHUNK_COUNT;
2823     int64_t i_pos;
2824     mtime_t i_pcr = -1;
2825     bool b_found = false;
2826
2827     do
2828     {
2829         i_pos = i_stream_size - (p_sys->i_packet_size * i_probe_count);
2830         i_pos = __MAX( i_pos, 0 );
2831
2832         if( stream_Seek( p_sys->stream, i_pos ) )
2833             return VLC_EGENERIC;
2834
2835         ProbeChunk( p_demux, i_program, true, &i_pcr, &b_found );
2836
2837         /* Go ahead one more chunk if end of file contained only stuffing packets */
2838         i_probe_count += PROBE_CHUNK_COUNT;
2839     } while( i_pos > 0 && (i_pcr == -1 || !b_found) && i_probe_count < (6 * PROBE_CHUNK_COUNT) );
2840
2841     stream_Seek( p_sys->stream, i_initial_pos );
2842
2843     return (b_found) ? VLC_SUCCESS : VLC_EGENERIC;
2844 }
2845
2846 static void ProgramSetPCR( demux_t *p_demux, ts_pmt_t *p_pmt, mtime_t i_pcr )
2847 {
2848     demux_sys_t *p_sys = p_demux->p_sys;
2849
2850     /* Check if we have enqueued blocks waiting the/before the
2851        PCR barrier, and then adapt pcr so they have valid PCR when dequeuing */
2852     if( p_pmt->pcr.i_current == -1 )
2853     {
2854         mtime_t i_mindts = -1;
2855
2856         ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
2857         for( int i=0; i< p_pat->programs.i_size; i++ )
2858         {
2859             ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2860             for( int j=0; j<p_pmt->e_streams.i_size; j++ )
2861             {
2862                 ts_pid_t *p_pid = p_pmt->e_streams.p_elems[j];
2863                 block_t *p_block = p_pid->u.p_pes->p_prepcr_outqueue;
2864                 while( p_block && p_block->i_dts == VLC_TS_INVALID )
2865                     p_block = p_block->p_next;
2866
2867                 if( p_block && ( i_mindts == -1 || p_block->i_dts < i_mindts ) )
2868                     i_mindts = p_block->i_dts;
2869             }
2870         }
2871
2872         if( i_mindts > VLC_TS_INVALID )
2873         {
2874             msg_Dbg( p_demux, "Program %d PCR prequeue fixup %"PRId64"->%"PRId64,
2875                      p_pmt->i_number, TO_SCALE(i_mindts), i_pcr );
2876             i_pcr = TO_SCALE(i_mindts);
2877         }
2878     }
2879
2880     p_pmt->pcr.i_current = i_pcr;
2881     if( p_pmt->pcr.i_first == -1 )
2882     {
2883         p_pmt->pcr.i_first = i_pcr; // now seen
2884     }
2885
2886     if ( p_sys->i_pmt_es )
2887     {
2888         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
2889                         p_pmt->i_number, VLC_TS_0 + i_pcr * 100 / 9 );
2890     }
2891 }
2892
2893 static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
2894 {
2895     demux_sys_t   *p_sys = p_demux->p_sys;
2896
2897     if( p_sys->i_pmt_es <= 0 )
2898         return;
2899
2900     mtime_t i_pcr = GetPCR( p_bk );
2901     if( i_pcr < 0 )
2902         return;
2903
2904     pid->probed.i_pcr_count++;
2905
2906     if(unlikely(p_sys->pid[0].type != TYPE_PAT))
2907         return;
2908
2909     /* Search program and set the PCR */
2910     ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
2911     for( int i = 0; i < p_pat->programs.i_size; i++ )
2912     {
2913         ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
2914         mtime_t i_program_pcr = TimeStampWrapAround( p_pmt, i_pcr );
2915
2916         if( p_pmt->i_pid_pcr == 0x1FFF ) /* That program has no dedicated PCR pid ISO/IEC 13818-1 2.4.4.9 */
2917         {
2918             if( pid->p_parent ) /* PCR shall be on pid itself */
2919             {
2920                 /* ? update PCR for the whole group program ? */
2921                 ProgramSetPCR( p_demux, p_pmt, i_program_pcr );
2922             }
2923             else
2924             {
2925                 msg_Warn(p_demux, "discarding PCR update from pid %d which has no owner", pid->i_pid);
2926             }
2927             break;
2928         }
2929         else /* set PCR provided by current pid to program(s) referencing it */
2930         {
2931             /* Can be dedicated PCR pid (no owned then) or another pid (owner == pmt) */
2932             if( p_pmt->i_pid_pcr == pid->i_pid ) /* If that program references current pid as PCR */
2933             {
2934                 /* We've found a target group for update */
2935                 ProgramSetPCR( p_demux, p_pmt, i_program_pcr );
2936             }
2937         }
2938
2939     }
2940 }
2941
2942 static int FindPCRCandidate( ts_pmt_t *p_pmt )
2943 {
2944     ts_pid_t *p_cand = NULL;
2945     int i_previous = p_pmt->i_pid_pcr;
2946
2947     for( int i=0; i<p_pmt->e_streams.i_size; i++ )
2948     {
2949         ts_pid_t *p_pid = p_pmt->e_streams.p_elems[i];
2950         if( SEEN(*p_pid) &&
2951             (!p_cand || p_cand->i_pid != i_previous) )
2952         {
2953             if( p_pid->probed.i_pcr_count ) /* check PCR frequency first */
2954             {
2955                 if( !p_cand || p_pid->probed.i_pcr_count > p_cand->probed.i_pcr_count )
2956                 {
2957                     p_cand = p_pid;
2958                     continue;
2959                 }
2960             }
2961
2962             if( p_pid->u.p_pes->es.fmt.i_cat == AUDIO_ES )
2963             {
2964                 if( !p_cand )
2965                     p_cand = p_pid;
2966             }
2967             else if ( p_pid->u.p_pes->es.fmt.i_cat == VIDEO_ES ) /* Otherwise prioritize video dts */
2968             {
2969                 if( !p_cand || p_cand->u.p_pes->es.fmt.i_cat == AUDIO_ES )
2970                     p_cand = p_pid;
2971             }
2972         }
2973     }
2974
2975     if( p_cand )
2976         return p_cand->i_pid;
2977     else
2978         return 0x1FFF;
2979 }
2980
2981 static void PCRFixHandle( demux_t *p_demux, ts_pmt_t *p_pmt, block_t *p_block )
2982 {
2983     if( p_pmt->pcr.i_first > -1 || p_pmt->pcr.b_disable )
2984         return;
2985
2986     /* Record the first data packet timestamp in case there wont be any PCR */
2987     if( !p_pmt->pcr.i_first_dts )
2988     {
2989         p_pmt->pcr.i_first_dts = p_block->i_dts;
2990     }
2991     else if( p_block->i_dts - p_pmt->pcr.i_first_dts > CLOCK_FREQ / 2 ) /* "shall not exceed 100ms" */
2992     {
2993         int i_cand = FindPCRCandidate( p_pmt );
2994         p_pmt->i_pid_pcr = i_cand;
2995         p_pmt->pcr.b_disable = true; /* So we do not wait packet PCR flag as there might be none on the pid */
2996         msg_Warn( p_demux, "No PCR received for program %d, set up workaround using pid %d",
2997                   p_pmt->i_number, i_cand );
2998     }
2999 }
3000
3001 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
3002 {
3003     const uint8_t *p = p_bk->p_buffer;
3004     const bool b_unit_start = p[1]&0x40;
3005     const bool b_scrambled  = p[3]&0x80;
3006     const bool b_adaptation = p[3]&0x20;
3007     const bool b_payload    = p[3]&0x10;
3008     const int  i_cc         = p[3]&0x0f; /* continuity counter */
3009     bool       b_discontinuity = false;  /* discontinuity */
3010
3011     /* transport_scrambling_control is ignored */
3012     int         i_skip = 0;
3013     bool        i_ret  = false;
3014
3015 #if 0
3016     msg_Dbg( p_demux, "pid=%d unit_start=%d adaptation=%d payload=%d "
3017              "cc=0x%x", pid->i_pid, b_unit_start, b_adaptation,
3018              b_payload, i_cc );
3019 #endif
3020
3021     /* For now, ignore additional error correction
3022      * TODO: handle Reed-Solomon 204,188 error correction */
3023     p_bk->i_buffer = TS_PACKET_SIZE_188;
3024
3025     if( p[1]&0x80 )
3026     {
3027         msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
3028                  pid->i_pid );
3029         if( pid->u.p_pes->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
3030             pid->u.p_pes->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
3031     }
3032
3033     if( p_demux->p_sys->csa )
3034     {
3035         vlc_mutex_lock( &p_demux->p_sys->csa_lock );
3036         csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer, p_demux->p_sys->i_csa_pkt_size );
3037         vlc_mutex_unlock( &p_demux->p_sys->csa_lock );
3038     }
3039
3040     if( !b_adaptation )
3041     {
3042         /* We don't have any adaptation_field, so payload starts
3043          * immediately after the 4 byte TS header */
3044         i_skip = 4;
3045     }
3046     else
3047     {
3048         /* p[4] is adaptation_field_length minus one */
3049         i_skip = 5 + p[4];
3050         if( p[4] > 0 )
3051         {
3052             /* discontinuity indicator found in stream */
3053             b_discontinuity = (p[5]&0x80) ? true : false;
3054             if( b_discontinuity && pid->u.p_pes->p_data )
3055             {
3056                 msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
3057                             pid->i_pid );
3058                 /* pid->es->p_data->i_flags |= BLOCK_FLAG_DISCONTINUITY; */
3059             }
3060 #if 0
3061             if( p[5]&0x40 )
3062                 msg_Dbg( p_demux, "random access indicator (pid=%d) ", pid->i_pid );
3063 #endif
3064         }
3065     }
3066
3067     /* Test continuity counter */
3068     /* continuous when (one of this):
3069         * diff == 1
3070         * diff == 0 and payload == 0
3071         * diff == 0 and duplicate packet (playload != 0) <- should we
3072         *   test the content ?
3073      */
3074     const int i_diff = ( i_cc - pid->i_cc )&0x0f;
3075     if( b_payload && i_diff == 1 )
3076     {
3077         pid->i_cc = ( pid->i_cc + 1 ) & 0xf;
3078     }
3079     else
3080     {
3081         if( pid->i_cc == 0xff )
3082         {
3083             msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
3084                       pid->i_pid, i_cc );
3085             pid->i_cc = i_cc;
3086         }
3087         else if( i_diff != 0 && !b_discontinuity )
3088         {
3089             msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x (pid=%d)",
3090                       i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );
3091
3092             pid->i_cc = i_cc;
3093             if( pid->u.p_pes->p_data && pid->u.p_pes->es.fmt.i_cat != VIDEO_ES &&
3094                 pid->u.p_pes->es.fmt.i_cat != AUDIO_ES )
3095             {
3096                 /* Small audio/video artifacts are usually better than
3097                  * dropping full frames */
3098                 pid->u.p_pes->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
3099             }
3100         }
3101     }
3102
3103     PCRHandle( p_demux, pid, p_bk );
3104
3105     if( i_skip >= 188 || pid->u.p_pes->es.id == NULL )
3106     {
3107         block_Release( p_bk );
3108         return i_ret;
3109     }
3110
3111     /* */
3112     if( !SCRAMBLED(*pid) != !b_scrambled )
3113     {
3114         msg_Warn( p_demux, "scrambled state changed on pid %d (%d->%d)",
3115                   pid->i_pid, SCRAMBLED(*pid), b_scrambled );
3116
3117         pid->i_flags |= (b_scrambled) ? FLAG_SCRAMBLED : FLAGS_NONE;
3118
3119         for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
3120         {
3121             es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
3122                             pid->u.p_pes->extra_es.p_elems[i]->id, b_scrambled );
3123         }
3124         es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
3125                         pid->u.p_pes->es.id, b_scrambled );
3126     }
3127
3128     /* We have to gather it */
3129     p_bk->p_buffer += i_skip;
3130     p_bk->i_buffer -= i_skip;
3131
3132     if( b_unit_start )
3133     {
3134         if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
3135         {
3136             int i_pointer_field = __MIN( p_bk->p_buffer[0], p_bk->i_buffer - 1 );
3137             block_t *p = block_Duplicate( p_bk );
3138             if( p )
3139             {
3140                 p->i_buffer = i_pointer_field;
3141                 p->p_buffer++;
3142                 block_ChainLastAppend( &pid->u.p_pes->pp_last, p );
3143             }
3144             p_bk->i_buffer -= 1 + i_pointer_field;
3145             p_bk->p_buffer += 1 + i_pointer_field;
3146         }
3147         if( pid->u.p_pes->p_data )
3148         {
3149             ParseData( p_demux, pid );
3150             i_ret = true;
3151         }
3152
3153         block_ChainLastAppend( &pid->u.p_pes->pp_last, p_bk );
3154         if( pid->u.p_pes->data_type == TS_ES_DATA_PES )
3155         {
3156             if( p_bk->i_buffer > 6 )
3157             {
3158                 pid->u.p_pes->i_data_size = GetWBE( &p_bk->p_buffer[4] );
3159                 if( pid->u.p_pes->i_data_size > 0 )
3160                 {
3161                     pid->u.p_pes->i_data_size += 6;
3162                 }
3163             }
3164         }
3165         else if( pid->u.p_pes->data_type == TS_ES_DATA_TABLE_SECTION )
3166         {
3167             if( p_bk->i_buffer > 3 && p_bk->p_buffer[0] != 0xff )
3168             {
3169                 pid->u.p_pes->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
3170             }
3171         }
3172         pid->u.p_pes->i_data_gathered += p_bk->i_buffer;
3173         if( pid->u.p_pes->i_data_size > 0 &&
3174             pid->u.p_pes->i_data_gathered >= pid->u.p_pes->i_data_size )
3175         {
3176             ParseData( p_demux, pid );
3177             i_ret = true;
3178         }
3179     }
3180     else
3181     {
3182         if( pid->u.p_pes->p_data == NULL )
3183         {
3184             /* msg_Dbg( p_demux, "broken packet" ); */
3185             block_Release( p_bk );
3186         }
3187         else
3188         {
3189             block_ChainLastAppend( &pid->u.p_pes->pp_last, p_bk );
3190             pid->u.p_pes->i_data_gathered += p_bk->i_buffer;
3191
3192             if( pid->u.p_pes->i_data_size > 0 &&
3193                 pid->u.p_pes->i_data_gathered >= pid->u.p_pes->i_data_size )
3194             {
3195                 ParseData( p_demux, pid );
3196                 i_ret = true;
3197             }
3198         }
3199     }
3200
3201     return i_ret;
3202 }
3203
3204 static void PIDFillFormat( es_format_t *fmt, int i_stream_type )
3205 {
3206     switch( i_stream_type )
3207     {
3208     case 0x01:  /* MPEG-1 video */
3209     case 0x02:  /* MPEG-2 video */
3210     case 0x80:  /* MPEG-2 MOTO video */
3211         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MPGV );
3212         break;
3213     case 0x03:  /* MPEG-1 audio */
3214     case 0x04:  /* MPEG-2 audio */
3215         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MPGA );
3216         break;
3217     case 0x11:  /* MPEG4 (audio) LATM */
3218     case 0x0f:  /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
3219     case 0x1c:  /* ISO/IEC 14496-3 Audio, without using any additional
3220                    transport syntax, such as DST, ALS and SLS */
3221         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MP4A );
3222         break;
3223     case 0x10:  /* MPEG4 (video) */
3224         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MP4V );
3225         break;
3226     case 0x1B:  /* H264 <- check transport syntax/needed descriptor */
3227         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_H264 );
3228         break;
3229     case 0x24:  /* HEVC */
3230         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_HEVC );
3231         break;
3232     case 0x42:  /* CAVS (Chinese AVS) */
3233         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_CAVS );
3234         break;
3235
3236     case 0x81:  /* A52 (audio) */
3237         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_A52 );
3238         break;
3239     case 0x82:  /* SCTE-27 (sub) */
3240         es_format_Init( fmt, SPU_ES, VLC_CODEC_SCTE_27 );
3241         break;
3242     case 0x84:  /* SDDS (audio) */
3243         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_SDDS );
3244         break;
3245     case 0x85:  /* DTS (audio) */
3246         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_DTS );
3247         break;
3248     case 0x87: /* E-AC3 */
3249         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_EAC3 );
3250         break;
3251
3252     case 0x91:  /* A52 vls (audio) */
3253         es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
3254         break;
3255     case 0x92:  /* DVD_SPU vls (sub) */
3256         es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
3257         break;
3258
3259     case 0x94:  /* SDDS (audio) */
3260         es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
3261         break;
3262
3263     case 0xa0:  /* MSCODEC vlc (video) (fixed later) */
3264         es_format_Init( fmt, UNKNOWN_ES, 0 );
3265         break;
3266
3267     case 0x06:  /* PES_PRIVATE  (fixed later) */
3268     case 0x12:  /* MPEG-4 generic (sub/scene/...) (fixed later) */
3269     case 0xEA:  /* Privately managed ES (VC-1) (fixed later */
3270     default:
3271         es_format_Init( fmt, UNKNOWN_ES, 0 );
3272         break;
3273     }
3274
3275     /* PES packets usually contain truncated frames */
3276     fmt->b_packetized = false;
3277 }
3278
3279 /*****************************************************************************
3280  * MP4 specific functions (IOD parser)
3281  *****************************************************************************/
3282 static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
3283 {
3284     unsigned int i_b;
3285     unsigned int i_len = 0;
3286     do
3287     {
3288         i_b = **pp_data;
3289         (*pp_data)++;
3290         (*pi_data)--;
3291         i_len = ( i_len << 7 ) + ( i_b&0x7f );
3292
3293     } while( i_b&0x80 && *pi_data > 0 );
3294
3295     if (i_len > *pi_data)
3296         i_len = *pi_data;
3297
3298     return i_len;
3299 }
3300
3301 static int IODGetBytes( int *pi_data, uint8_t **pp_data, size_t bytes )
3302 {
3303     uint32_t res = 0;
3304     while( *pi_data > 0 && bytes-- )
3305     {
3306         res <<= 8;
3307         res |= **pp_data;
3308         (*pp_data)++;
3309         (*pi_data)--;
3310     }
3311
3312     return res;
3313 }
3314
3315 static char* IODGetURL( int *pi_data, uint8_t **pp_data )
3316 {
3317     int len = IODGetBytes( pi_data, pp_data, 1 );
3318     if (len > *pi_data)
3319         len = *pi_data;
3320     char *url = strndup( (char*)*pp_data, len );
3321     *pp_data += len;
3322     *pi_data -= len;
3323     return url;
3324 }
3325
3326 static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
3327 {
3328     uint8_t i_iod_tag, i_iod_label, byte1, byte2, byte3;
3329
3330     iod_descriptor_t *p_iod = calloc( 1, sizeof( iod_descriptor_t ) );
3331     if( !p_iod )
3332         return NULL;
3333
3334     if( i_data < 3 )
3335     {
3336         return p_iod;
3337     }
3338
3339     byte1 = IODGetBytes( &i_data, &p_data, 1 );
3340     byte2 = IODGetBytes( &i_data, &p_data, 1 );
3341     byte3 = IODGetBytes( &i_data, &p_data, 1 );
3342     if( byte2 == 0x02 ) //old vlc's buggy implementation of the IOD_descriptor
3343     {
3344         i_iod_label = byte1;
3345         i_iod_tag = byte2;
3346     }
3347     else  //correct implementation of the IOD_descriptor
3348     {
3349         i_iod_label = byte2;
3350         i_iod_tag = byte3;
3351     }
3352
3353     ts_debug( "\n* iod label:%d tag:0x%x", i_iod_label, i_iod_tag );
3354
3355     if( i_iod_tag != 0x02 )
3356     {
3357         ts_debug( "\n ERR: tag %02x != 0x02", i_iod_tag );
3358         return p_iod;
3359     }
3360
3361     IODDescriptorLength( &i_data, &p_data );
3362
3363     uint16_t i_od_id = ( IODGetBytes( &i_data, &p_data, 1 ) << 2 );
3364     uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
3365     i_od_id |= i_flags >> 6;
3366     ts_debug( "\n* od_id:%d", i_od_id );
3367     ts_debug( "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
3368     if ((i_flags >> 5) & 0x01)
3369     {
3370         p_iod->psz_url = IODGetURL( &i_data, &p_data );
3371         ts_debug( "\n* url string:%s", p_iod->psz_url );
3372         ts_debug( "\n*****************************\n" );
3373         return p_iod;
3374     }
3375     else
3376     {
3377         p_iod->psz_url = NULL;
3378     }
3379
3380     /* Profile Level Indication */
3381     IODGetBytes( &i_data, &p_data, 1 ); /* OD */
3382     IODGetBytes( &i_data, &p_data, 1 ); /* scene */
3383     IODGetBytes( &i_data, &p_data, 1 ); /* audio */
3384     IODGetBytes( &i_data, &p_data, 1 ); /* visual */
3385     IODGetBytes( &i_data, &p_data, 1 ); /* graphics */
3386
3387     int i_length = 0;
3388     int i_data_sav = i_data;
3389     uint8_t *p_data_sav = p_data;
3390     for (int i = 0; i_data > 0 && i < ES_DESCRIPTOR_COUNT; i++)
3391     {
3392         es_mpeg4_descriptor_t *es_descr = &p_iod->es_descr[i];
3393
3394         p_data = p_data_sav + i_length;
3395         i_data = i_data_sav - i_length;
3396
3397         int i_tag = IODGetBytes( &i_data, &p_data, 1 );
3398         i_length = IODDescriptorLength( &i_data, &p_data );
3399
3400         i_data_sav = i_data;
3401         p_data_sav = p_data;
3402
3403         i_data = i_length;
3404
3405         if ( i_tag != 0x03 )
3406         {
3407             ts_debug( "\n* - OD tag:0x%x Unsupported", i_tag );
3408             continue;
3409         }
3410
3411         es_descr->i_es_id = IODGetBytes( &i_data, &p_data, 2 );
3412         int i_flags = IODGetBytes( &i_data, &p_data, 1 );
3413         bool b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
3414         if( b_streamDependenceFlag )
3415             IODGetBytes( &i_data, &p_data, 2 ); /* dependOn_es_id */
3416
3417         if( (i_flags >> 6) & 0x01 )
3418             es_descr->psz_url = IODGetURL( &i_data, &p_data );
3419
3420         bool b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
3421         if( b_OCRStreamFlag )
3422             IODGetBytes( &i_data, &p_data, 2 ); /* OCR_es_id */
3423
3424         if( IODGetBytes( &i_data, &p_data, 1 ) != 0x04 )
3425         {
3426             ts_debug( "\n* ERR missing DecoderConfigDescr" );
3427             continue;
3428         }
3429         int i_config_desc_length = IODDescriptorLength( &i_data, &p_data ); /* DecoderConfigDescr_length */
3430         decoder_config_descriptor_t *dec_descr = &es_descr->dec_descr;
3431         dec_descr->i_objectTypeIndication = IODGetBytes( &i_data, &p_data, 1 );
3432         i_flags = IODGetBytes( &i_data, &p_data, 1 );
3433         dec_descr->i_streamType = i_flags >> 2;
3434
3435         IODGetBytes( &i_data, &p_data, 3); /* bufferSizeDB */
3436         IODGetBytes( &i_data, &p_data, 4); /* maxBitrate */
3437         IODGetBytes( &i_data, &p_data, 4 ); /* avgBitrate */
3438
3439         if( i_config_desc_length > 13 && IODGetBytes( &i_data, &p_data, 1 ) == 0x05 )
3440         {
3441             dec_descr->i_extra = IODDescriptorLength( &i_data, &p_data );
3442             if( dec_descr->i_extra > 0 )
3443             {
3444                 dec_descr->p_extra = xmalloc( dec_descr->i_extra );
3445                 memcpy(dec_descr->p_extra, p_data, dec_descr->i_extra);
3446                 p_data += dec_descr->i_extra;
3447                 i_data -= dec_descr->i_extra;
3448             }
3449         }
3450         else
3451         {
3452             dec_descr->i_extra = 0;
3453             dec_descr->p_extra = NULL;
3454         }
3455
3456         if( IODGetBytes( &i_data, &p_data, 1 ) != 0x06 )
3457         {
3458             ts_debug( "\n* ERR missing SLConfigDescr" );
3459             continue;
3460         }
3461         IODDescriptorLength( &i_data, &p_data ); /* SLConfigDescr_length */
3462         switch( IODGetBytes( &i_data, &p_data, 1 ) /* predefined */ )
3463         {
3464         default:
3465             ts_debug( "\n* ERR unsupported SLConfigDescr predefined" );
3466         case 0x01:
3467             // FIXME
3468             break;
3469         }
3470         es_descr->b_ok = true;
3471     }
3472
3473     return p_iod;
3474 }
3475
3476 static void IODFree( iod_descriptor_t *p_iod )
3477 {
3478     if( p_iod->psz_url )
3479     {
3480         free( p_iod->psz_url );
3481         free( p_iod );
3482         return;
3483     }
3484
3485     for( int i = 0; i < 255; i++ )
3486     {
3487 #define es_descr p_iod->es_descr[i]
3488         if( es_descr.b_ok )
3489         {
3490             if( es_descr.psz_url )
3491                 free( es_descr.psz_url );
3492             else
3493                 free( es_descr.dec_descr.p_extra );
3494         }
3495 #undef  es_descr
3496     }
3497     free( p_iod );
3498 }
3499
3500 /****************************************************************************
3501  ****************************************************************************
3502  ** libdvbpsi callbacks
3503  ****************************************************************************
3504  ****************************************************************************/
3505 static bool ProgramIsSelected( demux_t *p_demux, uint16_t i_pgrm )
3506 {
3507     demux_sys_t          *p_sys = p_demux->p_sys;
3508
3509     for(int i=0; i<p_sys->programs.i_size; i++)
3510         if( p_sys->programs.p_elems[i] == i_pgrm )
3511             return true;
3512
3513     return false;
3514 }
3515
3516 static void ValidateDVBMeta( demux_t *p_demux, int i_pid )
3517 {
3518     demux_sys_t *p_sys = p_demux->p_sys;
3519
3520     if( !p_sys->b_dvb_meta || ( i_pid != 0x11 && i_pid != 0x12 && i_pid != 0x14 ) )
3521         return;
3522
3523     msg_Warn( p_demux, "Switching to non DVB mode" );
3524
3525     /* This doesn't look like a DVB stream so don't try
3526      * parsing the SDT/EDT/TDT */
3527
3528     PIDRelease( p_demux, &p_sys->pid[0x11] );
3529     PIDRelease( p_demux, &p_sys->pid[0x12] );
3530     PIDRelease( p_demux, &p_sys->pid[0x14] );
3531     p_sys->b_dvb_meta = false;
3532 }
3533
3534 #include "dvb-text.h"
3535
3536 static char *EITConvertToUTF8( demux_t *p_demux,
3537                                const unsigned char *psz_instring,
3538                                size_t i_length,
3539                                bool b_broken )
3540 {
3541     demux_sys_t *p_sys = p_demux->p_sys;
3542 #ifdef HAVE_ARIBB24
3543     if( p_sys->arib.e_mode == ARIBMODE_ENABLED )
3544     {
3545         if ( !p_sys->arib.p_instance )
3546             p_sys->arib.p_instance = arib_instance_new( p_demux );
3547         if ( !p_sys->arib.p_instance )
3548             return NULL;
3549         arib_decoder_t *p_decoder = arib_get_decoder( p_sys->arib.p_instance );
3550         if ( !p_decoder )
3551             return NULL;
3552
3553         char *psz_outstring = NULL;
3554         size_t i_out;
3555
3556         i_out = i_length * 4;
3557         psz_outstring = (char*) calloc( i_out + 1, sizeof(char) );
3558         if( !psz_outstring )
3559             return NULL;
3560
3561         arib_initialize_decoder( p_decoder );
3562         i_out = arib_decode_buffer( p_decoder, psz_instring, i_length,
3563                                     psz_outstring, i_out );
3564         arib_finalize_decoder( p_decoder );
3565
3566         return psz_outstring;
3567     }
3568 #else
3569     VLC_UNUSED(p_sys);
3570 #endif
3571     /* Deal with no longer broken providers (no switch byte
3572       but sending ISO_8859-1 instead of ISO_6937) without
3573       removing them from the broken providers table
3574       (keep the entry for correctly handling recorded TS).
3575     */
3576     b_broken = b_broken && i_length && *psz_instring > 0x20;
3577
3578     if( b_broken )
3579         return FromCharset( "ISO_8859-1", psz_instring, i_length );
3580     return vlc_from_EIT( psz_instring, i_length );
3581 }
3582
3583 static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
3584 {
3585     demux_sys_t          *p_sys = p_demux->p_sys;
3586     ts_pid_t             *sdt = &p_sys->pid[0x11];
3587     dvbpsi_sdt_service_t *p_srv;
3588
3589     msg_Dbg( p_demux, "SDTCallBack called" );
3590
3591     if( p_sys->es_creation != CREATE_ES ||
3592        !p_sdt->b_current_next ||
3593         p_sdt->i_version == sdt->u.p_psi->i_version )
3594     {
3595         dvbpsi_sdt_delete( p_sdt );
3596         return;
3597     }
3598
3599     msg_Dbg( p_demux, "new SDT ts_id=%d version=%d current_next=%d "
3600              "network_id=%d",
3601              p_sdt->i_extension,
3602              p_sdt->i_version, p_sdt->b_current_next,
3603              p_sdt->i_network_id );
3604
3605     p_sys->b_broken_charset = false;
3606
3607     for( p_srv = p_sdt->p_first_service; p_srv; p_srv = p_srv->p_next )
3608     {
3609         vlc_meta_t          *p_meta;
3610         dvbpsi_descriptor_t *p_dr;
3611
3612         const char *psz_type = NULL;
3613         const char *psz_status = NULL;
3614
3615         msg_Dbg( p_demux, "  * service id=%d eit schedule=%d present=%d "
3616                  "running=%d free_ca=%d",
3617                  p_srv->i_service_id, p_srv->b_eit_schedule,
3618                  p_srv->b_eit_present, p_srv->i_running_status,
3619                  p_srv->b_free_ca );
3620
3621         if( p_sys->vdr.i_service && p_srv->i_service_id != p_sys->vdr.i_service )
3622         {
3623             msg_Dbg( p_demux, "  * service id=%d skipped (not declared in vdr header)",
3624                      p_sys->vdr.i_service );
3625             continue;
3626         }
3627
3628         p_meta = vlc_meta_New();
3629         for( p_dr = p_srv->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3630         {
3631             if( p_dr->i_tag == 0x48 )
3632             {
3633                 static const char *ppsz_type[17] = {
3634                     "Reserved",
3635                     "Digital television service",
3636                     "Digital radio sound service",
3637                     "Teletext service",
3638                     "NVOD reference service",
3639                     "NVOD time-shifted service",
3640                     "Mosaic service",
3641                     "PAL coded signal",
3642                     "SECAM coded signal",
3643                     "D/D2-MAC",
3644                     "FM Radio",
3645                     "NTSC coded signal",
3646                     "Data broadcast service",
3647                     "Reserved for Common Interface Usage",
3648                     "RCS Map (see EN 301 790 [35])",
3649                     "RCS FLS (see EN 301 790 [35])",
3650                     "DVB MHP service"
3651                 };
3652                 dvbpsi_service_dr_t *pD = dvbpsi_DecodeServiceDr( p_dr );
3653                 char *str1 = NULL;
3654                 char *str2 = NULL;
3655
3656                 /* Workarounds for broadcasters with broken EPG */
3657
3658                 if( p_sdt->i_network_id == 133 )
3659                     p_sys->b_broken_charset = true;  /* SKY DE & BetaDigital use ISO8859-1 */
3660
3661                 /* List of providers using ISO8859-1 */
3662                 static const char ppsz_broken_providers[][8] = {
3663                     "CSAT",     /* CanalSat FR */
3664                     "GR1",      /* France televisions */
3665                     "MULTI4",   /* NT1 */
3666                     "MR5",      /* France 2/M6 HD */
3667                     ""
3668                 };
3669                 for( int i = 0; *ppsz_broken_providers[i]; i++ )
3670                 {
3671                     const size_t i_length = strlen(ppsz_broken_providers[i]);
3672                     if( pD->i_service_provider_name_length == i_length &&
3673                         !strncmp( (char *)pD->i_service_provider_name, ppsz_broken_providers[i], i_length ) )
3674                         p_sys->b_broken_charset = true;
3675                 }
3676
3677                 /* FIXME: Digital+ ES also uses ISO8859-1 */
3678
3679                 str1 = EITConvertToUTF8(p_demux,
3680                                         pD->i_service_provider_name,
3681                                         pD->i_service_provider_name_length,
3682                                         p_sys->b_broken_charset );
3683                 str2 = EITConvertToUTF8(p_demux,
3684                                         pD->i_service_name,
3685                                         pD->i_service_name_length,
3686                                         p_sys->b_broken_charset );
3687
3688                 msg_Dbg( p_demux, "    - type=%d provider=%s name=%s",
3689                          pD->i_service_type, str1, str2 );
3690
3691                 vlc_meta_SetTitle( p_meta, str2 );
3692                 vlc_meta_SetPublisher( p_meta, str1 );
3693                 if( pD->i_service_type >= 0x01 && pD->i_service_type <= 0x10 )
3694                     psz_type = ppsz_type[pD->i_service_type];
3695                 free( str1 );
3696                 free( str2 );
3697             }
3698         }
3699
3700         if( p_srv->i_running_status >= 0x01 && p_srv->i_running_status <= 0x04 )
3701         {
3702             static const char *ppsz_status[5] = {
3703                 "Unknown",
3704                 "Not running",
3705                 "Starts in a few seconds",
3706                 "Pausing",
3707                 "Running"
3708             };
3709             psz_status = ppsz_status[p_srv->i_running_status];
3710         }
3711
3712         if( psz_type )
3713             vlc_meta_AddExtra( p_meta, "Type", psz_type );
3714         if( psz_status )
3715             vlc_meta_AddExtra( p_meta, "Status", psz_status );
3716
3717         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_META,
3718                         p_srv->i_service_id, p_meta );
3719         vlc_meta_Delete( p_meta );
3720     }
3721
3722     sdt->u.p_psi->i_version = p_sdt->i_version;
3723     dvbpsi_sdt_delete( p_sdt );
3724 }
3725
3726 /* i_year: year - 1900  i_month: 0-11  i_mday: 1-31 i_hour: 0-23 i_minute: 0-59 i_second: 0-59 */
3727 static int64_t vlc_timegm( int i_year, int i_month, int i_mday, int i_hour, int i_minute, int i_second )
3728 {
3729     static const int pn_day[12+1] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
3730     int64_t i_day;
3731
3732     if( i_year < 70 ||
3733         i_month < 0 || i_month > 11 || i_mday < 1 || i_mday > 31 ||
3734         i_hour < 0 || i_hour > 23 || i_minute < 0 || i_minute > 59 || i_second < 0 || i_second > 59 )
3735         return -1;
3736
3737     /* Count the number of days */
3738     i_day = 365 * (i_year-70) + pn_day[i_month] + i_mday - 1;
3739 #define LEAP(y) ( ((y)%4) == 0 && (((y)%100) != 0 || ((y)%400) == 0) ? 1 : 0)
3740     for( int i = 70; i < i_year; i++ )
3741         i_day += LEAP(1900+i);
3742     if( i_month > 1 )
3743         i_day += LEAP(1900+i_year);
3744 #undef LEAP
3745     /**/
3746     return ((24*i_day + i_hour)*60 + i_minute)*60 + i_second;
3747 }
3748
3749 static void EITDecodeMjd( int i_mjd, int *p_y, int *p_m, int *p_d )
3750 {
3751     const int yp = (int)( ( (double)i_mjd - 15078.2)/365.25 );
3752     const int mp = (int)( ((double)i_mjd - 14956.1 - (int)(yp * 365.25)) / 30.6001 );
3753     const int c = ( mp == 14 || mp == 15 ) ? 1 : 0;
3754
3755     *p_y = 1900 + yp + c*1;
3756     *p_m = mp - 1 - c*12;
3757     *p_d = i_mjd - 14956 - (int)(yp*365.25) - (int)(mp*30.6001);
3758 }
3759 #define CVT_FROM_BCD(v) ((((v) >> 4)&0xf)*10 + ((v)&0xf))
3760 static int64_t EITConvertStartTime( uint64_t i_date )
3761 {
3762     const int i_mjd = i_date >> 24;
3763     const int i_hour   = CVT_FROM_BCD(i_date >> 16);
3764     const int i_minute = CVT_FROM_BCD(i_date >>  8);
3765     const int i_second = CVT_FROM_BCD(i_date      );
3766     int i_year;
3767     int i_month;
3768     int i_day;
3769
3770     /* if all 40 bits are 1, the start is unknown */
3771     if( i_date == UINT64_C(0xffffffffff) )
3772         return -1;
3773
3774     EITDecodeMjd( i_mjd, &i_year, &i_month, &i_day );
3775     return vlc_timegm( i_year - 1900, i_month - 1, i_day, i_hour, i_minute, i_second );
3776 }
3777 static int EITConvertDuration( uint32_t i_duration )
3778 {
3779     return CVT_FROM_BCD(i_duration >> 16) * 3600 +
3780            CVT_FROM_BCD(i_duration >> 8 ) * 60 +
3781            CVT_FROM_BCD(i_duration      );
3782 }
3783 #undef CVT_FROM_BCD
3784
3785 static void TDTCallBack( demux_t *p_demux, dvbpsi_tot_t *p_tdt )
3786 {
3787     demux_sys_t        *p_sys = p_demux->p_sys;
3788
3789     p_sys->i_tdt_delta = CLOCK_FREQ * EITConvertStartTime( p_tdt->i_utc_time )
3790                          - mdate();
3791     dvbpsi_tot_delete(p_tdt);
3792 }
3793
3794
3795 static void EITCallBack( demux_t *p_demux,
3796                          dvbpsi_eit_t *p_eit, bool b_current_following )
3797 {
3798     demux_sys_t        *p_sys = p_demux->p_sys;
3799     dvbpsi_eit_event_t *p_evt;
3800     vlc_epg_t *p_epg;
3801
3802     msg_Dbg( p_demux, "EITCallBack called" );
3803     if( !p_eit->b_current_next )
3804     {
3805         dvbpsi_eit_delete( p_eit );
3806         return;
3807     }
3808
3809     msg_Dbg( p_demux, "new EIT service_id=%d version=%d current_next=%d "
3810              "ts_id=%d network_id=%d segment_last_section_number=%d "
3811              "last_table_id=%d",
3812              p_eit->i_extension,
3813              p_eit->i_version, p_eit->b_current_next,
3814              p_eit->i_ts_id, p_eit->i_network_id,
3815              p_eit->i_segment_last_section_number, p_eit->i_last_table_id );
3816
3817     p_epg = vlc_epg_New( NULL );
3818     for( p_evt = p_eit->p_first_event; p_evt; p_evt = p_evt->p_next )
3819     {
3820         dvbpsi_descriptor_t *p_dr;
3821         char                *psz_name = NULL;
3822         char                *psz_text = NULL;
3823         char                *psz_extra = strdup("");
3824         int64_t i_start;
3825         int i_duration;
3826         int i_min_age = 0;
3827         int64_t i_tot_time = 0;
3828
3829         i_start = EITConvertStartTime( p_evt->i_start_time );
3830         i_duration = EITConvertDuration( p_evt->i_duration );
3831
3832         if( p_sys->arib.e_mode == ARIBMODE_ENABLED )
3833         {
3834             if( p_sys->i_tdt_delta == 0 )
3835                 p_sys->i_tdt_delta = CLOCK_FREQ * (i_start + i_duration - 5) - mdate();
3836
3837             i_tot_time = (mdate() + p_sys->i_tdt_delta) / CLOCK_FREQ;
3838
3839             tzset(); // JST -> UTC
3840             i_start += timezone; // FIXME: what about DST?
3841             i_tot_time += timezone;
3842
3843             if( p_evt->i_running_status == 0x00 &&
3844                 (i_start - 5 < i_tot_time &&
3845                  i_tot_time < i_start + i_duration + 5) )
3846             {
3847                 p_evt->i_running_status = 0x04;
3848                 msg_Dbg( p_demux, "  EIT running status 0x00 -> 0x04" );
3849             }
3850         }
3851
3852         msg_Dbg( p_demux, "  * event id=%d start_time:%d duration=%d "
3853                           "running=%d free_ca=%d",
3854                  p_evt->i_event_id, (int)i_start, (int)i_duration,
3855                  p_evt->i_running_status, p_evt->b_free_ca );
3856
3857         for( p_dr = p_evt->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3858         {
3859             switch(p_dr->i_tag)
3860             {
3861             case 0x4d:
3862             {
3863                 dvbpsi_short_event_dr_t *pE = dvbpsi_DecodeShortEventDr( p_dr );
3864
3865                 /* Only take first description, as we don't handle language-info
3866                    for epg atm*/
3867                 if( pE && psz_name == NULL )
3868                 {
3869                     psz_name = EITConvertToUTF8( p_demux,
3870                                                  pE->i_event_name, pE->i_event_name_length,
3871                                                  p_sys->b_broken_charset );
3872                     free( psz_text );
3873                     psz_text = EITConvertToUTF8( p_demux,
3874                                                  pE->i_text, pE->i_text_length,
3875                                                  p_sys->b_broken_charset );
3876                     msg_Dbg( p_demux, "    - short event lang=%3.3s '%s' : '%s'",
3877                              pE->i_iso_639_code, psz_name, psz_text );
3878                 }
3879             }
3880                 break;
3881
3882             case 0x4e:
3883             {
3884                 dvbpsi_extended_event_dr_t *pE = dvbpsi_DecodeExtendedEventDr( p_dr );
3885                 if( pE )
3886                 {
3887                     msg_Dbg( p_demux, "    - extended event lang=%3.3s [%d/%d]",
3888                              pE->i_iso_639_code,
3889                              pE->i_descriptor_number, pE->i_last_descriptor_number );
3890
3891                     if( pE->i_text_length > 0 )
3892                     {
3893                         char *psz_text = EITConvertToUTF8( p_demux,
3894                                                            pE->i_text, pE->i_text_length,
3895                                                            p_sys->b_broken_charset );
3896                         if( psz_text )
3897                         {
3898                             msg_Dbg( p_demux, "       - text='%s'", psz_text );
3899
3900                             psz_extra = xrealloc( psz_extra,
3901                                    strlen(psz_extra) + strlen(psz_text) + 1 );
3902                             strcat( psz_extra, psz_text );
3903                             free( psz_text );
3904                         }
3905                     }
3906
3907                     for( int i = 0; i < pE->i_entry_count; i++ )
3908                     {
3909                         char *psz_dsc = EITConvertToUTF8( p_demux,
3910                                                           pE->i_item_description[i],
3911                                                           pE->i_item_description_length[i],
3912                                                           p_sys->b_broken_charset );
3913                         char *psz_itm = EITConvertToUTF8( p_demux,
3914                                                           pE->i_item[i], pE->i_item_length[i],
3915                                                           p_sys->b_broken_charset );
3916
3917                         if( psz_dsc && psz_itm )
3918                         {
3919                             msg_Dbg( p_demux, "       - desc='%s' item='%s'", psz_dsc, psz_itm );
3920 #if 0
3921                             psz_extra = xrealloc( psz_extra,
3922                                          strlen(psz_extra) + strlen(psz_dsc) +
3923                                          strlen(psz_itm) + 3 + 1 );
3924                             strcat( psz_extra, "(" );
3925                             strcat( psz_extra, psz_dsc );
3926                             strcat( psz_extra, " " );
3927                             strcat( psz_extra, psz_itm );
3928                             strcat( psz_extra, ")" );
3929 #endif
3930                         }
3931                         free( psz_dsc );
3932                         free( psz_itm );
3933                     }
3934                 }
3935             }
3936                 break;
3937
3938             case 0x55:
3939             {
3940                 dvbpsi_parental_rating_dr_t *pR = dvbpsi_DecodeParentalRatingDr( p_dr );
3941                 if ( pR )
3942                 {
3943                     for ( int i = 0; i < pR->i_ratings_number; i++ )
3944                     {
3945                         const dvbpsi_parental_rating_t *p_rating = & pR->p_parental_rating[ i ];
3946                         if ( p_rating->i_rating > 0x00 && p_rating->i_rating <= 0x0F )
3947                         {
3948                             if ( p_rating->i_rating + 3 > i_min_age )
3949                                 i_min_age = p_rating->i_rating + 3;
3950                             msg_Dbg( p_demux, "    - parental control set to %d years",
3951                                      i_min_age );
3952                         }
3953                     }
3954                 }
3955             }
3956                 break;
3957
3958             default:
3959                 msg_Dbg( p_demux, "    - event unknown dr 0x%x(%d)", p_dr->i_tag, p_dr->i_tag );
3960                 break;
3961             }
3962         }
3963
3964         /* */
3965         if( i_start > 0 && psz_name && psz_text)
3966             vlc_epg_AddEvent( p_epg, i_start, i_duration, psz_name, psz_text,
3967                               *psz_extra ? psz_extra : NULL, i_min_age );
3968
3969         /* Update "now playing" field */
3970         if( p_evt->i_running_status == 0x04 && i_start > 0  && psz_name && psz_text )
3971             vlc_epg_SetCurrent( p_epg, i_start );
3972
3973         free( psz_name );
3974         free( psz_text );
3975
3976         free( psz_extra );
3977     }
3978     if( p_epg->i_event > 0 )
3979     {
3980         if( b_current_following &&
3981             (  p_sys->programs.i_size == 0 ||
3982                p_sys->programs.p_elems[0] ==
3983                     p_eit->i_extension
3984                 ) )
3985         {
3986             p_sys->i_dvb_length = 0;
3987             p_sys->i_dvb_start = 0;
3988
3989             if( p_epg->p_current )
3990             {
3991                 p_sys->i_dvb_start = CLOCK_FREQ * p_epg->p_current->i_start;
3992                 p_sys->i_dvb_length = CLOCK_FREQ * p_epg->p_current->i_duration;
3993             }
3994         }
3995         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_EPG,
3996                         p_eit->i_extension,
3997                         p_epg );
3998     }
3999     vlc_epg_Delete( p_epg );
4000
4001     dvbpsi_eit_delete( p_eit );
4002 }
4003 static void EITCallBackCurrentFollowing( demux_t *p_demux, dvbpsi_eit_t *p_eit )
4004 {
4005     EITCallBack( p_demux, p_eit, true );
4006 }
4007 static void EITCallBackSchedule( demux_t *p_demux, dvbpsi_eit_t *p_eit )
4008 {
4009     EITCallBack( p_demux, p_eit, false );
4010 }
4011
4012 static void PSINewTableCallBack( dvbpsi_t *h, uint8_t i_table_id,
4013                                  uint16_t i_extension, demux_t *p_demux )
4014 {
4015     demux_sys_t *p_sys = p_demux->p_sys;
4016     assert( h );
4017 #if 0
4018     msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4019              i_table_id, i_table_id, i_extension, i_extension );
4020 #endif
4021     if( p_sys->pid[0].u.p_pat->i_version != -1 && i_table_id == 0x42 )
4022     {
4023         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4024                  i_table_id, i_table_id, i_extension, i_extension );
4025
4026         if( !dvbpsi_sdt_attach( h, i_table_id, i_extension, (dvbpsi_sdt_callback)SDTCallBack, p_demux ) )
4027             msg_Err( p_demux, "PSINewTableCallback: failed attaching SDTCallback" );
4028     }
4029     else if( p_sys->pid[0x11].u.p_psi->i_version != -1 &&
4030              ( i_table_id == 0x4e || /* Current/Following */
4031                (i_table_id >= 0x50 && i_table_id <= 0x5f) ) ) /* Schedule */
4032     {
4033         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4034                  i_table_id, i_table_id, i_extension, i_extension );
4035
4036         dvbpsi_eit_callback cb = i_table_id == 0x4e ?
4037                                     (dvbpsi_eit_callback)EITCallBackCurrentFollowing :
4038                                     (dvbpsi_eit_callback)EITCallBackSchedule;
4039
4040         if( !dvbpsi_eit_attach( h, i_table_id, i_extension, cb, p_demux ) )
4041             msg_Err( p_demux, "PSINewTableCallback: failed attaching EITCallback" );
4042     }
4043     else if( p_demux->p_sys->pid[0x11].u.p_psi->i_version != -1 &&
4044             (i_table_id == 0x70 /* TDT */ || i_table_id == 0x73 /* TOT */) )
4045     {
4046          msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
4047                  i_table_id, i_table_id, i_extension, i_extension );
4048
4049         if( !dvbpsi_tot_attach( h, i_table_id, i_extension, (dvbpsi_tot_callback)TDTCallBack, p_demux ) )
4050             msg_Err( p_demux, "PSINewTableCallback: failed attaching TDTCallback" );
4051     }
4052 }
4053
4054 /*****************************************************************************
4055  * PMT callback and helpers
4056  *****************************************************************************/
4057 static dvbpsi_descriptor_t *PMTEsFindDescriptor( const dvbpsi_pmt_es_t *p_es,
4058                                                  int i_tag )
4059 {
4060     dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
4061     while( p_dr && ( p_dr->i_tag != i_tag ) )
4062         p_dr = p_dr->p_next;
4063     return p_dr;
4064 }
4065 static bool PMTEsHasRegistration( demux_t *p_demux,
4066                                   const dvbpsi_pmt_es_t *p_es,
4067                                   const char *psz_tag )
4068 {
4069     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x05 );
4070     if( !p_dr )
4071         return false;
4072
4073     if( p_dr->i_length < 4 )
4074     {
4075         msg_Warn( p_demux, "invalid Registration Descriptor" );
4076         return false;
4077     }
4078
4079     assert( strlen(psz_tag) == 4 );
4080     return !memcmp( p_dr->p_data, psz_tag, 4 );
4081 }
4082
4083 static bool PMTEsHasComponentTag( const dvbpsi_pmt_es_t *p_es,
4084                                   int i_component_tag )
4085 {
4086     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x52 );
4087     if( !p_dr )
4088         return false;
4089     dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4090     if( !p_si )
4091         return false;
4092
4093     return p_si->i_component_tag == i_component_tag;
4094 }
4095
4096 static void PMTSetupEsISO14496( demux_t *p_demux, ts_pes_es_t *p_es,
4097                                 const ts_pmt_t *p_pmt, const dvbpsi_pmt_es_t *p_dvbpsies )
4098 {
4099     es_format_t *p_fmt = &p_es->fmt;
4100
4101     /* MPEG-4 stream: search FMC_DESCRIPTOR (SL Packetized stream) */
4102     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x1f );
4103
4104     if( p_dr && p_dr->i_length == 2 )
4105     {
4106         const int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
4107
4108         msg_Dbg( p_demux, "found FMC_descriptor declaring sl packetization on es_id=%d", i_es_id );
4109
4110         p_es->p_mpeg4desc = NULL;
4111
4112         for( int i = 0; i < ES_DESCRIPTOR_COUNT; i++ )
4113         {
4114             iod_descriptor_t *iod = p_pmt->iod;
4115             if( iod->es_descr[i].i_es_id == i_es_id )
4116             {
4117                 if ( iod->es_descr[i].b_ok )
4118                     p_es->p_mpeg4desc = &iod->es_descr[i];
4119                 else
4120                     msg_Dbg( p_demux, "MPEG-4 descriptor not yet available on es_id=%d", i_es_id );
4121                 break;
4122             }
4123         }
4124     }
4125     if( !p_es->p_mpeg4desc )
4126     {
4127         switch( p_dvbpsies->i_type )
4128         {
4129         /* non fatal, set by packetizer */
4130         case 0x0f: /* ADTS */
4131         case 0x11: /* LOAS */
4132             msg_Info( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4133                       p_dvbpsies->i_pid, p_dvbpsies->i_type );
4134             break;
4135         default:
4136             msg_Err( p_demux, "MPEG-4 descriptor not found for pid 0x%x type 0x%x",
4137                      p_dvbpsies->i_pid, p_dvbpsies->i_type );
4138             break;
4139         }
4140         return;
4141     }
4142
4143     const decoder_config_descriptor_t *dcd = &p_es->p_mpeg4desc->dec_descr;
4144     if( dcd->i_streamType == 0x04 )    /* VisualStream */
4145     {
4146         p_fmt->i_cat = VIDEO_ES;
4147         switch( dcd->i_objectTypeIndication )
4148         {
4149         case 0x0B: /* mpeg4 sub */
4150             p_fmt->i_cat = SPU_ES;
4151             p_fmt->i_codec = VLC_CODEC_SUBT;
4152             break;
4153
4154         case 0x20: /* mpeg4 */
4155             p_fmt->i_codec = VLC_CODEC_MP4V;
4156             break;
4157         case 0x21: /* h264 */
4158             p_fmt->i_codec = VLC_CODEC_H264;
4159             break;
4160         case 0x60:
4161         case 0x61:
4162         case 0x62:
4163         case 0x63:
4164         case 0x64:
4165         case 0x65: /* mpeg2 */
4166             p_fmt->i_codec = VLC_CODEC_MPGV;
4167             break;
4168         case 0x6a: /* mpeg1 */
4169             p_fmt->i_codec = VLC_CODEC_MPGV;
4170             break;
4171         case 0x6c: /* mpeg1 */
4172             p_fmt->i_codec = VLC_CODEC_JPEG;
4173             break;
4174         default:
4175             p_fmt->i_cat = UNKNOWN_ES;
4176             break;
4177         }
4178     }
4179     else if( dcd->i_streamType == 0x05 )    /* AudioStream */
4180     {
4181         p_fmt->i_cat = AUDIO_ES;
4182         switch( dcd->i_objectTypeIndication )
4183         {
4184         case 0x40: /* mpeg4 */
4185             p_fmt->i_codec = VLC_CODEC_MP4A;
4186             break;
4187         case 0x66:
4188         case 0x67:
4189         case 0x68: /* mpeg2 aac */
4190             p_fmt->i_codec = VLC_CODEC_MP4A;
4191             break;
4192         case 0x69: /* mpeg2 */
4193             p_fmt->i_codec = VLC_CODEC_MPGA;
4194             break;
4195         case 0x6b: /* mpeg1 */
4196             p_fmt->i_codec = VLC_CODEC_MPGA;
4197             break;
4198         default:
4199             p_fmt->i_cat = UNKNOWN_ES;
4200             break;
4201         }
4202     }
4203     else
4204     {
4205         p_fmt->i_cat = UNKNOWN_ES;
4206     }
4207
4208     if( p_fmt->i_cat != UNKNOWN_ES )
4209     {
4210         p_fmt->i_extra = dcd->i_extra;
4211         if( p_fmt->i_extra > 0 )
4212         {
4213             p_fmt->p_extra = malloc( p_fmt->i_extra );
4214             if( p_fmt->p_extra )
4215                 memcpy( p_fmt->p_extra, dcd->p_extra, p_fmt->i_extra );
4216             else
4217                 p_fmt->i_extra = 0;
4218         }
4219     }
4220 }
4221
4222 typedef struct
4223 {
4224     int  i_type;
4225     int  i_magazine;
4226     int  i_page;
4227     char p_iso639[3];
4228 } ts_teletext_page_t;
4229
4230 static void PMTSetupEsTeletext( demux_t *p_demux, ts_pes_t *p_pes,
4231                                 const dvbpsi_pmt_es_t *p_dvbpsies )
4232 {
4233     es_format_t *p_fmt = &p_pes->es.fmt;
4234
4235     ts_teletext_page_t p_page[2 * 64 + 20];
4236     unsigned i_page = 0;
4237
4238     /* Gather pages information */
4239     for( unsigned i_tag_idx = 0; i_tag_idx < 2; i_tag_idx++ )
4240     {
4241         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, i_tag_idx == 0 ? 0x46 : 0x56 );
4242         if( !p_dr )
4243             continue;
4244
4245         dvbpsi_teletext_dr_t *p_sub = dvbpsi_DecodeTeletextDr( p_dr );
4246         if( !p_sub )
4247             continue;
4248
4249         for( int i = 0; i < p_sub->i_pages_number; i++ )
4250         {
4251             const dvbpsi_teletextpage_t *p_src = &p_sub->p_pages[i];
4252
4253             if( p_src->i_teletext_type >= 0x06 )
4254                 continue;
4255
4256             assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4257
4258             ts_teletext_page_t *p_dst = &p_page[i_page++];
4259
4260             p_dst->i_type = p_src->i_teletext_type;
4261             p_dst->i_magazine = p_src->i_teletext_magazine_number
4262                 ? p_src->i_teletext_magazine_number : 8;
4263             p_dst->i_page = p_src->i_teletext_page_number;
4264             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4265         }
4266     }
4267
4268     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4269     if( p_dr )
4270     {
4271         dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4272         for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4273         {
4274             dvbpsi_subtitle_t *p_src = &p_sub->p_subtitle[i];
4275
4276             if( p_src->i_subtitling_type < 0x01 || p_src->i_subtitling_type > 0x03 )
4277                 continue;
4278
4279             assert( i_page < sizeof(p_page)/sizeof(*p_page) );
4280
4281             ts_teletext_page_t *p_dst = &p_page[i_page++];
4282
4283             switch( p_src->i_subtitling_type )
4284             {
4285             case 0x01:
4286                 p_dst->i_type = 0x02;
4287                 break;
4288             default:
4289                 p_dst->i_type = 0x03;
4290                 break;
4291             }
4292             /* FIXME check if it is the right split */
4293             p_dst->i_magazine = (p_src->i_composition_page_id >> 8)
4294                 ? (p_src->i_composition_page_id >> 8) : 8;
4295             p_dst->i_page = p_src->i_composition_page_id & 0xff;
4296             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
4297         }
4298     }
4299
4300     /* */
4301     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_TELETEXT );
4302
4303     if( !p_demux->p_sys->b_split_es || i_page <= 0 )
4304     {
4305         p_fmt->subs.teletext.i_magazine = -1;
4306         p_fmt->subs.teletext.i_page = 0;
4307         p_fmt->psz_description = strdup( vlc_gettext(ppsz_teletext_type[1]) );
4308
4309         dvbpsi_descriptor_t *p_dr;
4310         p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x46 );
4311         if( !p_dr )
4312             p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x56 );
4313
4314         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4315         {
4316             /* Descriptor pass-through */
4317             p_fmt->p_extra = malloc( p_dr->i_length );
4318             if( p_fmt->p_extra )
4319             {
4320                 p_fmt->i_extra = p_dr->i_length;
4321                 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4322             }
4323         }
4324     }
4325     else
4326     {
4327         for( unsigned i = 0; i < i_page; i++ )
4328         {
4329             ts_pes_es_t *p_page_es;
4330
4331             /* */
4332             if( i == 0 )
4333             {
4334                 p_page_es = &p_pes->es;
4335             }
4336             else
4337             {
4338                 p_page_es = malloc( sizeof(*p_page_es) );
4339                 if( !p_page_es )
4340                     break;
4341
4342                 es_format_Copy( &p_page_es->fmt, p_fmt );
4343                 free( p_page_es->fmt.psz_language );
4344                 free( p_page_es->fmt.psz_description );
4345                 p_page_es->fmt.psz_language = NULL;
4346                 p_page_es->fmt.psz_description = NULL;
4347
4348                 ARRAY_APPEND( p_pes->extra_es, p_page_es );
4349             }
4350
4351             /* */
4352             const ts_teletext_page_t *p = &p_page[i];
4353             p_page_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ?
4354                       ES_PRIORITY_SELECTABLE_MIN : ES_PRIORITY_NOT_DEFAULTABLE;
4355             p_page_es->fmt.psz_language = strndup( p->p_iso639, 3 );
4356             p_page_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
4357             p_page_es->fmt.subs.teletext.i_magazine = p->i_magazine;
4358             p_page_es->fmt.subs.teletext.i_page = p->i_page;
4359
4360             msg_Dbg( p_demux,
4361                          "    * ttxt type=%s lan=%s page=%d%02x",
4362                          p_page_es->fmt.psz_description,
4363                          p_page_es->fmt.psz_language,
4364                          p->i_magazine, p->i_page );
4365         }
4366     }
4367 }
4368 static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pes_t *p_pes,
4369                                    const dvbpsi_pmt_es_t *p_dvbpsies )
4370 {
4371     es_format_t *p_fmt = &p_pes->es.fmt;
4372
4373     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_DVBS );
4374
4375     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4376     int i_page = 0;
4377     dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
4378     for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
4379     {
4380         const int i_type = p_sub->p_subtitle[i].i_subtitling_type;
4381         if( ( i_type >= 0x10 && i_type <= 0x14 ) ||
4382             ( i_type >= 0x20 && i_type <= 0x24 ) )
4383             i_page++;
4384     }
4385
4386     if( !p_demux->p_sys->b_split_es  || i_page <= 0 )
4387     {
4388         p_fmt->subs.dvb.i_id = -1;
4389         p_fmt->psz_description = strdup( _("DVB subtitles") );
4390
4391         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
4392         {
4393             /* Descriptor pass-through */
4394             p_fmt->p_extra = malloc( p_dr->i_length );
4395             if( p_fmt->p_extra )
4396             {
4397                 p_fmt->i_extra = p_dr->i_length;
4398                 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
4399             }
4400         }
4401     }
4402     else
4403     {
4404         for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4405         {
4406             ts_pes_es_t *p_subs_es;
4407
4408             /* */
4409             if( i == 0 )
4410             {
4411                 p_subs_es = &p_pes->es;
4412             }
4413             else
4414             {
4415                 p_subs_es = malloc( sizeof(*p_subs_es) );
4416                 if( !p_subs_es )
4417                     break;
4418
4419                 es_format_Copy( &p_subs_es->fmt, p_fmt );
4420                 free( p_subs_es->fmt.psz_language );
4421                 free( p_subs_es->fmt.psz_description );
4422                 p_subs_es->fmt.psz_language = NULL;
4423                 p_subs_es->fmt.psz_description = NULL;
4424
4425                 ARRAY_APPEND( p_pes->extra_es, p_subs_es );
4426             }
4427
4428             /* */
4429             const dvbpsi_subtitle_t *p = &p_sub->p_subtitle[i];
4430             p_subs_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
4431             switch( p->i_subtitling_type )
4432             {
4433             case 0x10: /* unspec. */
4434             case 0x11: /* 4:3 */
4435             case 0x12: /* 16:9 */
4436             case 0x13: /* 2.21:1 */
4437             case 0x14: /* HD monitor */
4438                 p_subs_es->fmt.psz_description = strdup( _("DVB subtitles") );
4439                 break;
4440             case 0x20: /* Hearing impaired unspec. */
4441             case 0x21: /* h.i. 4:3 */
4442             case 0x22: /* h.i. 16:9 */
4443             case 0x23: /* h.i. 2.21:1 */
4444             case 0x24: /* h.i. HD monitor */
4445                 p_subs_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
4446                 break;
4447             default:
4448                 break;
4449             }
4450
4451             /* Hack, FIXME */
4452             p_subs_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id <<  0 ) |
4453                                       ( p->i_ancillary_page_id   << 16 );
4454         }
4455     }
4456 }
4457
4458 static int vlc_ceil_log2( const unsigned int val )
4459 {
4460     int n = 31 - clz(val);
4461     if ((1U << n) != val)
4462         n++;
4463
4464     return n;
4465 }
4466
4467 static void OpusSetup(demux_t *demux, uint8_t *p, size_t len, es_format_t *p_fmt)
4468 {
4469     OpusHeader h;
4470
4471     /* default mapping */
4472     static const unsigned char map[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
4473     memcpy(h.stream_map, map, sizeof(map));
4474
4475     int csc, mapping;
4476     int channels = 0;
4477     int stream_count = 0;
4478     int ccc = p[1]; // channel_config_code
4479     if (ccc <= 8) {
4480         channels = ccc;
4481         if (channels)
4482             mapping = channels > 2;
4483         else {
4484             mapping = 255;
4485             channels = 2; // dual mono
4486         }
4487         static const uint8_t p_csc[8] = { 0, 1, 1, 2, 2, 2, 3, 3 };
4488         csc = p_csc[channels - 1];
4489         stream_count = channels - csc;
4490
4491         static const uint8_t map[6][7] = {
4492             { 2,1 },
4493             { 1,2,3 },
4494             { 4,1,2,3 },
4495             { 4,1,2,3,5 },
4496             { 4,1,2,3,5,6 },
4497             { 6,1,2,3,4,5,7 },
4498         };
4499         if (channels > 2)
4500             memcpy(&h.stream_map[1], map[channels-3], channels - 1);
4501     } else if (ccc == 0x81) {
4502         if (len < 4)
4503             goto explicit_config_too_short;
4504
4505         channels = p[2];
4506         mapping = p[3];
4507         csc = 0;
4508         if (mapping) {
4509             bs_t s;
4510             bs_init(&s, &p[4], len - 4);
4511             stream_count = 1;
4512             if (channels) {
4513                 int bits = vlc_ceil_log2(channels);
4514                 if (s.i_left < bits)
4515                     goto explicit_config_too_short;
4516                 stream_count = bs_read(&s, bits) + 1;
4517                 bits = vlc_ceil_log2(stream_count + 1);
4518                 if (s.i_left < bits)
4519                     goto explicit_config_too_short;
4520                 csc = bs_read(&s, bits);
4521             }
4522             int channel_bits = vlc_ceil_log2(stream_count + csc + 1);
4523             if (s.i_left < channels * channel_bits)
4524                 goto explicit_config_too_short;
4525
4526             unsigned char silence = (1U << (stream_count + csc + 1)) - 1;
4527             for (int i = 0; i < channels; i++) {
4528                 unsigned char m = bs_read(&s, channel_bits);
4529                 if (m == silence)
4530                     m = 0xff;
4531                 h.stream_map[i] = m;
4532             }
4533         }
4534     } else if (ccc >= 0x80 && ccc <= 0x88) {
4535         channels = ccc - 0x80;
4536         if (channels)
4537             mapping = 1;
4538         else {
4539             mapping = 255;
4540             channels = 2; // dual mono
4541         }
4542         csc = 0;
4543         stream_count = channels;
4544     } else {
4545         msg_Err(demux, "Opus channel configuration 0x%.2x is reserved", ccc);
4546     }
4547
4548     if (!channels) {
4549         msg_Err(demux, "Opus channel configuration 0x%.2x not supported yet", p[1]);
4550         return;
4551     }
4552
4553     opus_prepare_header(channels, 0, &h);
4554     h.preskip = 0;
4555     h.input_sample_rate = 48000;
4556     h.nb_coupled = csc;
4557     h.nb_streams = channels - csc;
4558     h.channel_mapping = mapping;
4559
4560     if (h.channels) {
4561         opus_write_header((uint8_t**)&p_fmt->p_extra, &p_fmt->i_extra, &h, NULL /* FIXME */);
4562         if (p_fmt->p_extra) {
4563             p_fmt->i_cat = AUDIO_ES;
4564             p_fmt->i_codec = VLC_CODEC_OPUS;
4565             p_fmt->audio.i_channels = h.channels;
4566             p_fmt->audio.i_rate = 48000;
4567         }
4568     }
4569
4570     return;
4571
4572 explicit_config_too_short:
4573     msg_Err(demux, "Opus descriptor too short");
4574 }
4575
4576 static void PMTSetupEs0x06( demux_t *p_demux, ts_pes_t *p_pes,
4577                             const dvbpsi_pmt_es_t *p_dvbpsies )
4578 {
4579     es_format_t *p_fmt = &p_pes->es.fmt;
4580     dvbpsi_descriptor_t *p_subs_dr = PMTEsFindDescriptor( p_dvbpsies, 0x59 );
4581     dvbpsi_descriptor_t *desc;
4582
4583     if( PMTEsHasRegistration( p_demux, p_dvbpsies, "AC-3" ) ||
4584         PMTEsFindDescriptor( p_dvbpsies, 0x6a ) ||
4585         PMTEsFindDescriptor( p_dvbpsies, 0x81 ) )
4586     {
4587         p_fmt->i_cat = AUDIO_ES;
4588         p_fmt->i_codec = VLC_CODEC_A52;
4589     }
4590     else if( (desc = PMTEsFindDescriptor( p_dvbpsies, 0x7f ) ) && desc->i_length >= 2 &&
4591               PMTEsHasRegistration(p_demux, p_dvbpsies, "Opus"))
4592     {
4593         OpusSetup(p_demux, desc->p_data, desc->i_length, p_fmt);
4594     }
4595     else if( PMTEsFindDescriptor( p_dvbpsies, 0x7a ) )
4596     {
4597         /* DVB with stream_type 0x06 (ETS EN 300 468) */
4598         p_fmt->i_cat = AUDIO_ES;
4599         p_fmt->i_codec = VLC_CODEC_EAC3;
4600     }
4601     else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS1" ) ||
4602              PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS2" ) ||
4603              PMTEsHasRegistration( p_demux, p_dvbpsies, "DTS3" ) ||
4604              PMTEsFindDescriptor( p_dvbpsies, 0x73 ) )
4605     {
4606         /*registration descriptor(ETSI TS 101 154 Annex F)*/
4607         p_fmt->i_cat = AUDIO_ES;
4608         p_fmt->i_codec = VLC_CODEC_DTS;
4609     }
4610     else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "BSSD" ) && !p_subs_dr )
4611     {
4612         /* BSSD is AES3 DATA, but could also be subtitles
4613          * we need to check for secondary descriptor then s*/
4614         p_fmt->i_cat = AUDIO_ES;
4615         p_fmt->b_packetized = true;
4616         p_fmt->i_codec = VLC_CODEC_302M;
4617     }
4618     else if( PMTEsHasRegistration( p_demux, p_dvbpsies, "HEVC" ) )
4619     {
4620         p_fmt->i_cat = VIDEO_ES;
4621         p_fmt->i_codec = VLC_CODEC_HEVC;
4622     }
4623     else if ( p_demux->p_sys->arib.e_mode == ARIBMODE_ENABLED )
4624     {
4625         /* Lookup our data component descriptor first ARIB STD B10 6.4 */
4626         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xFD );
4627         /* and check that it maps to something ARIB STD B14 Table 5.1/5.2 */
4628         if ( p_dr && p_dr->i_length >= 2 )
4629         {
4630             if( !memcmp( p_dr->p_data, "\x00\x08", 2 ) &&  (
4631                     PMTEsHasComponentTag( p_dvbpsies, 0x30 ) ||
4632                     PMTEsHasComponentTag( p_dvbpsies, 0x31 ) ||
4633                     PMTEsHasComponentTag( p_dvbpsies, 0x32 ) ||
4634                     PMTEsHasComponentTag( p_dvbpsies, 0x33 ) ||
4635                     PMTEsHasComponentTag( p_dvbpsies, 0x34 ) ||
4636                     PMTEsHasComponentTag( p_dvbpsies, 0x35 ) ||
4637                     PMTEsHasComponentTag( p_dvbpsies, 0x36 ) ||
4638                     PMTEsHasComponentTag( p_dvbpsies, 0x37 ) ) )
4639             {
4640                 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_A );
4641                 p_fmt->psz_language = strndup ( "jpn", 3 );
4642                 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4643             }
4644             else if( !memcmp( p_dr->p_data, "\x00\x12", 2 ) && (
4645                      PMTEsHasComponentTag( p_dvbpsies, 0x87 ) ||
4646                      PMTEsHasComponentTag( p_dvbpsies, 0x88 ) ) )
4647             {
4648                 es_format_Init( p_fmt, SPU_ES, VLC_CODEC_ARIB_C );
4649                 p_fmt->psz_language = strndup ( "jpn", 3 );
4650                 p_fmt->psz_description = strdup( _("ARIB subtitles") );
4651             }
4652         }
4653     }
4654     else
4655     {
4656         /* Subtitle/Teletext/VBI fallbacks */
4657         dvbpsi_subtitling_dr_t *p_sub;
4658         if( p_subs_dr && ( p_sub = dvbpsi_DecodeSubtitlingDr( p_subs_dr ) ) )
4659         {
4660             for( int i = 0; i < p_sub->i_subtitles_number; i++ )
4661             {
4662                 if( p_fmt->i_cat != UNKNOWN_ES )
4663                     break;
4664
4665                 switch( p_sub->p_subtitle[i].i_subtitling_type )
4666                 {
4667                 case 0x01: /* EBU Teletext subtitles */
4668                 case 0x02: /* Associated EBU Teletext */
4669                 case 0x03: /* VBI data */
4670                     PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
4671                     break;
4672                 case 0x10: /* DVB Subtitle (normal) with no monitor AR critical */
4673                 case 0x11: /*                 ...   on 4:3 AR monitor */
4674                 case 0x12: /*                 ...   on 16:9 AR monitor */
4675                 case 0x13: /*                 ...   on 2.21:1 AR monitor */
4676                 case 0x14: /*                 ...   for display on a high definition monitor */
4677                 case 0x20: /* DVB Subtitle (impaired) with no monitor AR critical */
4678                 case 0x21: /*                 ...   on 4:3 AR monitor */
4679                 case 0x22: /*                 ...   on 16:9 AR monitor */
4680                 case 0x23: /*                 ...   on 2.21:1 AR monitor */
4681                 case 0x24: /*                 ...   for display on a high definition monitor */
4682                     PMTSetupEsDvbSubtitle( p_demux, p_pes, p_dvbpsies );
4683                     break;
4684                 default:
4685                     msg_Err( p_demux, "Unrecognized DVB subtitle type (0x%x)",
4686                              p_sub->p_subtitle[i].i_subtitling_type );
4687                     break;
4688                 }
4689             }
4690         }
4691
4692         if( p_fmt->i_cat == UNKNOWN_ES &&
4693             ( PMTEsFindDescriptor( p_dvbpsies, 0x45 ) ||  /* VBI Data descriptor */
4694               PMTEsFindDescriptor( p_dvbpsies, 0x46 ) ||  /* VBI Teletext descriptor */
4695               PMTEsFindDescriptor( p_dvbpsies, 0x56 ) ) ) /* EBU Teletext descriptor */
4696         {
4697             /* Teletext/VBI */
4698             PMTSetupEsTeletext( p_demux, p_pes, p_dvbpsies );
4699         }
4700     }
4701
4702     /* FIXME is it useful ? */
4703     if( PMTEsFindDescriptor( p_dvbpsies, 0x52 ) )
4704     {
4705         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x52 );
4706         dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
4707
4708         msg_Dbg( p_demux, "    * Stream Component Identifier: %d", p_si->i_component_tag );
4709     }
4710 }
4711
4712 static void PMTSetupEs0xEA( demux_t *p_demux, ts_pes_es_t *p_es,
4713                            const dvbpsi_pmt_es_t *p_dvbpsies )
4714 {
4715     /* Registration Descriptor */
4716     if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "VC-1" ) )
4717     {
4718         msg_Err( p_demux, "Registration descriptor not found or invalid" );
4719         return;
4720     }
4721
4722     es_format_t *p_fmt = &p_es->fmt;
4723
4724     /* registration descriptor for VC-1 (SMPTE rp227) */
4725     p_fmt->i_cat = VIDEO_ES;
4726     p_fmt->i_codec = VLC_CODEC_VC1;
4727
4728     /* XXX With Simple and Main profile the SEQUENCE
4729      * header is modified: video width and height are
4730      * inserted just after the start code as 2 int16_t
4731      * The packetizer will take care of that. */
4732 }
4733
4734 static void PMTSetupEs0xD1( demux_t *p_demux, ts_pes_es_t *p_es,
4735                            const dvbpsi_pmt_es_t *p_dvbpsies )
4736 {
4737     /* Registration Descriptor */
4738     if( !PMTEsHasRegistration( p_demux, p_dvbpsies, "drac" ) )
4739     {
4740         msg_Err( p_demux, "Registration descriptor not found or invalid" );
4741         return;
4742     }
4743
4744     es_format_t *p_fmt = &p_es->fmt;
4745
4746     /* registration descriptor for Dirac
4747      * (backwards compatable with VC-2 (SMPTE Sxxxx:2008)) */
4748     p_fmt->i_cat = VIDEO_ES;
4749     p_fmt->i_codec = VLC_CODEC_DIRAC;
4750 }
4751
4752 static void PMTSetupEs0xA0( demux_t *p_demux, ts_pes_es_t *p_es,
4753                            const dvbpsi_pmt_es_t *p_dvbpsies )
4754 {
4755     /* MSCODEC sent by vlc */
4756     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0xa0 );
4757     if( !p_dr || p_dr->i_length < 10 )
4758     {
4759         msg_Warn( p_demux,
4760                   "private MSCODEC (vlc) without bih private descriptor" );
4761         return;
4762     }
4763
4764     es_format_t *p_fmt = &p_es->fmt;
4765     p_fmt->i_cat = VIDEO_ES;
4766     p_fmt->i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
4767                                  p_dr->p_data[2], p_dr->p_data[3] );
4768     p_fmt->video.i_width = GetWBE( &p_dr->p_data[4] );
4769     p_fmt->video.i_height = GetWBE( &p_dr->p_data[6] );
4770     p_fmt->i_extra = GetWBE( &p_dr->p_data[8] );
4771
4772     if( p_fmt->i_extra > 0 )
4773     {
4774         p_fmt->p_extra = malloc( p_fmt->i_extra );
4775         if( p_fmt->p_extra )
4776             memcpy( p_fmt->p_extra, &p_dr->p_data[10],
4777                     __MIN( p_fmt->i_extra, p_dr->i_length - 10 ) );
4778         else
4779             p_fmt->i_extra = 0;
4780     }
4781     /* For such stream we will gather them ourself and don't launch a
4782      * packetizer.
4783      * Yes it's ugly but it's the only way to have DIV3 working */
4784     p_fmt->b_packetized = true;
4785 }
4786
4787 static void PMTSetupEs0x83( const dvbpsi_pmt_t *p_pmt, ts_pes_es_t *p_es, int i_pid )
4788 {
4789     /* WiDi broadcasts without registration on PMT 0x1, PCR 0x1000 and
4790      * with audio track pid being 0x1100..0x11FF */
4791     if ( p_pmt->i_program_number == 0x1 &&
4792          p_pmt->i_pcr_pid == 0x1000 &&
4793         ( i_pid >> 8 ) == 0x11 )
4794     {
4795         /* Not enough ? might contain 0x83 private descriptor, 2 bytes 0x473F */
4796         es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_WIDI_LPCM );
4797     }
4798     else
4799         es_format_Init( &p_es->fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
4800 }
4801
4802 static bool PMTSetupEsHDMV( demux_t *p_demux, ts_pes_es_t *p_es,
4803                             const dvbpsi_pmt_es_t *p_dvbpsies )
4804 {
4805     es_format_t *p_fmt = &p_es->fmt;
4806
4807     /* Blu-Ray mapping */
4808     switch( p_dvbpsies->i_type )
4809     {
4810     case 0x80:
4811         p_fmt->i_cat = AUDIO_ES;
4812         p_fmt->i_codec = VLC_CODEC_BD_LPCM;
4813         break;
4814     case 0x81:
4815         p_fmt->i_cat = AUDIO_ES;
4816         p_fmt->i_codec = VLC_CODEC_A52;
4817         break;
4818     case 0x82:
4819     case 0x85: /* DTS-HD High resolution audio */
4820     case 0x86: /* DTS-HD Master audio */
4821     case 0xA2: /* Secondary DTS audio */
4822         p_fmt->i_cat = AUDIO_ES;
4823         p_fmt->i_codec = VLC_CODEC_DTS;
4824         break;
4825
4826     case 0x83: /* TrueHD AC3 */
4827         p_fmt->i_cat = AUDIO_ES;
4828         p_fmt->i_codec = VLC_CODEC_TRUEHD;
4829         break;
4830
4831     case 0x84: /* E-AC3 */
4832     case 0xA1: /* Secondary E-AC3 */
4833         p_fmt->i_cat = AUDIO_ES;
4834         p_fmt->i_codec = VLC_CODEC_EAC3;
4835         break;
4836     case 0x90: /* Presentation graphics */
4837         p_fmt->i_cat = SPU_ES;
4838         p_fmt->i_codec = VLC_CODEC_BD_PG;
4839         break;
4840     case 0x91: /* Interactive graphics */
4841     case 0x92: /* Subtitle */
4842         return false;
4843     case 0xEA:
4844         p_fmt->i_cat = VIDEO_ES;
4845         p_fmt->i_codec = VLC_CODEC_VC1;
4846         break;
4847     default:
4848         msg_Info( p_demux, "HDMV registration not implemented for pid 0x%x type 0x%x",
4849                   p_dvbpsies->i_pid, p_dvbpsies->i_type );
4850         return false;
4851         break;
4852     }
4853     return true;
4854 }
4855
4856 static bool PMTSetupEsRegistration( demux_t *p_demux, ts_pes_es_t *p_es,
4857                                     const dvbpsi_pmt_es_t *p_dvbpsies )
4858 {
4859     static const struct
4860     {
4861         char         psz_tag[5];
4862         int          i_cat;
4863         vlc_fourcc_t i_codec;
4864     } p_regs[] = {
4865         { "AC-3", AUDIO_ES, VLC_CODEC_A52   },
4866         { "DTS1", AUDIO_ES, VLC_CODEC_DTS   },
4867         { "DTS2", AUDIO_ES, VLC_CODEC_DTS   },
4868         { "DTS3", AUDIO_ES, VLC_CODEC_DTS   },
4869         { "BSSD", AUDIO_ES, VLC_CODEC_302M  },
4870         { "VC-1", VIDEO_ES, VLC_CODEC_VC1   },
4871         { "drac", VIDEO_ES, VLC_CODEC_DIRAC },
4872         { "", UNKNOWN_ES, 0 }
4873     };
4874     es_format_t *p_fmt = &p_es->fmt;
4875
4876     for( int i = 0; p_regs[i].i_cat != UNKNOWN_ES; i++ )
4877     {
4878         if( PMTEsHasRegistration( p_demux, p_dvbpsies, p_regs[i].psz_tag ) )
4879         {
4880             p_fmt->i_cat   = p_regs[i].i_cat;
4881             p_fmt->i_codec = p_regs[i].i_codec;
4882             if (p_dvbpsies->i_type == 0x87)
4883                 p_fmt->i_codec = VLC_CODEC_EAC3;
4884             return true;
4885         }
4886     }
4887     return false;
4888 }
4889
4890 static char *GetAudioTypeDesc(demux_t *p_demux, int type)
4891 {
4892     static const char *audio_type[] = {
4893         NULL,
4894         N_("clean effects"),
4895         N_("hearing impaired"),
4896         N_("visual impaired commentary"),
4897     };
4898
4899     if (type < 0 || type > 3)
4900         msg_Dbg( p_demux, "unknown audio type: %d", type);
4901     else if (type > 0)
4902         return strdup(audio_type[type]);
4903
4904     return NULL;
4905 }
4906 static void PMTParseEsIso639( demux_t *p_demux, ts_pes_es_t *p_es,
4907                               const dvbpsi_pmt_es_t *p_dvbpsies )
4908 {
4909     /* get language descriptor */
4910     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x0a );
4911
4912     if( !p_dr )
4913         return;
4914
4915     dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
4916     if( !p_decoded )
4917     {
4918         msg_Err( p_demux, "Failed to decode a ISO 639 descriptor" );
4919         return;
4920     }
4921
4922 #if defined(DR_0A_API_VER) && (DR_0A_API_VER >= 2)
4923     p_es->fmt.psz_language = malloc( 4 );
4924     if( p_es->fmt.psz_language )
4925     {
4926         memcpy( p_es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
4927         p_es->fmt.psz_language[3] = 0;
4928         msg_Dbg( p_demux, "found language: %s", p_es->fmt.psz_language);
4929     }
4930     int type = p_decoded->code[0].i_audio_type;
4931     p_es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
4932     if (type == 0)
4933         p_es->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1; // prioritize normal audio tracks
4934
4935     p_es->fmt.i_extra_languages = p_decoded->i_code_count-1;
4936     if( p_es->fmt.i_extra_languages > 0 )
4937         p_es->fmt.p_extra_languages =
4938             malloc( sizeof(*p_es->fmt.p_extra_languages) *
4939                     p_es->fmt.i_extra_languages );
4940     if( p_es->fmt.p_extra_languages )
4941     {
4942         for( unsigned i = 0; i < p_es->fmt.i_extra_languages; i++ )
4943         {
4944             p_es->fmt.p_extra_languages[i].psz_language = malloc(4);
4945             if( p_es->fmt.p_extra_languages[i].psz_language )
4946             {
4947                 memcpy( p_es->fmt.p_extra_languages[i].psz_language,
4948                     p_decoded->code[i+1].iso_639_code, 3 );
4949                 p_es->fmt.p_extra_languages[i].psz_language[3] = '\0';
4950             }
4951             int type = p_decoded->code[i].i_audio_type;
4952             p_es->fmt.p_extra_languages[i].psz_description = GetAudioTypeDesc(p_demux, type);
4953         }
4954     }
4955 #else
4956     p_es->fmt.psz_language = malloc( 4 );
4957     if( p_es->fmt.psz_language )
4958     {
4959         memcpy( p_es->fmt.psz_language,
4960                 p_decoded->i_iso_639_code, 3 );
4961         p_es->fmt.psz_language[3] = 0;
4962     }
4963 #endif
4964 }
4965
4966 static void AddAndCreateES( demux_t *p_demux, ts_pid_t *pid )
4967 {
4968     demux_sys_t  *p_sys = p_demux->p_sys;
4969     bool b_create_delayed = false;
4970
4971     if( pid )
4972     {
4973         if( SEEN(*pid) && p_sys->es_creation == DELAY_ES )
4974         {
4975             p_sys->es_creation = CREATE_ES;
4976             b_create_delayed = true;
4977         }
4978
4979         if( p_sys->es_creation == CREATE_ES )
4980         {
4981             pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
4982             for( int i = 0; i < pid->u.p_pes->extra_es.i_size; i++ )
4983             {
4984                 pid->u.p_pes->extra_es.p_elems[i]->id =
4985                     es_out_Add( p_demux->out, &pid->u.p_pes->extra_es.p_elems[i]->fmt );
4986             }
4987             p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
4988         }
4989     }
4990     else if( p_sys->es_creation == DELAY_ES )
4991     {
4992         p_sys->es_creation = CREATE_ES;
4993         b_create_delayed = true;
4994     }
4995
4996     if( b_create_delayed )
4997     {
4998         ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
4999         for( int i=0; i< p_pat->programs.i_size; i++ )
5000         {
5001             ts_pmt_t *p_pmt = p_pat->programs.p_elems[i]->u.p_pmt;
5002             for( int j=0; j<p_pmt->e_streams.i_size; j++ )
5003             {
5004                 ts_pid_t *pid = p_pmt->e_streams.p_elems[j];
5005                 if( pid->u.p_pes->es.id )
5006                     continue;
5007
5008                 pid->u.p_pes->es.id = es_out_Add( p_demux->out, &pid->u.p_pes->es.fmt );
5009                 for( int k = 0; k < pid->u.p_pes->extra_es.i_size; k++ )
5010                 {
5011                     pid->u.p_pes->extra_es.p_elems[k]->id =
5012                         es_out_Add( p_demux->out, &pid->u.p_pes->extra_es.p_elems[k]->fmt );
5013                 }
5014                 p_sys->i_pmt_es += 1 + pid->u.p_pes->extra_es.i_size;
5015
5016                 if( pid->u.p_pes->es.id != NULL && ProgramIsSelected( p_sys, pid->p_parent->u.p_pmt->i_number ) )
5017                     SetPIDFilter( p_sys, pid, true );
5018             }
5019         }
5020     }
5021 }
5022
5023 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_dvbpsipmt )
5024 {
5025     demux_t      *p_demux = data;
5026     demux_sys_t  *p_sys = p_demux->p_sys;
5027
5028     ts_pid_t     *pmtpid = NULL;
5029     ts_pmt_t     *p_pmt = NULL;
5030
5031     msg_Dbg( p_demux, "PMTCallBack called" );
5032
5033     if (unlikely(p_sys->pid[0].type != TYPE_PAT))
5034     {
5035         assert(p_sys->pid[0].type == TYPE_PAT);
5036         dvbpsi_pmt_delete(p_dvbpsipmt);
5037     }
5038
5039     const ts_pat_t *p_pat = p_sys->pid[0].u.p_pat;
5040
5041     /* First find this PMT declared in PAT */
5042     for( int i = 0; !pmtpid && i < p_pat->programs.i_size; i++ )
5043     {
5044         const int i_pmt_prgnumber = p_pat->programs.p_elems[i]->u.p_pmt->i_number;
5045         if( i_pmt_prgnumber != TS_USER_PMT_NUMBER &&
5046             i_pmt_prgnumber == p_dvbpsipmt->i_program_number )
5047         {
5048             pmtpid = p_pat->programs.p_elems[i];
5049             assert(pmtpid->type == TYPE_PMT);
5050             p_pmt = pmtpid->u.p_pmt;
5051         }
5052     }
5053
5054     if( pmtpid == NULL )
5055     {
5056         msg_Warn( p_demux, "unreferenced program (broken stream)" );
5057         dvbpsi_pmt_delete(p_dvbpsipmt);
5058         return;
5059     }
5060
5061     pmtpid->i_flags |= FLAG_SEEN;
5062
5063     if( p_pmt->i_version != -1 &&
5064         ( !p_dvbpsipmt->b_current_next || p_pmt->i_version == p_dvbpsipmt->i_version ) )
5065     {
5066         dvbpsi_pmt_delete( p_dvbpsipmt );
5067         return;
5068     }
5069
5070     /* Save old es array */
5071     DECL_ARRAY(ts_pid_t *) old_es_rm;
5072     old_es_rm.i_alloc = p_pmt->e_streams.i_alloc;
5073     old_es_rm.i_size = p_pmt->e_streams.i_size;
5074     old_es_rm.p_elems = p_pmt->e_streams.p_elems;
5075     ARRAY_INIT(p_pmt->e_streams);
5076
5077     if( p_pmt->iod )
5078     {
5079         IODFree( p_pmt->iod );
5080         p_pmt->iod = NULL;
5081     }
5082
5083     msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
5084              p_dvbpsipmt->i_program_number, p_dvbpsipmt->i_version, p_dvbpsipmt->i_pcr_pid );
5085     p_pmt->i_pid_pcr = p_dvbpsipmt->i_pcr_pid;
5086     p_pmt->i_version = p_dvbpsipmt->i_version;
5087
5088     ValidateDVBMeta( p_demux, p_pmt->i_pid_pcr );
5089
5090     if( ProgramIsSelected( p_sys, p_pmt->i_number ) )
5091         SetPIDFilter( p_sys, &p_sys->pid[p_pmt->i_pid_pcr], true ); /* Set demux filter */
5092
5093     /* Parse PMT descriptors */
5094     ts_pmt_registration_type_t registration_type = TS_PMT_REGISTRATION_NONE;
5095     dvbpsi_descriptor_t  *p_dr;
5096
5097     /* First pass for standard detection */
5098     if ( p_sys->arib.e_mode == ARIBMODE_AUTO )
5099     {
5100         int i_arib_flags = 0; /* Descriptors can be repeated */
5101         for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5102         {
5103             switch(p_dr->i_tag)
5104             {
5105             case 0x09:
5106             {
5107                 dvbpsi_ca_dr_t *p_cadr = dvbpsi_DecodeCADr( p_dr );
5108                 i_arib_flags |= (p_cadr->i_ca_system_id == 0x05);
5109             }
5110                 break;
5111             case 0xF6:
5112                 i_arib_flags |= 1 << 1;
5113                 break;
5114             case 0xC1:
5115                 i_arib_flags |= 1 << 2;
5116                 break;
5117             default:
5118                 break;
5119             }
5120         }
5121         if ( i_arib_flags == 0x07 ) //0b111
5122             p_sys->arib.e_mode = ARIBMODE_ENABLED;
5123     }
5124
5125     for( p_dr = p_dvbpsipmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
5126     {
5127         /* special descriptors handling */
5128         switch(p_dr->i_tag)
5129         {
5130         case 0x1d: /* We have found an IOD descriptor */
5131             msg_Dbg( p_demux, " * PMT descriptor : IOD (0x1d)" );
5132             p_pmt->iod = IODNew( p_dr->i_length, p_dr->p_data );
5133             break;
5134
5135         case 0x9:
5136             msg_Dbg( p_demux, " * PMT descriptor : CA (0x9) SysID 0x%x",
5137                     (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5138             break;
5139
5140         case 0x5: /* Registration Descriptor */
5141             if( p_dr->i_length != 4 )
5142             {
5143                 msg_Warn( p_demux, " * PMT invalid Registration Descriptor" );
5144             }
5145             else
5146             {
5147                 msg_Dbg( p_demux, " * PMT descriptor : registration %4.4s", p_dr->p_data );
5148                 if( !memcmp( p_dr->p_data, "HDMV", 4 ) || !memcmp( p_dr->p_data, "HDPR", 4 ) )
5149                     registration_type = TS_PMT_REGISTRATION_HDMV; /* Blu-Ray */
5150             }
5151             break;
5152
5153         case 0x0f:
5154             msg_Dbg( p_demux, " * PMT descriptor : Private Data (0x0f)" );
5155             break;
5156
5157         case 0xC1:
5158             msg_Dbg( p_demux, " * PMT descriptor : Digital copy control (0xC1)" );
5159             break;
5160
5161         case 0x88: /* EACEM Simulcast HD Logical channels ordering */
5162             msg_Dbg( p_demux, " * descriptor : EACEM Simulcast HD" );
5163             /* TODO: apply visibility flags */
5164             break;
5165
5166         default:
5167             msg_Dbg( p_demux, " * PMT descriptor : unknown (0x%x)", p_dr->i_tag );
5168         }
5169     }
5170
5171     dvbpsi_pmt_es_t      *p_dvbpsies;
5172     for( p_dvbpsies = p_dvbpsipmt->p_first_es; p_dvbpsies != NULL; p_dvbpsies = p_dvbpsies->p_next )
5173     {
5174         bool b_reusing_pid = false;
5175         ts_pes_t *p_pes;
5176
5177         ts_pid_t *pespid = &p_sys->pid[p_dvbpsies->i_pid];
5178
5179         /* Find out if the PID was already declared */
5180         for( int i = 0; i < old_es_rm.i_size; i++ )
5181         {
5182             if( old_es_rm.p_elems[i]->i_pid == p_dvbpsies->i_pid )
5183             {
5184                 b_reusing_pid = true;
5185                 break;
5186             }
5187         }
5188         ValidateDVBMeta( p_demux, p_dvbpsies->i_pid );
5189
5190         char const * psz_typedesc = "";
5191         switch(p_dvbpsies->i_type)
5192         {
5193         case 0x00:
5194             psz_typedesc = "ISO/IEC Reserved";
5195             break;
5196         case 0x01:
5197             psz_typedesc = "ISO/IEC 11172 Video";
5198             break;
5199         case 0x02:
5200             psz_typedesc = "ISO/IEC 13818-2 Video or ISO/IEC 11172-2 constrained parameter video stream";
5201             break;
5202         case 0x03:
5203             psz_typedesc = "ISO/IEC 11172 Audio";
5204             break;
5205         case 0x04:
5206             psz_typedesc = "ISO/IEC 13818-3 Audio";
5207             break;
5208         case 0x05:
5209             psz_typedesc = "ISO/IEC 13818-1 private_sections";
5210             break;
5211         case 0x06:
5212             psz_typedesc = "ISO/IEC 13818-1 PES packets containing private data";
5213             break;
5214         case 0x07:
5215             psz_typedesc = "ISO/IEC 13522 MHEG";
5216             break;
5217         case 0x08:
5218             psz_typedesc = "ISO/IEC 13818-1 Annex A DSM CC";
5219             break;
5220         case 0x09:
5221             psz_typedesc = "ITU-T Rec. H.222.1";
5222             break;
5223         case 0x0A:
5224             psz_typedesc = "ISO/IEC 13818-6 type A";
5225             break;
5226         case 0x0B:
5227             psz_typedesc = "ISO/IEC 13818-6 type B";
5228             break;
5229         case 0x0C:
5230             psz_typedesc = "ISO/IEC 13818-6 type C";
5231             break;
5232         case 0x0D:
5233             psz_typedesc = "ISO/IEC 13818-6 type D";
5234             break;
5235         case 0x0E:
5236             psz_typedesc = "ISO/IEC 13818-1 auxiliary";
5237             break;
5238         default:
5239             if (p_dvbpsies->i_type >= 0x0F && p_dvbpsies->i_type <=0x7F)
5240                 psz_typedesc = "ISO/IEC 13818-1 Reserved";
5241             else
5242                 psz_typedesc = "User Private";
5243         }
5244
5245         msg_Dbg( p_demux, "  * pid=%d type=0x%x %s",
5246                  p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
5247
5248         for( p_dr = p_dvbpsies->p_first_descriptor; p_dr != NULL;
5249              p_dr = p_dr->p_next )
5250         {
5251             msg_Dbg( p_demux, "    - descriptor tag 0x%x",
5252                      p_dr->i_tag );
5253         }
5254
5255         if ( !PIDSetup( p_demux, TYPE_PES, pespid, pmtpid ) )
5256         {
5257             msg_Warn( p_demux, "  * pid=%d type=0x%x %s (skipped)",
5258                       p_dvbpsies->i_pid, p_dvbpsies->i_type, psz_typedesc );
5259             continue;
5260         }
5261         else
5262         {
5263             if( b_reusing_pid )
5264             {
5265                 p_pes = ts_pes_New( p_demux );
5266                 if( !p_pes )
5267                     continue;
5268             }
5269             else
5270             {
5271                 p_pes = pespid->u.p_pes;
5272             }
5273         }
5274
5275         ARRAY_APPEND( p_pmt->e_streams, pespid );
5276
5277         PIDFillFormat( &p_pes->es.fmt, p_dvbpsies->i_type );
5278
5279         pespid->i_flags |= SEEN(p_sys->pid[p_dvbpsies->i_pid]);
5280
5281         bool b_registration_applied = false;
5282         if ( p_dvbpsies->i_type >= 0x80 ) /* non standard, extensions */
5283         {
5284             if ( registration_type == TS_PMT_REGISTRATION_HDMV )
5285             {
5286                 if (( b_registration_applied = PMTSetupEsHDMV( p_demux, &p_pes->es, p_dvbpsies ) ))
5287                     msg_Dbg( p_demux, "    + HDMV registration applied to pid %d type 0x%x",
5288                              p_dvbpsies->i_pid, p_dvbpsies->i_type );
5289             }
5290             else
5291             {
5292                 if (( b_registration_applied = PMTSetupEsRegistration( p_demux, &p_pes->es, p_dvbpsies ) ))
5293                     msg_Dbg( p_demux, "    + registration applied to pid %d type 0x%x",
5294                         p_dvbpsies->i_pid, p_dvbpsies->i_type );
5295             }
5296         }
5297
5298         if ( !b_registration_applied )
5299         {
5300             switch( p_dvbpsies->i_type )
5301             {
5302             case 0x06:
5303                 /* Handle PES private data */
5304                 PMTSetupEs0x06( p_demux, p_pes, p_dvbpsies );
5305                 break;
5306             /* All other private or reserved types */
5307             case 0x0f:
5308             case 0x10:
5309             case 0x11:
5310             case 0x12:
5311                 PMTSetupEsISO14496( p_demux, &p_pes->es, p_pmt, p_dvbpsies );
5312                 break;
5313             case 0x83:
5314                 /* LPCM (audio) */
5315                 PMTSetupEs0x83( p_dvbpsipmt, &p_pes->es, p_dvbpsies->i_pid );
5316                 break;
5317             case 0xa0:
5318                 PMTSetupEs0xA0( p_demux, &p_pes->es, p_dvbpsies );
5319                 break;
5320             case 0xd1:
5321                 PMTSetupEs0xD1( p_demux, &p_pes->es, p_dvbpsies );
5322                 break;
5323             case 0xEA:
5324                 PMTSetupEs0xEA( p_demux, &p_pes->es, p_dvbpsies );
5325             default:
5326                 break;
5327             }
5328         }
5329
5330         if( p_pes->es.fmt.i_cat == AUDIO_ES ||
5331             ( p_pes->es.fmt.i_cat == SPU_ES &&
5332               p_pes->es.fmt.i_codec != VLC_CODEC_DVBS &&
5333               p_pes->es.fmt.i_codec != VLC_CODEC_TELETEXT ) )
5334         {
5335             PMTParseEsIso639( p_demux, &p_pes->es, p_dvbpsies );
5336         }
5337
5338         switch( p_pes->es.fmt.i_codec )
5339         {
5340         case VLC_CODEC_SCTE_27:
5341             p_pes->data_type = TS_ES_DATA_TABLE_SECTION;
5342             break;
5343         default:
5344             //pid->es->data_type = TS_ES_DATA_PES;
5345             break;
5346         }
5347
5348         p_pes->es.fmt.i_group = p_dvbpsipmt->i_program_number;
5349         for( int i = 0; i < p_pes->extra_es.i_size; i++ )
5350             p_pes->extra_es.p_elems[i]->fmt.i_group = p_dvbpsipmt->i_program_number;
5351
5352         if( p_pes->es.fmt.i_cat == UNKNOWN_ES )
5353         {
5354             msg_Dbg( p_demux, "   => pid %d content is *unknown*",
5355                      p_dvbpsies->i_pid );
5356         }
5357         else
5358         {
5359             msg_Dbg( p_demux, "   => pid %d has now es fcc=%4.4s",
5360                      p_dvbpsies->i_pid, (char*)&p_pes->es.fmt.i_codec );
5361
5362             if( p_sys->b_es_id_pid ) p_pes->es.fmt.i_id = p_dvbpsies->i_pid;
5363
5364             /* Check if we can avoid restarting the ES */
5365             if( b_reusing_pid )
5366             {
5367                 /* p_pes points to a tmp pes */
5368                 if( pespid->u.p_pes->es.fmt.i_codec != p_pes->es.fmt.i_codec ||
5369                     pespid->u.p_pes->es.fmt.i_extra != p_pes->es.fmt.i_extra ||
5370                     pespid->u.p_pes->es.fmt.i_extra != 0 ||
5371                     pespid->u.p_pes->extra_es.i_size != p_pes->extra_es.i_size ||
5372                     !( ( !pespid->u.p_pes->es.fmt.psz_language &&
5373                         !p_pes->es.fmt.psz_language ) ||
5374                       ( pespid->u.p_pes->es.fmt.psz_language &&
5375                         p_pes->es.fmt.psz_language &&
5376                         !strcmp( pespid->u.p_pes->es.fmt.psz_language,
5377                                  p_pes->es.fmt.psz_language ) ) ) )
5378                 {
5379                     /* Differs, swap then */
5380                     ts_pes_t *e = pespid->u.p_pes;
5381                     pespid->u.p_pes = p_pes;
5382                     p_pes = e;
5383
5384                     /* p_pes still tmp, but now contains old config */
5385                     pespid->u.p_pes->es.id = p_pes->es.id;
5386                     if( pespid->u.p_pes->es.id )
5387                     {
5388                         p_pes->es.id = NULL;
5389                         es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
5390                                         pespid->u.p_pes->es.id, pespid->u.p_pes->es.fmt );
5391                     }
5392
5393                     for( int i=0; i<pespid->u.p_pes->extra_es.i_size &&
5394                                   i<p_pes->extra_es.i_size; i++ )
5395                     {
5396                         pespid->u.p_pes->extra_es.p_elems[i]->id = p_pes->extra_es.p_elems[i]->id;
5397                         if( pespid->u.p_pes->extra_es.p_elems[i]->id )
5398                         {
5399                             es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT,
5400                                             pespid->u.p_pes->extra_es.p_elems[i]->id,
5401                                             pespid->u.p_pes->extra_es.p_elems[i]->fmt );
5402                             p_pes->extra_es.p_elems[i]->id = NULL;
5403                         }
5404                     }
5405                 }
5406
5407                 ts_pes_Del( p_demux, p_pes ); // delete temp
5408             }
5409             else
5410             {
5411                 AddAndCreateES( p_demux, pespid );
5412             }
5413         }
5414
5415         p_dr = PMTEsFindDescriptor( p_dvbpsies, 0x09 );
5416         if( p_dr && p_dr->i_length >= 2 )
5417         {
5418             msg_Dbg( p_demux, "   * PMT descriptor : CA (0x9) SysID 0x%x",
5419                      (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
5420         }
5421
5422         if( ProgramIsSelected( p_demux, p_pmt->i_number ) && pespid->u.p_pes->es.id != NULL )
5423             SetPIDFilter( p_sys, pespid, true ); /* Set demux filter */
5424     }
5425
5426     /* Set CAM descrambling */
5427     if( !ProgramIsSelected( p_demux, p_pmt->i_number ) )
5428     {
5429         dvbpsi_pmt_delete( p_dvbpsipmt );
5430     }
5431     else if( stream_Control( p_sys->stream, STREAM_SET_PRIVATE_ID_CA,
5432                              p_dvbpsipmt ) != VLC_SUCCESS )
5433     {
5434         if ( p_sys->arib.e_mode == ARIBMODE_ENABLED )
5435         {
5436             p_sys->arib.b25stream = stream_FilterNew( p_demux->s, "aribcam" );
5437             p_sys->stream = ( p_sys->arib.b25stream ) ? p_sys->arib.b25stream : p_demux->s;
5438             if (!p_sys->arib.b25stream)
5439                 dvbpsi_pmt_delete( p_dvbpsipmt );
5440         } else dvbpsi_pmt_delete( p_dvbpsipmt );
5441     }
5442
5443     /* Decref or clean now unused es */
5444     for( int i = 0; i < old_es_rm.i_size; i++ )
5445         PIDRelease( p_demux, old_es_rm.p_elems[i] );
5446     ARRAY_RESET( old_es_rm );
5447
5448     if( !p_sys->b_trust_pcr )
5449     {
5450         int i_cand = FindPCRCandidate( p_pmt );
5451         p_pmt->i_pid_pcr = i_cand;
5452         p_pmt->pcr.b_disable = true;
5453         msg_Warn( p_demux, "PCR not trusted for program %d, set up workaround using pid %d",
5454                   p_pmt->i_number, i_cand );
5455     }
5456
5457     /* Probe Boundaries */
5458     if( p_sys->b_canfastseek && p_pmt->i_last_dts == -1 )
5459     {
5460         p_pmt->i_last_dts = 0;
5461         ProbeStart( p_demux, p_pmt->i_number );
5462         ProbeEnd( p_demux, p_pmt->i_number );
5463     }
5464 }
5465
5466 static int PATCheck( demux_t *p_demux, dvbpsi_pat_t *p_pat )
5467 {
5468     /* Some Dreambox streams have all PMT set to same pid */
5469     int i_prev_pid = -1;
5470     for( dvbpsi_pat_program_t * p_program = p_pat->p_first_program;
5471          p_program != NULL;
5472          p_program = p_program->p_next )
5473     {
5474         if( p_program->i_pid == i_prev_pid )
5475         {
5476             msg_Warn( p_demux, "PAT check failed: duplicate program pid %d", i_prev_pid );
5477             return VLC_EGENERIC;
5478         }
5479         i_prev_pid = p_program->i_pid;
5480     }
5481     return VLC_SUCCESS;
5482 }
5483
5484 static void PATCallBack( void *data, dvbpsi_pat_t *p_dvbpsipat )
5485 {
5486     demux_t              *p_demux = data;
5487     demux_sys_t          *p_sys = p_demux->p_sys;
5488     dvbpsi_pat_program_t *p_program;
5489     ts_pid_t             *patpid = &p_sys->pid[0];
5490     ts_pat_t             *p_pat = p_sys->pid[0].u.p_pat;
5491
5492     patpid->i_flags |= FLAG_SEEN;
5493
5494     msg_Dbg( p_demux, "PATCallBack called" );
5495
5496     if(unlikely( p_sys->pid[0].type != TYPE_PAT ))
5497     {
5498         msg_Warn( p_demux, "PATCallBack called on invalid pid" );
5499         return;
5500     }
5501
5502     if( ( p_pat->i_version != -1 &&
5503             ( !p_dvbpsipat->b_current_next ||
5504               p_dvbpsipat->i_version == p_pat->i_version ) ) ||
5505         ( p_pat->i_ts_id != -1 && p_dvbpsipat->i_ts_id != p_pat->i_ts_id ) ||
5506         p_sys->b_user_pmt || PATCheck( p_demux, p_dvbpsipat ) )
5507     {
5508         dvbpsi_pat_delete( p_dvbpsipat );
5509         return;
5510     }
5511
5512     msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
5513              p_dvbpsipat->i_ts_id, p_dvbpsipat->i_version, p_dvbpsipat->b_current_next );
5514
5515     /* Save old programs array */
5516     DECL_ARRAY(ts_pid_t *) old_pmt_rm;
5517     old_pmt_rm.i_alloc = p_pat->programs.i_alloc;
5518     old_pmt_rm.i_size = p_pat->programs.i_size;
5519     old_pmt_rm.p_elems = p_pat->programs.p_elems;
5520     ARRAY_INIT(p_pat->programs);
5521
5522     /* now create programs */
5523     for( p_program = p_dvbpsipat->p_first_program; p_program != NULL;
5524          p_program = p_program->p_next )
5525     {
5526         msg_Dbg( p_demux, "  * number=%d pid=%d", p_program->i_number,
5527                  p_program->i_pid );
5528         if( p_program->i_number == 0 )
5529             continue;
5530
5531         ts_pid_t *pmtpid = &p_sys->pid[p_program->i_pid];
5532
5533         ValidateDVBMeta( p_demux, p_program->i_pid );
5534
5535         /* create or temporary incref pid */
5536         if( !PIDSetup( p_demux, TYPE_PMT, pmtpid, patpid ) )
5537         {
5538             msg_Warn( p_demux, "  * number=%d pid=%d (ignored)", p_program->i_number,
5539                      p_program->i_pid );
5540             continue;
5541         }
5542
5543         pmtpid->u.p_pmt->i_number = p_program->i_number;
5544
5545         if( !dvbpsi_pmt_attach( pmtpid->u.p_pmt->handle, p_program->i_number, PMTCallBack, p_demux ) )
5546             msg_Err( p_demux, "PATCallback failed attaching PMTCallback to program %d",
5547                      p_program->i_number );
5548
5549         ARRAY_APPEND( p_pat->programs, pmtpid );
5550
5551         /* Now select PID at access level */
5552         if( p_sys->programs.i_size == 0 ||
5553             ProgramIsSelected( p_demux, p_program->i_number ) )
5554         {
5555             if( p_sys->programs.i_size == 0 )
5556             {
5557                 p_sys->b_default_selection = true;
5558                 ARRAY_APPEND( p_sys->programs, p_program->i_number );
5559             }
5560
5561             if( SetPIDFilter( p_sys, pmtpid, true ) )
5562                 p_sys->b_access_control = false;
5563             else if ( p_sys->es_creation == DELAY_ES )
5564                 p_sys->es_creation = CREATE_ES;
5565         }
5566     }
5567     p_pat->i_version = p_dvbpsipat->i_version;
5568     p_pat->i_ts_id = p_dvbpsipat->i_ts_id;
5569
5570     for(int i=0; i<old_pmt_rm.i_size; i++)
5571     {
5572         /* decref current or release now unreferenced */
5573         PIDRelease( p_demux, old_pmt_rm.p_elems[i] );
5574     }
5575     ARRAY_RESET(old_pmt_rm);
5576
5577     dvbpsi_pat_delete( p_dvbpsipat );
5578 }
5579
5580 static inline bool handle_Init( demux_t *p_demux, dvbpsi_t **handle )
5581 {
5582     *handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
5583     if( !*handle )
5584         return false;
5585     (*handle)->p_sys = (void *) p_demux;
5586     return true;
5587 }
5588
5589 static ts_pat_t *ts_pat_New( demux_t *p_demux )
5590 {
5591     ts_pat_t *pat = malloc( sizeof( ts_pat_t ) );
5592     if( !pat )
5593         return NULL;
5594
5595     if( !handle_Init( p_demux, &pat->handle ) )
5596     {
5597         free( pat );
5598         return NULL;
5599     }
5600
5601     pat->i_version  = -1;
5602     pat->i_ts_id    = -1;
5603     ARRAY_INIT( pat->programs );
5604
5605     return pat;
5606 }
5607
5608 static void ts_pat_Del( demux_t *p_demux, ts_pat_t *pat )
5609 {
5610     if( dvbpsi_decoder_present( pat->handle ) )
5611         dvbpsi_pat_detach( pat->handle );
5612     dvbpsi_delete( pat->handle );
5613     for( int i=0; i<pat->programs.i_size; i++ )
5614         PIDRelease( p_demux, pat->programs.p_elems[i] );
5615     ARRAY_RESET( pat->programs );
5616     free( pat );
5617 }
5618
5619 static ts_pmt_t *ts_pmt_New( demux_t *p_demux )
5620 {
5621     ts_pmt_t *pmt = malloc( sizeof( ts_pmt_t ) );
5622     if( !pmt )
5623         return NULL;
5624
5625     if( !handle_Init( p_demux, &pmt->handle ) )
5626     {
5627         free( pmt );
5628         return NULL;
5629     }
5630
5631     ARRAY_INIT( pmt->e_streams );
5632
5633     pmt->i_version  = -1;
5634     pmt->i_number   = -1;
5635     pmt->i_pid_pcr  = -1;
5636     pmt->iod        = NULL;
5637
5638     pmt->i_last_dts = -1;
5639
5640     pmt->pcr.i_current = -1;
5641     pmt->pcr.i_first  = -1;
5642     pmt->pcr.b_disable = false;
5643     pmt->pcr.i_first_dts = VLC_TS_INVALID;
5644     pmt->pcr.i_pcroffset = -1;
5645
5646     return pmt;
5647 }
5648
5649 static void ts_pmt_Del( demux_t *p_demux, ts_pmt_t *pmt )
5650 {
5651     if( dvbpsi_decoder_present( pmt->handle ) )
5652         dvbpsi_pmt_detach( pmt->handle );
5653     dvbpsi_delete( pmt->handle );
5654     for( int i=0; i<pmt->e_streams.i_size; i++ )
5655         PIDRelease( p_demux, pmt->e_streams.p_elems[i] );
5656     ARRAY_RESET( pmt->e_streams );
5657     if( pmt->iod )
5658         IODFree( pmt->iod );
5659     es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, pmt->i_number );
5660     free( pmt );
5661 }
5662
5663 static ts_pes_t *ts_pes_New( demux_t *p_demux )
5664 {
5665     VLC_UNUSED(p_demux);
5666     ts_pes_t *pes = malloc( sizeof( ts_pes_t ) );
5667     if( !pes )
5668         return NULL;
5669
5670     pes->es.id = NULL;
5671     pes->es.p_mpeg4desc = NULL;
5672     es_format_Init( &pes->es.fmt, UNKNOWN_ES, 0 );
5673     ARRAY_INIT( pes->extra_es );
5674     pes->data_type = TS_ES_DATA_PES;
5675     pes->i_data_size = 0;
5676     pes->i_data_gathered = 0;
5677     pes->p_data = NULL;
5678     pes->pp_last = &pes->p_data;
5679     pes->p_prepcr_outqueue = NULL;
5680
5681     return pes;
5682 }
5683
5684 static void ts_pes_Del( demux_t *p_demux, ts_pes_t *pes )
5685 {
5686     if( pes->es.id )
5687     {
5688         es_out_Del( p_demux->out, pes->es.id );
5689         p_demux->p_sys->i_pmt_es--;
5690     }
5691
5692     if( pes->p_data )
5693         block_ChainRelease( pes->p_data );
5694
5695     if( pes->p_prepcr_outqueue )
5696         block_ChainRelease( pes->p_prepcr_outqueue );
5697
5698     es_format_Clean( &pes->es.fmt );
5699     free( pes->es.p_mpeg4desc );
5700
5701     for( int i = 0; i < pes->extra_es.i_size; i++ )
5702     {
5703         if( pes->extra_es.p_elems[i]->id )
5704         {
5705             es_out_Del( p_demux->out, pes->extra_es.p_elems[i]->id );
5706             p_demux->p_sys->i_pmt_es--;
5707         }
5708         es_format_Clean( &pes->extra_es.p_elems[i]->fmt );
5709         free( pes->extra_es.p_elems[i] );
5710     }
5711     ARRAY_RESET( pes->extra_es );
5712
5713     free( pes );
5714 }
5715
5716 static ts_psi_t *ts_psi_New( demux_t *p_demux )
5717 {
5718     ts_psi_t *psi = malloc( sizeof( ts_psi_t ) );
5719     if( !psi )
5720         return NULL;
5721
5722     if( !handle_Init( p_demux, &psi->handle ) )
5723     {
5724         free( psi );
5725         return NULL;
5726     }
5727
5728     psi->i_version  = -1;
5729
5730     return psi;
5731 }
5732
5733 static void ts_psi_Del( demux_t *p_demux, ts_psi_t *psi )
5734 {
5735     VLC_UNUSED(p_demux);
5736     if( dvbpsi_decoder_present( psi->handle ) )
5737         dvbpsi_DetachDemux( psi->handle );
5738     dvbpsi_delete( psi->handle );
5739     free( psi );
5740 }