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