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