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