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