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