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