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