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