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