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