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