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