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