]> git.sesse.net Git - vlc/blob - modules/demux/ts.c
demux: ts: fix IOD parsing (fix #11573)
[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
38 #include <vlc_access.h>    /* DVB-specific things */
39 #include <vlc_demux.h>
40 #include <vlc_meta.h>
41 #include <vlc_epg.h>
42 #include <vlc_charset.h>   /* FromCharset, for EIT */
43
44 #include "../mux/mpeg/csa.h"
45
46 /* Include dvbpsi headers */
47 # include <dvbpsi/dvbpsi.h>
48 # include <dvbpsi/demux.h>
49 # include <dvbpsi/descriptor.h>
50 # include <dvbpsi/pat.h>
51 # include <dvbpsi/pmt.h>
52 # include <dvbpsi/sdt.h>
53 # include <dvbpsi/dr.h>
54 # include <dvbpsi/psi.h>
55
56 /* EIT support */
57 # include <dvbpsi/eit.h>
58
59 /* TDT support */
60 # include <dvbpsi/tot.h>
61
62 #include "../mux/mpeg/dvbpsi_compat.h"
63
64 #undef TS_DEBUG
65 VLC_FORMAT(1, 2) static void ts_debug(const char *format, ...)
66 {
67 #ifdef TS_DEBUG
68     va_list ap;
69     va_start(ap, format);
70     vfprintf(stderr, format, ap);
71     va_end(ap);
72 #else
73     (void)format;
74 #endif
75 }
76
77 /*****************************************************************************
78  * Module descriptor
79  *****************************************************************************/
80 static int  Open  ( vlc_object_t * );
81 static void Close ( vlc_object_t * );
82
83 /* TODO
84  * - Rename "extra pmt" to "user pmt"
85  * - Update extra pmt description
86  *      pmt_pid[:pmt_number][=pid_description[,pid_description]]
87  *      where pid_description could take 3 forms:
88  *          1. pid:pcr (to force the pcr pid)
89  *          2. pid:stream_type
90  *          3. pid:type=fourcc where type=(video|audio|spu)
91  */
92 #define PMT_TEXT N_("Extra PMT")
93 #define PMT_LONGTEXT N_( \
94   "Allows a user to specify an extra pmt (pmt_pid=pid:stream_type[,...])." )
95
96 #define PID_TEXT N_("Set id of ES to PID")
97 #define PID_LONGTEXT N_("Set the internal ID of each elementary stream" \
98                        " handled by VLC to the same value as the PID in" \
99                        " the TS stream, instead of 1, 2, 3, etc. Useful to" \
100                        " do \'#duplicate{..., select=\"es=<pid>\"}\'.")
101
102 #define TSOUT_TEXT N_("Fast udp streaming")
103 #define TSOUT_LONGTEXT N_( \
104   "Sends TS to specific ip:port by udp (you must know what you are doing).")
105
106 #define MTUOUT_TEXT N_("MTU for out mode")
107 #define MTUOUT_LONGTEXT N_("MTU for out mode.")
108
109 #define CSA_TEXT N_("CSA Key")
110 #define CSA_LONGTEXT N_("CSA encryption key. This must be a " \
111   "16 char string (8 hexadecimal bytes).")
112
113 #define CSA2_TEXT N_("Second CSA Key")
114 #define CSA2_LONGTEXT N_("The even CSA encryption key. This must be a " \
115   "16 char string (8 hexadecimal bytes).")
116
117
118 #define CPKT_TEXT N_("Packet size in bytes to decrypt")
119 #define CPKT_LONGTEXT N_("Specify the size of the TS packet to decrypt. " \
120     "The decryption routines subtract the TS-header from the value before " \
121     "decrypting. " )
122
123 #define SPLIT_ES_TEXT N_("Separate sub-streams")
124 #define SPLIT_ES_LONGTEXT N_( \
125     "Separate teletex/dvbs pages into independent ES. " \
126     "It can be useful to turn off this option when using stream output." )
127
128 #define SEEK_PERCENT_TEXT N_("Seek based on percent not time")
129 #define SEEK_PERCENT_LONGTEXT N_( \
130     "Seek and position based on a percent byte position, not a PCR generated " \
131     "time position. If seeking doesn't work property, turn on this option." )
132
133 #define PCR_TEXT N_("Trust in-stream PCR")
134 #define PCR_LONGTEXT N_("Use the stream PCR as a reference.")
135
136 vlc_module_begin ()
137     set_description( N_("MPEG Transport Stream demuxer") )
138     set_shortname ( "MPEG-TS" )
139     set_category( CAT_INPUT )
140     set_subcategory( SUBCAT_INPUT_DEMUX )
141
142     add_string( "ts-extra-pmt", NULL, PMT_TEXT, PMT_LONGTEXT, true )
143     add_bool( "ts-trust-pcr", true, PCR_TEXT, PCR_LONGTEXT, true )
144         change_safe()
145     add_bool( "ts-es-id-pid", true, PID_TEXT, PID_LONGTEXT, true )
146         change_safe()
147     add_obsolete_string( "ts-out" ) /* since 2.2.0 */
148     add_obsolete_integer( "ts-out-mtu" ) /* since 2.2.0 */
149     add_string( "ts-csa-ck", NULL, CSA_TEXT, CSA_LONGTEXT, true )
150         change_safe()
151     add_string( "ts-csa2-ck", NULL, CSA2_TEXT, CSA2_LONGTEXT, true )
152         change_safe()
153     add_integer( "ts-csa-pkt", 188, CPKT_TEXT, CPKT_LONGTEXT, true )
154         change_safe()
155
156     add_bool( "ts-split-es", true, SPLIT_ES_TEXT, SPLIT_ES_LONGTEXT, false )
157     add_bool( "ts-seek-percent", false, SEEK_PERCENT_TEXT, SEEK_PERCENT_LONGTEXT, true )
158
159     add_obsolete_bool( "ts-silent" );
160
161     set_capability( "demux", 10 )
162     set_callbacks( Open, Close )
163     add_shortcut( "ts" )
164 vlc_module_end ()
165
166 /*****************************************************************************
167  * Local prototypes
168  *****************************************************************************/
169 static const char *const ppsz_teletext_type[] = {
170  "",
171  N_("Teletext"),
172  N_("Teletext subtitles"),
173  N_("Teletext: additional information"),
174  N_("Teletext: program schedule"),
175  N_("Teletext subtitles: hearing impaired")
176 };
177
178 typedef struct
179 {
180     uint8_t                 i_objectTypeIndication;
181     uint8_t                 i_streamType;
182
183     int                     i_extra;
184     uint8_t                 *p_extra;
185
186 } decoder_config_descriptor_t;
187
188 typedef struct
189 {
190     bool                    b_ok;
191     uint16_t                i_es_id;
192
193     char                    *psz_url;
194
195     decoder_config_descriptor_t    dec_descr;
196
197 } es_mpeg4_descriptor_t;
198
199 #define ES_DESCRIPTOR_COUNT 255
200 typedef struct
201 {
202     /* IOD */
203     char                    *psz_url;
204
205     es_mpeg4_descriptor_t   es_descr[ES_DESCRIPTOR_COUNT];
206
207 } iod_descriptor_t;
208
209 typedef struct
210 {
211     dvbpsi_handle   handle;
212     int             i_version;
213     int             i_number;
214     int             i_pid_pcr;
215     int             i_pid_pmt;
216     mtime_t         i_pcr_value;
217     /* IOD stuff (mpeg4) */
218     iod_descriptor_t *iod;
219
220 } ts_prg_psi_t;
221
222 typedef struct
223 {
224     /* for special PAT/SDT case */
225     dvbpsi_handle   handle; /* PAT/SDT/EIT */
226     int             i_pat_version;
227     int             i_sdt_version;
228
229     /* For PMT */
230     int             i_prg;
231     ts_prg_psi_t    **prg;
232
233 } ts_psi_t;
234
235 typedef enum
236 {
237     TS_ES_DATA_PES,
238     TS_ES_DATA_TABLE_SECTION
239 } ts_es_data_type_t;
240
241 typedef enum
242 {
243     TS_REGISTRATION_OTHER = 0,
244     TS_REGISTRATION_HDMV
245 } ts_registration_type_t;
246
247 typedef struct
248 {
249     es_format_t  fmt;
250     es_out_id_t *id;
251     ts_es_data_type_t data_type;
252     int         i_data_size;
253     int         i_data_gathered;
254     block_t     *p_data;
255     block_t     **pp_last;
256
257     es_mpeg4_descriptor_t *p_mpeg4desc;
258
259 } ts_es_t;
260
261 typedef struct
262 {
263     int         i_pid;
264
265     bool        b_seen;
266     bool        b_valid;
267     int         i_cc;   /* countinuity counter */
268     bool        b_scrambled;
269
270     /* PSI owner (ie PMT -> PAT, ES -> PMT */
271     ts_psi_t   *p_owner;
272     int         i_owner_number;
273
274     /* */
275     ts_psi_t    *psi;
276     ts_es_t     *es;
277
278     /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
279     ts_es_t     **extra_es;
280     int         i_extra_es;
281
282 } ts_pid_t;
283
284 struct demux_sys_t
285 {
286     vlc_mutex_t     csa_lock;
287
288     /* TS packet size (188, 192, 204) */
289     int         i_packet_size;
290
291     /* Additional TS packet header size (BluRay TS packets have 4-byte header before sync byte) */
292     int         i_packet_header_size;
293
294     /* how many TS packet we read at once */
295     int         i_ts_read;
296
297     /* to determine length and time */
298     int         i_pid_ref_pcr;
299     mtime_t     i_first_pcr;
300     mtime_t     i_current_pcr;
301     mtime_t     i_last_pcr;
302     bool        b_force_seek_per_percent;
303     int         i_pcrs_num;
304     mtime_t     *p_pcrs;
305     int64_t     *p_pos;
306
307     /* All pid */
308     ts_pid_t    pid[8192];
309
310     /* All PMT */
311     bool        b_user_pmt;
312     int         i_pmt;
313     ts_pid_t    **pmt;
314     int         i_pmt_es;
315
316     /* */
317     bool        b_es_id_pid;
318     csa_t       *csa;
319     int         i_csa_pkt_size;
320     bool        b_split_es;
321
322     bool        b_trust_pcr;
323
324     /* */
325     bool        b_access_control;
326
327     /* */
328     bool        b_dvb_meta;
329     int64_t     i_tdt_delta;
330     int64_t     i_dvb_start;
331     int64_t     i_dvb_length;
332     bool        b_broken_charset; /* True if broken encoding is used in EPG/SDT */
333
334     /* */
335     int         i_current_program;
336     vlc_list_t  programs_list;
337
338     /* */
339     bool        b_start_record;
340 };
341
342 static int Demux    ( demux_t *p_demux );
343 static int Control( demux_t *p_demux, int i_query, va_list args );
344
345 static void PIDInit ( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner );
346 static void PIDClean( demux_t *, ts_pid_t *pid );
347 static void PIDFillFormat( es_format_t *fmt, int i_stream_type );
348
349 static void PATCallBack( void*, dvbpsi_pat_t * );
350 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt );
351 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
352 static void PSINewTableCallBack( dvbpsi_t *handle, uint8_t  i_table_id,
353                                  uint16_t i_extension, demux_t * );
354 #else
355 static void PSINewTableCallBack( demux_t *, dvbpsi_handle,
356                                  uint8_t  i_table_id, uint16_t i_extension );
357 #endif
358
359 static int ChangeKeyCallback( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
360
361 static inline int PIDGet( block_t *p )
362 {
363     return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
364 }
365
366 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
367
368 static block_t* ReadTSPacket( demux_t *p_demux );
369 static int Seek( demux_t *p_demux, double f_percent );
370 static void GetFirstPCR( demux_t *p_demux );
371 static void GetLastPCR( demux_t *p_demux );
372 static void CheckPCR( demux_t *p_demux );
373 static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );
374
375 static void              IODFree( iod_descriptor_t * );
376
377 #define TS_USER_PMT_NUMBER (0)
378 static int UserPmt( demux_t *p_demux, const char * );
379
380 static int  SetPIDFilter( demux_t *, int i_pid, bool b_selected );
381 static void SetPrgFilter( demux_t *, int i_prg, bool b_selected );
382
383 #define TS_PACKET_SIZE_188 188
384 #define TS_PACKET_SIZE_192 192
385 #define TS_PACKET_SIZE_204 204
386 #define TS_PACKET_SIZE_MAX 204
387 #define TS_TOPFIELD_HEADER 1320
388
389 static int DetectPacketSize( demux_t *p_demux, int *pi_header_size )
390 {
391     const uint8_t *p_peek;
392     if( stream_Peek( p_demux->s,
393                      &p_peek, TS_PACKET_SIZE_MAX ) < TS_PACKET_SIZE_MAX )
394         return -1;
395
396     *pi_header_size = 0;
397
398     if( memcmp( p_peek, "TFrc", 4 ) == 0 )
399     {
400 #if 0
401         /* I used the TF5000PVR 2004 Firmware .doc header documentation,
402          * http://www.i-topfield.com/data/product/firmware/Structure%20of%20Recorded%20File%20in%20TF5000PVR%20(Feb%2021%202004).doc
403          * but after the filename the offsets seem to be incorrect.  - DJ */
404         int i_duration, i_name;
405         char *psz_name = xmalloc(25);
406         char *psz_event_name;
407         char *psz_event_text = xmalloc(130);
408         char *psz_ext_text = xmalloc(1025);
409
410         // 2 bytes version Uimsbf (4,5)
411         // 2 bytes reserved (6,7)
412         // 2 bytes duration in minutes Uimsbf (8,9(
413         i_duration = (int) (p_peek[8] << 8) | p_peek[9];
414         msg_Dbg( p_demux, "Topfield recording length: +/- %d minutes", i_duration);
415         // 2 bytes service number in channel list (10, 11)
416         // 2 bytes service type Bslbf 0=TV 1=Radio Bslb (12, 13)
417         // 4 bytes of reserved + tuner info (14,15,16,17)
418         // 2 bytes of Service ID  Bslbf (18,19)
419         // 2 bytes of PMT PID  Uimsbf (20,21)
420         // 2 bytes of PCR PID  Uimsbf (22,23)
421         // 2 bytes of Video PID  Uimsbf (24,25)
422         // 2 bytes of Audio PID  Uimsbf (26,27)
423         // 24 bytes filename Bslbf
424         memcpy( psz_name, &p_peek[28], 24 );
425         psz_name[24] = '\0';
426         msg_Dbg( p_demux, "recordingname=%s", psz_name );
427         // 1 byte of sat index Uimsbf  (52)
428         // 3 bytes (1 bit of polarity Bslbf +23 bits reserved)
429         // 4 bytes of freq. Uimsbf (56,57,58,59)
430         // 2 bytes of symbol rate Uimsbf (60,61)
431         // 2 bytes of TS stream ID Uimsbf (62,63)
432         // 4 bytes reserved
433         // 2 bytes reserved
434         // 2 bytes duration Uimsbf (70,71)
435         //i_duration = (int) (p_peek[70] << 8) | p_peek[71];
436         //msg_Dbg( p_demux, "Topfield 2nd duration field: +/- %d minutes", i_duration);
437         // 4 bytes EventID Uimsbf (72-75)
438         // 8 bytes of Start and End time info (76-83)
439         // 1 byte reserved (84)
440         // 1 byte event name length Uimsbf (89)
441         i_name = (int)(p_peek[89]&~0x81);
442         msg_Dbg( p_demux, "event name length = %d", i_name);
443         psz_event_name = xmalloc( i_name+1 );
444         // 1 byte parental rating (90)
445         // 129 bytes of event text
446         memcpy( psz_event_name, &p_peek[91], i_name );
447         psz_event_name[i_name] = '\0';
448         memcpy( psz_event_text, &p_peek[91+i_name], 129-i_name );
449         psz_event_text[129-i_name] = '\0';
450         msg_Dbg( p_demux, "event name=%s", psz_event_name );
451         msg_Dbg( p_demux, "event text=%s", psz_event_text );
452         // 12 bytes reserved (220)
453         // 6 bytes reserved
454         // 2 bytes Event Text Length Uimsbf
455         // 4 bytes EventID Uimsbf
456         // FIXME We just have 613 bytes. not enough for this entire text
457         // 1024 bytes Extended Event Text Bslbf
458         memcpy( psz_ext_text, p_peek+372, 1024 );
459         psz_ext_text[1024] = '\0';
460         msg_Dbg( p_demux, "extended event text=%s", psz_ext_text );
461         // 52 bytes reserved Bslbf
462 #endif
463         msg_Dbg( p_demux, "this is a topfield file" );
464         return TS_PACKET_SIZE_188;
465     }
466
467     for( int i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
468     {
469         if( p_peek[i_sync] != 0x47 )
470             continue;
471
472         /* Check next 3 sync bytes */
473         int i_peek = TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
474         if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
475         {
476             msg_Err( p_demux, "cannot peek" );
477             return -1;
478         }
479         if( p_peek[i_sync + 1 * TS_PACKET_SIZE_188] == 0x47 &&
480             p_peek[i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
481             p_peek[i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
482         {
483             return TS_PACKET_SIZE_188;
484         }
485         else if( p_peek[i_sync + 1 * TS_PACKET_SIZE_192] == 0x47 &&
486                  p_peek[i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
487                  p_peek[i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
488         {
489             if( i_sync == 4 )
490             {
491                 *pi_header_size = 4; /* BluRay TS packets have 4-byte header */
492             }
493             return TS_PACKET_SIZE_192;
494         }
495         else if( p_peek[i_sync + 1 * TS_PACKET_SIZE_204] == 0x47 &&
496                  p_peek[i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
497                  p_peek[i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
498         {
499             return TS_PACKET_SIZE_204;
500         }
501     }
502
503     if( p_demux->b_force )
504     {
505         msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
506         return TS_PACKET_SIZE_188;
507     }
508     msg_Dbg( p_demux, "TS module discarded (lost sync)" );
509     return -1;
510 }
511
512 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
513 static void vlc_dvbpsi_reset( demux_t *p_demux )
514 {
515     demux_sys_t *p_sys = p_demux->p_sys;
516
517     ts_pid_t *pat = &p_sys->pid[0];
518     ts_pid_t *sdt = &p_sys->pid[0x11];
519     ts_pid_t *eit = &p_sys->pid[0x12];
520     ts_pid_t *tdt = &p_sys->pid[0x14];
521
522     if( pat->psi->handle )
523     {
524         if( dvbpsi_decoder_present( pat->psi->handle ) )
525             dvbpsi_pat_detach( pat->psi->handle );
526         dvbpsi_delete( pat->psi->handle );
527         pat->psi->handle = NULL;
528     }
529
530     if( sdt->psi->handle )
531     {
532         if( dvbpsi_decoder_present( sdt->psi->handle ) )
533             dvbpsi_DetachDemux( sdt->psi->handle );
534         dvbpsi_delete( sdt->psi->handle );
535         sdt->psi->handle = NULL;
536     }
537
538     if( eit->psi->handle )
539     {
540         if( dvbpsi_decoder_present( eit->psi->handle ) )
541             dvbpsi_DetachDemux( eit->psi->handle );
542         dvbpsi_delete( eit->psi->handle );
543         eit->psi->handle = NULL;
544     }
545
546     if( tdt->psi->handle )
547     {
548         if( dvbpsi_decoder_present( tdt->psi->handle ) )
549             dvbpsi_DetachDemux( tdt->psi->handle );
550         dvbpsi_delete( tdt->psi->handle );
551         tdt->psi->handle = NULL;
552     }
553 }
554 #endif
555
556 /*****************************************************************************
557  * Open
558  *****************************************************************************/
559 static int Open( vlc_object_t *p_this )
560 {
561     demux_t     *p_demux = (demux_t*)p_this;
562     demux_sys_t *p_sys;
563
564     int          i_packet_size, i_packet_header_size = 0;
565
566     ts_pid_t    *pat;
567
568     /* Search first sync byte */
569     i_packet_size = DetectPacketSize( p_demux, &i_packet_header_size );
570     if( i_packet_size < 0 )
571         return VLC_EGENERIC;
572
573     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
574     if( !p_sys )
575         return VLC_ENOMEM;
576     memset( p_sys, 0, sizeof( demux_sys_t ) );
577     vlc_mutex_init( &p_sys->csa_lock );
578
579     p_demux->pf_demux = Demux;
580     p_demux->pf_control = Control;
581
582     /* Init p_sys field */
583     p_sys->b_dvb_meta = true;
584     p_sys->b_access_control = true;
585     p_sys->i_current_program = 0;
586     p_sys->programs_list.i_count = 0;
587     p_sys->programs_list.p_values = NULL;
588     p_sys->i_tdt_delta = 0;
589     p_sys->i_dvb_start = 0;
590     p_sys->i_dvb_length = 0;
591
592     p_sys->b_broken_charset = false;
593
594     for( int i = 0; i < 8192; i++ )
595     {
596         ts_pid_t *pid = &p_sys->pid[i];
597         pid->i_pid      = i;
598         pid->b_seen     = false;
599         pid->b_valid    = false;
600     }
601     /* PID 8191 is padding */
602     p_sys->pid[8191].b_seen = true;
603     p_sys->i_packet_size = i_packet_size;
604     p_sys->i_packet_header_size = i_packet_header_size;
605     p_sys->i_ts_read = 50;
606     p_sys->csa = NULL;
607     p_sys->b_start_record = false;
608
609 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
610 # define VLC_DVBPSI_DEMUX_TABLE_INIT(table,obj) \
611     do { \
612         (table)->psi->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG ); \
613         if( ! (table)->psi->handle ) \
614         { \
615             vlc_mutex_destroy( &p_sys->csa_lock ); \
616             free( p_sys ); \
617             return VLC_ENOMEM; \
618         } \
619         (table)->psi->handle->p_sys = (void *) VLC_OBJECT(obj); \
620         if( !dvbpsi_AttachDemux( (table)->psi->handle, (dvbpsi_demux_new_cb_t)PSINewTableCallBack, (obj) ) ) \
621         { \
622             vlc_dvbpsi_reset( obj ); \
623             vlc_mutex_destroy( &p_sys->csa_lock ); \
624             free( p_sys ); \
625             return VLC_EGENERIC; \
626         } \
627     } while (0);
628 #endif
629
630     /* Init PAT handler */
631     pat = &p_sys->pid[0];
632     PIDInit( pat, true, NULL );
633 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
634     pat->psi->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
635     if( !pat->psi->handle )
636     {
637         vlc_mutex_destroy( &p_sys->csa_lock );
638         free( p_sys );
639         return VLC_ENOMEM;
640     }
641     pat->psi->handle->p_sys = (void *) p_demux;
642     if( !dvbpsi_pat_attach( pat->psi->handle, PATCallBack, p_demux ) )
643     {
644         vlc_dvbpsi_reset( p_demux );
645         vlc_mutex_destroy( &p_sys->csa_lock );
646         free( p_sys );
647         return VLC_EGENERIC;
648     }
649 #else
650     pat->psi->handle = dvbpsi_AttachPAT( PATCallBack, p_demux );
651 #endif
652     if( p_sys->b_dvb_meta )
653     {
654         ts_pid_t *sdt = &p_sys->pid[0x11];
655         ts_pid_t *eit = &p_sys->pid[0x12];
656
657         PIDInit( sdt, true, NULL );
658 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
659         VLC_DVBPSI_DEMUX_TABLE_INIT( sdt, p_demux )
660 #else
661         sdt->psi->handle =
662             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
663                                 p_demux );
664 #endif
665         PIDInit( eit, true, NULL );
666 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
667         VLC_DVBPSI_DEMUX_TABLE_INIT( eit, p_demux )
668 #else
669         eit->psi->handle =
670             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
671                                 p_demux );
672 #endif
673         ts_pid_t *tdt = &p_sys->pid[0x14];
674         PIDInit( tdt, true, NULL );
675 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
676         VLC_DVBPSI_DEMUX_TABLE_INIT( tdt, p_demux )
677 #else
678         tdt->psi->handle =
679             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
680                                 p_demux );
681 #endif
682
683         if( p_sys->b_access_control )
684         {
685             if( SetPIDFilter( p_demux, 0x11, true ) ||
686                 SetPIDFilter( p_demux, 0x14, true ) ||
687                 SetPIDFilter( p_demux, 0x12, true ) )
688                 p_sys->b_access_control = false;
689         }
690     }
691
692 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
693 # undef VLC_DVBPSI_DEMUX_TABLE_INIT
694 #endif
695
696     /* Init PMT array */
697     TAB_INIT( p_sys->i_pmt, p_sys->pmt );
698     p_sys->i_pmt_es = 0;
699
700     /* Read config */
701     p_sys->b_es_id_pid = var_CreateGetBool( p_demux, "ts-es-id-pid" );
702
703     p_sys->b_trust_pcr = var_CreateGetBool( p_demux, "ts-trust-pcr" );
704
705     /* We handle description of an extra PMT */
706     char* psz_string = var_CreateGetString( p_demux, "ts-extra-pmt" );
707     p_sys->b_user_pmt = false;
708     if( psz_string && *psz_string )
709         UserPmt( p_demux, psz_string );
710     free( psz_string );
711
712     psz_string = var_CreateGetStringCommand( p_demux, "ts-csa-ck" );
713     if( psz_string && *psz_string )
714     {
715         int i_res;
716         char* psz_csa2;
717
718         p_sys->csa = csa_New();
719
720         psz_csa2 = var_CreateGetStringCommand( p_demux, "ts-csa2-ck" );
721         i_res = csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, true );
722         if( i_res == VLC_SUCCESS && psz_csa2 && *psz_csa2 )
723         {
724             if( csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_csa2, false ) != VLC_SUCCESS )
725             {
726                 csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
727             }
728         }
729         else if ( i_res == VLC_SUCCESS )
730         {
731             csa_SetCW( (vlc_object_t*)p_demux, p_sys->csa, psz_string, false );
732         }
733         else
734         {
735             csa_Delete( p_sys->csa );
736             p_sys->csa = NULL;
737         }
738
739         if( p_sys->csa )
740         {
741             var_AddCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, (void *)1 );
742             var_AddCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
743
744             int i_pkt = var_CreateGetInteger( p_demux, "ts-csa-pkt" );
745             if( i_pkt < 4 || i_pkt > 188 )
746             {
747                 msg_Err( p_demux, "wrong packet size %d specified.", i_pkt );
748                 msg_Warn( p_demux, "using default packet size of 188 bytes" );
749                 p_sys->i_csa_pkt_size = 188;
750             }
751             else
752                 p_sys->i_csa_pkt_size = i_pkt;
753             msg_Dbg( p_demux, "decrypting %d bytes of packet", p_sys->i_csa_pkt_size );
754         }
755         free( psz_csa2 );
756     }
757     free( psz_string );
758
759     p_sys->b_split_es = var_InheritBool( p_demux, "ts-split-es" );
760
761     p_sys->i_pid_ref_pcr = -1;
762     p_sys->i_first_pcr = -1;
763     p_sys->i_current_pcr = -1;
764     p_sys->i_last_pcr = -1;
765     p_sys->b_force_seek_per_percent = var_InheritBool( p_demux, "ts-seek-percent" );
766     p_sys->i_pcrs_num = 10;
767     p_sys->p_pcrs = (mtime_t *)calloc( p_sys->i_pcrs_num, sizeof( mtime_t ) );
768     p_sys->p_pos = (int64_t *)calloc( p_sys->i_pcrs_num, sizeof( int64_t ) );
769
770     if( !p_sys->p_pcrs || !p_sys->p_pos )
771     {
772         Close( p_this );
773         return VLC_ENOMEM;
774     }
775
776     bool can_seek = false;
777     stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &can_seek );
778     if( can_seek  )
779     {
780         GetFirstPCR( p_demux );
781         CheckPCR( p_demux );
782         GetLastPCR( p_demux );
783     }
784     if( p_sys->i_first_pcr < 0 || p_sys->i_last_pcr < 0 )
785     {
786         msg_Dbg( p_demux, "Force Seek Per Percent: PCR's not found,");
787         p_sys->b_force_seek_per_percent = true;
788     }
789
790     while( p_sys->i_pmt_es <= 0 && vlc_object_alive( p_demux ) )
791     {
792         if( Demux( p_demux ) != 1 )
793             break;
794     }
795     return VLC_SUCCESS;
796 }
797
798 /*****************************************************************************
799  * Close
800  *****************************************************************************/
801 static void Close( vlc_object_t *p_this )
802 {
803     demux_t     *p_demux = (demux_t*)p_this;
804     demux_sys_t *p_sys = p_demux->p_sys;
805
806     msg_Dbg( p_demux, "pid list:" );
807     for( int i = 0; i < 8192; i++ )
808     {
809         ts_pid_t *pid = &p_sys->pid[i];
810
811         if( pid->b_valid && pid->psi )
812         {
813             switch( pid->i_pid )
814             {
815             case 0: /* PAT */
816 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
817                 if( dvbpsi_decoder_present( pid->psi->handle ) )
818                     dvbpsi_pat_detach( pid->psi->handle );
819                 dvbpsi_delete( pid->psi->handle );
820                 pid->psi->handle = NULL;
821 #else
822                 dvbpsi_DetachPAT( pid->psi->handle );
823 #endif
824                 free( pid->psi );
825                 break;
826             case 1: /* CAT */
827                 free( pid->psi );
828                 break;
829             default:
830                 if( p_sys->b_dvb_meta && ( pid->i_pid == 0x11 || pid->i_pid == 0x12 || pid->i_pid == 0x14 ) )
831                 {
832                     /* SDT or EIT or TDT */
833                     dvbpsi_DetachDemux( pid->psi->handle );
834 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
835                     dvbpsi_delete( pid->psi->handle );
836                     pid->psi->handle = NULL;
837 #endif
838                     free( pid->psi );
839                 }
840                 else
841                 {
842                     PIDClean( p_demux, pid );
843                 }
844                 break;
845             }
846         }
847         else if( pid->b_valid && pid->es )
848         {
849             PIDClean( p_demux, pid );
850         }
851
852         if( pid->b_seen )
853         {
854             msg_Dbg( p_demux, "  - pid[%d] seen", pid->i_pid );
855         }
856
857         /* too much */
858         if( pid->i_pid > 0 )
859             SetPIDFilter( p_demux, pid->i_pid, false );
860     }
861
862     vlc_mutex_lock( &p_sys->csa_lock );
863     if( p_sys->csa )
864     {
865         var_DelCallback( p_demux, "ts-csa-ck", ChangeKeyCallback, NULL );
866         var_DelCallback( p_demux, "ts-csa2-ck", ChangeKeyCallback, NULL );
867         csa_Delete( p_sys->csa );
868     }
869     vlc_mutex_unlock( &p_sys->csa_lock );
870
871     TAB_CLEAN( p_sys->i_pmt, p_sys->pmt );
872
873     free( p_sys->programs_list.p_values );
874
875     free( p_sys->p_pcrs );
876     free( p_sys->p_pos );
877
878     vlc_mutex_destroy( &p_sys->csa_lock );
879     free( p_sys );
880 }
881
882 /*****************************************************************************
883  * ChangeKeyCallback: called when changing the odd encryption key on the fly.
884  *****************************************************************************/
885 static int ChangeKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
886                            vlc_value_t oldval, vlc_value_t newval,
887                            void *p_data )
888 {
889     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
890     demux_t     *p_demux = (demux_t*)p_this;
891     demux_sys_t *p_sys = p_demux->p_sys;
892     int         i_tmp = (intptr_t)p_data;
893
894     vlc_mutex_lock( &p_sys->csa_lock );
895     if ( i_tmp )
896         i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, true );
897     else
898         i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, false );
899
900     vlc_mutex_unlock( &p_sys->csa_lock );
901     return i_tmp;
902 }
903
904 /*****************************************************************************
905  * Demux:
906  *****************************************************************************/
907 static int Demux( demux_t *p_demux )
908 {
909     demux_sys_t *p_sys = p_demux->p_sys;
910     bool b_wait_es = p_sys->i_pmt_es <= 0;
911
912     /* We read at most 100 TS packet or until a frame is completed */
913     for( int i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
914     {
915         bool         b_frame = false;
916         block_t     *p_pkt;
917         if( !(p_pkt = ReadTSPacket( p_demux )) )
918         {
919             return 0;
920         }
921
922         if( p_sys->b_start_record )
923         {
924             /* Enable recording once synchronized */
925             stream_Control( p_demux->s, STREAM_SET_RECORD_STATE, true, "ts" );
926             p_sys->b_start_record = false;
927         }
928
929         /* Parse the TS packet */
930         ts_pid_t *p_pid = &p_sys->pid[PIDGet( p_pkt )];
931
932         if( p_pid->b_valid )
933         {
934             if( p_pid->psi )
935             {
936                 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 ) ) )
937                 {
938                     dvbpsi_PushPacket( p_pid->psi->handle, p_pkt->p_buffer );
939                 }
940                 else
941                 {
942                     for( int i_prg = 0; i_prg < p_pid->psi->i_prg; i_prg++ )
943                     {
944                         dvbpsi_PushPacket( p_pid->psi->prg[i_prg]->handle,
945                                            p_pkt->p_buffer );
946                     }
947                 }
948                 block_Release( p_pkt );
949             }
950             else
951             {
952                 b_frame = GatherData( p_demux, p_pid, p_pkt );
953             }
954         }
955         else
956         {
957             if( !p_pid->b_seen )
958             {
959                 msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid );
960             }
961             /* We have to handle PCR if present */
962             PCRHandle( p_demux, p_pid, p_pkt );
963             block_Release( p_pkt );
964         }
965         p_pid->b_seen = true;
966
967         if( b_frame || ( b_wait_es && p_sys->i_pmt_es > 0 ) )
968             break;
969     }
970
971     demux_UpdateTitleFromStream( p_demux );
972     return 1;
973 }
974
975 /*****************************************************************************
976  * Control:
977  *****************************************************************************/
978 static int DVBEventInformation( demux_t *p_demux, int64_t *pi_time, int64_t *pi_length )
979 {
980     demux_sys_t *p_sys = p_demux->p_sys;
981     if( pi_length )
982         *pi_length = 0;
983     if( pi_time )
984         *pi_time = 0;
985
986     if( p_sys->i_dvb_length > 0 )
987     {
988         const int64_t t = mdate() + p_sys->i_tdt_delta;
989
990         if( p_sys->i_dvb_start <= t && t < p_sys->i_dvb_start + p_sys->i_dvb_length )
991         {
992             if( pi_length )
993                 *pi_length = p_sys->i_dvb_length;
994             if( pi_time )
995                 *pi_time   = t - p_sys->i_dvb_start;
996             return VLC_SUCCESS;
997         }
998     }
999     return VLC_EGENERIC;
1000 }
1001
1002 static int Control( demux_t *p_demux, int i_query, va_list args )
1003 {
1004     demux_sys_t *p_sys = p_demux->p_sys;
1005     double f, *pf;
1006     bool b_bool, *pb_bool;
1007     int64_t i64;
1008     int64_t *pi64;
1009     int i_int;
1010
1011     switch( i_query )
1012     {
1013     case DEMUX_GET_POSITION:
1014         pf = (double*) va_arg( args, double* );
1015
1016         if( p_sys->b_force_seek_per_percent ||
1017             (p_sys->b_dvb_meta && p_sys->b_access_control) ||
1018             p_sys->i_current_pcr - p_sys->i_first_pcr < 0 ||
1019             p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
1020         {
1021             int64_t i_time, i_length;
1022             if( !DVBEventInformation( p_demux, &i_time, &i_length ) && i_length > 0 )
1023                 *pf = (double)i_time/(double)i_length;
1024             else if( (i64 = stream_Size( p_demux->s) ) > 0 )
1025             {
1026                 int64_t offset = stream_Tell( p_demux->s );
1027
1028                 *pf = (double)offset / (double)i64;
1029             }
1030             else
1031                 *pf = 0.0;
1032         }
1033         else
1034         {
1035             *pf = (double)(p_sys->i_current_pcr - p_sys->i_first_pcr) / (double)(p_sys->i_last_pcr - p_sys->i_first_pcr);
1036         }
1037         return VLC_SUCCESS;
1038
1039     case DEMUX_SET_POSITION:
1040         f = (double) va_arg( args, double );
1041
1042         if( p_sys->b_force_seek_per_percent ||
1043             (p_sys->b_dvb_meta && p_sys->b_access_control) ||
1044             p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
1045         {
1046             i64 = stream_Size( p_demux->s );
1047             if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
1048                 return VLC_EGENERIC;
1049         }
1050         else
1051         {
1052             if( Seek( p_demux, f ) )
1053             {
1054                 p_sys->b_force_seek_per_percent = true;
1055                 return VLC_EGENERIC;
1056             }
1057         }
1058         return VLC_SUCCESS;
1059
1060     case DEMUX_GET_TIME:
1061         pi64 = (int64_t*)va_arg( args, int64_t * );
1062         if( (p_sys->b_dvb_meta && p_sys->b_access_control) ||
1063             p_sys->b_force_seek_per_percent ||
1064             p_sys->i_current_pcr - p_sys->i_first_pcr < 0 )
1065         {
1066             if( DVBEventInformation( p_demux, pi64, NULL ) )
1067             {
1068                 *pi64 = 0;
1069             }
1070         }
1071         else
1072         {
1073             *pi64 = (p_sys->i_current_pcr - p_sys->i_first_pcr) * 100 / 9;
1074         }
1075         return VLC_SUCCESS;
1076
1077     case DEMUX_GET_LENGTH:
1078         pi64 = (int64_t*)va_arg( args, int64_t * );
1079         if( (p_sys->b_dvb_meta && p_sys->b_access_control) ||
1080             p_sys->b_force_seek_per_percent ||
1081             p_sys->i_last_pcr - p_sys->i_first_pcr <= 0 )
1082         {
1083             if( DVBEventInformation( p_demux, NULL, pi64 ) )
1084             {
1085                 *pi64 = 0;
1086             }
1087         }
1088         else
1089         {
1090             *pi64 = (p_sys->i_last_pcr - p_sys->i_first_pcr) * 100 / 9;
1091         }
1092         return VLC_SUCCESS;
1093
1094     case DEMUX_SET_GROUP:
1095     {
1096         vlc_list_t *p_list;
1097
1098         i_int = (int)va_arg( args, int );
1099         p_list = (vlc_list_t *)va_arg( args, vlc_list_t * );
1100         msg_Dbg( p_demux, "DEMUX_SET_GROUP %d %p", i_int, p_list );
1101
1102         if( i_int == 0 && p_sys->i_current_program > 0 )
1103             i_int = p_sys->i_current_program;
1104
1105         if( p_sys->i_current_program > 0 )
1106         {
1107             if( p_sys->i_current_program != i_int )
1108                 SetPrgFilter( p_demux, p_sys->i_current_program, false );
1109         }
1110         else if( p_sys->i_current_program < 0 )
1111         {
1112             for( int i = 0; i < p_sys->programs_list.i_count; i++ )
1113                 SetPrgFilter( p_demux, p_sys->programs_list.p_values[i].i_int, false );
1114         }
1115
1116         if( i_int > 0 )
1117         {
1118             p_sys->i_current_program = i_int;
1119             SetPrgFilter( p_demux, p_sys->i_current_program, true );
1120         }
1121         else if( i_int < 0 )
1122         {
1123             p_sys->i_current_program = -1;
1124             p_sys->programs_list.i_count = 0;
1125             if( p_list )
1126             {
1127                 vlc_list_t *p_dst = &p_sys->programs_list;
1128                 free( p_dst->p_values );
1129
1130                 p_dst->p_values = calloc( p_list->i_count,
1131                                           sizeof(*p_dst->p_values) );
1132                 if( p_dst->p_values )
1133                 {
1134                     p_dst->i_count = p_list->i_count;
1135                     for( int i = 0; i < p_list->i_count; i++ )
1136                     {
1137                         p_dst->p_values[i] = p_list->p_values[i];
1138                         SetPrgFilter( p_demux, p_dst->p_values[i].i_int, true );
1139                     }
1140                 }
1141             }
1142         }
1143         return VLC_SUCCESS;
1144     }
1145
1146     case DEMUX_GET_TITLE_INFO:
1147     {
1148         struct input_title_t ***v = va_arg( args, struct input_title_t*** );
1149         int *c = va_arg( args, int * );
1150
1151         *va_arg( args, int* ) = 0; /* Title offset */
1152         *va_arg( args, int* ) = 0; /* Chapter offset */
1153         return stream_Control( p_demux->s, STREAM_GET_TITLE_INFO, v, c );
1154     }
1155
1156     case DEMUX_SET_TITLE:
1157         return stream_vaControl( p_demux->s, STREAM_SET_TITLE, args );
1158
1159     case DEMUX_SET_SEEKPOINT:
1160         return stream_vaControl( p_demux->s, STREAM_SET_SEEKPOINT, args );
1161
1162     case DEMUX_GET_META:
1163         return stream_vaControl( p_demux->s, STREAM_GET_META, args );
1164
1165     case DEMUX_CAN_RECORD:
1166         pb_bool = (bool*)va_arg( args, bool * );
1167         *pb_bool = true;
1168         return VLC_SUCCESS;
1169
1170     case DEMUX_SET_RECORD_STATE:
1171         b_bool = (bool)va_arg( args, int );
1172
1173         if( !b_bool )
1174             stream_Control( p_demux->s, STREAM_SET_RECORD_STATE, false );
1175         p_sys->b_start_record = b_bool;
1176         return VLC_SUCCESS;
1177
1178     case DEMUX_GET_SIGNAL:
1179         return stream_vaControl( p_demux->s, STREAM_GET_SIGNAL, args );
1180
1181     default:
1182         return VLC_EGENERIC;
1183     }
1184 }
1185
1186 /*****************************************************************************
1187  *
1188  *****************************************************************************/
1189 static int UserPmt( demux_t *p_demux, const char *psz_fmt )
1190 {
1191     demux_sys_t *p_sys = p_demux->p_sys;
1192     char *psz_dup = strdup( psz_fmt );
1193     char *psz = psz_dup;
1194     int  i_pid;
1195     int  i_number;
1196     ts_prg_psi_t *prg = NULL;
1197
1198     if( !psz_dup )
1199         return VLC_ENOMEM;
1200
1201     /* Parse PID */
1202     i_pid = strtol( psz, &psz, 0 );
1203     if( i_pid < 2 || i_pid >= 8192 )
1204         goto error;
1205
1206     /* Parse optional program number */
1207     i_number = 0;
1208     if( *psz == ':' )
1209         i_number = strtol( &psz[1], &psz, 0 );
1210
1211     /* */
1212     ts_pid_t *pmt = &p_sys->pid[i_pid];
1213
1214     msg_Dbg( p_demux, "user pmt specified (pid=%d,number=%d)", i_pid, i_number );
1215     PIDInit( pmt, true, NULL );
1216
1217     /* Dummy PMT */
1218     prg = calloc( 1, sizeof( ts_prg_psi_t ) );
1219     if( !prg )
1220         goto error;
1221
1222     prg->i_pid_pcr  = -1;
1223     prg->i_pid_pmt  = -1;
1224     prg->i_version  = -1;
1225     prg->i_number   = i_number != 0 ? i_number : TS_USER_PMT_NUMBER;
1226 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1227     prg->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
1228     if( !prg->handle )
1229         goto error;
1230     prg->handle->p_sys = (void *) VLC_OBJECT(p_demux);
1231     if( !dvbpsi_pmt_attach( prg->handle,
1232                             ((i_number != TS_USER_PMT_NUMBER ? i_number : 1)),
1233                             PMTCallBack, p_demux ) )
1234     {
1235         dvbpsi_delete( prg->handle );
1236         prg->handle = NULL;
1237         goto error;
1238     }
1239 #else
1240     prg->handle     = dvbpsi_AttachPMT(
1241         ((i_number != TS_USER_PMT_NUMBER) ? i_number : 1),
1242         PMTCallBack, p_demux );
1243 #endif
1244     TAB_APPEND( pmt->psi->i_prg, pmt->psi->prg, prg );
1245
1246     psz = strchr( psz, '=' );
1247     if( psz )
1248         psz++;
1249     while( psz && *psz )
1250     {
1251         char *psz_next = strchr( psz, ',' );
1252         int i_pid;
1253
1254         if( psz_next )
1255             *psz_next++ = '\0';
1256
1257         i_pid = strtol( psz, &psz, 0 );
1258         if( *psz != ':' || i_pid < 2 || i_pid >= 8192 )
1259             goto next;
1260
1261         char *psz_opt = &psz[1];
1262         if( !strcmp( psz_opt, "pcr" ) )
1263         {
1264             prg->i_pid_pcr = i_pid;
1265         }
1266         else if( !p_sys->pid[i_pid].b_valid )
1267         {
1268             ts_pid_t *pid = &p_sys->pid[i_pid];
1269
1270             char *psz_arg = strchr( psz_opt, '=' );
1271             if( psz_arg )
1272                 *psz_arg++ = '\0';
1273
1274             PIDInit( pid, false, pmt->psi);
1275             if( prg->i_pid_pcr <= 0 )
1276                 prg->i_pid_pcr = i_pid;
1277
1278             if( psz_arg && strlen( psz_arg ) == 4 )
1279             {
1280                 const vlc_fourcc_t i_codec = VLC_FOURCC( psz_arg[0], psz_arg[1],
1281                                                          psz_arg[2], psz_arg[3] );
1282                 int i_cat = UNKNOWN_ES;
1283                 es_format_t *fmt = &pid->es->fmt;
1284
1285                 if( !strcmp( psz_opt, "video" ) )
1286                     i_cat = VIDEO_ES;
1287                 else if( !strcmp( psz_opt, "audio" ) )
1288                     i_cat = AUDIO_ES;
1289                 else if( !strcmp( psz_opt, "spu" ) )
1290                     i_cat = SPU_ES;
1291
1292                 es_format_Init( fmt, i_cat, i_codec );
1293                 fmt->b_packetized = false;
1294             }
1295             else
1296             {
1297                 const int i_stream_type = strtol( psz_opt, NULL, 0 );
1298                 PIDFillFormat( &pid->es->fmt, i_stream_type );
1299             }
1300             pid->es->fmt.i_group = i_number;
1301             if( p_sys->b_es_id_pid )
1302                 pid->es->fmt.i_id = i_pid;
1303
1304             if( pid->es->fmt.i_cat != UNKNOWN_ES )
1305             {
1306                 msg_Dbg( p_demux, "  * es pid=%d fcc=%4.4s", i_pid,
1307                          (char*)&pid->es->fmt.i_codec );
1308                 pid->es->id = es_out_Add( p_demux->out,
1309                                           &pid->es->fmt );
1310                 p_sys->i_pmt_es++;
1311             }
1312         }
1313
1314     next:
1315         psz = psz_next;
1316     }
1317
1318     p_sys->b_user_pmt = true;
1319     TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
1320     free( psz_dup );
1321     return VLC_SUCCESS;
1322
1323 error:
1324     free( prg );
1325     free( psz_dup );
1326     return VLC_EGENERIC;
1327 }
1328
1329 static int SetPIDFilter( demux_t *p_demux, int i_pid, bool b_selected )
1330 {
1331     demux_sys_t *p_sys = p_demux->p_sys;
1332
1333     if( !p_sys->b_access_control )
1334         return VLC_EGENERIC;
1335
1336     return stream_Control( p_demux->s, STREAM_SET_PRIVATE_ID_STATE,
1337                            i_pid, b_selected );
1338 }
1339
1340 static void SetPrgFilter( demux_t *p_demux, int i_prg_id, bool b_selected )
1341 {
1342     demux_sys_t *p_sys = p_demux->p_sys;
1343     ts_prg_psi_t *p_prg = NULL;
1344     int i_pmt_pid = -1;
1345
1346     /* Search pmt to be unselected */
1347     for( int i = 0; i < p_sys->i_pmt; i++ )
1348     {
1349         ts_pid_t *pmt = p_sys->pmt[i];
1350
1351         for( int i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
1352         {
1353             if( pmt->psi->prg[i_prg]->i_number == i_prg_id )
1354             {
1355                 i_pmt_pid = p_sys->pmt[i]->i_pid;
1356                 p_prg = p_sys->pmt[i]->psi->prg[i_prg];
1357                 break;
1358             }
1359         }
1360         if( i_pmt_pid > 0 )
1361             break;
1362     }
1363     if( i_pmt_pid <= 0 )
1364         return;
1365     assert( p_prg );
1366
1367     SetPIDFilter( p_demux, i_pmt_pid, b_selected );
1368     if( p_prg->i_pid_pcr > 0 )
1369         SetPIDFilter( p_demux, p_prg->i_pid_pcr, b_selected );
1370
1371     /* All ES */
1372     for( int i = 2; i < 8192; i++ )
1373     {
1374         ts_pid_t *pid = &p_sys->pid[i];
1375
1376         if( !pid->b_valid || pid->psi )
1377             continue;
1378
1379         for( int i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
1380         {
1381             if( pid->p_owner->prg[i_prg]->i_pid_pmt == i_pmt_pid && pid->es->id )
1382             {
1383                 /* We only remove/select es that aren't defined by extra pmt */
1384                 SetPIDFilter( p_demux, i, b_selected );
1385                 break;
1386             }
1387         }
1388     }
1389 }
1390
1391 static void PIDInit( ts_pid_t *pid, bool b_psi, ts_psi_t *p_owner )
1392 {
1393     bool b_old_valid = pid->b_valid;
1394
1395     pid->b_valid    = true;
1396     pid->i_cc       = 0xff;
1397     pid->b_scrambled = false;
1398     pid->p_owner    = p_owner;
1399     pid->i_owner_number = 0;
1400
1401     TAB_INIT( pid->i_extra_es, pid->extra_es );
1402
1403     if( b_psi )
1404     {
1405         pid->es  = NULL;
1406
1407         if( !b_old_valid )
1408         {
1409             pid->psi = xmalloc( sizeof( ts_psi_t ) );
1410             pid->psi->handle = NULL;
1411             TAB_INIT( pid->psi->i_prg, pid->psi->prg );
1412         }
1413         assert( pid->psi );
1414
1415         pid->psi->i_pat_version  = -1;
1416         pid->psi->i_sdt_version  = -1;
1417         if( p_owner )
1418         {
1419             ts_prg_psi_t *prg = malloc( sizeof( ts_prg_psi_t ) );
1420             if( !prg )
1421                 return;
1422             /* PMT */
1423             prg->i_version  = -1;
1424             prg->i_number   = -1;
1425             prg->i_pid_pcr  = -1;
1426             prg->i_pid_pmt  = -1;
1427             prg->i_pcr_value= -1;
1428             prg->iod        = NULL;
1429             prg->handle     = NULL;
1430
1431             TAB_APPEND( pid->psi->i_prg, pid->psi->prg, prg );
1432         }
1433     }
1434     else
1435     {
1436         pid->psi = NULL;
1437         pid->es  = calloc( 1, sizeof( ts_es_t ) );
1438         if( !pid->es )
1439             return;
1440
1441         es_format_Init( &pid->es->fmt, UNKNOWN_ES, 0 );
1442         pid->es->data_type = TS_ES_DATA_PES;
1443         pid->es->pp_last = &pid->es->p_data;
1444     }
1445 }
1446
1447 static void PIDClean( demux_t *p_demux, ts_pid_t *pid )
1448 {
1449     demux_sys_t *p_sys = p_demux->p_sys;
1450     es_out_t *out = p_demux->out;
1451
1452     if( pid->psi )
1453     {
1454         if( pid->psi->handle )
1455         {
1456 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1457             if( dvbpsi_decoder_present( pid->psi->handle ) )
1458                 dvbpsi_pmt_detach( pid->psi->handle );
1459             dvbpsi_delete( pid->psi->handle );
1460             pid->psi->handle = NULL;
1461 #else
1462             dvbpsi_DetachPMT( pid->psi->handle );
1463 #endif
1464         }
1465         for( int i = 0; i < pid->psi->i_prg; i++ )
1466         {
1467             if( pid->psi->prg[i]->iod )
1468                 IODFree( pid->psi->prg[i]->iod );
1469             if( pid->psi->prg[i]->handle )
1470             {
1471 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
1472                 if( dvbpsi_decoder_present( pid->psi->prg[i]->handle ) )
1473                     dvbpsi_pmt_detach( pid->psi->prg[i]->handle );
1474                 dvbpsi_delete( pid->psi->prg[i]->handle );
1475 #else
1476                 dvbpsi_DetachPMT( pid->psi->prg[i]->handle );
1477 #endif
1478             }
1479             free( pid->psi->prg[i] );
1480         }
1481         free( pid->psi->prg );
1482         free( pid->psi );
1483     }
1484     else
1485     {
1486         if( pid->es->id )
1487         {
1488             es_out_Del( out, pid->es->id );
1489             p_sys->i_pmt_es--;
1490         }
1491
1492         if( pid->es->p_data )
1493             block_ChainRelease( pid->es->p_data );
1494
1495         es_format_Clean( &pid->es->fmt );
1496
1497         free( pid->es );
1498
1499         for( int i = 0; i < pid->i_extra_es; i++ )
1500         {
1501             if( pid->extra_es[i]->id )
1502             {
1503                 es_out_Del( out, pid->extra_es[i]->id );
1504                 p_sys->i_pmt_es--;
1505             }
1506
1507             if( pid->extra_es[i]->p_data )
1508                 block_ChainRelease( pid->extra_es[i]->p_data );
1509
1510             es_format_Clean( &pid->extra_es[i]->fmt );
1511
1512             free( pid->extra_es[i] );
1513         }
1514         if( pid->i_extra_es )
1515             free( pid->extra_es );
1516     }
1517
1518     pid->b_valid = false;
1519 }
1520
1521 /****************************************************************************
1522  * gathering stuff
1523  ****************************************************************************/
1524 static void ParsePES( demux_t *p_demux, ts_pid_t *pid, block_t *p_pes )
1525 {
1526     demux_sys_t *p_sys = p_demux->p_sys;
1527     uint8_t header[34];
1528     unsigned i_pes_size = 0;
1529     unsigned i_skip = 0;
1530     mtime_t i_dts = -1;
1531     mtime_t i_pts = -1;
1532     mtime_t i_length = 0;
1533
1534     /* FIXME find real max size */
1535     /* const int i_max = */ block_ChainExtract( p_pes, header, 34 );
1536
1537     if( header[0] != 0 || header[1] != 0 || header[2] != 1 )
1538     {
1539         msg_Warn( p_demux, "invalid header [0x%02x:%02x:%02x:%02x] (pid: %d)",
1540                     header[0], header[1],header[2],header[3], pid->i_pid );
1541         block_ChainRelease( p_pes );
1542         return;
1543     }
1544
1545     /* TODO check size */
1546     switch( header[3] )
1547     {
1548     case 0xBC:  /* Program stream map */
1549     case 0xBE:  /* Padding */
1550     case 0xBF:  /* Private stream 2 */
1551     case 0xF0:  /* ECM */
1552     case 0xF1:  /* EMM */
1553     case 0xFF:  /* Program stream directory */
1554     case 0xF2:  /* DSMCC stream */
1555     case 0xF8:  /* ITU-T H.222.1 type E stream */
1556         i_skip = 6;
1557         break;
1558     default:
1559         if( ( header[6]&0xC0 ) == 0x80 )
1560         {
1561             /* mpeg2 PES */
1562             i_skip = header[8] + 9;
1563
1564             if( header[7]&0x80 )    /* has pts */
1565             {
1566                 i_pts = ((mtime_t)(header[ 9]&0x0e ) << 29)|
1567                          (mtime_t)(header[10] << 22)|
1568                         ((mtime_t)(header[11]&0xfe) << 14)|
1569                          (mtime_t)(header[12] << 7)|
1570                          (mtime_t)(header[13] >> 1);
1571
1572                 if( header[7]&0x40 )    /* has dts */
1573                 {
1574                      i_dts = ((mtime_t)(header[14]&0x0e ) << 29)|
1575                              (mtime_t)(header[15] << 22)|
1576                             ((mtime_t)(header[16]&0xfe) << 14)|
1577                              (mtime_t)(header[17] << 7)|
1578                              (mtime_t)(header[18] >> 1);
1579                 }
1580             }
1581         }
1582         else
1583         {
1584             i_skip = 6;
1585             while( i_skip < 23 && header[i_skip] == 0xff )
1586             {
1587                 i_skip++;
1588             }
1589             if( i_skip == 23 )
1590             {
1591                 msg_Err( p_demux, "too much MPEG-1 stuffing" );
1592                 block_ChainRelease( p_pes );
1593                 return;
1594             }
1595             if( ( header[i_skip] & 0xC0 ) == 0x40 )
1596             {
1597                 i_skip += 2;
1598             }
1599
1600             if(  header[i_skip]&0x20 )
1601             {
1602                  i_pts = ((mtime_t)(header[i_skip]&0x0e ) << 29)|
1603                           (mtime_t)(header[i_skip+1] << 22)|
1604                          ((mtime_t)(header[i_skip+2]&0xfe) << 14)|
1605                           (mtime_t)(header[i_skip+3] << 7)|
1606                           (mtime_t)(header[i_skip+4] >> 1);
1607
1608                 if( header[i_skip]&0x10 )    /* has dts */
1609                 {
1610                      i_dts = ((mtime_t)(header[i_skip+5]&0x0e ) << 29)|
1611                               (mtime_t)(header[i_skip+6] << 22)|
1612                              ((mtime_t)(header[i_skip+7]&0xfe) << 14)|
1613                               (mtime_t)(header[i_skip+8] << 7)|
1614                               (mtime_t)(header[i_skip+9] >> 1);
1615                      i_skip += 10;
1616                 }
1617                 else
1618                 {
1619                     i_skip += 5;
1620                 }
1621             }
1622             else
1623             {
1624                 i_skip += 1;
1625             }
1626         }
1627         break;
1628     }
1629
1630     if( pid->es->fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
1631         pid->es->fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
1632     {
1633         i_skip += 4;
1634     }
1635     else if( pid->es->fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
1636              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
1637              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
1638     {
1639         i_skip += 1;
1640     }
1641     else if( pid->es->fmt.i_codec == VLC_CODEC_SUBT &&
1642              pid->es->p_mpeg4desc )
1643     {
1644         decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
1645
1646         if( dcd->i_extra > 2 &&
1647             dcd->p_extra[0] == 0x10 &&
1648             ( dcd->p_extra[1]&0x10 ) )
1649         {
1650             /* display length */
1651             if( p_pes->i_buffer + 2 <= i_skip )
1652                 i_length = GetWBE( &p_pes->p_buffer[i_skip] );
1653
1654             i_skip += 2;
1655         }
1656         if( p_pes->i_buffer + 2 <= i_skip )
1657             i_pes_size = GetWBE( &p_pes->p_buffer[i_skip] );
1658         /* */
1659         i_skip += 2;
1660     }
1661
1662     /* skip header */
1663     while( p_pes && i_skip > 0 )
1664     {
1665         if( p_pes->i_buffer <= i_skip )
1666         {
1667             block_t *p_next = p_pes->p_next;
1668
1669             i_skip -= p_pes->i_buffer;
1670             block_Release( p_pes );
1671             p_pes = p_next;
1672         }
1673         else
1674         {
1675             p_pes->i_buffer -= i_skip;
1676             p_pes->p_buffer += i_skip;
1677             break;
1678         }
1679     }
1680
1681     /* ISO/IEC 13818-1 2.7.5: if no pts and no dts, then dts == pts */
1682     if( i_pts >= 0 && i_dts < 0 )
1683         i_dts = i_pts;
1684
1685     if( p_pes )
1686     {
1687         block_t *p_block;
1688
1689         if( i_dts >= 0 )
1690             p_pes->i_dts = VLC_TS_0 + i_dts * 100 / 9;
1691
1692         if( i_pts >= 0 )
1693             p_pes->i_pts = VLC_TS_0 + i_pts * 100 / 9;
1694
1695         p_pes->i_length = i_length * 100 / 9;
1696
1697         p_block = block_ChainGather( p_pes );
1698         if( pid->es->fmt.i_codec == VLC_CODEC_SUBT )
1699         {
1700             if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
1701             {
1702                 p_block->i_buffer = i_pes_size;
1703             }
1704             /* Append a \0 */
1705             p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
1706             if( !p_block )
1707                 abort();
1708             p_block->p_buffer[p_block->i_buffer -1] = '\0';
1709         }
1710         else if( pid->es->fmt.i_codec == VLC_CODEC_TELETEXT )
1711         {
1712             if( p_block->i_pts <= VLC_TS_INVALID )
1713             {
1714                 /* Teletext may have missing PTS (ETSI EN 300 472 Annexe A)
1715                  * In this case use the last PCR + 40ms */
1716                 for( int i = 0; pid->p_owner && i < pid->p_owner->i_prg; i++ )
1717                 {
1718                     if( pid->i_owner_number == pid->p_owner->prg[i]->i_number )
1719                     {
1720                         mtime_t i_pcr = pid->p_owner->prg[i]->i_pcr_value;
1721                         if( i_pcr > VLC_TS_INVALID )
1722                             p_block->i_pts = VLC_TS_0 + i_pcr * 100 / 9 + 40000;
1723                         break;
1724                     }
1725                 }
1726             }
1727         }
1728
1729         for( int i = 0; i < pid->i_extra_es; i++ )
1730         {
1731             es_out_Send( p_demux->out, pid->extra_es[i]->id,
1732                          block_Duplicate( p_block ) );
1733         }
1734
1735         if (!p_sys->b_trust_pcr)
1736             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts);
1737
1738         es_out_Send( p_demux->out, pid->es->id, p_block );
1739     }
1740     else
1741     {
1742         msg_Warn( p_demux, "empty pes" );
1743     }
1744 }
1745
1746 static void ParseTableSection( demux_t *p_demux, ts_pid_t *pid, block_t *p_data )
1747 {
1748     block_t *p_content = block_ChainGather( p_data );
1749     mtime_t i_date = -1;
1750     for( int i = 0; pid->p_owner && i < pid->p_owner->i_prg; i++ )
1751     {
1752         if( pid->i_owner_number == pid->p_owner->prg[i]->i_number )
1753         {
1754             i_date = pid->p_owner->prg[i]->i_pcr_value;
1755             if( i_date >= 0 )
1756                 break;
1757         }
1758     }
1759     if( i_date >= 0 )
1760     {
1761         if( pid->es->fmt.i_codec == VLC_CODEC_SCTE_27 )
1762         {
1763             /* We need to extract the truncated pts stored inside the payload */
1764             if( p_content->i_buffer > 9 && p_content->p_buffer[0] == 0xc6 )
1765             {
1766                 int i_index = 0;
1767                 size_t i_offset = 4;
1768                 if( p_content->p_buffer[3] & 0x40 )
1769                 {
1770                     i_index = ((p_content->p_buffer[7] & 0x0f) << 8) |
1771                               p_content->p_buffer[8];
1772                     i_offset = 9;
1773                 }
1774                 if( i_index == 0 && p_content->i_buffer > i_offset + 8 )
1775                 {
1776                     bool is_immediate = p_content->p_buffer[i_offset + 3] & 0x40;
1777                     if( !is_immediate )
1778                     {
1779                         mtime_t i_display_in = GetDWBE( &p_content->p_buffer[i_offset + 4] );
1780                         if( i_display_in < i_date )
1781                             i_date = i_display_in + (1ll << 32);
1782                         else
1783                             i_date = i_display_in;
1784                     }
1785
1786                 }
1787             }
1788         }
1789         p_content->i_dts =
1790         p_content->i_pts = VLC_TS_0 + i_date * 100 / 9;
1791     }
1792     es_out_Send( p_demux->out, pid->es->id, p_content );
1793 }
1794 static void ParseData( demux_t *p_demux, ts_pid_t *pid )
1795 {
1796     block_t *p_data = pid->es->p_data;
1797
1798     /* remove the pes from pid */
1799     pid->es->p_data = NULL;
1800     pid->es->i_data_size = 0;
1801     pid->es->i_data_gathered = 0;
1802     pid->es->pp_last = &pid->es->p_data;
1803
1804     if( pid->es->data_type == TS_ES_DATA_PES )
1805     {
1806         ParsePES( p_demux, pid, p_data );
1807     }
1808     else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
1809     {
1810         ParseTableSection( p_demux, pid, p_data );
1811     }
1812     else
1813     {
1814         block_ChainRelease( p_data );
1815     }
1816 }
1817
1818 static block_t* ReadTSPacket( demux_t *p_demux )
1819 {
1820     demux_sys_t *p_sys = p_demux->p_sys;
1821
1822     block_t     *p_pkt;
1823
1824     /* Get a new TS packet */
1825     if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
1826     {
1827         msg_Dbg( p_demux, "eof ?" );
1828         return NULL;
1829     }
1830
1831     /* Skip header (BluRay streams).
1832      * re-sync logic would do this (by adjusting packet start), but this would result in losing first and last ts packets.
1833      * First packet is usually PAT, and losing it means losing whole first GOP. This is fatal with still-image based menus.
1834      */
1835     p_pkt->p_buffer += p_sys->i_packet_header_size;
1836     p_pkt->i_buffer -= p_sys->i_packet_header_size;
1837
1838     /* Check sync byte and re-sync if needed */
1839     if( p_pkt->p_buffer[0] != 0x47 )
1840     {
1841         msg_Warn( p_demux, "lost synchro" );
1842         block_Release( p_pkt );
1843         while( vlc_object_alive (p_demux) )
1844         {
1845             const uint8_t *p_peek;
1846             int i_peek, i_skip = 0;
1847
1848             i_peek = stream_Peek( p_demux->s, &p_peek,
1849                     p_sys->i_packet_size * 10 );
1850             if( i_peek < p_sys->i_packet_size + 1 )
1851             {
1852                 msg_Dbg( p_demux, "eof ?" );
1853                 return NULL;
1854             }
1855
1856             while( i_skip < i_peek - p_sys->i_packet_size )
1857             {
1858                 if( p_peek[i_skip + p_sys->i_packet_header_size] == 0x47 &&
1859                         p_peek[i_skip + p_sys->i_packet_header_size + p_sys->i_packet_size] == 0x47 )
1860                 {
1861                     break;
1862                 }
1863                 i_skip++;
1864             }
1865             msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
1866             stream_Read( p_demux->s, NULL, i_skip );
1867
1868             if( i_skip < i_peek - p_sys->i_packet_size )
1869             {
1870                 break;
1871             }
1872         }
1873         if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
1874         {
1875             msg_Dbg( p_demux, "eof ?" );
1876             return NULL;
1877         }
1878     }
1879     return p_pkt;
1880 }
1881
1882 static mtime_t AdjustPCRWrapAround( demux_t *p_demux, mtime_t i_pcr )
1883 {
1884     demux_sys_t   *p_sys = p_demux->p_sys;
1885     /*
1886      * PCR is 33bit. If PCR reaches to 0x1FFFFFFFF (26:30:43.717), ressets from 0.
1887      * So, need to add 0x1FFFFFFFF, for calculating duration or current position.
1888      */
1889     mtime_t i_adjust = 0;
1890     int64_t i_pos = stream_Tell( p_demux->s );
1891     int i;
1892     for( i = 1; i < p_sys->i_pcrs_num && p_sys->p_pos[i] <= i_pos; ++i )
1893     {
1894         if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
1895             i_adjust += 0x1FFFFFFFF;
1896     }
1897     if( p_sys->p_pcrs[i-1] > i_pcr )
1898         i_adjust += 0x1FFFFFFFF;
1899
1900     return i_pcr + i_adjust;
1901 }
1902
1903 static mtime_t GetPCR( block_t *p_pkt )
1904 {
1905     const uint8_t *p = p_pkt->p_buffer;
1906
1907     mtime_t i_pcr = -1;
1908
1909     if( ( p[3]&0x20 ) && /* adaptation */
1910         ( p[5]&0x10 ) &&
1911         ( p[4] >= 7 ) )
1912     {
1913         /* PCR is 33 bits */
1914         i_pcr = ( (mtime_t)p[6] << 25 ) |
1915                 ( (mtime_t)p[7] << 17 ) |
1916                 ( (mtime_t)p[8] << 9 ) |
1917                 ( (mtime_t)p[9] << 1 ) |
1918                 ( (mtime_t)p[10] >> 7 );
1919     }
1920     return i_pcr;
1921 }
1922
1923 static int SeekToPCR( demux_t *p_demux, int64_t i_pos )
1924 {
1925     demux_sys_t *p_sys = p_demux->p_sys;
1926
1927     mtime_t i_pcr = -1;
1928     const int64_t i_initial_pos = stream_Tell( p_demux->s );
1929
1930     if( i_pos < 0 )
1931         return VLC_EGENERIC;
1932
1933     int64_t i_last_pos = stream_Size( p_demux->s ) - p_sys->i_packet_size;
1934     if( i_pos > i_last_pos )
1935         i_pos = i_last_pos;
1936
1937     if( stream_Seek( p_demux->s, i_pos ) )
1938         return VLC_EGENERIC;
1939
1940     while( vlc_object_alive( p_demux ) )
1941     {
1942         block_t *p_pkt;
1943
1944         if( !( p_pkt = ReadTSPacket( p_demux ) ) )
1945         {
1946             break;
1947         }
1948         if( PIDGet( p_pkt ) == p_sys->i_pid_ref_pcr )
1949         {
1950             i_pcr = GetPCR( p_pkt );
1951         }
1952         block_Release( p_pkt );
1953         if( i_pcr >= 0 )
1954             break;
1955         if( stream_Tell( p_demux->s ) >= i_last_pos )
1956             break;
1957     }
1958     if( i_pcr < 0 )
1959     {
1960         stream_Seek( p_demux->s, i_initial_pos );
1961         assert( i_initial_pos == stream_Tell( p_demux->s ) );
1962         return VLC_EGENERIC;
1963     }
1964
1965     p_sys->i_current_pcr = i_pcr;
1966     return VLC_SUCCESS;
1967 }
1968
1969 static int Seek( demux_t *p_demux, double f_percent )
1970 {
1971     demux_sys_t *p_sys = p_demux->p_sys;
1972
1973     int64_t i_initial_pos = stream_Tell( p_demux->s );
1974     mtime_t i_initial_pcr = p_sys->i_current_pcr;
1975
1976     /*
1977      * Find the time position by using binary search algorithm.
1978      */
1979     mtime_t i_target_pcr = (p_sys->i_last_pcr - p_sys->i_first_pcr) * f_percent + p_sys->i_first_pcr;
1980
1981     int64_t i_head_pos = 0;
1982     int64_t i_tail_pos;
1983     {
1984         mtime_t i_adjust = 0;
1985         int i;
1986         for( i = 1; i < p_sys->i_pcrs_num; ++i )
1987         {
1988             if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
1989                 i_adjust += 0x1FFFFFFFF;
1990             if( p_sys->p_pcrs[i] + i_adjust > i_target_pcr )
1991                 break;
1992         }
1993         i_head_pos = p_sys->p_pos[i-1];
1994         i_tail_pos = ( i < p_sys->i_pcrs_num ) ?  p_sys->p_pos[i] : stream_Size( p_demux->s );
1995     }
1996     msg_Dbg( p_demux, "Seek():i_head_pos:%"PRId64", i_tail_pos:%"PRId64, i_head_pos, i_tail_pos);
1997
1998     bool b_found = false;
1999     int i_cnt = 0;
2000     while( i_head_pos <= i_tail_pos )
2001     {
2002         /* Round i_pos to a multiple of p_sys->i_packet_size */
2003         int64_t i_pos = i_head_pos + (i_tail_pos - i_head_pos) / 2;
2004         int64_t i_div = i_pos % p_sys->i_packet_size;
2005         i_pos -= i_div;
2006         if( SeekToPCR( p_demux, i_pos ) )
2007             break;
2008         p_sys->i_current_pcr = AdjustPCRWrapAround( p_demux, p_sys->i_current_pcr );
2009         int64_t i_diff_msec = (p_sys->i_current_pcr - i_target_pcr) * 100 / 9 / 1000;
2010         if( i_diff_msec > 500 )
2011         {
2012             i_tail_pos = i_pos - p_sys->i_packet_size;
2013         }
2014         else if( i_diff_msec < -500 )
2015         {
2016             i_head_pos = i_pos + p_sys->i_packet_size;
2017         }
2018         else
2019         {
2020             // diff time <= 500msec
2021             b_found = true;
2022             break;
2023         }
2024         ++i_cnt;
2025     }
2026     if( !b_found )
2027     {
2028         msg_Dbg( p_demux, "Seek():cannot find a time position. i_cnt:%d", i_cnt );
2029         stream_Seek( p_demux->s, i_initial_pos );
2030         p_sys->i_current_pcr = i_initial_pcr;
2031         return VLC_EGENERIC;
2032     }
2033     else
2034     {
2035         msg_Dbg( p_demux, "Seek():can find a time position. i_cnt:%d", i_cnt );
2036         return VLC_SUCCESS;
2037     }
2038 }
2039
2040 static void GetFirstPCR( demux_t *p_demux )
2041 {
2042     demux_sys_t *p_sys = p_demux->p_sys;
2043
2044     int64_t i_initial_pos = stream_Tell( p_demux->s );
2045
2046     if( stream_Seek( p_demux->s, 0 ) )
2047         return;
2048
2049     while( vlc_object_alive (p_demux) )
2050     {
2051         block_t     *p_pkt;
2052
2053         if( !( p_pkt = ReadTSPacket( p_demux ) ) )
2054         {
2055             break;
2056         }
2057         mtime_t i_pcr = GetPCR( p_pkt );
2058         if( i_pcr >= 0 )
2059         {
2060             p_sys->i_pid_ref_pcr = PIDGet( p_pkt );
2061             p_sys->i_first_pcr = i_pcr;
2062             p_sys->i_current_pcr = i_pcr;
2063         }
2064         block_Release( p_pkt );
2065         if( p_sys->i_first_pcr >= 0 )
2066             break;
2067     }
2068     stream_Seek( p_demux->s, i_initial_pos );
2069 }
2070
2071 static void GetLastPCR( demux_t *p_demux )
2072 {
2073     demux_sys_t *p_sys = p_demux->p_sys;
2074
2075     const int64_t i_initial_pos = stream_Tell( p_demux->s );
2076     mtime_t i_initial_pcr = p_sys->i_current_pcr;
2077
2078     int64_t i_stream_size = stream_Size( p_demux->s );
2079     int64_t i_last_pos = i_stream_size - p_sys->i_packet_size;
2080     /* Round i_pos to a multiple of p_sys->i_packet_size */
2081     int64_t i_pos = i_last_pos - p_sys->i_packet_size * 4500; /* FIXME if the value is not reasonable, please change it. */
2082     int64_t i_div = i_pos % p_sys->i_packet_size;
2083     i_pos -= i_div;
2084
2085     if( i_pos <= i_initial_pos && i_pos >= i_stream_size )
2086         i_pos = i_initial_pos + p_sys->i_packet_size;
2087     if( i_pos < 0 && i_pos >= i_stream_size )
2088         return;
2089
2090     while( vlc_object_alive( p_demux ) )
2091     {
2092         if( SeekToPCR( p_demux, i_pos ) )
2093             break;
2094         p_sys->i_last_pcr = AdjustPCRWrapAround( p_demux, p_sys->i_current_pcr );
2095         if( ( i_pos = stream_Tell( p_demux->s ) ) >= i_last_pos )
2096             break;
2097     }
2098     if( p_sys->i_last_pcr >= 0 )
2099     {
2100         int64_t i_size = stream_Size( p_demux->s );
2101         mtime_t i_duration_msec = ( p_sys->i_last_pcr - p_sys->i_first_pcr ) * 100 / 9 / 1000;
2102         int64_t i_rate = ( i_size < 0 || i_duration_msec <= 0 ) ? 0 : i_size * 1000 * 8 / i_duration_msec;
2103         const int64_t TS_SUPPOSED_MAXRATE = 55 * 1000 * 1000; //FIXME I think it's enough.
2104         const int64_t TS_SUPPOSED_MINRATE = 0.5 * 1000 * 1000; //FIXME
2105         if( i_rate < TS_SUPPOSED_MINRATE || i_rate > TS_SUPPOSED_MAXRATE )
2106         {
2107             msg_Dbg( p_demux, "calculated bitrate (%"PRId64"bit/s) is too low or too high. min bitrate (%"PRId64"bit/s) max bitrate (%"PRId64"bit/s)",
2108                      i_rate, TS_SUPPOSED_MINRATE, TS_SUPPOSED_MAXRATE );
2109             p_sys->i_last_pcr = -1;
2110         }
2111     }
2112     stream_Seek( p_demux->s, i_initial_pos );
2113     assert( i_initial_pos == stream_Tell( p_demux->s ) );
2114     p_sys->i_current_pcr = i_initial_pcr;
2115 }
2116
2117 static void CheckPCR( demux_t *p_demux )
2118 {
2119     demux_sys_t   *p_sys = p_demux->p_sys;
2120
2121     int64_t i_initial_pos = stream_Tell( p_demux->s );
2122     mtime_t i_initial_pcr = p_sys->i_current_pcr;
2123
2124     int64_t i_size = stream_Size( p_demux->s );
2125
2126     int i = 0;
2127     p_sys->p_pcrs[0] = p_sys->i_first_pcr;
2128     p_sys->p_pos[0] = i_initial_pos;
2129
2130     for( i = 1; i < p_sys->i_pcrs_num && vlc_object_alive( p_demux ); ++i )
2131     {
2132         /* Round i_pos to a multiple of p_sys->i_packet_size */
2133         int64_t i_pos = i_size / p_sys->i_pcrs_num * i;
2134         int64_t i_div = i_pos % p_sys->i_packet_size;
2135         i_pos -= i_div;
2136         if( SeekToPCR( p_demux, i_pos ) )
2137             break;
2138         p_sys->p_pcrs[i] = p_sys->i_current_pcr;
2139         p_sys->p_pos[i] = stream_Tell( p_demux->s );
2140         if( p_sys->p_pcrs[i-1] > p_sys->p_pcrs[i] )
2141         {
2142             msg_Dbg( p_demux, "PCR Wrap Around found between %d%% and %d%% (pcr:%"PRId64"(0x%09"PRIx64") pcr:%"PRId64"(0x%09"PRIx64"))",
2143                     (int)((i-1)*100/p_sys->i_pcrs_num), (int)(i*100/p_sys->i_pcrs_num), p_sys->p_pcrs[i-1], p_sys->p_pcrs[i-1], p_sys->p_pcrs[i], p_sys->p_pcrs[i] );
2144         }
2145     }
2146     if( i < p_sys->i_pcrs_num )
2147     {
2148         msg_Dbg( p_demux, "Force Seek Per Percent: Seeking failed at %d%%.", (int)(i*100/p_sys->i_pcrs_num) );
2149         p_sys->b_force_seek_per_percent = true;
2150     }
2151
2152     stream_Seek( p_demux->s, i_initial_pos );
2153     p_sys->i_current_pcr = i_initial_pcr;
2154 }
2155
2156 static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
2157 {
2158     demux_sys_t   *p_sys = p_demux->p_sys;
2159
2160     if( p_sys->i_pmt_es <= 0 )
2161         return;
2162
2163     mtime_t i_pcr = GetPCR( p_bk );
2164     if( i_pcr < 0 )
2165         return;
2166
2167     if( p_sys->i_pid_ref_pcr == pid->i_pid )
2168         p_sys->i_current_pcr = AdjustPCRWrapAround( p_demux, i_pcr );
2169
2170     /* Search program and set the PCR */
2171     int i_group = -1;
2172     for( int i = 0; i < p_sys->i_pmt && i_group < 0 ; i++ )
2173     {
2174         bool b_pmt_has_es = false;
2175
2176         for( int i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
2177         {
2178             if( pid->i_pid == p_sys->pmt[i]->psi->prg[i_prg]->i_pid_pcr )
2179             {
2180                 /* We've found our target group */
2181                 p_sys->pmt[i]->psi->prg[i_prg]->i_pcr_value = i_pcr;
2182                 i_group = p_sys->pmt[i]->psi->prg[i_prg]->i_number;
2183                 for( int j = 0; j < 8192; j++ )
2184                 {
2185                     const ts_pid_t *pid = &p_sys->pid[j];
2186                     if( pid->b_valid && pid->p_owner == p_sys->pmt[i]->psi && pid->es )
2187                     {
2188                         b_pmt_has_es = true;
2189                         break;
2190                     }
2191                 }
2192             }
2193         }
2194
2195         if ( p_sys->b_trust_pcr && i_group > 0 && b_pmt_has_es )
2196             es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
2197               i_group, VLC_TS_0 + i_pcr * 100 / 9 );
2198     }
2199 }
2200
2201 static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
2202 {
2203     const uint8_t *p = p_bk->p_buffer;
2204     const bool b_unit_start = p[1]&0x40;
2205     const bool b_scrambled  = p[3]&0x80;
2206     const bool b_adaptation = p[3]&0x20;
2207     const bool b_payload    = p[3]&0x10;
2208     const int  i_cc         = p[3]&0x0f; /* continuity counter */
2209     bool       b_discontinuity = false;  /* discontinuity */
2210
2211     /* transport_scrambling_control is ignored */
2212     int         i_skip = 0;
2213     bool        i_ret  = false;
2214
2215 #if 0
2216     msg_Dbg( p_demux, "pid=%d unit_start=%d adaptation=%d payload=%d "
2217              "cc=0x%x", pid->i_pid, b_unit_start, b_adaptation,
2218              b_payload, i_cc );
2219 #endif
2220
2221     /* For now, ignore additional error correction
2222      * TODO: handle Reed-Solomon 204,188 error correction */
2223     p_bk->i_buffer = TS_PACKET_SIZE_188;
2224
2225     if( p[1]&0x80 )
2226     {
2227         msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
2228                  pid->i_pid );
2229         if( pid->es->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
2230             pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
2231     }
2232
2233     if( p_demux->p_sys->csa )
2234     {
2235         vlc_mutex_lock( &p_demux->p_sys->csa_lock );
2236         csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer, p_demux->p_sys->i_csa_pkt_size );
2237         vlc_mutex_unlock( &p_demux->p_sys->csa_lock );
2238     }
2239
2240     if( !b_adaptation )
2241     {
2242         /* We don't have any adaptation_field, so payload starts
2243          * immediately after the 4 byte TS header */
2244         i_skip = 4;
2245     }
2246     else
2247     {
2248         /* p[4] is adaptation_field_length minus one */
2249         i_skip = 5 + p[4];
2250         if( p[4] > 0 )
2251         {
2252             /* discontinuity indicator found in stream */
2253             b_discontinuity = (p[5]&0x80) ? true : false;
2254             if( b_discontinuity && pid->es->p_data )
2255             {
2256                 msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
2257                             pid->i_pid );
2258                 /* pid->es->p_data->i_flags |= BLOCK_FLAG_DISCONTINUITY; */
2259             }
2260 #if 0
2261             if( p[5]&0x40 )
2262                 msg_Dbg( p_demux, "random access indicator (pid=%d) ", pid->i_pid );
2263 #endif
2264         }
2265     }
2266
2267     /* Test continuity counter */
2268     /* continuous when (one of this):
2269         * diff == 1
2270         * diff == 0 and payload == 0
2271         * diff == 0 and duplicate packet (playload != 0) <- should we
2272         *   test the content ?
2273      */
2274     const int i_diff = ( i_cc - pid->i_cc )&0x0f;
2275     if( b_payload && i_diff == 1 )
2276     {
2277         pid->i_cc = ( pid->i_cc + 1 ) & 0xf;
2278     }
2279     else
2280     {
2281         if( pid->i_cc == 0xff )
2282         {
2283             msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
2284                       pid->i_pid, i_cc );
2285             pid->i_cc = i_cc;
2286         }
2287         else if( i_diff != 0 && !b_discontinuity )
2288         {
2289             msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x (pid=%d)",
2290                       i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );
2291
2292             pid->i_cc = i_cc;
2293             if( pid->es->p_data && pid->es->fmt.i_cat != VIDEO_ES )
2294             {
2295                 /* Small video artifacts are usually better than
2296                  * dropping full frames */
2297                 pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
2298             }
2299         }
2300     }
2301
2302     PCRHandle( p_demux, pid, p_bk );
2303
2304     if( i_skip >= 188 || pid->es->id == NULL )
2305     {
2306         block_Release( p_bk );
2307         return i_ret;
2308     }
2309
2310     /* */
2311     if( !pid->b_scrambled != !b_scrambled )
2312     {
2313         msg_Warn( p_demux, "scrambled state changed on pid %d (%d->%d)",
2314                   pid->i_pid, pid->b_scrambled, b_scrambled );
2315
2316         pid->b_scrambled = b_scrambled;
2317
2318         for( int i = 0; i < pid->i_extra_es; i++ )
2319         {
2320             es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
2321                             pid->extra_es[i]->id, b_scrambled );
2322         }
2323         es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
2324                         pid->es->id, b_scrambled );
2325     }
2326
2327     /* We have to gather it */
2328     p_bk->p_buffer += i_skip;
2329     p_bk->i_buffer -= i_skip;
2330
2331     if( b_unit_start )
2332     {
2333         if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
2334         {
2335             int i_pointer_field = __MIN( p_bk->p_buffer[0], p_bk->i_buffer - 1 );
2336             block_t *p = block_Duplicate( p_bk );
2337             if( p )
2338             {
2339                 p->i_buffer = i_pointer_field;
2340                 p->p_buffer++;
2341                 block_ChainLastAppend( &pid->es->pp_last, p );
2342             }
2343             p_bk->i_buffer -= 1 + i_pointer_field;
2344             p_bk->p_buffer += 1 + i_pointer_field;
2345         }
2346         if( pid->es->p_data )
2347         {
2348             ParseData( p_demux, pid );
2349             i_ret = true;
2350         }
2351
2352         block_ChainLastAppend( &pid->es->pp_last, p_bk );
2353         if( pid->es->data_type == TS_ES_DATA_PES )
2354         {
2355             if( p_bk->i_buffer > 6 )
2356             {
2357                 pid->es->i_data_size = GetWBE( &p_bk->p_buffer[4] );
2358                 if( pid->es->i_data_size > 0 )
2359                 {
2360                     pid->es->i_data_size += 6;
2361                 }
2362             }
2363         }
2364         else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
2365         {
2366             if( p_bk->i_buffer > 3 && p_bk->p_buffer[0] != 0xff )
2367             {
2368                 pid->es->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
2369             }
2370         }
2371         pid->es->i_data_gathered += p_bk->i_buffer;
2372         if( pid->es->i_data_size > 0 &&
2373             pid->es->i_data_gathered >= pid->es->i_data_size )
2374         {
2375             ParseData( p_demux, pid );
2376             i_ret = true;
2377         }
2378     }
2379     else
2380     {
2381         if( pid->es->p_data == NULL )
2382         {
2383             /* msg_Dbg( p_demux, "broken packet" ); */
2384             block_Release( p_bk );
2385         }
2386         else
2387         {
2388             block_ChainLastAppend( &pid->es->pp_last, p_bk );
2389             pid->es->i_data_gathered += p_bk->i_buffer;
2390
2391             if( pid->es->i_data_size > 0 &&
2392                 pid->es->i_data_gathered >= pid->es->i_data_size )
2393             {
2394                 ParseData( p_demux, pid );
2395                 i_ret = true;
2396             }
2397         }
2398     }
2399
2400     return i_ret;
2401 }
2402
2403 static void PIDFillFormat( es_format_t *fmt, int i_stream_type )
2404 {
2405     switch( i_stream_type )
2406     {
2407     case 0x01:  /* MPEG-1 video */
2408     case 0x02:  /* MPEG-2 video */
2409     case 0x80:  /* MPEG-2 MOTO video */
2410         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MPGV );
2411         break;
2412     case 0x03:  /* MPEG-1 audio */
2413     case 0x04:  /* MPEG-2 audio */
2414         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MPGA );
2415         break;
2416     case 0x11:  /* MPEG4 (audio) LATM */
2417     case 0x0f:  /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
2418     case 0x1c:  /* ISO/IEC 14496-3 Audio, without using any additional
2419                    transport syntax, such as DST, ALS and SLS */
2420         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_MP4A );
2421         break;
2422     case 0x10:  /* MPEG4 (video) */
2423         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_MP4V );
2424         break;
2425     case 0x1B:  /* H264 <- check transport syntax/needed descriptor */
2426         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_H264 );
2427         break;
2428     case 0x24:  /* HEVC */
2429         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_HEVC );
2430         break;
2431     case 0x42:  /* CAVS (Chinese AVS) */
2432         es_format_Init( fmt, VIDEO_ES, VLC_CODEC_CAVS );
2433         break;
2434
2435     case 0x81:  /* A52 (audio) */
2436         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_A52 );
2437         break;
2438     case 0x82:  /* SCTE-27 (sub) */
2439         es_format_Init( fmt, SPU_ES, VLC_CODEC_SCTE_27 );
2440         break;
2441     case 0x84:  /* SDDS (audio) */
2442         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_SDDS );
2443         break;
2444     case 0x85:  /* DTS (audio) */
2445         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_DTS );
2446         break;
2447     case 0x87: /* E-AC3 */
2448         es_format_Init( fmt, AUDIO_ES, VLC_CODEC_EAC3 );
2449         break;
2450
2451     case 0x91:  /* A52 vls (audio) */
2452         es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
2453         break;
2454     case 0x92:  /* DVD_SPU vls (sub) */
2455         es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
2456         break;
2457
2458     case 0x94:  /* SDDS (audio) */
2459         es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
2460         break;
2461
2462     case 0xa0:  /* MSCODEC vlc (video) (fixed later) */
2463         es_format_Init( fmt, UNKNOWN_ES, 0 );
2464         break;
2465
2466     case 0x06:  /* PES_PRIVATE  (fixed later) */
2467     case 0x12:  /* MPEG-4 generic (sub/scene/...) (fixed later) */
2468     case 0xEA:  /* Privately managed ES (VC-1) (fixed later */
2469     default:
2470         es_format_Init( fmt, UNKNOWN_ES, 0 );
2471         break;
2472     }
2473
2474     /* PES packets usually contain truncated frames */
2475     fmt->b_packetized = false;
2476 }
2477
2478 /*****************************************************************************
2479  * MP4 specific functions (IOD parser)
2480  *****************************************************************************/
2481 static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
2482 {
2483     unsigned int i_b;
2484     unsigned int i_len = 0;
2485     do
2486     {
2487         i_b = **pp_data;
2488         (*pp_data)++;
2489         (*pi_data)--;
2490         i_len = ( i_len << 7 ) + ( i_b&0x7f );
2491
2492     } while( i_b&0x80 && *pi_data > 0 );
2493
2494     if (i_len > *pi_data)
2495         i_len = *pi_data;
2496
2497     return i_len;
2498 }
2499
2500 static int IODGetBytes( int *pi_data, uint8_t **pp_data, size_t bytes )
2501 {
2502     uint32_t res = 0;
2503     while( *pi_data > 0 && bytes-- )
2504     {
2505         res <<= 8;
2506         res |= **pp_data;
2507         (*pp_data)++;
2508         (*pi_data)--;
2509     }
2510
2511     return res;
2512 }
2513
2514 static char* IODGetURL( int *pi_data, uint8_t **pp_data )
2515 {
2516     int len = IODGetBytes( pi_data, pp_data, 1 );
2517     if (len > *pi_data)
2518         len = *pi_data;
2519     char *url = strndup( (char*)*pp_data, len );
2520     *pp_data += len;
2521     *pi_data -= len;
2522     return url;
2523 }
2524
2525 static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
2526 {
2527     uint8_t i_iod_tag, i_iod_label, byte1, byte2, byte3;
2528
2529     iod_descriptor_t *p_iod = calloc( 1, sizeof( iod_descriptor_t ) );
2530     if( !p_iod )
2531         return NULL;
2532
2533     if( i_data < 3 )
2534     {
2535         return p_iod;
2536     }
2537
2538     byte1 = IODGetBytes( &i_data, &p_data, 1 );
2539     byte2 = IODGetBytes( &i_data, &p_data, 1 );
2540     byte3 = IODGetBytes( &i_data, &p_data, 1 );
2541     if( byte2 == 0x02 ) //old vlc's buggy implementation of the IOD_descriptor
2542     {
2543         i_iod_label = byte1;
2544         i_iod_tag = byte2;
2545     }
2546     else  //correct implementation of the IOD_descriptor
2547     {
2548         i_iod_label = byte2;
2549         i_iod_tag = byte3;
2550     }
2551
2552     ts_debug( "\n* iod label:%d tag:0x%x", i_iod_label, i_iod_tag );
2553
2554     if( i_iod_tag != 0x02 )
2555     {
2556         ts_debug( "\n ERR: tag %02x != 0x02", i_iod_tag );
2557         return p_iod;
2558     }
2559
2560     IODDescriptorLength( &i_data, &p_data );
2561
2562     uint16_t i_od_id = ( IODGetBytes( &i_data, &p_data, 1 ) << 2 );
2563     uint8_t i_flags = IODGetBytes( &i_data, &p_data, 1 );
2564     i_od_id |= i_flags >> 6;
2565     ts_debug( "\n* od_id:%d", i_od_id );
2566     ts_debug( "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
2567     if ((i_flags >> 5) & 0x01)
2568     {
2569         p_iod->psz_url = IODGetURL( &i_data, &p_data );
2570         ts_debug( "\n* url string:%s", p_iod->psz_url );
2571         ts_debug( "\n*****************************\n" );
2572         return p_iod;
2573     }
2574     else
2575     {
2576         p_iod->psz_url = NULL;
2577     }
2578
2579     /* Profile Level Indication */
2580     IODGetBytes( &i_data, &p_data, 1 ); /* OD */
2581     IODGetBytes( &i_data, &p_data, 1 ); /* scene */
2582     IODGetBytes( &i_data, &p_data, 1 ); /* audio */
2583     IODGetBytes( &i_data, &p_data, 1 ); /* visual */
2584     IODGetBytes( &i_data, &p_data, 1 ); /* graphics */
2585
2586     int i_length = 0;
2587     int i_data_sav = i_data;
2588     uint8_t *p_data_sav = p_data;
2589     for (int i = 0; i_data > 0 && i < ES_DESCRIPTOR_COUNT; i++)
2590     {
2591         es_mpeg4_descriptor_t *es_descr = &p_iod->es_descr[i];
2592
2593         p_data = p_data_sav + i_length;
2594         i_data = i_data_sav - i_length;
2595
2596         int i_tag = IODGetBytes( &i_data, &p_data, 1 );
2597         i_length = IODDescriptorLength( &i_data, &p_data );
2598
2599         i_data_sav = i_data;
2600         p_data_sav = p_data;
2601
2602         i_data = i_length;
2603
2604         if ( i_tag != 0x03 )
2605         {
2606             ts_debug( "\n* - OD tag:0x%x Unsupported", i_tag );
2607             continue;
2608         }
2609
2610         es_descr->i_es_id = IODGetBytes( &i_data, &p_data, 2 );
2611         int i_flags = IODGetBytes( &i_data, &p_data, 1 );
2612         bool b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
2613         if( b_streamDependenceFlag )
2614             IODGetBytes( &i_data, &p_data, 2 ); /* dependOn_es_id */
2615
2616         if( (i_flags >> 6) & 0x01 )
2617             es_descr->psz_url = IODGetURL( &i_data, &p_data );
2618
2619         bool b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
2620         if( b_OCRStreamFlag )
2621             IODGetBytes( &i_data, &p_data, 2 ); /* OCR_es_id */
2622
2623         if( IODGetBytes( &i_data, &p_data, 1 ) != 0x04 )
2624         {
2625             ts_debug( "\n* ERR missing DecoderConfigDescr" );
2626             continue;
2627         }
2628         int i_config_desc_length = IODDescriptorLength( &i_data, &p_data ); /* DecoderConfigDescr_length */
2629         decoder_config_descriptor_t *dec_descr = &es_descr->dec_descr;
2630         dec_descr->i_objectTypeIndication = IODGetBytes( &i_data, &p_data, 1 );
2631         i_flags = IODGetBytes( &i_data, &p_data, 1 );
2632         dec_descr->i_streamType = i_flags >> 2;
2633
2634         IODGetBytes( &i_data, &p_data, 3); /* bufferSizeDB */
2635         IODGetBytes( &i_data, &p_data, 4); /* maxBitrate */
2636         IODGetBytes( &i_data, &p_data, 4 ); /* avgBitrate */
2637
2638         if( i_config_desc_length > 13 && IODGetBytes( &i_data, &p_data, 1 ) == 0x05 )
2639         {
2640             dec_descr->i_extra = IODDescriptorLength( &i_data, &p_data );
2641             if( dec_descr->i_extra > 0 )
2642             {
2643                 dec_descr->p_extra = xmalloc( dec_descr->i_extra );
2644                 memcpy(dec_descr->p_extra, p_data, dec_descr->i_extra);
2645                 p_data += dec_descr->i_extra;
2646                 i_data -= dec_descr->i_extra;
2647             }
2648         }
2649         else
2650         {
2651             dec_descr->i_extra = 0;
2652             dec_descr->p_extra = NULL;
2653         }
2654
2655         if( IODGetBytes( &i_data, &p_data, 1 ) != 0x06 )
2656         {
2657             ts_debug( "\n* ERR missing SLConfigDescr" );
2658             continue;
2659         }
2660         IODDescriptorLength( &i_data, &p_data ); /* SLConfigDescr_length */
2661         switch( IODGetBytes( &i_data, &p_data, 1 ) /* predefined */ )
2662         {
2663         default:
2664             ts_debug( "\n* ERR unsupported SLConfigDescr predefined" );
2665         case 0x01:
2666             // FIXME
2667             break;
2668         }
2669         es_descr->b_ok = true;
2670     }
2671
2672     return p_iod;
2673 }
2674
2675 static void IODFree( iod_descriptor_t *p_iod )
2676 {
2677     if( p_iod->psz_url )
2678     {
2679         free( p_iod->psz_url );
2680         free( p_iod );
2681         return;
2682     }
2683
2684     for( int i = 0; i < 255; i++ )
2685     {
2686 #define es_descr p_iod->es_descr[i]
2687         if( es_descr.b_ok )
2688         {
2689             if( es_descr.psz_url )
2690                 free( es_descr.psz_url );
2691             else
2692                 free( es_descr.dec_descr.p_extra );
2693         }
2694 #undef  es_descr
2695     }
2696     free( p_iod );
2697 }
2698
2699 /****************************************************************************
2700  ****************************************************************************
2701  ** libdvbpsi callbacks
2702  ****************************************************************************
2703  ****************************************************************************/
2704 static bool ProgramIsSelected( demux_t *p_demux, uint16_t i_pgrm )
2705 {
2706     demux_sys_t          *p_sys = p_demux->p_sys;
2707
2708     if( ( p_sys->i_current_program == -1 && p_sys->programs_list.i_count == 0 ) ||
2709         p_sys->i_current_program == 0 )
2710         return true;
2711     if( p_sys->i_current_program == i_pgrm )
2712         return true;
2713
2714     if( p_sys->programs_list.i_count != 0 )
2715     {
2716         for( int i = 0; i < p_sys->programs_list.i_count; i++ )
2717         {
2718             if( i_pgrm == p_sys->programs_list.p_values[i].i_int )
2719                 return true;
2720         }
2721     }
2722     return false;
2723 }
2724
2725 static void ValidateDVBMeta( demux_t *p_demux, int i_pid )
2726 {
2727     demux_sys_t *p_sys = p_demux->p_sys;
2728
2729     if( !p_sys->b_dvb_meta || ( i_pid != 0x11 && i_pid != 0x12 && i_pid != 0x14 ) )
2730         return;
2731
2732     msg_Warn( p_demux, "Switching to non DVB mode" );
2733
2734     /* This doesn't look like a DVB stream so don't try
2735      * parsing the SDT/EDT/TDT */
2736
2737     for( int i = 0x11; i <= 0x14; i++ )
2738     {
2739         if( i == 0x13 ) continue;
2740         ts_pid_t *p_pid = &p_sys->pid[i];
2741         if( p_pid->psi )
2742         {
2743
2744 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
2745             if( dvbpsi_decoder_present( p_pid->psi->handle ))
2746                 dvbpsi_DetachDemux( p_pid->psi->handle );
2747             dvbpsi_delete( p_pid->psi->handle );
2748 #else
2749             dvbpsi_DetachDemux( p_pid->psi->handle );
2750 #endif
2751             free( p_pid->psi );
2752             p_pid->psi = NULL;
2753             p_pid->b_valid = false;
2754         }
2755         SetPIDFilter( p_demux, i, false );
2756     }
2757     p_sys->b_dvb_meta = false;
2758 }
2759
2760 #include "dvb-text.h"
2761
2762 static char *EITConvertToUTF8( const unsigned char *psz_instring,
2763                                size_t i_length,
2764                                bool b_broken )
2765 {
2766     /* Deal with no longer broken providers (no switch byte
2767       but sending ISO_8859-1 instead of ISO_6937) without
2768       removing them from the broken providers table
2769       (keep the entry for correctly handling recorded TS).
2770     */
2771     b_broken = b_broken && i_length && *psz_instring > 0x20;
2772
2773     if( b_broken )
2774         return FromCharset( "ISO_8859-1", psz_instring, i_length );
2775     return vlc_from_EIT( psz_instring, i_length );
2776 }
2777
2778 static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
2779 {
2780     demux_sys_t          *p_sys = p_demux->p_sys;
2781     ts_pid_t             *sdt = &p_sys->pid[0x11];
2782     dvbpsi_sdt_service_t *p_srv;
2783
2784     msg_Dbg( p_demux, "SDTCallBack called" );
2785
2786     if( sdt->psi->i_sdt_version != -1 &&
2787         ( !p_sdt->b_current_next ||
2788           p_sdt->i_version == sdt->psi->i_sdt_version ) )
2789     {
2790         dvbpsi_DeleteSDT( p_sdt );
2791         return;
2792     }
2793
2794     msg_Dbg( p_demux, "new SDT ts_id=%d version=%d current_next=%d "
2795              "network_id=%d",
2796 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
2797              p_sdt->i_extension,
2798 #else
2799              p_sdt->i_ts_id,
2800 #endif
2801              p_sdt->i_version, p_sdt->b_current_next,
2802              p_sdt->i_network_id );
2803
2804     p_sys->b_broken_charset = false;
2805
2806     for( p_srv = p_sdt->p_first_service; p_srv; p_srv = p_srv->p_next )
2807     {
2808         vlc_meta_t          *p_meta;
2809         dvbpsi_descriptor_t *p_dr;
2810
2811         const char *psz_type = NULL;
2812         const char *psz_status = NULL;
2813
2814         msg_Dbg( p_demux, "  * service id=%d eit schedule=%d present=%d "
2815                  "running=%d free_ca=%d",
2816                  p_srv->i_service_id, p_srv->b_eit_schedule,
2817                  p_srv->b_eit_present, p_srv->i_running_status,
2818                  p_srv->b_free_ca );
2819
2820         p_meta = vlc_meta_New();
2821         for( p_dr = p_srv->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
2822         {
2823             if( p_dr->i_tag == 0x48 )
2824             {
2825                 static const char *ppsz_type[17] = {
2826                     "Reserved",
2827                     "Digital television service",
2828                     "Digital radio sound service",
2829                     "Teletext service",
2830                     "NVOD reference service",
2831                     "NVOD time-shifted service",
2832                     "Mosaic service",
2833                     "PAL coded signal",
2834                     "SECAM coded signal",
2835                     "D/D2-MAC",
2836                     "FM Radio",
2837                     "NTSC coded signal",
2838                     "Data broadcast service",
2839                     "Reserved for Common Interface Usage",
2840                     "RCS Map (see EN 301 790 [35])",
2841                     "RCS FLS (see EN 301 790 [35])",
2842                     "DVB MHP service"
2843                 };
2844                 dvbpsi_service_dr_t *pD = dvbpsi_DecodeServiceDr( p_dr );
2845                 char *str1 = NULL;
2846                 char *str2 = NULL;
2847
2848                 /* Workarounds for broadcasters with broken EPG */
2849
2850                 if( p_sdt->i_network_id == 133 )
2851                     p_sys->b_broken_charset = true;  /* SKY DE & BetaDigital use ISO8859-1 */
2852
2853                 /* List of providers using ISO8859-1 */
2854                 static const char ppsz_broken_providers[][8] = {
2855                     "CSAT",     /* CanalSat FR */
2856                     "GR1",      /* France televisions */
2857                     "MULTI4",   /* NT1 */
2858                     "MR5",      /* France 2/M6 HD */
2859                     ""
2860                 };
2861                 for( int i = 0; *ppsz_broken_providers[i]; i++ )
2862                 {
2863                     const size_t i_length = strlen(ppsz_broken_providers[i]);
2864                     if( pD->i_service_provider_name_length == i_length &&
2865                         !strncmp( (char *)pD->i_service_provider_name, ppsz_broken_providers[i], i_length ) )
2866                         p_sys->b_broken_charset = true;
2867                 }
2868
2869                 /* FIXME: Digital+ ES also uses ISO8859-1 */
2870
2871                 str1 = EITConvertToUTF8(pD->i_service_provider_name,
2872                                         pD->i_service_provider_name_length,
2873                                         p_sys->b_broken_charset );
2874                 str2 = EITConvertToUTF8(pD->i_service_name,
2875                                         pD->i_service_name_length,
2876                                         p_sys->b_broken_charset );
2877
2878                 msg_Dbg( p_demux, "    - type=%d provider=%s name=%s",
2879                          pD->i_service_type, str1, str2 );
2880
2881                 vlc_meta_SetTitle( p_meta, str2 );
2882                 vlc_meta_SetPublisher( p_meta, str1 );
2883                 if( pD->i_service_type >= 0x01 && pD->i_service_type <= 0x10 )
2884                     psz_type = ppsz_type[pD->i_service_type];
2885                 free( str1 );
2886                 free( str2 );
2887             }
2888         }
2889
2890         if( p_srv->i_running_status >= 0x01 && p_srv->i_running_status <= 0x04 )
2891         {
2892             static const char *ppsz_status[5] = {
2893                 "Unknown",
2894                 "Not running",
2895                 "Starts in a few seconds",
2896                 "Pausing",
2897                 "Running"
2898             };
2899             psz_status = ppsz_status[p_srv->i_running_status];
2900         }
2901
2902         if( psz_type )
2903             vlc_meta_AddExtra( p_meta, "Type", psz_type );
2904         if( psz_status )
2905             vlc_meta_AddExtra( p_meta, "Status", psz_status );
2906
2907         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_META,
2908                         p_srv->i_service_id, p_meta );
2909         vlc_meta_Delete( p_meta );
2910     }
2911
2912     sdt->psi->i_sdt_version = p_sdt->i_version;
2913     dvbpsi_DeleteSDT( p_sdt );
2914 }
2915
2916 /* i_year: year - 1900  i_month: 0-11  i_mday: 1-31 i_hour: 0-23 i_minute: 0-59 i_second: 0-59 */
2917 static int64_t vlc_timegm( int i_year, int i_month, int i_mday, int i_hour, int i_minute, int i_second )
2918 {
2919     static const int pn_day[12+1] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
2920     int64_t i_day;
2921
2922     if( i_year < 70 ||
2923         i_month < 0 || i_month > 11 || i_mday < 1 || i_mday > 31 ||
2924         i_hour < 0 || i_hour > 23 || i_minute < 0 || i_minute > 59 || i_second < 0 || i_second > 59 )
2925         return -1;
2926
2927     /* Count the number of days */
2928     i_day = 365 * (i_year-70) + pn_day[i_month] + i_mday - 1;
2929 #define LEAP(y) ( ((y)%4) == 0 && (((y)%100) != 0 || ((y)%400) == 0) ? 1 : 0)
2930     for( int i = 70; i < i_year; i++ )
2931         i_day += LEAP(1900+i);
2932     if( i_month > 1 )
2933         i_day += LEAP(1900+i_year);
2934 #undef LEAP
2935     /**/
2936     return ((24*i_day + i_hour)*60 + i_minute)*60 + i_second;
2937 }
2938
2939 static void EITDecodeMjd( int i_mjd, int *p_y, int *p_m, int *p_d )
2940 {
2941     const int yp = (int)( ( (double)i_mjd - 15078.2)/365.25 );
2942     const int mp = (int)( ((double)i_mjd - 14956.1 - (int)(yp * 365.25)) / 30.6001 );
2943     const int c = ( mp == 14 || mp == 15 ) ? 1 : 0;
2944
2945     *p_y = 1900 + yp + c*1;
2946     *p_m = mp - 1 - c*12;
2947     *p_d = i_mjd - 14956 - (int)(yp*365.25) - (int)(mp*30.6001);
2948 }
2949 #define CVT_FROM_BCD(v) ((((v) >> 4)&0xf)*10 + ((v)&0xf))
2950 static int64_t EITConvertStartTime( uint64_t i_date )
2951 {
2952     const int i_mjd = i_date >> 24;
2953     const int i_hour   = CVT_FROM_BCD(i_date >> 16);
2954     const int i_minute = CVT_FROM_BCD(i_date >>  8);
2955     const int i_second = CVT_FROM_BCD(i_date      );
2956     int i_year;
2957     int i_month;
2958     int i_day;
2959
2960     /* if all 40 bits are 1, the start is unknown */
2961     if( i_date == UINT64_C(0xffffffffff) )
2962         return -1;
2963
2964     EITDecodeMjd( i_mjd, &i_year, &i_month, &i_day );
2965     return vlc_timegm( i_year - 1900, i_month - 1, i_day, i_hour, i_minute, i_second );
2966 }
2967 static int EITConvertDuration( uint32_t i_duration )
2968 {
2969     return CVT_FROM_BCD(i_duration >> 16) * 3600 +
2970            CVT_FROM_BCD(i_duration >> 8 ) * 60 +
2971            CVT_FROM_BCD(i_duration      );
2972 }
2973 #undef CVT_FROM_BCD
2974
2975 static void TDTCallBack( demux_t *p_demux, dvbpsi_tot_t *p_tdt )
2976 {
2977     demux_sys_t        *p_sys = p_demux->p_sys;
2978
2979     p_sys->i_tdt_delta = CLOCK_FREQ * EITConvertStartTime( p_tdt->i_utc_time )
2980                          - mdate();
2981     dvbpsi_DeleteTOT(p_tdt);
2982 }
2983
2984
2985 static void EITCallBack( demux_t *p_demux,
2986                          dvbpsi_eit_t *p_eit, bool b_current_following )
2987 {
2988     demux_sys_t        *p_sys = p_demux->p_sys;
2989     dvbpsi_eit_event_t *p_evt;
2990     vlc_epg_t *p_epg;
2991
2992     msg_Dbg( p_demux, "EITCallBack called" );
2993     if( !p_eit->b_current_next )
2994     {
2995         dvbpsi_DeleteEIT( p_eit );
2996         return;
2997     }
2998
2999     msg_Dbg( p_demux, "new EIT service_id=%d version=%d current_next=%d "
3000              "ts_id=%d network_id=%d segment_last_section_number=%d "
3001              "last_table_id=%d",
3002 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
3003              p_eit->i_extension,
3004 #else
3005              p_eit->i_service_id,
3006 #endif
3007              p_eit->i_version, p_eit->b_current_next,
3008              p_eit->i_ts_id, p_eit->i_network_id,
3009              p_eit->i_segment_last_section_number, p_eit->i_last_table_id );
3010
3011     p_epg = vlc_epg_New( NULL );
3012     for( p_evt = p_eit->p_first_event; p_evt; p_evt = p_evt->p_next )
3013     {
3014         dvbpsi_descriptor_t *p_dr;
3015         char                *psz_name = NULL;
3016         char                *psz_text = NULL;
3017         char                *psz_extra = strdup("");
3018         int64_t i_start;
3019         int i_duration;
3020         int i_min_age = 0;
3021
3022         i_start = EITConvertStartTime( p_evt->i_start_time );
3023         i_duration = EITConvertDuration( p_evt->i_duration );
3024
3025         msg_Dbg( p_demux, "  * event id=%d start_time:%d duration=%d "
3026                           "running=%d free_ca=%d",
3027                  p_evt->i_event_id, (int)i_start, (int)i_duration,
3028                  p_evt->i_running_status, p_evt->b_free_ca );
3029
3030         for( p_dr = p_evt->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
3031         {
3032             if( p_dr->i_tag == 0x4d )
3033             {
3034                 dvbpsi_short_event_dr_t *pE = dvbpsi_DecodeShortEventDr( p_dr );
3035
3036                 /* Only take first description, as we don't handle language-info
3037                    for epg atm*/
3038                 if( pE && psz_name == NULL)
3039                 {
3040                     psz_name = EITConvertToUTF8( pE->i_event_name, pE->i_event_name_length,
3041                                                  p_sys->b_broken_charset );
3042                     psz_text = EITConvertToUTF8( pE->i_text, pE->i_text_length,
3043                                                  p_sys->b_broken_charset );
3044                     msg_Dbg( p_demux, "    - short event lang=%3.3s '%s' : '%s'",
3045                              pE->i_iso_639_code, psz_name, psz_text );
3046                 }
3047             }
3048             else if( p_dr->i_tag == 0x4e )
3049             {
3050                 dvbpsi_extended_event_dr_t *pE = dvbpsi_DecodeExtendedEventDr( p_dr );
3051                 if( pE )
3052                 {
3053                     msg_Dbg( p_demux, "    - extended event lang=%3.3s [%d/%d]",
3054                              pE->i_iso_639_code,
3055                              pE->i_descriptor_number, pE->i_last_descriptor_number );
3056
3057                     if( pE->i_text_length > 0 )
3058                     {
3059                         char *psz_text = EITConvertToUTF8( pE->i_text, pE->i_text_length,
3060                                                            p_sys->b_broken_charset );
3061                         if( psz_text )
3062                         {
3063                             msg_Dbg( p_demux, "       - text='%s'", psz_text );
3064
3065                             psz_extra = xrealloc( psz_extra,
3066                                    strlen(psz_extra) + strlen(psz_text) + 1 );
3067                             strcat( psz_extra, psz_text );
3068                             free( psz_text );
3069                         }
3070                     }
3071
3072                     for( int i = 0; i < pE->i_entry_count; i++ )
3073                     {
3074                         char *psz_dsc = EITConvertToUTF8( pE->i_item_description[i],
3075                                                           pE->i_item_description_length[i],
3076                                                           p_sys->b_broken_charset );
3077                         char *psz_itm = EITConvertToUTF8( pE->i_item[i], pE->i_item_length[i],
3078                                                           p_sys->b_broken_charset );
3079
3080                         if( psz_dsc && psz_itm )
3081                         {
3082                             msg_Dbg( p_demux, "       - desc='%s' item='%s'", psz_dsc, psz_itm );
3083 #if 0
3084                             psz_extra = xrealloc( psz_extra,
3085                                          strlen(psz_extra) + strlen(psz_dsc) +
3086                                          strlen(psz_itm) + 3 + 1 );
3087                             strcat( psz_extra, "(" );
3088                             strcat( psz_extra, psz_dsc );
3089                             strcat( psz_extra, " " );
3090                             strcat( psz_extra, psz_itm );
3091                             strcat( psz_extra, ")" );
3092 #endif
3093                         }
3094                         free( psz_dsc );
3095                         free( psz_itm );
3096                     }
3097                 }
3098             }
3099             else if( p_dr->i_tag == 0x55 )
3100             {
3101                 dvbpsi_parental_rating_dr_t *pR = dvbpsi_DecodeParentalRatingDr( p_dr );
3102                 if ( pR )
3103                 {
3104                     for ( int i = 0; i < pR->i_ratings_number; i++ )
3105                     {
3106                         const dvbpsi_parental_rating_t *p_rating = & pR->p_parental_rating[ i ];
3107                         if ( p_rating->i_rating > 0x00 && p_rating->i_rating <= 0x0F )
3108                         {
3109                             if ( p_rating->i_rating + 3 > i_min_age )
3110                                 i_min_age = p_rating->i_rating + 3;
3111                             msg_Dbg( p_demux, "..* event parental control set to %d years",
3112                                      i_min_age );
3113                         }
3114                     }
3115                 }
3116             }
3117             else
3118             {
3119                 msg_Dbg( p_demux, "    - tag=0x%x(%d)", p_dr->i_tag, p_dr->i_tag );
3120             }
3121         }
3122
3123         /* */
3124         if( i_start > 0 )
3125             vlc_epg_AddEvent( p_epg, i_start, i_duration, psz_name, psz_text,
3126                               *psz_extra ? psz_extra : NULL, i_min_age );
3127
3128         /* Update "now playing" field */
3129         if( p_evt->i_running_status == 0x04 && i_start > 0 )
3130             vlc_epg_SetCurrent( p_epg, i_start );
3131
3132         free( psz_name );
3133         free( psz_text );
3134
3135         free( psz_extra );
3136     }
3137     if( p_epg->i_event > 0 )
3138     {
3139         if( b_current_following &&
3140             (  p_sys->i_current_program == -1 ||
3141                p_sys->i_current_program ==
3142 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
3143                     p_eit->i_extension
3144 #else
3145                     p_eit->i_service_id
3146 #endif
3147                 ) )
3148         {
3149             p_sys->i_dvb_length = 0;
3150             p_sys->i_dvb_start = 0;
3151
3152             if( p_epg->p_current )
3153             {
3154                 p_sys->i_dvb_start = CLOCK_FREQ * p_epg->p_current->i_start;
3155                 p_sys->i_dvb_length = CLOCK_FREQ * p_epg->p_current->i_duration;
3156             }
3157         }
3158         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_EPG,
3159 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
3160                         p_eit->i_extension,
3161 #else
3162                         p_eit->i_service_id,
3163 #endif
3164                         p_epg );
3165     }
3166     vlc_epg_Delete( p_epg );
3167
3168     dvbpsi_DeleteEIT( p_eit );
3169 }
3170 static void EITCallBackCurrentFollowing( demux_t *p_demux, dvbpsi_eit_t *p_eit )
3171 {
3172     EITCallBack( p_demux, p_eit, true );
3173 }
3174 static void EITCallBackSchedule( demux_t *p_demux, dvbpsi_eit_t *p_eit )
3175 {
3176     EITCallBack( p_demux, p_eit, false );
3177 }
3178
3179 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
3180 static void PSINewTableCallBack( dvbpsi_t *h, uint8_t i_table_id,
3181                                  uint16_t i_extension, demux_t *p_demux )
3182 #else
3183 static void PSINewTableCallBack( demux_t *p_demux, dvbpsi_handle h,
3184                                  uint8_t  i_table_id, uint16_t i_extension )
3185 #endif
3186 {
3187     assert( h );
3188 #if 0
3189     msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
3190              i_table_id, i_table_id, i_extension, i_extension );
3191 #endif
3192     if( p_demux->p_sys->pid[0].psi->i_pat_version != -1 && i_table_id == 0x42 )
3193     {
3194         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
3195                  i_table_id, i_table_id, i_extension, i_extension );
3196 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
3197         if( !dvbpsi_sdt_attach( h, i_table_id, i_extension, (dvbpsi_sdt_callback)SDTCallBack, p_demux ) )
3198             msg_Err( p_demux, "PSINewTableCallback: failed attaching SDTCallback" );
3199 #else
3200         dvbpsi_AttachSDT( h, i_table_id, i_extension,
3201                           (dvbpsi_sdt_callback)SDTCallBack, p_demux );
3202 #endif
3203     }
3204     else if( p_demux->p_sys->pid[0x11].psi->i_sdt_version != -1 &&
3205              ( i_table_id == 0x4e || /* Current/Following */
3206                (i_table_id >= 0x50 && i_table_id <= 0x5f) ) ) /* Schedule */
3207     {
3208         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
3209                  i_table_id, i_table_id, i_extension, i_extension );
3210
3211         dvbpsi_eit_callback cb = i_table_id == 0x4e ?
3212                                     (dvbpsi_eit_callback)EITCallBackCurrentFollowing :
3213                                     (dvbpsi_eit_callback)EITCallBackSchedule;
3214 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
3215         if( !dvbpsi_eit_attach( h, i_table_id, i_extension, cb, p_demux ) )
3216             msg_Err( p_demux, "PSINewTableCallback: failed attaching EITCallback" );
3217 #else
3218         dvbpsi_AttachEIT( h, i_table_id, i_extension, cb, p_demux );
3219 #endif
3220     }
3221     else if( p_demux->p_sys->pid[0x11].psi->i_sdt_version != -1 &&
3222               i_table_id == 0x70 )  /* TDT */
3223     {
3224          msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
3225                  i_table_id, i_table_id, i_extension, i_extension );
3226 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
3227         if( !dvbpsi_tot_attach( h, i_table_id, i_extension, (dvbpsi_tot_callback)TDTCallBack, p_demux ) )
3228             msg_Err( p_demux, "PSINewTableCallback: failed attaching TDTCallback" );
3229 #else
3230          dvbpsi_AttachTOT( h, i_table_id, i_extension,
3231                            (dvbpsi_tot_callback)TDTCallBack, p_demux);
3232 #endif
3233     }
3234 }
3235
3236 /*****************************************************************************
3237  * PMT callback and helpers
3238  *****************************************************************************/
3239 static dvbpsi_descriptor_t *PMTEsFindDescriptor( const dvbpsi_pmt_es_t *p_es,
3240                                                  int i_tag )
3241 {
3242     dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
3243     while( p_dr && ( p_dr->i_tag != i_tag ) )
3244         p_dr = p_dr->p_next;
3245     return p_dr;
3246 }
3247 static bool PMTEsHasRegistration( demux_t *p_demux,
3248                                   const dvbpsi_pmt_es_t *p_es,
3249                                   const char *psz_tag )
3250 {
3251     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x05 );
3252     if( !p_dr )
3253         return false;
3254
3255     if( p_dr->i_length < 4 )
3256     {
3257         msg_Warn( p_demux, "invalid Registration Descriptor" );
3258         return false;
3259     }
3260
3261     assert( strlen(psz_tag) == 4 );
3262     return !memcmp( p_dr->p_data, psz_tag, 4 );
3263 }
3264 static void PMTSetupEsISO14496( demux_t *p_demux, ts_pid_t *pid,
3265                                 const ts_prg_psi_t *prg, const dvbpsi_pmt_es_t *p_es )
3266 {
3267     es_format_t *p_fmt = &pid->es->fmt;
3268
3269     /* MPEG-4 stream: search FMC_DESCRIPTOR (SL Packetized stream) */
3270     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x1f );
3271
3272     if( p_dr && p_dr->i_length == 2 )
3273     {
3274         const int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
3275
3276         msg_Dbg( p_demux, "found FMC_descriptor declaring sl packetization on es_id=%d", i_es_id );
3277
3278         pid->es->p_mpeg4desc = NULL;
3279
3280         for( int i = 0; i < ES_DESCRIPTOR_COUNT; i++ )
3281         {
3282             iod_descriptor_t *iod = prg->iod;
3283             if( iod->es_descr[i].i_es_id == i_es_id )
3284             {
3285                 if ( iod->es_descr[i].b_ok )
3286                     pid->es->p_mpeg4desc = &iod->es_descr[i];
3287                 else
3288                     msg_Dbg( p_demux, "MPEG-4 descriptor not yet available on es_id=%d", i_es_id );
3289                 break;
3290             }
3291         }
3292     }
3293     if( !pid->es->p_mpeg4desc )
3294     {
3295         msg_Err( p_demux, "MPEG-4 descriptor not found" );
3296         return;
3297     }
3298
3299     const decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
3300     if( dcd->i_streamType == 0x04 )    /* VisualStream */
3301     {
3302         p_fmt->i_cat = VIDEO_ES;
3303         switch( dcd->i_objectTypeIndication )
3304         {
3305         case 0x0B: /* mpeg4 sub */
3306             p_fmt->i_cat = SPU_ES;
3307             p_fmt->i_codec = VLC_CODEC_SUBT;
3308             break;
3309
3310         case 0x20: /* mpeg4 */
3311             p_fmt->i_codec = VLC_CODEC_MP4V;
3312             break;
3313         case 0x21: /* h264 */
3314             p_fmt->i_codec = VLC_CODEC_H264;
3315             break;
3316         case 0x60:
3317         case 0x61:
3318         case 0x62:
3319         case 0x63:
3320         case 0x64:
3321         case 0x65: /* mpeg2 */
3322             p_fmt->i_codec = VLC_CODEC_MPGV;
3323             break;
3324         case 0x6a: /* mpeg1 */
3325             p_fmt->i_codec = VLC_CODEC_MPGV;
3326             break;
3327         case 0x6c: /* mpeg1 */
3328             p_fmt->i_codec = VLC_CODEC_JPEG;
3329             break;
3330         default:
3331             p_fmt->i_cat = UNKNOWN_ES;
3332             break;
3333         }
3334     }
3335     else if( dcd->i_streamType == 0x05 )    /* AudioStream */
3336     {
3337         p_fmt->i_cat = AUDIO_ES;
3338         switch( dcd->i_objectTypeIndication )
3339         {
3340         case 0x40: /* mpeg4 */
3341             p_fmt->i_codec = VLC_CODEC_MP4A;
3342             break;
3343         case 0x66:
3344         case 0x67:
3345         case 0x68: /* mpeg2 aac */
3346             p_fmt->i_codec = VLC_CODEC_MP4A;
3347             break;
3348         case 0x69: /* mpeg2 */
3349             p_fmt->i_codec = VLC_CODEC_MPGA;
3350             break;
3351         case 0x6b: /* mpeg1 */
3352             p_fmt->i_codec = VLC_CODEC_MPGA;
3353             break;
3354         default:
3355             p_fmt->i_cat = UNKNOWN_ES;
3356             break;
3357         }
3358     }
3359     else
3360     {
3361         p_fmt->i_cat = UNKNOWN_ES;
3362     }
3363
3364     if( p_fmt->i_cat != UNKNOWN_ES )
3365     {
3366         p_fmt->i_extra = dcd->i_extra;
3367         if( p_fmt->i_extra > 0 )
3368         {
3369             p_fmt->p_extra = malloc( p_fmt->i_extra );
3370             if( p_fmt->p_extra )
3371                 memcpy( p_fmt->p_extra, dcd->p_extra, p_fmt->i_extra );
3372             else
3373                 p_fmt->i_extra = 0;
3374         }
3375     }
3376 }
3377
3378 typedef struct
3379 {
3380     int  i_type;
3381     int  i_magazine;
3382     int  i_page;
3383     char p_iso639[3];
3384 } ts_teletext_page_t;
3385
3386 static void PMTSetupEsTeletext( demux_t *p_demux, ts_pid_t *pid,
3387                                 const dvbpsi_pmt_es_t *p_es )
3388 {
3389     es_format_t *p_fmt = &pid->es->fmt;
3390
3391     ts_teletext_page_t p_page[2 * 64 + 20];
3392     unsigned i_page = 0;
3393
3394     /* Gather pages information */
3395 #if defined _DVBPSI_DR_56_H_ && \
3396     defined DVBPSI_VERSION && DVBPSI_VERSION_INT > DVBPSI_VERSION_WANTED(0,1,5)
3397     for( unsigned i_tag_idx = 0; i_tag_idx < 2; i_tag_idx++ )
3398     {
3399         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, i_tag_idx == 0 ? 0x46 : 0x56 );
3400         if( !p_dr )
3401             continue;
3402
3403         dvbpsi_teletext_dr_t *p_sub = dvbpsi_DecodeTeletextDr( p_dr );
3404         if( !p_sub )
3405             continue;
3406
3407         for( int i = 0; i < p_sub->i_pages_number; i++ )
3408         {
3409             const dvbpsi_teletextpage_t *p_src = &p_sub->p_pages[i];
3410
3411             if( p_src->i_teletext_type >= 0x06 )
3412                 continue;
3413
3414             assert( i_page < sizeof(p_page)/sizeof(*p_page) );
3415
3416             ts_teletext_page_t *p_dst = &p_page[i_page++];
3417
3418             p_dst->i_type = p_src->i_teletext_type;
3419             p_dst->i_magazine = p_src->i_teletext_magazine_number
3420                 ? p_src->i_teletext_magazine_number : 8;
3421             p_dst->i_page = p_src->i_teletext_page_number;
3422             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
3423         }
3424     }
3425 #endif
3426
3427     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
3428     if( p_dr )
3429     {
3430         dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
3431         for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
3432         {
3433             dvbpsi_subtitle_t *p_src = &p_sub->p_subtitle[i];
3434
3435             if( p_src->i_subtitling_type < 0x01 || p_src->i_subtitling_type > 0x03 )
3436                 continue;
3437
3438             assert( i_page < sizeof(p_page)/sizeof(*p_page) );
3439
3440             ts_teletext_page_t *p_dst = &p_page[i_page++];
3441
3442             switch( p_src->i_subtitling_type )
3443             {
3444             case 0x01:
3445                 p_dst->i_type = 0x02;
3446                 break;
3447             default:
3448                 p_dst->i_type = 0x03;
3449                 break;
3450             }
3451             /* FIXME check if it is the right split */
3452             p_dst->i_magazine = (p_src->i_composition_page_id >> 8)
3453                 ? (p_src->i_composition_page_id >> 8) : 8;
3454             p_dst->i_page = p_src->i_composition_page_id & 0xff;
3455             memcpy( p_dst->p_iso639, p_src->i_iso6392_language_code, 3 );
3456         }
3457     }
3458
3459     /* */
3460     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_TELETEXT );
3461
3462     if( !p_demux->p_sys->b_split_es || i_page <= 0 )
3463     {
3464         p_fmt->subs.teletext.i_magazine = -1;
3465         p_fmt->subs.teletext.i_page = 0;
3466         p_fmt->psz_description = strdup( vlc_gettext(ppsz_teletext_type[1]) );
3467
3468         dvbpsi_descriptor_t *p_dr;
3469         p_dr = PMTEsFindDescriptor( p_es, 0x46 );
3470         if( !p_dr )
3471             p_dr = PMTEsFindDescriptor( p_es, 0x56 );
3472
3473         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
3474         {
3475             /* Descriptor pass-through */
3476             p_fmt->p_extra = malloc( p_dr->i_length );
3477             if( p_fmt->p_extra )
3478             {
3479                 p_fmt->i_extra = p_dr->i_length;
3480                 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
3481             }
3482         }
3483     }
3484     else
3485     {
3486         for( unsigned i = 0; i < i_page; i++ )
3487         {
3488             ts_es_t *p_es;
3489
3490             /* */
3491             if( i == 0 )
3492             {
3493                 p_es = pid->es;
3494             }
3495             else
3496             {
3497                 p_es = malloc( sizeof(*p_es) );
3498                 if( !p_es )
3499                     break;
3500
3501                 es_format_Copy( &p_es->fmt, &pid->es->fmt );
3502                 free( p_es->fmt.psz_language );
3503                 free( p_es->fmt.psz_description );
3504                 p_es->fmt.psz_language = NULL;
3505                 p_es->fmt.psz_description = NULL;
3506
3507                 p_es->id      = NULL;
3508                 p_es->p_data  = NULL;
3509                 p_es->i_data_size = 0;
3510                 p_es->i_data_gathered = 0;
3511                 p_es->pp_last = &p_es->p_data;
3512                 p_es->data_type = TS_ES_DATA_PES;
3513                 p_es->p_mpeg4desc = NULL;
3514
3515                 TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
3516             }
3517
3518             /* */
3519             const ts_teletext_page_t *p = &p_page[i];
3520             p_es->fmt.i_priority = (p->i_type == 0x02 || p->i_type == 0x05) ?
3521                       ES_PRIORITY_SELECTABLE_MIN : ES_PRIORITY_NOT_DEFAULTABLE;
3522             p_es->fmt.psz_language = strndup( p->p_iso639, 3 );
3523             p_es->fmt.psz_description = strdup(vlc_gettext(ppsz_teletext_type[p->i_type]));
3524             p_es->fmt.subs.teletext.i_magazine = p->i_magazine;
3525             p_es->fmt.subs.teletext.i_page = p->i_page;
3526
3527             msg_Dbg( p_demux,
3528                          "    * ttxt type=%s lan=%s page=%d%02x",
3529                          p_es->fmt.psz_description,
3530                          p_es->fmt.psz_language,
3531                          p->i_magazine, p->i_page );
3532         }
3533     }
3534 }
3535 static void PMTSetupEsDvbSubtitle( demux_t *p_demux, ts_pid_t *pid,
3536                                    const dvbpsi_pmt_es_t *p_es )
3537 {
3538     es_format_t *p_fmt = &pid->es->fmt;
3539
3540     es_format_Init( p_fmt, SPU_ES, VLC_CODEC_DVBS );
3541
3542     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
3543     int i_page = 0;
3544     dvbpsi_subtitling_dr_t *p_sub = dvbpsi_DecodeSubtitlingDr( p_dr );
3545     for( int i = 0; p_sub && i < p_sub->i_subtitles_number; i++ )
3546     {
3547         const int i_type = p_sub->p_subtitle[i].i_subtitling_type;
3548         if( ( i_type >= 0x10 && i_type <= 0x14 ) ||
3549             ( i_type >= 0x20 && i_type <= 0x24 ) )
3550             i_page++;
3551     }
3552
3553     if( !p_demux->p_sys->b_split_es  || i_page <= 0 )
3554     {
3555         p_fmt->subs.dvb.i_id = -1;
3556         p_fmt->psz_description = strdup( _("DVB subtitles") );
3557
3558         if( !p_demux->p_sys->b_split_es && p_dr && p_dr->i_length > 0 )
3559         {
3560             /* Descriptor pass-through */
3561             p_fmt->p_extra = malloc( p_dr->i_length );
3562             if( p_fmt->p_extra )
3563             {
3564                 p_fmt->i_extra = p_dr->i_length;
3565                 memcpy( p_fmt->p_extra, p_dr->p_data, p_dr->i_length );
3566             }
3567         }
3568     }
3569     else
3570     {
3571         for( int i = 0; i < p_sub->i_subtitles_number; i++ )
3572         {
3573             ts_es_t *p_es;
3574
3575             /* */
3576             if( i == 0 )
3577             {
3578                 p_es = pid->es;
3579             }
3580             else
3581             {
3582                 p_es = malloc( sizeof(*p_es) );
3583                 if( !p_es )
3584                     break;
3585
3586                 es_format_Copy( &p_es->fmt, &pid->es->fmt );
3587                 free( p_es->fmt.psz_language );
3588                 free( p_es->fmt.psz_description );
3589                 p_es->fmt.psz_language = NULL;
3590                 p_es->fmt.psz_description = NULL;
3591
3592                 p_es->id      = NULL;
3593                 p_es->p_data   = NULL;
3594                 p_es->i_data_size = 0;
3595                 p_es->i_data_gathered = 0;
3596                 p_es->pp_last = &p_es->p_data;
3597                 p_es->data_type = TS_ES_DATA_PES;
3598                 p_es->p_mpeg4desc = NULL;
3599
3600                 TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
3601             }
3602
3603             /* */
3604             const dvbpsi_subtitle_t *p = &p_sub->p_subtitle[i];
3605             p_es->fmt.psz_language = strndup( (char *)p->i_iso6392_language_code, 3 );
3606             switch( p->i_subtitling_type )
3607             {
3608             case 0x10: /* unspec. */
3609             case 0x11: /* 4:3 */
3610             case 0x12: /* 16:9 */
3611             case 0x13: /* 2.21:1 */
3612             case 0x14: /* HD monitor */
3613                 p_es->fmt.psz_description = strdup( _("DVB subtitles") );
3614                 break;
3615             case 0x20: /* Hearing impaired unspec. */
3616             case 0x21: /* h.i. 4:3 */
3617             case 0x22: /* h.i. 16:9 */
3618             case 0x23: /* h.i. 2.21:1 */
3619             case 0x24: /* h.i. HD monitor */
3620                 p_es->fmt.psz_description = strdup( _("DVB subtitles: hearing impaired") );
3621                 break;
3622             default:
3623                 break;
3624             }
3625
3626             /* Hack, FIXME */
3627             p_es->fmt.subs.dvb.i_id = ( p->i_composition_page_id <<  0 ) |
3628                                       ( p->i_ancillary_page_id   << 16 );
3629         }
3630     }
3631 }
3632 static void PMTSetupEs0x06( demux_t *p_demux, ts_pid_t *pid,
3633                             const dvbpsi_pmt_es_t *p_es )
3634 {
3635     es_format_t *p_fmt = &pid->es->fmt;
3636
3637     if( PMTEsHasRegistration( p_demux, p_es, "AC-3" ) ||
3638         PMTEsFindDescriptor( p_es, 0x6a ) ||
3639         PMTEsFindDescriptor( p_es, 0x81 ) )
3640     {
3641         p_fmt->i_cat = AUDIO_ES;
3642         p_fmt->i_codec = VLC_CODEC_A52;
3643     }
3644     else if( PMTEsFindDescriptor( p_es, 0x7a ) )
3645     {
3646         /* DVB with stream_type 0x06 (ETS EN 300 468) */
3647         p_fmt->i_cat = AUDIO_ES;
3648         p_fmt->i_codec = VLC_CODEC_EAC3;
3649     }
3650     else if( PMTEsHasRegistration( p_demux, p_es, "DTS1" ) ||
3651              PMTEsHasRegistration( p_demux, p_es, "DTS2" ) ||
3652              PMTEsHasRegistration( p_demux, p_es, "DTS3" ) ||
3653              PMTEsFindDescriptor( p_es, 0x73 ) )
3654     {
3655         /*registration descriptor(ETSI TS 101 154 Annex F)*/
3656         p_fmt->i_cat = AUDIO_ES;
3657         p_fmt->i_codec = VLC_CODEC_DTS;
3658     }
3659     else if( PMTEsHasRegistration( p_demux, p_es, "BSSD" ) )
3660     {
3661         p_fmt->i_cat = AUDIO_ES;
3662         p_fmt->b_packetized = true;
3663         p_fmt->i_codec = VLC_CODEC_302M;
3664     }
3665     else if( PMTEsHasRegistration( p_demux, p_es, "HEVC" ) )
3666     {
3667         p_fmt->i_cat = VIDEO_ES;
3668         p_fmt->i_codec = VLC_CODEC_HEVC;
3669     }
3670     else
3671     {
3672         /* Subtitle/Teletext/VBI fallbacks */
3673         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x59 );
3674
3675         dvbpsi_subtitling_dr_t *p_sub;
3676         if( p_dr && ( p_sub = dvbpsi_DecodeSubtitlingDr( p_dr ) ) )
3677         {
3678             for( int i = 0; i < p_sub->i_subtitles_number; i++ )
3679             {
3680                 if( p_fmt->i_cat != UNKNOWN_ES )
3681                     break;
3682
3683                 switch( p_sub->p_subtitle[i].i_subtitling_type )
3684                 {
3685                 case 0x01: /* EBU Teletext subtitles */
3686                 case 0x02: /* Associated EBU Teletext */
3687                 case 0x03: /* VBI data */
3688                     PMTSetupEsTeletext( p_demux, pid, p_es );
3689                     break;
3690                 case 0x10: /* DVB Subtitle (normal) with no monitor AR critical */
3691                 case 0x11: /*                 ...   on 4:3 AR monitor */
3692                 case 0x12: /*                 ...   on 16:9 AR monitor */
3693                 case 0x13: /*                 ...   on 2.21:1 AR monitor */
3694                 case 0x14: /*                 ...   for display on a high definition monitor */
3695                 case 0x20: /* DVB Subtitle (impaired) with no monitor AR critical */
3696                 case 0x21: /*                 ...   on 4:3 AR monitor */
3697                 case 0x22: /*                 ...   on 16:9 AR monitor */
3698                 case 0x23: /*                 ...   on 2.21:1 AR monitor */
3699                 case 0x24: /*                 ...   for display on a high definition monitor */
3700                     PMTSetupEsDvbSubtitle( p_demux, pid, p_es );
3701                     break;
3702                 default:
3703                     msg_Err( p_demux, "Unrecognized DVB subtitle type (0x%x)",
3704                              p_sub->p_subtitle[i].i_subtitling_type );
3705                     break;
3706                 }
3707             }
3708         }
3709
3710         if( p_fmt->i_cat == UNKNOWN_ES &&
3711             ( PMTEsFindDescriptor( p_es, 0x45 ) ||  /* VBI Data descriptor */
3712               PMTEsFindDescriptor( p_es, 0x46 ) ||  /* VBI Teletext descriptor */
3713               PMTEsFindDescriptor( p_es, 0x56 ) ) ) /* EBU Teletext descriptor */
3714         {
3715             /* Teletext/VBI */
3716             PMTSetupEsTeletext( p_demux, pid, p_es );
3717         }
3718     }
3719
3720     /* FIXME is it useful ? */
3721     if( PMTEsFindDescriptor( p_es, 0x52 ) )
3722     {
3723         dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x52 );
3724         dvbpsi_stream_identifier_dr_t *p_si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
3725
3726         msg_Dbg( p_demux, "    * Stream Component Identifier: %d", p_si->i_component_tag );
3727     }
3728 }
3729
3730 static void PMTSetupEs0xEA( demux_t *p_demux, ts_pid_t *pid,
3731                            const dvbpsi_pmt_es_t *p_es )
3732 {
3733     /* Registration Descriptor */
3734     if( !PMTEsHasRegistration( p_demux, p_es, "VC-1" ) )
3735     {
3736         msg_Err( p_demux, "Registration descriptor not found or invalid" );
3737         return;
3738     }
3739
3740     es_format_t *p_fmt = &pid->es->fmt;
3741
3742     /* registration descriptor for VC-1 (SMPTE rp227) */
3743     p_fmt->i_cat = VIDEO_ES;
3744     p_fmt->i_codec = VLC_CODEC_VC1;
3745
3746     /* XXX With Simple and Main profile the SEQUENCE
3747      * header is modified: video width and height are
3748      * inserted just after the start code as 2 int16_t
3749      * The packetizer will take care of that. */
3750 }
3751
3752 static void PMTSetupEs0xD1( demux_t *p_demux, ts_pid_t *pid,
3753                            const dvbpsi_pmt_es_t *p_es )
3754 {
3755     /* Registration Descriptor */
3756     if( !PMTEsHasRegistration( p_demux, p_es, "drac" ) )
3757     {
3758         msg_Err( p_demux, "Registration descriptor not found or invalid" );
3759         return;
3760     }
3761
3762     es_format_t *p_fmt = &pid->es->fmt;
3763
3764     /* registration descriptor for Dirac
3765      * (backwards compatable with VC-2 (SMPTE Sxxxx:2008)) */
3766     p_fmt->i_cat = VIDEO_ES;
3767     p_fmt->i_codec = VLC_CODEC_DIRAC;
3768 }
3769
3770 static void PMTSetupEs0xA0( demux_t *p_demux, ts_pid_t *pid,
3771                            const dvbpsi_pmt_es_t *p_es )
3772 {
3773     /* MSCODEC sent by vlc */
3774     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0xa0 );
3775     if( !p_dr || p_dr->i_length < 10 )
3776     {
3777         msg_Warn( p_demux,
3778                   "private MSCODEC (vlc) without bih private descriptor" );
3779         return;
3780     }
3781
3782     es_format_t *p_fmt = &pid->es->fmt;
3783     p_fmt->i_cat = VIDEO_ES;
3784     p_fmt->i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
3785                                  p_dr->p_data[2], p_dr->p_data[3] );
3786     p_fmt->video.i_width = GetWBE( &p_dr->p_data[4] );
3787     p_fmt->video.i_height = GetWBE( &p_dr->p_data[6] );
3788     p_fmt->i_extra = GetWBE( &p_dr->p_data[8] );
3789
3790     if( p_fmt->i_extra > 0 )
3791     {
3792         p_fmt->p_extra = malloc( p_fmt->i_extra );
3793         if( p_fmt->p_extra )
3794             memcpy( p_fmt->p_extra, &p_dr->p_data[10],
3795                     __MIN( p_fmt->i_extra, p_dr->i_length - 10 ) );
3796         else
3797             p_fmt->i_extra = 0;
3798     }
3799     /* For such stream we will gather them ourself and don't launch a
3800      * packetizer.
3801      * Yes it's ugly but it's the only way to have DIV3 working */
3802     p_fmt->b_packetized = true;
3803 }
3804
3805 static void PMTSetupEs0x83( const dvbpsi_pmt_t *p_pmt, ts_pid_t *pid )
3806 {
3807     /* WiDi broadcasts without registration on PMT 0x1, PCR 0x1000 and
3808      * with audio track pid being 0x1100..0x11FF */
3809     if ( p_pmt->i_program_number == 0x1 &&
3810          p_pmt->i_pcr_pid == 0x1000 &&
3811         ( pid->i_pid >> 8 ) == 0x11 )
3812     {
3813         /* Not enough ? might contain 0x83 private descriptor, 2 bytes 0x473F */
3814         es_format_Init( &pid->es->fmt, AUDIO_ES, VLC_CODEC_WIDI_LPCM );
3815     }
3816     else
3817         es_format_Init( &pid->es->fmt, AUDIO_ES, VLC_CODEC_DVD_LPCM );
3818 }
3819
3820 static void PMTSetupEsHDMV( ts_pid_t *pid, const dvbpsi_pmt_es_t *p_es )
3821 {
3822     es_format_t *p_fmt = &pid->es->fmt;
3823
3824     /* Blu-Ray mapping */
3825     switch( p_es->i_type )
3826     {
3827     case 0x80:
3828         p_fmt->i_cat = AUDIO_ES;
3829         p_fmt->i_codec = VLC_CODEC_BD_LPCM;
3830         break;
3831     case 0x82:
3832     case 0x85: /* DTS-HD High resolution audio */
3833     case 0x86: /* DTS-HD Master audio */
3834     case 0xA2: /* Secondary DTS audio */
3835         p_fmt->i_cat = AUDIO_ES;
3836         p_fmt->i_codec = VLC_CODEC_DTS;
3837         break;
3838
3839     case 0x83: /* TrueHD AC3 */
3840         p_fmt->i_cat = AUDIO_ES;
3841         p_fmt->i_codec = VLC_CODEC_TRUEHD;
3842         break;
3843
3844     case 0x84: /* E-AC3 */
3845     case 0xA1: /* Secondary E-AC3 */
3846         p_fmt->i_cat = AUDIO_ES;
3847         p_fmt->i_codec = VLC_CODEC_EAC3;
3848         break;
3849     case 0x90: /* Presentation graphics */
3850         p_fmt->i_cat = SPU_ES;
3851         p_fmt->i_codec = VLC_CODEC_BD_PG;
3852         break;
3853     case 0x91: /* Interactive graphics */
3854     case 0x92: /* Subtitle */
3855     default:
3856         break;
3857     }
3858 }
3859
3860 static void PMTSetupEsRegistration( demux_t *p_demux, ts_pid_t *pid,
3861                                     const dvbpsi_pmt_es_t *p_es )
3862 {
3863     static const struct
3864     {
3865         char         psz_tag[5];
3866         int          i_cat;
3867         vlc_fourcc_t i_codec;
3868     } p_regs[] = {
3869         { "AC-3", AUDIO_ES, VLC_CODEC_A52   },
3870         { "DTS1", AUDIO_ES, VLC_CODEC_DTS   },
3871         { "DTS2", AUDIO_ES, VLC_CODEC_DTS   },
3872         { "DTS3", AUDIO_ES, VLC_CODEC_DTS   },
3873         { "BSSD", AUDIO_ES, VLC_CODEC_302M  },
3874         { "VC-1", VIDEO_ES, VLC_CODEC_VC1   },
3875         { "drac", VIDEO_ES, VLC_CODEC_DIRAC },
3876         { "", UNKNOWN_ES, 0 }
3877     };
3878     es_format_t *p_fmt = &pid->es->fmt;
3879
3880     for( int i = 0; p_regs[i].i_cat != UNKNOWN_ES; i++ )
3881     {
3882         if( PMTEsHasRegistration( p_demux, p_es, p_regs[i].psz_tag ) )
3883         {
3884             p_fmt->i_cat   = p_regs[i].i_cat;
3885             p_fmt->i_codec = p_regs[i].i_codec;
3886             if (p_es->i_type == 0x87)
3887                 p_fmt->i_codec = VLC_CODEC_EAC3;
3888             return;
3889         }
3890     }
3891 }
3892
3893 static char *GetAudioTypeDesc(demux_t *p_demux, int type)
3894 {
3895     static const char *audio_type[] = {
3896         NULL,
3897         N_("clean effects"),
3898         N_("hearing impaired"),
3899         N_("visual impaired commentary"),
3900     };
3901
3902     if (type < 0 || type > 3)
3903         msg_Dbg( p_demux, "unknown audio type: %d", type);
3904     else if (type > 0)
3905         return strdup(audio_type[type]);
3906
3907     return NULL;
3908 }
3909 static void PMTParseEsIso639( demux_t *p_demux, ts_pid_t *pid,
3910                               const dvbpsi_pmt_es_t *p_es )
3911 {
3912     /* get language descriptor */
3913     dvbpsi_descriptor_t *p_dr = PMTEsFindDescriptor( p_es, 0x0a );
3914
3915     if( !p_dr )
3916         return;
3917
3918     dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
3919     if( !p_decoded )
3920     {
3921         msg_Err( p_demux, "Failed to decode a ISO 639 descriptor" );
3922         return;
3923     }
3924
3925 #if defined(DR_0A_API_VER) && (DR_0A_API_VER >= 2)
3926     pid->es->fmt.psz_language = malloc( 4 );
3927     if( pid->es->fmt.psz_language )
3928     {
3929         memcpy( pid->es->fmt.psz_language, p_decoded->code[0].iso_639_code, 3 );
3930         pid->es->fmt.psz_language[3] = 0;
3931         msg_Dbg( p_demux, "found language: %s", pid->es->fmt.psz_language);
3932     }
3933     int type = p_decoded->code[0].i_audio_type;
3934     pid->es->fmt.psz_description = GetAudioTypeDesc(p_demux, type);
3935     if (type == 0)
3936         pid->es->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1; // prioritize normal audio tracks
3937
3938     pid->es->fmt.i_extra_languages = p_decoded->i_code_count-1;
3939     if( pid->es->fmt.i_extra_languages > 0 )
3940         pid->es->fmt.p_extra_languages =
3941             malloc( sizeof(*pid->es->fmt.p_extra_languages) *
3942                     pid->es->fmt.i_extra_languages );
3943     if( pid->es->fmt.p_extra_languages )
3944     {
3945         for( int i = 0; i < pid->es->fmt.i_extra_languages; i++ )
3946         {
3947             pid->es->fmt.p_extra_languages[i].psz_language = malloc(4);
3948             if( pid->es->fmt.p_extra_languages[i].psz_language )
3949             {
3950                 memcpy( pid->es->fmt.p_extra_languages[i].psz_language,
3951                     p_decoded->code[i+1].iso_639_code, 3 );
3952                 pid->es->fmt.p_extra_languages[i].psz_language[3] = '\0';
3953             }
3954             int type = p_decoded->code[i].i_audio_type;
3955             pid->es->fmt.p_extra_languages[i].psz_description = GetAudioTypeDesc(p_demux, type);
3956         }
3957     }
3958 #else
3959     pid->es->fmt.psz_language = malloc( 4 );
3960     if( pid->es->fmt.psz_language )
3961     {
3962         memcpy( pid->es->fmt.psz_language,
3963                 p_decoded->i_iso_639_code, 3 );
3964         pid->es->fmt.psz_language[3] = 0;
3965     }
3966 #endif
3967 }
3968
3969 static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt )
3970 {
3971     demux_t      *p_demux = data;
3972     demux_sys_t  *p_sys = p_demux->p_sys;
3973
3974     ts_pid_t     *pmt = NULL;
3975     ts_prg_psi_t *prg;
3976
3977     msg_Dbg( p_demux, "PMTCallBack called" );
3978
3979     /* First find this PMT declared in PAT */
3980     for( int i = 0; !pmt && i < p_sys->i_pmt; i++ )
3981         for( int i_prg = 0; !pmt && i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
3982         {
3983             const int i_pmt_number = p_sys->pmt[i]->psi->prg[i_prg]->i_number;
3984             if( i_pmt_number != TS_USER_PMT_NUMBER &&
3985                 i_pmt_number == p_pmt->i_program_number )
3986             {
3987                 pmt = p_sys->pmt[i];
3988                 prg = p_sys->pmt[i]->psi->prg[i_prg];
3989             }
3990         }
3991
3992     if( pmt == NULL )
3993     {
3994         msg_Warn( p_demux, "unreferenced program (broken stream)" );
3995         dvbpsi_DeletePMT(p_pmt);
3996         return;
3997     }
3998
3999
4000     if( prg->i_version != -1 &&
4001         ( !p_pmt->b_current_next || prg->i_version == p_pmt->i_version ) )
4002     {
4003         dvbpsi_DeletePMT( p_pmt );
4004         return;
4005     }
4006
4007     ts_pid_t **pp_clean = NULL;
4008     int      i_clean = 0;
4009     /* Clean this program (remove all es) */
4010     for( int i = 0; i < 8192; i++ )
4011     {
4012         ts_pid_t *pid = &p_sys->pid[i];
4013
4014         if( pid->b_valid && pid->p_owner == pmt->psi &&
4015             pid->i_owner_number == prg->i_number && pid->psi == NULL )
4016         {
4017             TAB_APPEND( i_clean, pp_clean, pid );
4018         }
4019     }
4020     if( prg->iod )
4021     {
4022         IODFree( prg->iod );
4023         prg->iod = NULL;
4024     }
4025
4026     msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
4027              p_pmt->i_program_number, p_pmt->i_version, p_pmt->i_pcr_pid );
4028     prg->i_pid_pcr = p_pmt->i_pcr_pid;
4029     prg->i_version = p_pmt->i_version;
4030
4031     ValidateDVBMeta( p_demux, prg->i_pid_pcr );
4032     if( ProgramIsSelected( p_demux, prg->i_number ) )
4033         SetPIDFilter( p_demux, prg->i_pid_pcr, true ); /* Set demux filter */
4034
4035     /* Parse descriptor */
4036     ts_registration_type_t registration_type = TS_REGISTRATION_OTHER;
4037     dvbpsi_descriptor_t  *p_dr;
4038     for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
4039         switch(p_dr->i_tag)
4040         {
4041         case 0x1d: /* We have found an IOD descriptor */
4042             msg_Dbg( p_demux, " * descriptor : IOD (0x1d)" );
4043             prg->iod = IODNew( p_dr->i_length, p_dr->p_data );
4044             break;
4045
4046         case 0x9:
4047             msg_Dbg( p_demux, " * descriptor : CA (0x9) SysID 0x%x",
4048                     (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
4049             break;
4050
4051         case 0x5: /* Registration Descriptor */
4052             if( p_dr->i_length != 4 )
4053             {
4054                 msg_Warn( p_demux, "invalid Registration Descriptor" );
4055             }
4056             else
4057             {
4058                 msg_Dbg( p_demux, " * descriptor : registration %4.4s", p_dr->p_data );
4059                 if( !memcmp( p_dr->p_data, "HDMV", 4 ) || !memcmp( p_dr->p_data, "HDPR", 4 ) )
4060                     registration_type = TS_REGISTRATION_HDMV; /* Blu-Ray */
4061             }
4062             break;
4063
4064         default:
4065             msg_Dbg( p_demux, " * descriptor : unknown (0x%x)", p_dr->i_tag );
4066         }
4067
4068     dvbpsi_pmt_es_t      *p_es;
4069     for( p_es = p_pmt->p_first_es; p_es != NULL; p_es = p_es->p_next )
4070     {
4071         ts_pid_t tmp_pid, *old_pid = 0, *pid = &tmp_pid;
4072
4073         /* Find out if the PID was already declared */
4074         for( int i = 0; i < i_clean; i++ )
4075         {
4076             if( pp_clean[i] == &p_sys->pid[p_es->i_pid] )
4077             {
4078                 old_pid = pp_clean[i];
4079                 break;
4080             }
4081         }
4082         ValidateDVBMeta( p_demux, p_es->i_pid );
4083
4084         if( !old_pid && p_sys->pid[p_es->i_pid].b_valid )
4085         {
4086             msg_Warn( p_demux, "pmt error: pid=%d already defined",
4087                       p_es->i_pid );
4088             continue;
4089         }
4090
4091         for( p_dr = p_es->p_first_descriptor; p_dr != NULL;
4092              p_dr = p_dr->p_next )
4093         {
4094             msg_Dbg( p_demux, "  * es pid=%d type=%d dr->i_tag=0x%x",
4095                      p_es->i_pid, p_es->i_type, p_dr->i_tag );
4096         }
4097
4098         PIDInit( pid, false, pmt->psi );
4099         PIDFillFormat( &pid->es->fmt, p_es->i_type );
4100         pid->i_owner_number = prg->i_number;
4101         pid->i_pid          = p_es->i_pid;
4102         pid->b_seen         = p_sys->pid[p_es->i_pid].b_seen;
4103
4104         switch( p_es->i_type )
4105         {
4106         case 0x10:
4107         case 0x11:
4108         case 0x12:
4109         case 0x0f:
4110             PMTSetupEsISO14496( p_demux, pid, prg, p_es );
4111             break;
4112         case 0x06:
4113             PMTSetupEs0x06( p_demux, pid, p_es );
4114             break;
4115         case 0x83:
4116             /* LPCM (audio) */
4117             PMTSetupEs0x83( p_pmt, pid );
4118             break;
4119         case 0xa0:
4120             PMTSetupEs0xA0( p_demux, pid, p_es );
4121             break;
4122         case 0xd1:
4123             PMTSetupEs0xD1( p_demux, pid, p_es );
4124             break;
4125         case 0xEA:
4126             PMTSetupEs0xEA( p_demux, pid, p_es );
4127             break;
4128         default:
4129             if( registration_type == TS_REGISTRATION_HDMV )
4130                 PMTSetupEsHDMV( pid, p_es );
4131             else if( p_es->i_type >= 0x80 )
4132                 PMTSetupEsRegistration( p_demux, pid, p_es );
4133             break;
4134         }
4135
4136         if( pid->es->fmt.i_cat == AUDIO_ES ||
4137             ( pid->es->fmt.i_cat == SPU_ES &&
4138               pid->es->fmt.i_codec != VLC_CODEC_DVBS &&
4139               pid->es->fmt.i_codec != VLC_CODEC_TELETEXT ) )
4140         {
4141             PMTParseEsIso639( p_demux, pid, p_es );
4142         }
4143
4144         switch( pid->es->fmt.i_codec )
4145         {
4146         case VLC_CODEC_SCTE_27:
4147             pid->es->data_type = TS_ES_DATA_TABLE_SECTION;
4148             break;
4149         default:
4150             //pid->es->data_type = TS_ES_DATA_PES;
4151             break;
4152         }
4153
4154         pid->es->fmt.i_group = p_pmt->i_program_number;
4155         for( int i = 0; i < pid->i_extra_es; i++ )
4156             pid->extra_es[i]->fmt.i_group = p_pmt->i_program_number;
4157
4158         if( pid->es->fmt.i_cat == UNKNOWN_ES )
4159         {
4160             msg_Dbg( p_demux, "  * es pid=%d type=%d *unknown*",
4161                      p_es->i_pid, p_es->i_type );
4162         }
4163         else
4164         {
4165             msg_Dbg( p_demux, "  * es pid=%d type=%d fcc=%4.4s",
4166                      p_es->i_pid, p_es->i_type, (char*)&pid->es->fmt.i_codec );
4167
4168             if( p_sys->b_es_id_pid ) pid->es->fmt.i_id = p_es->i_pid;
4169
4170             /* Check if we can avoid restarting the ES */
4171             if( old_pid &&
4172                 pid->es->fmt.i_codec == old_pid->es->fmt.i_codec &&
4173                 pid->es->fmt.i_extra == old_pid->es->fmt.i_extra &&
4174                 pid->es->fmt.i_extra == 0 &&
4175                 pid->i_extra_es == old_pid->i_extra_es &&
4176                 ( ( !pid->es->fmt.psz_language &&
4177                     !old_pid->es->fmt.psz_language ) ||
4178                   ( pid->es->fmt.psz_language &&
4179                     old_pid->es->fmt.psz_language &&
4180                     !strcmp( pid->es->fmt.psz_language,
4181                              old_pid->es->fmt.psz_language ) ) ) )
4182             {
4183                 pid->i_cc = old_pid->i_cc;
4184                 ts_es_t *e = pid->es;
4185                 pid->es = old_pid->es;
4186                 old_pid->es = e;
4187                 for( int i = 0; i < pid->i_extra_es; i++ )
4188                 {
4189                     e = pid->extra_es[i];
4190                     pid->extra_es[i] = old_pid->extra_es[i];
4191                     old_pid->extra_es[i] = e;
4192                 }
4193             }
4194             else
4195             {
4196                 pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
4197                 for( int i = 0; i < pid->i_extra_es; i++ )
4198                 {
4199                     pid->extra_es[i]->id =
4200                         es_out_Add( p_demux->out, &pid->extra_es[i]->fmt );
4201                 }
4202                 p_sys->i_pmt_es += 1 + pid->i_extra_es;
4203             }
4204         }
4205
4206         /* Add ES to the list */
4207         if( old_pid )
4208         {
4209             PIDClean( p_demux, old_pid );
4210             TAB_REMOVE( i_clean, pp_clean, old_pid );
4211         }
4212         p_sys->pid[p_es->i_pid] = *pid;
4213
4214         p_dr = PMTEsFindDescriptor( p_es, 0x09 );
4215         if( p_dr && p_dr->i_length >= 2 )
4216         {
4217             msg_Dbg( p_demux, "   * descriptor : CA (0x9) SysID 0x%x",
4218                      (p_dr->p_data[0] << 8) | p_dr->p_data[1] );
4219         }
4220
4221         if( ProgramIsSelected( p_demux, prg->i_number ) && pid->es->id != NULL )
4222             SetPIDFilter( p_demux, p_es->i_pid, true ); /* Set demux filter */
4223     }
4224
4225     /* Set CAM descrambling */
4226     if( !ProgramIsSelected( p_demux, prg->i_number )
4227      || stream_Control( p_demux->s, STREAM_SET_PRIVATE_ID_CA,
4228                         p_pmt ) != VLC_SUCCESS )
4229         dvbpsi_DeletePMT( p_pmt );
4230
4231     for( int i = 0; i < i_clean; i++ )
4232     {
4233         if( ProgramIsSelected( p_demux, prg->i_number ) )
4234             SetPIDFilter( p_demux, pp_clean[i]->i_pid, false );
4235
4236         PIDClean( p_demux, pp_clean[i] );
4237     }
4238     if( i_clean )
4239         free( pp_clean );
4240 }
4241
4242 static void PATCallBack( void *data, dvbpsi_pat_t *p_pat )
4243 {
4244     demux_t              *p_demux = data;
4245     demux_sys_t          *p_sys = p_demux->p_sys;
4246     dvbpsi_pat_program_t *p_program;
4247     ts_pid_t             *pat = &p_sys->pid[0];
4248
4249     msg_Dbg( p_demux, "PATCallBack called" );
4250
4251     if( ( pat->psi->i_pat_version != -1 &&
4252             ( !p_pat->b_current_next ||
4253               p_pat->i_version == pat->psi->i_pat_version ) ) ||
4254         p_sys->b_user_pmt )
4255     {
4256         dvbpsi_DeletePAT( p_pat );
4257         return;
4258     }
4259
4260     msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
4261              p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
4262
4263     /* Clean old */
4264     if( p_sys->i_pmt > 0 )
4265     {
4266         int      i_pmt_rm = 0;
4267         ts_pid_t **pmt_rm = NULL;
4268
4269         /* Search pmt to be deleted */
4270         for( int i = 0; i < p_sys->i_pmt; i++ )
4271         {
4272             ts_pid_t *pmt = p_sys->pmt[i];
4273             bool b_keep = false;
4274
4275             for( p_program = p_pat->p_first_program; !b_keep && p_program;
4276                  p_program = p_program->p_next )
4277             {
4278                 if( p_program->i_pid != pmt->i_pid )
4279                     continue;
4280
4281                 for( int i_prg = 0; !b_keep && i_prg < pmt->psi->i_prg; i_prg++ )
4282                     if( p_program->i_number == pmt->psi->prg[i_prg]->i_number )
4283                         b_keep = true;
4284             }
4285
4286             if( b_keep )
4287                 continue;
4288
4289             TAB_APPEND( i_pmt_rm, pmt_rm, pmt );
4290         }
4291
4292         /* Delete all ES attached to thoses PMT */
4293         for( int i = 2; i < 8192; i++ )
4294         {
4295             ts_pid_t *pid = &p_sys->pid[i];
4296
4297             if( !pid->b_valid || pid->psi )
4298                 continue;
4299
4300             for( int j = 0; j < i_pmt_rm && pid->b_valid; j++ )
4301             {
4302                 for( int i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
4303                 {
4304                     /* We only remove es that aren't defined by extra pmt */
4305                     if( pid->p_owner->prg[i_prg]->i_pid_pmt != pmt_rm[j]->i_pid )
4306                         continue;
4307
4308                     if( pid->es->id )
4309                         SetPIDFilter( p_demux, i, false );
4310
4311                     PIDClean( p_demux, pid );
4312                     break;
4313                 }
4314             }
4315         }
4316
4317         /* Delete PMT pid */
4318         for( int i = 0; i < i_pmt_rm; i++ )
4319         {
4320             ts_pid_t *pid = pmt_rm[i];
4321             SetPIDFilter( p_demux, pid->i_pid, false );
4322
4323             for( int i_prg = 0; i_prg < pid->psi->i_prg; i_prg++ )
4324             {
4325                 const int i_number = pid->psi->prg[i_prg]->i_number;
4326                 es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, i_number );
4327             }
4328
4329             PIDClean( p_demux, &p_sys->pid[pid->i_pid] );
4330             TAB_REMOVE( p_sys->i_pmt, p_sys->pmt, pid );
4331         }
4332
4333         free( pmt_rm );
4334     }
4335
4336     /* now create programs */
4337     for( p_program = p_pat->p_first_program; p_program != NULL;
4338          p_program = p_program->p_next )
4339     {
4340         msg_Dbg( p_demux, "  * number=%d pid=%d", p_program->i_number,
4341                  p_program->i_pid );
4342         if( p_program->i_number == 0 )
4343             continue;
4344
4345         ts_pid_t *pmt = &p_sys->pid[p_program->i_pid];
4346
4347         ValidateDVBMeta( p_demux, p_program->i_pid );
4348
4349         if( pmt->b_valid )
4350         {
4351             bool b_add = true;
4352             for( int i_prg = 0; b_add && i_prg < pmt->psi->i_prg; i_prg++ )
4353                 if( pmt->psi->prg[i_prg]->i_number == p_program->i_number )
4354                     b_add = false;
4355
4356             if( !b_add )
4357                 continue;
4358         }
4359         else
4360         {
4361             TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
4362         }
4363
4364         PIDInit( pmt, true, pat->psi );
4365         ts_prg_psi_t *prg = pmt->psi->prg[pmt->psi->i_prg-1];
4366 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
4367         prg->handle = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
4368         if( !prg->handle )
4369         {
4370             dvbpsi_DeletePAT( p_pat );
4371             return;
4372         }
4373         prg->handle->p_sys = (void *) VLC_OBJECT(p_demux);
4374         if( !dvbpsi_pmt_attach( prg->handle, p_program->i_number, PMTCallBack, p_demux ) )
4375             msg_Err( p_demux, "PATCallback failed attaching PMTCallback to program %d",
4376                      p_program->i_number );
4377 #else
4378         prg->handle = dvbpsi_AttachPMT( p_program->i_number, PMTCallBack, p_demux );
4379 #endif
4380         prg->i_number = p_program->i_number;
4381         prg->i_pid_pmt = p_program->i_pid;
4382
4383         /* Now select PID at access level */
4384         if( ProgramIsSelected( p_demux, p_program->i_number ) )
4385         {
4386             if( p_sys->i_current_program == 0 )
4387                 p_sys->i_current_program = p_program->i_number;
4388
4389             if( SetPIDFilter( p_demux, p_program->i_pid, true ) )
4390                 p_sys->b_access_control = false;
4391         }
4392     }
4393     pat->psi->i_pat_version = p_pat->i_version;
4394
4395     dvbpsi_DeletePAT( p_pat );
4396 }