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