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