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