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