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