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