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