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