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