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