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