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