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