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