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