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