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