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