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