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