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