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