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