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