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