]> git.sesse.net Git - vlc/blob - modules/demux/ts.c
Don't add MPEG-TS program data for programs that don't exist. Patch by Dnumgis. This...
[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 #include <vlc/vlc.h>
30
31 #include <stdio.h>
32 #include <stdlib.h>                                      /* malloc(), free() */
33 #include <ctype.h>
34
35 #include <vlc/input.h>
36
37 #include "iso_lang.h"
38 #include "network.h"
39 #include "charset.h"
40
41 #include "../mux/mpeg/csa.h"
42
43 /* Include dvbpsi headers */
44 #ifdef HAVE_DVBPSI_DR_H
45 #   include <dvbpsi/dvbpsi.h>
46 #   include <dvbpsi/demux.h>
47 #   include <dvbpsi/descriptor.h>
48 #   include <dvbpsi/pat.h>
49 #   include <dvbpsi/pmt.h>
50 #   include <dvbpsi/sdt.h>
51 #   include <dvbpsi/dr.h>
52 #   include <dvbpsi/psi.h>
53 #else
54 #   include "dvbpsi.h"
55 #   include "demux.h"
56 #   include "descriptor.h"
57 #   include "tables/pat.h"
58 #   include "tables/pmt.h"
59 #   include "tables/sdt.h"
60 #   include "descriptors/dr.h"
61 #   include "psi.h"
62 #endif
63
64 /* EIT support */
65 #ifdef _DVBPSI_DR_4D_H_
66 #   define TS_USE_DVB_SI 1
67 #   ifdef HAVE_DVBPSI_DR_H
68 #       include <dvbpsi/eit.h>
69 #   else
70 #       include "tables/eit.h"
71 #   endif
72 #endif
73
74 #undef TS_DEBUG
75
76 /* TODO:
77  *  - XXX: do not mark options message to be translated, they are too osbcure for now ...
78  *  - test it
79  *  - ...
80  */
81
82 #define vlc_meta_Add(a,b,c) fprintf(stderr, "FIXME: TS demuxer meta is broken\n" )
83 /*****************************************************************************
84  * Module descriptor
85  *****************************************************************************/
86 static int  Open  ( vlc_object_t * );
87 static void Close ( vlc_object_t * );
88
89 #define PMT_TEXT N_("Extra PMT")
90 #define PMT_LONGTEXT N_( \
91   "Allows a user to specify an extra pmt (pmt_pid=pid:stream_type[,...])." )
92
93 #define PID_TEXT N_("Set id of ES to PID")
94 #define PID_LONGTEXT N_("Set the internal ID of each elementary stream" \
95                        " handled by VLC to the same value as the PID in" \
96                        " the TS stream, instead of 1, 2, 3, etc. Useful to" \
97                        " do \'#duplicate{..., select=\"es=<pid>\"}\'.")
98
99 #define TSOUT_TEXT N_("Fast udp streaming")
100 #define TSOUT_LONGTEXT N_( \
101   "Sends TS to specific ip:port by udp (you must know what you are doing).")
102
103 #define MTUOUT_TEXT N_("MTU for out mode")
104 #define MTUOUT_LONGTEXT N_("MTU for out mode.")
105
106 #define CSA_TEXT N_("CSA ck")
107 #define CSA_LONGTEXT N_("Control word for the CSA encryption algorithm")
108
109 #define SILENT_TEXT N_("Silent mode")
110 #define SILENT_LONGTEXT N_("Do not complain on encrypted PES.")
111
112 #define CAPMT_SYSID_TEXT N_("CAPMT System ID")
113 #define CAPMT_SYSID_LONGTEXT N_("Only forward descriptors from this SysID to the CAM.")
114
115 #define CPKT_TEXT N_("Packet size in bytes to decrypt")
116 #define CPKT_LONGTEXT N_("Specify the size of the TS packet to decrypt. " \
117     "The decryption routines subtract the TS-header from the value before " \
118     "decrypting. " )
119
120 #define TSDUMP_TEXT N_("Filename of dump")
121 #define TSDUMP_LONGTEXT N_("Specify a filename where to dump the TS in.")
122
123 #define APPEND_TEXT N_("Append")
124 #define APPEND_LONGTEXT N_( \
125     "If the file exists and this option is selected, the existing file " \
126     "will not be overwritten." )
127
128 #define DUMPSIZE_TEXT N_("Dump buffer size")
129 #define DUMPSIZE_LONGTEXT N_( \
130     "Tweak the buffer size for reading and writing an integer number of packets." \
131     "Specify the size of the buffer here and not the number of packets." )
132
133 vlc_module_begin();
134     set_description( _("MPEG Transport Stream demuxer") );
135     set_shortname ( "MPEG-TS" );
136     set_category( CAT_INPUT );
137     set_subcategory( SUBCAT_INPUT_DEMUX );
138
139     add_string( "ts-extra-pmt", NULL, NULL, PMT_TEXT, PMT_LONGTEXT, VLC_TRUE );
140     add_bool( "ts-es-id-pid", 1, NULL, PID_TEXT, PID_LONGTEXT, VLC_TRUE );
141     add_string( "ts-out", NULL, NULL, TSOUT_TEXT, TSOUT_LONGTEXT, VLC_TRUE );
142     add_integer( "ts-out-mtu", 1500, NULL, MTUOUT_TEXT,
143                  MTUOUT_LONGTEXT, VLC_TRUE );
144     add_string( "ts-csa-ck", NULL, NULL, CSA_TEXT, CSA_LONGTEXT, VLC_TRUE );
145     add_integer( "ts-csa-pkt", 188, NULL, CPKT_TEXT, CPKT_LONGTEXT, VLC_TRUE );
146     add_bool( "ts-silent", 0, NULL, SILENT_TEXT, SILENT_LONGTEXT, VLC_TRUE );
147
148     add_file( "ts-dump-file", NULL, NULL, TSDUMP_TEXT, TSDUMP_LONGTEXT, VLC_FALSE );
149     add_bool( "ts-dump-append", 0, NULL, APPEND_TEXT, APPEND_LONGTEXT, VLC_FALSE );
150     add_integer( "ts-dump-size", 16384, NULL, DUMPSIZE_TEXT,
151                  DUMPSIZE_LONGTEXT, VLC_TRUE );
152
153     set_capability( "demux2", 10 );
154     set_callbacks( Open, Close );
155     add_shortcut( "ts" );
156 vlc_module_end();
157
158 /*****************************************************************************
159  * Local prototypes
160  *****************************************************************************/
161
162 typedef struct
163 {
164     uint8_t                 i_objectTypeIndication;
165     uint8_t                 i_streamType;
166     vlc_bool_t              b_upStream;
167     uint32_t                i_bufferSizeDB;
168     uint32_t                i_maxBitrate;
169     uint32_t                i_avgBitrate;
170
171     int                     i_decoder_specific_info_len;
172     uint8_t                 *p_decoder_specific_info;
173
174 } decoder_config_descriptor_t;
175
176 typedef struct
177 {
178     vlc_bool_t              b_useAccessUnitStartFlag;
179     vlc_bool_t              b_useAccessUnitEndFlag;
180     vlc_bool_t              b_useRandomAccessPointFlag;
181     vlc_bool_t              b_useRandomAccessUnitsOnlyFlag;
182     vlc_bool_t              b_usePaddingFlag;
183     vlc_bool_t              b_useTimeStampsFlags;
184     vlc_bool_t              b_useIdleFlag;
185     vlc_bool_t              b_durationFlag;
186     uint32_t                i_timeStampResolution;
187     uint32_t                i_OCRResolution;
188     uint8_t                 i_timeStampLength;
189     uint8_t                 i_OCRLength;
190     uint8_t                 i_AU_Length;
191     uint8_t                 i_instantBitrateLength;
192     uint8_t                 i_degradationPriorityLength;
193     uint8_t                 i_AU_seqNumLength;
194     uint8_t                 i_packetSeqNumLength;
195
196     uint32_t                i_timeScale;
197     uint16_t                i_accessUnitDuration;
198     uint16_t                i_compositionUnitDuration;
199
200     uint64_t                i_startDecodingTimeStamp;
201     uint64_t                i_startCompositionTimeStamp;
202
203 } sl_config_descriptor_t;
204
205 typedef struct
206 {
207     vlc_bool_t              b_ok;
208     uint16_t                i_es_id;
209
210     vlc_bool_t              b_streamDependenceFlag;
211     vlc_bool_t              b_OCRStreamFlag;
212     uint8_t                 i_streamPriority;
213
214     char                    *psz_url;
215
216     uint16_t                i_dependOn_es_id;
217     uint16_t                i_OCR_es_id;
218
219     decoder_config_descriptor_t    dec_descr;
220     sl_config_descriptor_t         sl_descr;
221
222 } es_mpeg4_descriptor_t;
223
224 typedef struct
225 {
226     uint8_t                i_iod_label, i_iod_label_scope;
227
228     /* IOD */
229     uint16_t                i_od_id;
230     char                    *psz_url;
231
232     uint8_t                 i_ODProfileLevelIndication;
233     uint8_t                 i_sceneProfileLevelIndication;
234     uint8_t                 i_audioProfileLevelIndication;
235     uint8_t                 i_visualProfileLevelIndication;
236     uint8_t                 i_graphicsProfileLevelIndication;
237
238     es_mpeg4_descriptor_t   es_descr[255];
239
240 } iod_descriptor_t;
241
242 typedef struct
243 {
244     dvbpsi_handle   handle;
245
246     int             i_version;
247     int             i_number;
248     int             i_pid_pcr;
249     int             i_pid_pmt;
250     /* IOD stuff (mpeg4) */
251     iod_descriptor_t *iod;
252
253 } ts_prg_psi_t;
254
255 typedef struct
256 {
257     /* for special PAT/SDT case */
258     dvbpsi_handle   handle; /* PAT/SDT/EIT */
259     int             i_pat_version;
260     int             i_sdt_version;
261
262     /* For PMT */
263     int             i_prg;
264     ts_prg_psi_t    **prg;
265
266 } ts_psi_t;
267
268 typedef struct
269 {
270     es_format_t  fmt;
271     es_out_id_t *id;
272     int         i_pes_size;
273     int         i_pes_gathered;
274     block_t     *p_pes;
275     block_t     **pp_last;
276
277     es_mpeg4_descriptor_t *p_mpeg4desc;
278     int         b_gather;
279
280 } ts_es_t;
281
282 typedef struct
283 {
284     int         i_pid;
285
286     vlc_bool_t  b_seen;
287     vlc_bool_t  b_valid;
288     int         i_cc;   /* countinuity counter */
289
290     /* PSI owner (ie PMT -> PAT, ES -> PMT */
291     ts_psi_t   *p_owner;
292     int         i_owner_number;
293
294     /* */
295     ts_psi_t    *psi;
296     ts_es_t     *es;
297
298     /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
299     ts_es_t     **extra_es;
300     int         i_extra_es;
301
302 } ts_pid_t;
303
304 struct demux_sys_t
305 {
306     /* TS packet size (188, 192, 204) */
307     int         i_packet_size;
308
309     /* how many TS packet we read at once */
310     int         i_ts_read;
311
312     /* All pid */
313     ts_pid_t    pid[8192];
314
315     /* All PMT */
316     int         i_pmt;
317     ts_pid_t    **pmt;
318
319     /* */
320     vlc_bool_t  b_es_id_pid;
321     csa_t       *csa;
322     int         i_csa_pkt_size;
323     vlc_bool_t  b_silent;
324
325     vlc_bool_t  b_udp_out;
326     int         fd; /* udp socket */
327     uint8_t     *buffer;
328
329     vlc_bool_t  b_dvb_control;
330     int         i_dvb_program;
331     vlc_list_t  *p_programs_list;
332
333     /* TS dump */
334     char        *psz_file;  /* file to dump data in */
335     FILE        *p_file;    /* filehandle */
336     uint64_t    i_write;    /* bytes written */
337     vlc_bool_t  b_file_out; /* dump mode enabled */
338
339     /* */
340     vlc_bool_t  b_meta;
341 };
342
343 static int Demux    ( demux_t *p_demux );
344 static int DemuxFile( demux_t *p_demux );
345 static int Control( demux_t *p_demux, int i_query, va_list args );
346
347 static void PIDInit ( ts_pid_t *pid, vlc_bool_t b_psi, ts_psi_t *p_owner );
348 static void PIDClean( es_out_t *out, ts_pid_t *pid );
349 static int  PIDFillFormat( ts_pid_t *pid, int i_stream_type );
350
351 static void PATCallBack( demux_t *, dvbpsi_pat_t * );
352 static void PMTCallBack( demux_t *p_demux, dvbpsi_pmt_t *p_pmt );
353 #ifdef TS_USE_DVB_SI
354 static void PSINewTableCallBack( demux_t *, dvbpsi_handle,
355                                  uint8_t  i_table_id, uint16_t i_extension );
356 #endif
357
358 static inline int PIDGet( block_t *p )
359 {
360     return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
361 }
362
363 static vlc_bool_t GatherPES( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
364
365 static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );
366
367 static iod_descriptor_t *IODNew( int , uint8_t * );
368 static void              IODFree( iod_descriptor_t * );
369
370 #define TS_PACKET_SIZE_188 188
371 #define TS_PACKET_SIZE_192 192
372 #define TS_PACKET_SIZE_204 204
373 #define TS_PACKET_SIZE_MAX 204
374 #define TS_TOPFIELD_HEADER 1320
375
376 /*****************************************************************************
377  * Open
378  *****************************************************************************/
379 static int Open( vlc_object_t *p_this )
380 {
381     demux_t     *p_demux = (demux_t*)p_this;
382     demux_sys_t *p_sys;
383
384     uint8_t     *p_peek;
385     int          i_sync, i_peek, i;
386     int          i_packet_size;
387
388     ts_pid_t    *pat;
389     char        *psz_mode;
390     vlc_bool_t   b_append;
391     vlc_bool_t   b_topfield = VLC_FALSE;
392
393     vlc_value_t  val;
394
395     if( stream_Peek( p_demux->s, &p_peek, TS_PACKET_SIZE_MAX ) <
396         TS_PACKET_SIZE_MAX ) return VLC_EGENERIC;
397
398     if( p_peek[0] == 'T' && p_peek[1] == 'F' &&
399         p_peek[2] == 'r' && p_peek[3] == 'c' )
400     {
401         b_topfield = VLC_TRUE;
402         msg_Dbg( p_demux, "this is a topfield file" );
403     }
404
405     /* Search first sync byte */
406     for( i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
407     {
408         if( p_peek[i_sync] == 0x47 ) break;
409     }
410     if( i_sync >= TS_PACKET_SIZE_MAX && !b_topfield )
411     {
412         if( strcmp( p_demux->psz_demux, "ts" ) ) return VLC_EGENERIC;
413         msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
414     }
415
416     if( b_topfield )
417     {
418         /* Read the entire Topfield header */
419         i_peek = TS_TOPFIELD_HEADER;
420     }
421     else
422     {
423         /* Check next 3 sync bytes */
424         i_peek = TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
425     }
426     
427     if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
428     {
429         msg_Err( p_demux, "cannot peek" );
430         return VLC_EGENERIC;
431     }
432     if( p_peek[i_sync + TS_PACKET_SIZE_188] == 0x47 &&
433         p_peek[i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
434         p_peek[i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
435     {
436         i_packet_size = TS_PACKET_SIZE_188;
437     }
438     else if( p_peek[i_sync + TS_PACKET_SIZE_192] == 0x47 &&
439              p_peek[i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
440              p_peek[i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
441     {
442         i_packet_size = TS_PACKET_SIZE_192;
443     }
444     else if( p_peek[i_sync + TS_PACKET_SIZE_204] == 0x47 &&
445              p_peek[i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
446              p_peek[i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
447     {
448         i_packet_size = TS_PACKET_SIZE_204;
449     }
450     else if( !strcmp( p_demux->psz_demux, "ts" ) )
451     {
452         i_packet_size = TS_PACKET_SIZE_188;
453     }
454     else if( b_topfield )
455     {
456         i_packet_size = TS_PACKET_SIZE_188;
457 #if 0
458         /* I used the TF5000PVR 2004 Firmware .doc header documentation, 
459          * http://www.i-topfield.com/data/product/firmware/Structure%20of%20Recorded%20File%20in%20TF5000PVR%20(Feb%2021%202004).doc
460          * but after the filename the offsets seem to be incorrect.  - DJ */
461         int i_duration, i_name;
462         char *psz_name = malloc(25);
463         char *psz_event_name;
464         char *psz_event_text = malloc(130);
465         char *psz_ext_text = malloc(1025);
466
467         // 2 bytes version Uimsbf (4,5)
468         // 2 bytes reserved (6,7)
469         // 2 bytes duration in minutes Uimsbf (8,9(
470         i_duration = (int) (p_peek[8] << 8) | p_peek[9];
471         msg_Dbg( p_demux, "Topfield recording length: +/- %d minutes", i_duration);
472         // 2 bytes service number in channel list (10, 11)
473         // 2 bytes service type Bslbf 0=TV 1=Radio Bslb (12, 13)
474         // 4 bytes of reserved + tuner info (14,15,16,17)
475         // 2 bytes of Service ID  Bslbf (18,19)
476         // 2 bytes of PMT PID  Uimsbf (20,21)
477         // 2 bytes of PCR PID  Uimsbf (22,23)
478         // 2 bytes of Video PID  Uimsbf (24,25)
479         // 2 bytes of Audio PID  Uimsbf (26,27)
480         // 24 bytes filename Bslbf
481         memcpy( psz_name, &p_peek[28], 24 );
482         psz_name[24] = '\0';
483         msg_Dbg( p_demux, "recordingname=%s", psz_name );
484         // 1 byte of sat index Uimsbf  (52)
485         // 3 bytes (1 bit of polarity Bslbf +23 bits reserved)
486         // 4 bytes of freq. Uimsbf (56,57,58,59)
487         // 2 bytes of symbol rate Uimsbf (60,61)
488         // 2 bytes of TS stream ID Uimsbf (62,63)
489         // 4 bytes reserved 
490         // 2 bytes reserved
491         // 2 bytes duration Uimsbf (70,71)
492         //i_duration = (int) (p_peek[70] << 8) | p_peek[71];
493         //msg_Dbg( p_demux, "Topfield 2nd duration field: +/- %d minutes", i_duration);
494         // 4 bytes EventID Uimsbf (72-75)
495         // 8 bytes of Start and End time info (76-83)
496         // 1 byte reserved (84)
497         // 1 byte event name length Uimsbf (89)
498         i_name = (int)(p_peek[89]&~0x81);
499         msg_Dbg( p_demux, "event name length = %d", i_name);
500         psz_event_name = malloc( i_name+1 );
501         // 1 byte parental rating (90)
502         // 129 bytes of event text
503         memcpy( psz_event_name, &p_peek[91], i_name );
504         psz_event_name[i_name] = '\0';
505         memcpy( psz_event_text, &p_peek[91+i_name], 129-i_name );
506         psz_event_text[129-i_name] = '\0';
507         msg_Dbg( p_demux, "event name=%s", psz_event_name );
508         msg_Dbg( p_demux, "event text=%s", psz_event_text );
509         // 12 bytes reserved (220)
510         // 6 bytes reserved
511         // 2 bytes Event Text Length Uimsbf
512         // 4 bytes EventID Uimsbf
513         // FIXME We just have 613 bytes. not enough for this entire text
514         // 1024 bytes Extended Event Text Bslbf
515         memcpy( psz_ext_text, p_peek+372, 1024 );
516         psz_ext_text[1024] = '\0';
517         msg_Dbg( p_demux, "extended event text=%s", psz_ext_text );
518         // 52 bytes reserved Bslbf
519 #endif
520     }
521     else
522     {
523         msg_Warn( p_demux, "TS module discarded (lost sync)" );
524         return VLC_EGENERIC;
525     }
526
527     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
528     memset( p_sys, 0, sizeof( demux_sys_t ) );
529     p_sys->i_packet_size = i_packet_size;
530
531     /* Fill dump mode fields */
532     p_sys->i_write = 0;
533     p_sys->p_file = NULL;
534     p_sys->b_file_out = VLC_FALSE;
535     p_sys->psz_file = var_CreateGetString( p_demux, "ts-dump-file" );
536     if( *p_sys->psz_file != '\0' )
537     {
538         p_sys->b_file_out = VLC_TRUE;
539
540         var_Create( p_demux, "ts-dump-append", VLC_VAR_BOOL|VLC_VAR_DOINHERIT );
541         var_Get( p_demux, "ts-dump-append", &val );
542         b_append = val.b_bool;
543         if ( b_append )
544             psz_mode = "ab";
545         else
546             psz_mode = "wb";
547
548         if( !strcmp( p_sys->psz_file, "-" ) )
549         {
550             msg_Info( p_demux, "dumping raw stream to standard output" );
551             p_sys->p_file = stdout;
552         }
553         else if( ( p_sys->p_file = utf8_fopen( p_sys->psz_file, psz_mode ) ) == NULL )
554         {
555             msg_Err( p_demux, "cannot create `%s' for writing", p_sys->psz_file );
556             p_sys->b_file_out = VLC_FALSE;
557         }
558
559         if( p_sys->b_file_out )
560         {
561             vlc_value_t bufsize;
562
563             /* Determine how many packets to read. */
564             var_Create( p_demux, "ts-dump-size",
565                         VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
566             var_Get( p_demux, "ts-dump-size", &bufsize );
567             p_sys->i_ts_read = (int) (bufsize.i_int / p_sys->i_packet_size);
568             if( p_sys->i_ts_read <= 0 )
569             {
570                 p_sys->i_ts_read = 1500 / p_sys->i_packet_size;
571             }
572             p_sys->buffer = malloc( p_sys->i_packet_size * p_sys->i_ts_read );
573             msg_Info( p_demux, "%s raw stream to file `%s' reading packets %d",
574                       b_append ? "appending" : "dumping", p_sys->psz_file,
575                       p_sys->i_ts_read );
576         }
577     }
578
579     /* Fill p_demux field */
580     if( p_sys->b_file_out )
581         p_demux->pf_demux = DemuxFile;
582     else
583         p_demux->pf_demux = Demux;
584     p_demux->pf_control = Control;
585
586     /* Init p_sys field */
587     p_sys->b_meta = VLC_TRUE;
588     p_sys->b_dvb_control = VLC_TRUE;
589     p_sys->i_dvb_program = 0;
590     for( i = 0; i < 8192; i++ )
591     {
592         ts_pid_t *pid = &p_sys->pid[i];
593
594         pid->i_pid      = i;
595         pid->b_seen     = VLC_FALSE;
596         pid->b_valid    = VLC_FALSE;
597     }
598     /* PID 8191 is padding */
599     p_sys->pid[8191].b_seen = VLC_TRUE;
600     p_sys->i_packet_size = i_packet_size;
601     p_sys->b_udp_out = VLC_FALSE;
602     p_sys->i_ts_read = 50;
603     p_sys->csa = NULL;
604
605     /* Init PAT handler */
606     pat = &p_sys->pid[0];
607     PIDInit( pat, VLC_TRUE, NULL );
608     pat->psi->handle = dvbpsi_AttachPAT( (dvbpsi_pat_callback)PATCallBack,
609                                          p_demux );
610 #ifdef TS_USE_DVB_SI
611     if( p_sys->b_meta )
612     {
613         ts_pid_t *sdt = &p_sys->pid[0x11];
614         ts_pid_t *eit = &p_sys->pid[0x12];
615
616         PIDInit( sdt, VLC_TRUE, NULL );
617         sdt->psi->handle =
618             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
619                                 p_demux );
620         PIDInit( eit, VLC_TRUE, NULL );
621         eit->psi->handle =
622             dvbpsi_AttachDemux( (dvbpsi_demux_new_cb_t)PSINewTableCallBack,
623                                 p_demux );
624         if( p_sys->b_dvb_control )
625         {
626             stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
627                             ACCESS_SET_PRIVATE_ID_STATE, 0x11, VLC_TRUE );
628             stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
629                             ACCESS_SET_PRIVATE_ID_STATE, 0x12, VLC_TRUE );
630         }
631     }
632 #endif
633
634     /* Init PMT array */
635     p_sys->i_pmt = 0;
636     p_sys->pmt   = NULL;
637
638     /* Read config */
639     var_Create( p_demux, "ts-es-id-pid", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
640     var_Get( p_demux, "ts-es-id-pid", &val );
641     p_sys->b_es_id_pid = val.b_bool;
642
643     var_Create( p_demux, "ts-out", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
644     var_Get( p_demux, "ts-out", &val );
645     if( val.psz_string && *val.psz_string && !p_sys->b_file_out )
646     {
647         vlc_value_t mtu;
648         char *psz = strchr( val.psz_string, ':' );
649         int   i_port = 0;
650
651         p_sys->b_udp_out = VLC_TRUE;
652
653         if( psz )
654         {
655             *psz++ = '\0';
656             i_port = atoi( psz );
657         }
658         if( i_port <= 0 ) i_port  = 1234;
659         msg_Dbg( p_demux, "resend ts to '%s:%d'", val.psz_string, i_port );
660
661         p_sys->fd = net_ConnectUDP( p_demux, val.psz_string, i_port, 0 );
662         if( p_sys->fd < 0 )
663         {
664             msg_Err( p_demux, "failed to open udp socket, send disabled" );
665             p_sys->b_udp_out = VLC_FALSE;
666         }
667         else
668         {
669             var_Create( p_demux, "ts-out-mtu",
670                         VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
671             var_Get( p_demux, "ts-out-mtu", &mtu );
672             p_sys->i_ts_read = mtu.i_int / p_sys->i_packet_size;
673             if( p_sys->i_ts_read <= 0 )
674             {
675                 p_sys->i_ts_read = 1500 / p_sys->i_packet_size;
676             }
677             p_sys->buffer = malloc( p_sys->i_packet_size * p_sys->i_ts_read );
678         }
679     }
680     if( val.psz_string )
681     {
682         free( val.psz_string );
683     }
684
685     /* We handle description of an extra PMT */
686     var_Create( p_demux, "ts-extra-pmt", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
687     var_Get( p_demux, "ts-extra-pmt", &val );
688     if( val.psz_string && strchr( val.psz_string, '=' ) != NULL )
689     {
690         char *psz = val.psz_string;
691         int  i_pid = strtol( psz, &psz, 0 );
692
693         if( i_pid >= 2 && i_pid < 8192 )
694         {
695             ts_pid_t *pmt = &p_sys->pid[i_pid];
696
697             msg_Dbg( p_demux, "extra pmt specified (pid=%d)", i_pid );
698             PIDInit( pmt, VLC_TRUE, NULL );
699             pmt->psi->i_prg = 1;
700             pmt->psi->prg = malloc( sizeof(ts_prg_psi_t) );
701             /* FIXME we should also ask for a number */
702             pmt->psi->prg[0]->handle =
703                 dvbpsi_AttachPMT( 1, (dvbpsi_pmt_callback)PMTCallBack,
704                                   p_demux );
705             pmt->psi->prg[0]->i_number = 0; /* special one */
706
707             psz = strchr( psz, '=' ) + 1;   /* can't failed */
708             while( psz && *psz )
709             {
710                 char *psz_next = strchr( psz, ',' );
711                 int i_pid, i_stream_type;
712
713                 if( psz_next )
714                 {
715                     *psz_next++ = '\0';
716                 }
717
718                 i_pid = strtol( psz, &psz, 0 );
719                 if( *psz == ':' )
720                 {
721                     i_stream_type = strtol( psz + 1, &psz, 0 );
722                     if( i_pid >= 2 && i_pid < 8192 &&
723                         !p_sys->pid[i_pid].b_valid )
724                     {
725                         ts_pid_t *pid = &p_sys->pid[i_pid];
726
727                         PIDInit( pid, VLC_FALSE, pmt->psi);
728                         if( pmt->psi->prg[0]->i_pid_pcr <= 0 )
729                         {
730                             pmt->psi->prg[0]->i_pid_pcr = i_pid;
731                         }
732                         PIDFillFormat( pid, i_stream_type);
733                         if( pid->es->fmt.i_cat != UNKNOWN_ES )
734                         {
735                             if( p_sys->b_es_id_pid )
736                             {
737                                 pid->es->fmt.i_id = i_pid;
738                             }
739                             msg_Dbg( p_demux, "  * es pid=%d type=%d "
740                                      "fcc=%4.4s", i_pid, i_stream_type,
741                                      (char*)&pid->es->fmt.i_codec );
742                             pid->es->id = es_out_Add( p_demux->out,
743                                                       &pid->es->fmt );
744                         }
745                     }
746                 }
747                 psz = psz_next;
748             }
749         }
750     }
751     if( val.psz_string )
752     {
753         free( val.psz_string );
754     }
755
756     var_Create( p_demux, "ts-csa-ck", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
757     var_Get( p_demux, "ts-csa-ck", &val );
758     if( val.psz_string && *val.psz_string )
759     {
760         char *psz = val.psz_string;
761         if( psz[0] == '0' && ( psz[1] == 'x' || psz[1] == 'X' ) )
762         {
763             psz += 2;
764         }
765         if( strlen( psz ) != 16 )
766         {
767             msg_Warn( p_demux, "invalid csa ck (it must be 16 chars long)" );
768         }
769         else
770         {
771 #ifndef UNDER_CE
772             uint64_t i_ck = strtoull( psz, NULL, 16 );
773 #else
774             uint64_t i_ck = strtoll( psz, NULL, 16 );
775 #endif
776             uint8_t ck[8];
777             int     i;
778             for( i = 0; i < 8; i++ )
779             {
780                 ck[i] = ( i_ck >> ( 56 - 8*i) )&0xff;
781             }
782 #ifndef TS_NO_CSA_CK_MSG
783             msg_Dbg( p_demux, "using CSA scrambling with "
784                      "ck=%x:%x:%x:%x:%x:%x:%x:%x",
785                      ck[0], ck[1], ck[2], ck[3], ck[4], ck[5], ck[6], ck[7] );
786 #endif
787             p_sys->csa = csa_New();
788
789             if( p_sys->csa )
790             {
791                 vlc_value_t pkt_val;
792
793                 csa_SetCW( p_sys->csa, ck, ck );
794
795                 var_Create( p_demux, "ts-csa-pkt", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
796                 var_Get( p_demux, "ts-csa-pkt", &pkt_val );
797                 if( pkt_val.i_int < 4 || pkt_val.i_int > 188 )
798                 {
799                     msg_Err( p_demux, "wrong packet size %d specified.", pkt_val.i_int );
800                     msg_Warn( p_demux, "using default packet size of 188 bytes" );
801                     p_sys->i_csa_pkt_size = 188;
802                 }
803                 else p_sys->i_csa_pkt_size = pkt_val.i_int;
804                 msg_Dbg( p_demux, "decrypting %d bytes of packet", p_sys->i_csa_pkt_size );
805             }
806         }
807     }
808     if( val.psz_string )
809     {
810         free( val.psz_string );
811     }
812
813     var_Create( p_demux, "ts-silent", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
814     var_Get( p_demux, "ts-silent", &val );
815     p_sys->b_silent = val.b_bool;
816
817     return VLC_SUCCESS;
818 }
819
820 /*****************************************************************************
821  * Close
822  *****************************************************************************/
823 static void Close( vlc_object_t *p_this )
824 {
825     demux_t     *p_demux = (demux_t*)p_this;
826     demux_sys_t *p_sys = p_demux->p_sys;
827
828     int          i;
829
830     msg_Dbg( p_demux, "pid list:" );
831     for( i = 0; i < 8192; i++ )
832     {
833         ts_pid_t *pid = &p_sys->pid[i];
834
835         if( pid->b_valid && pid->psi )
836         {
837             switch( pid->i_pid )
838             {
839                 case 0: /* PAT */
840                     dvbpsi_DetachPAT( pid->psi->handle );
841                     free( pid->psi );
842                     break;
843                 case 1: /* CAT */
844                     free( pid->psi );
845                     break;
846                 case 0x11: /* SDT */
847                 case 0x12: /* EIT */
848                     dvbpsi_DetachDemux( pid->psi->handle );
849                     free( pid->psi );
850                     break;
851                 default:
852                     PIDClean( p_demux->out, pid );
853                     break;
854             }
855         }
856         else if( pid->b_valid && pid->es )
857         {
858             PIDClean( p_demux->out, pid );
859         }
860
861         if( pid->b_seen )
862         {
863             msg_Dbg( p_demux, "  - pid[%d] seen", pid->i_pid );
864         }
865
866         if( p_sys->b_dvb_control && pid->i_pid > 0 )
867         {
868             /* too much */
869             stream_Control( p_demux->s, STREAM_CONTROL_ACCESS, ACCESS_SET_PRIVATE_ID_STATE, pid->i_pid, VLC_FALSE );
870         }
871
872     }
873
874     if( p_sys->b_udp_out )
875     {
876         net_Close( p_sys->fd );
877         free( p_sys->buffer );
878     }
879     if( p_sys->csa )
880     {
881         csa_Delete( p_sys->csa );
882     }
883
884     if( p_sys->i_pmt ) free( p_sys->pmt );
885
886     if ( p_sys->p_programs_list )
887     {
888         vlc_value_t val;
889         val.p_list = p_sys->p_programs_list;
890         var_Change( p_demux, "programs", VLC_VAR_FREELIST, &val, NULL );
891     }
892
893     /* If in dump mode, then close the file */
894     if( p_sys->b_file_out )
895     {
896         msg_Info( p_demux ,"closing %s ("I64Fd" Kbytes dumped)", p_sys->psz_file,
897                   p_sys->i_write / 1024 );
898
899         if( p_sys->p_file != stdout )
900         {
901             fclose( p_sys->p_file );
902             p_sys->p_file = NULL;
903         }
904
905         free( p_sys->buffer );
906     }
907
908     free( p_sys->psz_file );
909     p_sys->psz_file = NULL;
910
911     free( p_sys );
912 }
913
914 /*****************************************************************************
915  * DemuxFile:
916  *****************************************************************************/
917 static int DemuxFile( demux_t *p_demux )
918 {
919     demux_sys_t *p_sys = p_demux->p_sys;
920     uint8_t     *p_buffer = p_sys->buffer; /* Put first on sync byte */
921     int i_diff= 0;
922     int i_data= 0;
923     int i_pos = 0;
924     int i_bufsize = p_sys->i_packet_size * p_sys->i_ts_read;
925
926     i_data = stream_Read( p_demux->s, p_sys->buffer, i_bufsize );
927     if( (i_data <= 0) && (i_data < p_sys->i_packet_size) )
928     {
929         msg_Dbg( p_demux, "error reading malformed packets" );
930         return i_data;
931     }
932
933     /* Test continuity counter */
934     while( i_pos < i_data )
935     {
936         ts_pid_t    *p_pid;   /* point to a PID structure */
937         vlc_bool_t b_payload; /* indicates a packet with payload */
938         vlc_bool_t b_adaptation; /* adaptation field */
939         int i_cc  = 0;        /* continuity counter */
940
941         if( p_sys->buffer[i_pos] != 0x47 )
942         {
943             msg_Warn( p_demux, "lost sync" );
944             while( !p_demux->b_die && (i_pos < i_data) )
945             {
946                 i_pos++;
947                 if( p_sys->buffer[i_pos] == 0x47 )
948                     break;
949             }
950             if( !p_demux->b_die )
951                 msg_Warn( p_demux, "sync found" );
952         }
953
954         /* continuous when (one of this):
955          * diff == 1
956          * diff == 0 and payload == 0
957          * diff == 0 and duplicate packet (playload != 0) <- should we
958          *   test the content ?
959          */
960         i_cc  = p_buffer[i_pos+3]&0x0f;
961         b_payload = p_buffer[i_pos+3]&0x10;
962         b_adaptation = p_buffer[i_pos+3]&0x20;
963
964         /* Get the PID */
965         p_pid = &p_sys->pid[ ((p_buffer[i_pos+1]&0x1f)<<8)|p_buffer[i_pos+2] ];
966
967         /* Detect discontinuity indicator in adaptation field */
968         if( b_adaptation )
969         {
970             if( p_buffer[i_pos+5]&0x80 )
971                 msg_Warn( p_demux, "discontinuity indicator (pid=%d) ", p_pid->i_pid );
972             if( p_buffer[i_pos+5]&0x40 )
973                 msg_Warn( p_demux, "random access indicator (pid=%d) ", p_pid->i_pid );
974         }
975
976         i_diff = ( i_cc - p_pid->i_cc )&0x0f;
977         if( b_payload && i_diff == 1 )
978         {
979             p_pid->i_cc = ( p_pid->i_cc + 1 ) & 0xf;
980         }
981         else
982         {
983             if( p_pid->i_cc == 0xff )
984             {
985                 msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
986                         p_pid->i_pid, i_cc );
987                 p_pid->i_cc = i_cc;
988             }
989             else if( i_diff != 0 )
990             {
991                 /* FIXME what to do when discontinuity_indicator is set ? */
992                 msg_Warn( p_demux, "transport error detected 0x%x instead of 0x%x",
993                           i_cc, ( p_pid->i_cc + 1 )&0x0f );
994
995                 p_pid->i_cc = i_cc;
996                 /* Mark transport error in the TS packet. */
997                 p_buffer[i_pos+1] |= 0x80;
998             }
999         }
1000
1001         /* Test if user wants to decrypt it first */
1002         if( p_sys->csa )
1003             csa_Decrypt( p_demux->p_sys->csa, &p_buffer[i_pos], p_demux->p_sys->i_csa_pkt_size );
1004
1005         i_pos += p_sys->i_packet_size;
1006     }
1007
1008     /* Then write */
1009     i_data = fwrite( p_sys->buffer, 1, i_data, p_sys->p_file );
1010     if( i_data < 0 )
1011     {
1012         msg_Err( p_demux, "failed to write data" );
1013         return -1;
1014     }
1015 #if 0
1016     msg_Dbg( p_demux, "dumped %d bytes", i_data );
1017 #endif
1018
1019     p_sys->i_write += i_data;
1020     return 1;
1021 }
1022
1023 /*****************************************************************************
1024  * Demux:
1025  *****************************************************************************/
1026 static int Demux( demux_t *p_demux )
1027 {
1028     demux_sys_t *p_sys = p_demux->p_sys;
1029     int          i_pkt;
1030
1031     /* We read at most 100 TS packet or until a frame is completed */
1032     for( i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
1033     {
1034         vlc_bool_t  b_frame = VLC_FALSE;
1035         block_t     *p_pkt;
1036         ts_pid_t    *p_pid;
1037
1038         /* Get a new TS packet */
1039         if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
1040         {
1041             msg_Dbg( p_demux, "eof ?" );
1042             return 0;
1043         }
1044
1045         /* Check sync byte and re-sync if needed */
1046         if( p_pkt->p_buffer[0] != 0x47 )
1047         {
1048             msg_Warn( p_demux, "lost synchro" );
1049             block_Release( p_pkt );
1050
1051             while( !p_demux->b_die )
1052             {
1053                 uint8_t *p_peek;
1054                 int i_peek, i_skip = 0;
1055
1056                 i_peek = stream_Peek( p_demux->s, &p_peek,
1057                                       p_sys->i_packet_size * 10 );
1058                 if( i_peek < p_sys->i_packet_size + 1 )
1059                 {
1060                     msg_Dbg( p_demux, "eof ?" );
1061                     return 0;
1062                 }
1063
1064                 while( i_skip < i_peek - p_sys->i_packet_size )
1065                 {
1066                     if( p_peek[i_skip] == 0x47 &&
1067                         p_peek[i_skip + p_sys->i_packet_size] == 0x47 )
1068                     {
1069                         break;
1070                     }
1071                     i_skip++;
1072                 }
1073
1074                 msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
1075                 stream_Read( p_demux->s, NULL, i_skip );
1076
1077                 if( i_skip < i_peek - p_sys->i_packet_size )
1078                 {
1079                     break;
1080                 }
1081             }
1082
1083             if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
1084             {
1085                 msg_Dbg( p_demux, "eof ?" );
1086                 return 0;
1087             }
1088         }
1089
1090         if( p_sys->b_udp_out )
1091         {
1092             memcpy( &p_sys->buffer[i_pkt * p_sys->i_packet_size],
1093                     p_pkt->p_buffer, p_sys->i_packet_size );
1094         }
1095
1096         /* Parse the TS packet */
1097         p_pid = &p_sys->pid[PIDGet( p_pkt )];
1098
1099         if( p_pid->b_valid )
1100         {
1101             if( p_pid->psi )
1102             {
1103                 if( p_pid->i_pid == 0 || p_pid->i_pid == 0x11 || p_pid->i_pid == 0x12 )
1104                 {
1105                     dvbpsi_PushPacket( p_pid->psi->handle, p_pkt->p_buffer );
1106                 }
1107                 else
1108                 {
1109                     int i_prg;
1110                     for( i_prg = 0; i_prg < p_pid->psi->i_prg; i_prg++ )
1111                     {
1112                         dvbpsi_PushPacket( p_pid->psi->prg[i_prg]->handle,
1113                                            p_pkt->p_buffer );
1114                     }
1115                 }
1116                 block_Release( p_pkt );
1117             }
1118             else if( !p_sys->b_udp_out )
1119             {
1120                 b_frame = GatherPES( p_demux, p_pid, p_pkt );
1121             }
1122             else
1123             {
1124                 PCRHandle( p_demux, p_pid, p_pkt );
1125                 block_Release( p_pkt );
1126             }
1127         }
1128         else
1129         {
1130             if( !p_pid->b_seen )
1131             {
1132                 msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid );
1133             }
1134             /* We have to handle PCR if present */
1135             PCRHandle( p_demux, p_pid, p_pkt );
1136             block_Release( p_pkt );
1137         }
1138         p_pid->b_seen = VLC_TRUE;
1139
1140         if( b_frame )
1141         {
1142             break;
1143         }
1144     }
1145
1146     if( p_sys->b_udp_out )
1147     {
1148         /* Send the complete block */
1149         net_Write( p_demux, p_sys->fd, NULL, p_sys->buffer,
1150                    p_sys->i_ts_read * p_sys->i_packet_size );
1151     }
1152
1153     return 1;
1154 }
1155
1156 /*****************************************************************************
1157  * Control:
1158  *****************************************************************************/
1159 static int Control( demux_t *p_demux, int i_query, va_list args )
1160 {
1161     demux_sys_t *p_sys = p_demux->p_sys;
1162     double f, *pf;
1163     int64_t i64;
1164     int64_t *pi64;
1165     int i_int;
1166
1167     if( p_sys->b_file_out )
1168         return demux2_vaControlHelper( p_demux->s, 0, -1, 0, 1, i_query, args );
1169
1170     switch( i_query )
1171     {
1172         case DEMUX_GET_POSITION:
1173             pf = (double*) va_arg( args, double* );
1174             i64 = stream_Size( p_demux->s );
1175             if( i64 > 0 )
1176             {
1177                 *pf = (double)stream_Tell( p_demux->s ) / (double)i64;
1178             }
1179             else
1180             {
1181                 *pf = 0.0;
1182             }
1183             return VLC_SUCCESS;
1184         case DEMUX_SET_POSITION:
1185             f = (double) va_arg( args, double );
1186             i64 = stream_Size( p_demux->s );
1187
1188             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1189             if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
1190             {
1191                 return VLC_EGENERIC;
1192             }
1193             return VLC_SUCCESS;
1194 #if 0
1195
1196         case DEMUX_GET_TIME:
1197             pi64 = (int64_t*)va_arg( args, int64_t * );
1198             if( p_sys->i_time < 0 )
1199             {
1200                 *pi64 = 0;
1201                 return VLC_EGENERIC;
1202             }
1203             *pi64 = p_sys->i_time;
1204             return VLC_SUCCESS;
1205
1206         case DEMUX_GET_LENGTH:
1207             pi64 = (int64_t*)va_arg( args, int64_t * );
1208             if( p_sys->i_mux_rate > 0 )
1209             {
1210                 *pi64 = I64C(1000000) * ( stream_Size( p_demux->s ) / 50 ) /
1211                         p_sys->i_mux_rate;
1212                 return VLC_SUCCESS;
1213             }
1214             *pi64 = 0;
1215             return VLC_EGENERIC;
1216 #else
1217         case DEMUX_GET_TIME:
1218         case DEMUX_GET_LENGTH:
1219             pi64 = (int64_t*)va_arg( args, int64_t * );
1220             *pi64 = 0;
1221             return VLC_SUCCESS;
1222 #endif
1223         case DEMUX_SET_GROUP:
1224         {
1225             uint16_t i_vpid = 0, i_apid1 = 0, i_apid2 = 0, i_apid3 = 0;
1226             ts_prg_psi_t *p_prg = NULL;
1227             vlc_list_t *p_list;
1228
1229             i_int = (int)va_arg( args, int );
1230             p_list = (vlc_list_t *)va_arg( args, vlc_list_t * );
1231             msg_Dbg( p_demux, "DEMUX_SET_GROUP %d %p", i_int, p_list );
1232
1233             if( p_sys->b_dvb_control && i_int > 0 && i_int != p_sys->i_dvb_program )
1234             {
1235                 int i_pmt_pid = -1;
1236                 int i;
1237
1238                 /* Search pmt to be unselected */
1239                 for( i = 0; i < p_sys->i_pmt; i++ )
1240                 {
1241                     ts_pid_t *pmt = p_sys->pmt[i];
1242                     int i_prg;
1243
1244                     for( i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
1245                     {
1246                         if( pmt->psi->prg[i_prg]->i_number == p_sys->i_dvb_program )
1247                         {
1248                             i_pmt_pid = p_sys->pmt[i]->i_pid;
1249                             break;
1250                         }
1251                     }
1252                     if( i_pmt_pid > 0 ) break;
1253                 }
1254
1255                 if( i_pmt_pid > 0 )
1256                 {
1257                     stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
1258                                     ACCESS_SET_PRIVATE_ID_STATE, i_pmt_pid,
1259                                     VLC_FALSE );
1260                     /* All ES */
1261                     for( i = 2; i < 8192; i++ )
1262                     {
1263                         ts_pid_t *pid = &p_sys->pid[i];
1264                         int i_prg;
1265
1266                         if( !pid->b_valid || pid->psi ) continue;
1267
1268                         for( i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
1269                         {
1270                             if( pid->p_owner->prg[i_prg]->i_pid_pmt == i_pmt_pid && pid->es->id )
1271                             {
1272                                 /* We only remove es that aren't defined by extra pmt */
1273                                 stream_Control( p_demux->s,
1274                                                 STREAM_CONTROL_ACCESS,
1275                                                 ACCESS_SET_PRIVATE_ID_STATE,
1276                                                 i, VLC_FALSE );
1277                                 break;
1278                             }
1279                         }
1280                     }
1281                 }
1282
1283                 /* select new program */
1284                 p_sys->i_dvb_program = i_int;
1285                 i_pmt_pid = -1;
1286                 for( i = 0; i < p_sys->i_pmt; i++ )
1287                 {
1288                     ts_pid_t *pmt = p_sys->pmt[i];
1289                     int i_prg;
1290
1291                     for( i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
1292                     {
1293                         if( pmt->psi->prg[i_prg]->i_number == i_int )
1294                         {
1295                             i_pmt_pid = p_sys->pmt[i]->i_pid;
1296                             p_prg = p_sys->pmt[i]->psi->prg[i_prg];
1297                             break;
1298                         }
1299                     }
1300                     if( i_pmt_pid > 0 ) break;
1301                 }
1302                 if( i_pmt_pid > 0 )
1303                 {
1304                     stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
1305                                     ACCESS_SET_PRIVATE_ID_STATE, i_pmt_pid,
1306                                     VLC_TRUE );
1307                     stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
1308                                     ACCESS_SET_PRIVATE_ID_STATE, p_prg->i_pid_pcr,
1309                                     VLC_TRUE );
1310
1311                     for( i = 2; i < 8192; i++ )
1312                     {
1313                         ts_pid_t *pid = &p_sys->pid[i];
1314                         int i_prg;
1315
1316                         if( !pid->b_valid || pid->psi ) continue;
1317
1318                         for( i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
1319                         {
1320                             if( pid->p_owner->prg[i_prg]->i_pid_pmt == i_pmt_pid && pid->es->id )
1321                             {
1322                                 if ( pid->es->fmt.i_cat == VIDEO_ES && !i_vpid )
1323                                     i_vpid = i;
1324                                 if ( pid->es->fmt.i_cat == AUDIO_ES && !i_apid1 )
1325                                     i_apid1 = i;
1326                                 else if ( pid->es->fmt.i_cat == AUDIO_ES && !i_apid2 )
1327                                     i_apid2 = i;
1328                                 else if ( pid->es->fmt.i_cat == AUDIO_ES && !i_apid3 )
1329                                     i_apid3 = i;
1330
1331                                 stream_Control( p_demux->s,
1332                                                 STREAM_CONTROL_ACCESS,
1333                                                 ACCESS_SET_PRIVATE_ID_STATE,
1334                                                 i, VLC_TRUE );
1335                                 break;
1336                             }
1337                         }
1338                     }
1339                 }
1340             }
1341             else
1342             {
1343                 p_sys->i_dvb_program = -1;
1344                 p_sys->p_programs_list = p_list;
1345             }
1346             return VLC_SUCCESS;
1347         }
1348
1349         case DEMUX_GET_FPS:
1350         case DEMUX_SET_TIME:
1351         default:
1352             return VLC_EGENERIC;
1353     }
1354 }
1355
1356 static void PIDInit( ts_pid_t *pid, vlc_bool_t b_psi, ts_psi_t *p_owner )
1357 {
1358     vlc_bool_t b_old_valid = pid->b_valid;
1359
1360     pid->b_valid    = VLC_TRUE;
1361     pid->i_cc       = 0xff;
1362     pid->p_owner    = p_owner;
1363     pid->i_owner_number = 0;
1364
1365     pid->extra_es   = NULL;
1366     pid->i_extra_es = 0;
1367
1368     if( b_psi )
1369     {
1370         pid->es  = NULL;
1371
1372         if( !b_old_valid )
1373         {
1374             pid->psi = malloc( sizeof( ts_psi_t ) );
1375             pid->psi->handle= NULL;
1376             pid->psi->i_prg = 0;
1377             pid->psi->prg   = NULL;
1378         }
1379         pid->psi->i_pat_version  = -1;
1380         pid->psi->i_sdt_version  = -1;
1381         if( p_owner )
1382         {
1383             ts_prg_psi_t *prg = malloc( sizeof( ts_prg_psi_t ) );
1384             /* PMT */
1385             prg->i_version  = -1;
1386             prg->i_number   = -1;
1387             prg->i_pid_pcr  = -1;
1388             prg->i_pid_pmt  = -1;
1389             prg->iod        = NULL;
1390             prg->handle     = NULL;
1391
1392             TAB_APPEND( pid->psi->i_prg, pid->psi->prg, prg );
1393         }
1394     }
1395     else
1396     {
1397         pid->psi = NULL;
1398         pid->es  = malloc( sizeof( ts_es_t ) );
1399
1400         es_format_Init( &pid->es->fmt, UNKNOWN_ES, 0 );
1401         pid->es->id      = NULL;
1402         pid->es->p_pes   = NULL;
1403         pid->es->i_pes_size= 0;
1404         pid->es->i_pes_gathered= 0;
1405         pid->es->pp_last = &pid->es->p_pes;
1406         pid->es->p_mpeg4desc = NULL;
1407         pid->es->b_gather = VLC_FALSE;
1408     }
1409 }
1410
1411 static void PIDClean( es_out_t *out, ts_pid_t *pid )
1412 {
1413     if( pid->psi )
1414     {
1415         int i;
1416
1417         if( pid->psi->handle ) dvbpsi_DetachPMT( pid->psi->handle );
1418         for( i = 0; i < pid->psi->i_prg; i++ )
1419         {
1420             if( pid->psi->prg[i]->iod )
1421                 IODFree( pid->psi->prg[i]->iod );
1422             if( pid->psi->prg[i]->handle )
1423                 dvbpsi_DetachPMT( pid->psi->prg[i]->handle );
1424             free( pid->psi->prg[i] );
1425         }
1426         if( pid->psi->prg ) free( pid->psi->prg );
1427         free( pid->psi );
1428     }
1429     else
1430     {
1431         int i;
1432
1433         if( pid->es->id )
1434             es_out_Del( out, pid->es->id );
1435
1436         if( pid->es->p_pes )
1437             block_ChainRelease( pid->es->p_pes );
1438
1439         es_format_Clean( &pid->es->fmt );
1440
1441         free( pid->es );
1442
1443         for( i = 0; i < pid->i_extra_es; i++ )
1444         {
1445             if( pid->extra_es[i]->id )
1446                 es_out_Del( out, pid->extra_es[i]->id );
1447
1448             if( pid->extra_es[i]->p_pes )
1449                 block_ChainRelease( pid->extra_es[i]->p_pes );
1450
1451             es_format_Clean( &pid->extra_es[i]->fmt );
1452
1453             free( pid->extra_es[i] );
1454         }
1455         if( pid->i_extra_es ) free( pid->extra_es );
1456     }
1457
1458     pid->b_valid = VLC_FALSE;
1459 }
1460
1461 /****************************************************************************
1462  * gathering stuff
1463  ****************************************************************************/
1464 static void ParsePES( demux_t *p_demux, ts_pid_t *pid )
1465 {
1466     block_t *p_pes = pid->es->p_pes;
1467     uint8_t header[30];
1468     int     i_pes_size = 0;
1469     int     i_skip = 0;
1470     mtime_t i_dts = -1;
1471     mtime_t i_pts = -1;
1472     mtime_t i_length = 0;
1473     int i_max;
1474
1475     /* remove the pes from pid */
1476     pid->es->p_pes = NULL;
1477     pid->es->i_pes_size= 0;
1478     pid->es->i_pes_gathered= 0;
1479     pid->es->pp_last = &pid->es->p_pes;
1480
1481     /* FIXME find real max size */
1482     i_max = block_ChainExtract( p_pes, header, 30 );
1483
1484
1485     if( header[0] != 0 || header[1] != 0 || header[2] != 1 )
1486     {
1487         if( !p_demux->p_sys->b_silent )
1488             msg_Warn( p_demux, "invalid header [0x%x:%x:%x:%x] (pid: %d)",
1489                       header[0], header[1],header[2],header[3], pid->i_pid );
1490         block_ChainRelease( p_pes );
1491         return;
1492     }
1493
1494     /* TODO check size */
1495     switch( header[3] )
1496     {
1497         case 0xBC:  /* Program stream map */
1498         case 0xBE:  /* Padding */
1499         case 0xBF:  /* Private stream 2 */
1500         case 0xB0:  /* ECM */
1501         case 0xB1:  /* EMM */
1502         case 0xFF:  /* Program stream directory */
1503         case 0xF2:  /* DSMCC stream */
1504         case 0xF8:  /* ITU-T H.222.1 type E stream */
1505             i_skip = 6;
1506             break;
1507         default:
1508             if( ( header[6]&0xC0 ) == 0x80 )
1509             {
1510                 /* mpeg2 PES */
1511                 i_skip = header[8] + 9;
1512
1513                 if( header[7]&0x80 )    /* has pts */
1514                 {
1515                     i_pts = ((mtime_t)(header[ 9]&0x0e ) << 29)|
1516                              (mtime_t)(header[10] << 22)|
1517                             ((mtime_t)(header[11]&0xfe) << 14)|
1518                              (mtime_t)(header[12] << 7)|
1519                              (mtime_t)(header[13] >> 1);
1520
1521                     if( header[7]&0x40 )    /* has dts */
1522                     {
1523                          i_dts = ((mtime_t)(header[14]&0x0e ) << 29)|
1524                                  (mtime_t)(header[15] << 22)|
1525                                 ((mtime_t)(header[16]&0xfe) << 14)|
1526                                  (mtime_t)(header[17] << 7)|
1527                                  (mtime_t)(header[18] >> 1);
1528                     }
1529                 }
1530             }
1531             else
1532             {
1533                 i_skip = 6;
1534                 while( i_skip < 23 && header[i_skip] == 0xff )
1535                 {
1536                     i_skip++;
1537                 }
1538                 if( i_skip == 23 )
1539                 {
1540                     msg_Err( p_demux, "too much MPEG-1 stuffing" );
1541                     block_ChainRelease( p_pes );
1542                     return;
1543                 }
1544                 if( ( header[i_skip] & 0xC0 ) == 0x40 )
1545                 {
1546                     i_skip += 2;
1547                 }
1548
1549                 if(  header[i_skip]&0x20 )
1550                 {
1551                      i_pts = ((mtime_t)(header[i_skip]&0x0e ) << 29)|
1552                               (mtime_t)(header[i_skip+1] << 22)|
1553                              ((mtime_t)(header[i_skip+2]&0xfe) << 14)|
1554                               (mtime_t)(header[i_skip+3] << 7)|
1555                               (mtime_t)(header[i_skip+4] >> 1);
1556
1557                     if( header[i_skip]&0x10 )    /* has dts */
1558                     {
1559                          i_dts = ((mtime_t)(header[i_skip+5]&0x0e ) << 29)|
1560                                   (mtime_t)(header[i_skip+6] << 22)|
1561                                  ((mtime_t)(header[i_skip+7]&0xfe) << 14)|
1562                                   (mtime_t)(header[i_skip+8] << 7)|
1563                                   (mtime_t)(header[i_skip+9] >> 1);
1564                          i_skip += 10;
1565                     }
1566                     else
1567                     {
1568                         i_skip += 5;
1569                     }
1570                 }
1571                 else
1572                 {
1573                     i_skip += 1;
1574                 }
1575             }
1576             break;
1577     }
1578
1579     if( pid->es->fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
1580         pid->es->fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
1581     {
1582         i_skip += 4;
1583     }
1584     else if( pid->es->fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
1585              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
1586              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
1587     {
1588         i_skip += 1;
1589     }
1590     else if( pid->es->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) &&
1591              pid->es->p_mpeg4desc )
1592     {
1593         decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
1594
1595         if( dcd->i_decoder_specific_info_len > 2 &&
1596             dcd->p_decoder_specific_info[0] == 0x10 &&
1597             ( dcd->p_decoder_specific_info[1]&0x10 ) )
1598         {
1599             /* display length */
1600             if( p_pes->i_buffer + 2 <= i_skip )
1601             {
1602                 i_length = GetWBE( &p_pes->p_buffer[i_skip] );
1603             }
1604
1605             i_skip += 2;
1606         }
1607         if( p_pes->i_buffer + 2 <= i_skip )
1608         {
1609             i_pes_size = GetWBE( &p_pes->p_buffer[i_skip] );
1610         }
1611         /* */
1612         i_skip += 2;
1613     }
1614
1615     /* skip header */
1616     while( p_pes && i_skip > 0 )
1617     {
1618         if( p_pes->i_buffer <= i_skip )
1619         {
1620             block_t *p_next = p_pes->p_next;
1621
1622             i_skip -= p_pes->i_buffer;
1623             block_Release( p_pes );
1624             p_pes = p_next;
1625         }
1626         else
1627         {
1628             p_pes->i_buffer -= i_skip;
1629             p_pes->p_buffer += i_skip;
1630             break;
1631         }
1632     }
1633
1634     /* ISO/IEC 13818-1 2.7.5: if no pts and no dts, then dts == pts */
1635     if( i_pts >= 0 && i_dts < 0 )
1636         i_dts = i_pts;
1637
1638     if( p_pes )
1639     {
1640         block_t *p_block;
1641         int i;
1642
1643         if( i_dts >= 0 )
1644         {
1645             p_pes->i_dts = i_dts * 100 / 9;
1646         }
1647         if( i_pts >= 0 )
1648         {
1649             p_pes->i_pts = i_pts * 100 / 9;
1650         }
1651         p_pes->i_length = i_length * 100 / 9;
1652
1653         p_block = block_ChainGather( p_pes );
1654         if( pid->es->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) )
1655         {
1656             if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
1657             {
1658                 p_block->i_buffer = i_pes_size;
1659             }
1660             /* Append a \0 */
1661             p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
1662             p_block->p_buffer[p_block->i_buffer -1] = '\0';
1663         }
1664
1665         for( i = 0; i < pid->i_extra_es; i++ )
1666         {
1667             es_out_Send( p_demux->out, pid->extra_es[i]->id,
1668                          block_Duplicate( p_block ) );
1669         }
1670
1671         es_out_Send( p_demux->out, pid->es->id, p_block );
1672     }
1673     else
1674     {
1675         msg_Warn( p_demux, "empty pes" );
1676     }
1677 }
1678
1679 static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
1680 {
1681     demux_sys_t   *p_sys = p_demux->p_sys;
1682     const uint8_t *p = p_bk->p_buffer;
1683
1684     if( ( p[3]&0x20 ) && /* adaptation */
1685         ( p[5]&0x10 ) &&
1686         ( p[4] >= 7 ) )
1687     {
1688         int i;
1689         mtime_t i_pcr;  /* 33 bits */
1690
1691         i_pcr = ( (mtime_t)p[6] << 25 ) |
1692                 ( (mtime_t)p[7] << 17 ) |
1693                 ( (mtime_t)p[8] << 9 ) |
1694                 ( (mtime_t)p[9] << 1 ) |
1695                 ( (mtime_t)p[10] >> 7 );
1696
1697         /* Search program and set the PCR */
1698         for( i = 0; i < p_sys->i_pmt; i++ )
1699         {
1700             int i_prg;
1701             for( i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
1702             {
1703                 if( pid->i_pid == p_sys->pmt[i]->psi->prg[i_prg]->i_pid_pcr )
1704                 {
1705                     es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
1706                                     (int)p_sys->pmt[i]->psi->prg[i_prg]->i_number,
1707                                     (int64_t)(i_pcr * 100 / 9) );
1708                 }
1709             }
1710         }
1711     }
1712 }
1713
1714 static vlc_bool_t GatherPES( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
1715 {
1716     const uint8_t    *p = p_bk->p_buffer;
1717     const vlc_bool_t b_unit_start = p[1]&0x40;
1718     const vlc_bool_t b_adaptation = p[3]&0x20;
1719     const vlc_bool_t b_payload    = p[3]&0x10;
1720     const int        i_cc         = p[3]&0x0f;   /* continuity counter */
1721     vlc_bool_t       b_discontinuity = VLC_FALSE;/* discontinuity */    
1722
1723     /* transport_scrambling_control is ignored */
1724     int         i_skip = 0;
1725     vlc_bool_t  i_ret  = VLC_FALSE;
1726     int         i_diff;
1727
1728 #if 0
1729     msg_Dbg( p_demux, "pid=%d unit_start=%d adaptation=%d payload=%d "
1730              "cc=0x%x", pid->i_pid, b_unit_start, b_adaptation,
1731              b_payload, i_cc );
1732 #endif
1733
1734     /* For now, ignore additional error correction
1735      * TODO: handle Reed-Solomon 204,188 error correction */
1736     p_bk->i_buffer = TS_PACKET_SIZE_188;
1737
1738     if( p[1]&0x80 )
1739     {
1740         msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
1741                  pid->i_pid );
1742         if( pid->es->p_pes ) //&& pid->es->fmt.i_cat == VIDEO_ES )
1743             pid->es->p_pes->i_flags |= BLOCK_FLAG_CORRUPTED;
1744     }
1745
1746     if( p_demux->p_sys->csa )
1747     {
1748         csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer, p_demux->p_sys->i_csa_pkt_size );
1749     }
1750
1751     if( !b_adaptation )
1752     {
1753         /* We don't have any adaptation_field, so payload starts
1754          * immediately after the 4 byte TS header */
1755         i_skip = 4;
1756     }
1757     else
1758     {
1759         /* p[4] is adaptation_field_length minus one */
1760         i_skip = 5 + p[4];
1761         if( p[4] > 0 )
1762         {
1763             /* discontinuity indicator found in stream */
1764             b_discontinuity = (p[5]&0x80) ? VLC_TRUE : VLC_FALSE;
1765             if( b_discontinuity && pid->es->p_pes )
1766             {
1767                 msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
1768                             pid->i_pid );
1769                 /* pid->es->p_pes->i_flags |= BLOCK_FLAG_DISCONTINUITY; */
1770             }
1771 #if 0
1772             if( p[5]&0x40 )
1773                 msg_Dbg( p_demux, "random access indicator (pid=%d) ", pid->i_pid );
1774 #endif
1775         }
1776     }
1777
1778     /* Test continuity counter */
1779     /* continuous when (one of this):
1780         * diff == 1
1781         * diff == 0 and payload == 0
1782         * diff == 0 and duplicate packet (playload != 0) <- should we
1783         *   test the content ?
1784      */
1785     i_diff = ( i_cc - pid->i_cc )&0x0f;
1786     if( b_payload && i_diff == 1 )
1787     {
1788         pid->i_cc = ( pid->i_cc + 1 ) & 0xf;
1789     }
1790     else
1791     {
1792         if( pid->i_cc == 0xff )
1793         {
1794             msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
1795                       pid->i_pid, i_cc );
1796             pid->i_cc = i_cc;
1797         }
1798         else if( i_diff != 0 && !b_discontinuity )
1799         {
1800             msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x (pid=%d)",
1801                       i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );
1802
1803             pid->i_cc = i_cc;
1804             if( pid->es->p_pes && pid->es->fmt.i_cat != VIDEO_ES )
1805             {
1806                 /* Small video artifacts are usually better then
1807                  * dropping full frames */
1808                 pid->es->p_pes->i_flags |= BLOCK_FLAG_CORRUPTED;
1809             }
1810         }
1811     }
1812
1813     PCRHandle( p_demux, pid, p_bk );
1814
1815     if( i_skip >= 188 || pid->es->id == NULL || p_demux->p_sys->b_udp_out )
1816     {
1817         block_Release( p_bk );
1818         return i_ret;
1819     }
1820
1821     /* We have to gather it */
1822     p_bk->p_buffer += i_skip;
1823     p_bk->i_buffer -= i_skip;
1824
1825     if( b_unit_start )
1826     {
1827         if( pid->es->p_pes )
1828         {
1829             ParsePES( p_demux, pid );
1830             i_ret = VLC_TRUE;
1831         }
1832
1833         block_ChainLastAppend( &pid->es->pp_last, p_bk );
1834         if( p_bk->i_buffer > 6 )
1835         {
1836             pid->es->i_pes_size = GetWBE( &p_bk->p_buffer[4] );
1837             if( pid->es->i_pes_size > 0 )
1838             {
1839                 pid->es->i_pes_size += 6;
1840             }
1841         }
1842         pid->es->i_pes_gathered += p_bk->i_buffer;
1843         if( pid->es->i_pes_size > 0 &&
1844             pid->es->i_pes_gathered >= pid->es->i_pes_size )
1845         {
1846             ParsePES( p_demux, pid );
1847             i_ret = VLC_TRUE;
1848         }
1849     }
1850     else
1851     {
1852         if( pid->es->p_pes == NULL )
1853         {
1854             /* msg_Dbg( p_demux, "broken packet" ); */
1855             block_Release( p_bk );
1856         }
1857         else
1858         {
1859             block_ChainLastAppend( &pid->es->pp_last, p_bk );
1860             pid->es->i_pes_gathered += p_bk->i_buffer;
1861             if( pid->es->i_pes_size > 0 &&
1862                 pid->es->i_pes_gathered >= pid->es->i_pes_size )
1863             {
1864                 ParsePES( p_demux, pid );
1865                 i_ret = VLC_TRUE;
1866             }
1867         }
1868     }
1869
1870     return i_ret;
1871 }
1872
1873 static int PIDFillFormat( ts_pid_t *pid, int i_stream_type )
1874 {
1875     es_format_t *fmt = &pid->es->fmt;
1876
1877     switch( i_stream_type )
1878     {
1879         case 0x01:  /* MPEG-1 video */
1880         case 0x02:  /* MPEG-2 video */
1881         case 0x80:  /* MPEG-2 MOTO video */
1882             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'm', 'p', 'g', 'v' ) );
1883             break;
1884         case 0x03:  /* MPEG-1 audio */
1885         case 0x04:  /* MPEG-2 audio */
1886             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'm', 'p', 'g', 'a' ) );
1887             break;
1888         case 0x11:  /* MPEG4 (audio) */
1889         case 0x0f:  /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
1890             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'm', 'p', '4', 'a' ) );
1891             break;
1892         case 0x10:  /* MPEG4 (video) */
1893             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'm', 'p', '4', 'v' ) );
1894             pid->es->b_gather = VLC_TRUE;
1895             break;
1896         case 0x1B:  /* H264 <- check transport syntax/needed descriptor */
1897             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'h', '2', '6', '4' ) );
1898             break;
1899
1900         case 0x81:  /* A52 (audio) */
1901             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', ' ' ) );
1902             break;
1903         case 0x82:  /* DVD_SPU (sub) */
1904             es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', ' ' ) );
1905             break;
1906         case 0x83:  /* LPCM (audio) */
1907             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'l', 'p', 'c', 'm' ) );
1908             break;
1909         case 0x84:  /* SDDS (audio) */
1910             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 's' ) );
1911             break;
1912         case 0x85:  /* DTS (audio) */
1913             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'd', 't', 's', ' ' ) );
1914             break;
1915
1916         case 0x91:  /* A52 vls (audio) */
1917             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
1918             break;
1919         case 0x92:  /* DVD_SPU vls (sub) */
1920             es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
1921             break;
1922
1923         case 0x94:  /* SDDS (audio) */
1924             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
1925             break;
1926
1927         case 0xa0:  /* MSCODEC vlc (video) (fixed later) */
1928             es_format_Init( fmt, UNKNOWN_ES, 0 );
1929             pid->es->b_gather = VLC_TRUE;
1930             break;
1931
1932         case 0x06:  /* PES_PRIVATE  (fixed later) */
1933         case 0x12:  /* MPEG-4 generic (sub/scene/...) (fixed later) */
1934         default:
1935             es_format_Init( fmt, UNKNOWN_ES, 0 );
1936             break;
1937     }
1938
1939     /* PES packets usually contain truncated frames */
1940     fmt->b_packetized = VLC_FALSE;
1941
1942     return fmt->i_cat == UNKNOWN_ES ? VLC_EGENERIC : VLC_SUCCESS ;
1943 }
1944
1945 /*****************************************************************************
1946  * MP4 specific functions (IOD parser)
1947  *****************************************************************************/
1948 static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
1949 {
1950     unsigned int i_b;
1951     unsigned int i_len = 0;
1952     do
1953     {
1954         i_b = **pp_data;
1955         (*pp_data)++;
1956         (*pi_data)--;
1957         i_len = ( i_len << 7 ) + ( i_b&0x7f );
1958
1959     } while( i_b&0x80 );
1960
1961     return( i_len );
1962 }
1963 static int IODGetByte( int *pi_data, uint8_t **pp_data )
1964 {
1965     if( *pi_data > 0 )
1966     {
1967         const int i_b = **pp_data;
1968         (*pp_data)++;
1969         (*pi_data)--;
1970         return( i_b );
1971     }
1972     return( 0 );
1973 }
1974 static int IODGetWord( int *pi_data, uint8_t **pp_data )
1975 {
1976     const int i1 = IODGetByte( pi_data, pp_data );
1977     const int i2 = IODGetByte( pi_data, pp_data );
1978     return( ( i1 << 8 ) | i2 );
1979 }
1980 static int IODGet3Bytes( int *pi_data, uint8_t **pp_data )
1981 {
1982     const int i1 = IODGetByte( pi_data, pp_data );
1983     const int i2 = IODGetByte( pi_data, pp_data );
1984     const int i3 = IODGetByte( pi_data, pp_data );
1985
1986     return( ( i1 << 16 ) | ( i2 << 8) | i3 );
1987 }
1988
1989 static uint32_t IODGetDWord( int *pi_data, uint8_t **pp_data )
1990 {
1991     const uint32_t i1 = IODGetWord( pi_data, pp_data );
1992     const uint32_t i2 = IODGetWord( pi_data, pp_data );
1993     return( ( i1 << 16 ) | i2 );
1994 }
1995
1996 static char* IODGetURL( int *pi_data, uint8_t **pp_data )
1997 {
1998     char *url;
1999     int i_url_len, i;
2000
2001     i_url_len = IODGetByte( pi_data, pp_data );
2002     url = malloc( i_url_len + 1 );
2003     for( i = 0; i < i_url_len; i++ )
2004     {
2005         url[i] = IODGetByte( pi_data, pp_data );
2006     }
2007     url[i_url_len] = '\0';
2008     return( url );
2009 }
2010
2011 static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
2012 {
2013     iod_descriptor_t *p_iod;
2014     int i;
2015     int i_es_index;
2016     uint8_t     i_flags, i_iod_tag, byte1, byte2, byte3;
2017     vlc_bool_t  b_url;
2018     int         i_iod_length;
2019
2020     p_iod = malloc( sizeof( iod_descriptor_t ) );
2021     memset( p_iod, 0, sizeof( iod_descriptor_t ) );
2022
2023 #ifdef TS_DEBUG
2024     fprintf( stderr, "\n************ IOD ************" );
2025 #endif
2026     for( i = 0; i < 255; i++ )
2027     {
2028         p_iod->es_descr[i].b_ok = 0;
2029     }
2030     i_es_index = 0;
2031
2032     if( i_data < 3 )
2033     {
2034         return p_iod;
2035     }
2036
2037     byte1 = IODGetByte( &i_data, &p_data );
2038     byte2 = IODGetByte( &i_data, &p_data );
2039     byte3 = IODGetByte( &i_data, &p_data );
2040     if( byte2 == 0x02 ) //old vlc's buggy implementation of the IOD_descriptor
2041     {
2042         p_iod->i_iod_label_scope = 0x11;
2043         p_iod->i_iod_label = byte1;
2044         i_iod_tag = byte2;
2045     }
2046     else  //correct implementation of the IOD_descriptor
2047     {
2048         p_iod->i_iod_label_scope = byte1;
2049         p_iod->i_iod_label = byte2;
2050         i_iod_tag = byte3;
2051     }
2052 #ifdef TS_DEBUG
2053     fprintf( stderr, "\n* iod_label:%d", p_iod->i_iod_label );
2054     fprintf( stderr, "\n* ===========" );
2055     fprintf( stderr, "\n* tag:0x%x", i_iod_tag );
2056 #endif
2057     if( i_iod_tag != 0x02 )
2058     {
2059 #ifdef TS_DEBUG
2060         fprintf( stderr, "\n ERR: tag %02x != 0x02", i_iod_tag );
2061 #endif
2062         return p_iod;
2063     }
2064
2065     i_iod_length = IODDescriptorLength( &i_data, &p_data );
2066 #ifdef TS_DEBUG
2067     fprintf( stderr, "\n* length:%d", i_iod_length );
2068 #endif
2069     if( i_iod_length > i_data )
2070     {
2071         i_iod_length = i_data;
2072     }
2073
2074     p_iod->i_od_id = ( IODGetByte( &i_data, &p_data ) << 2 );
2075     i_flags = IODGetByte( &i_data, &p_data );
2076     p_iod->i_od_id |= i_flags >> 6;
2077     b_url = ( i_flags >> 5  )&0x01;
2078 #ifdef TS_DEBUG
2079     fprintf( stderr, "\n* od_id:%d", p_iod->i_od_id );
2080     fprintf( stderr, "\n* url flag:%d", b_url );
2081     fprintf( stderr, "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
2082 #endif
2083     if( b_url )
2084     {
2085         p_iod->psz_url = IODGetURL( &i_data, &p_data );
2086 #ifdef TS_DEBUG
2087         fprintf( stderr, "\n* url string:%s", p_iod->psz_url );
2088         fprintf( stderr, "\n*****************************\n" );
2089 #endif
2090         return p_iod;
2091     }
2092     else
2093     {
2094         p_iod->psz_url = NULL;
2095     }
2096
2097     p_iod->i_ODProfileLevelIndication = IODGetByte( &i_data, &p_data );
2098     p_iod->i_sceneProfileLevelIndication = IODGetByte( &i_data, &p_data );
2099     p_iod->i_audioProfileLevelIndication = IODGetByte( &i_data, &p_data );
2100     p_iod->i_visualProfileLevelIndication = IODGetByte( &i_data, &p_data );
2101     p_iod->i_graphicsProfileLevelIndication = IODGetByte( &i_data, &p_data );
2102 #ifdef TS_DEBUG
2103     fprintf( stderr, "\n* ODProfileLevelIndication:%d", p_iod->i_ODProfileLevelIndication );
2104     fprintf( stderr, "\n* sceneProfileLevelIndication:%d", p_iod->i_sceneProfileLevelIndication );
2105     fprintf( stderr, "\n* audioProfileLevelIndication:%d", p_iod->i_audioProfileLevelIndication );
2106     fprintf( stderr, "\n* visualProfileLevelIndication:%d", p_iod->i_visualProfileLevelIndication );
2107     fprintf( stderr, "\n* graphicsProfileLevelIndication:%d", p_iod->i_graphicsProfileLevelIndication );
2108 #endif
2109
2110     while( i_data > 0 && i_es_index < 255)
2111     {
2112         int i_tag, i_length;
2113         int     i_data_sav;
2114         uint8_t *p_data_sav;
2115
2116         i_tag = IODGetByte( &i_data, &p_data );
2117         i_length = IODDescriptorLength( &i_data, &p_data );
2118
2119         i_data_sav = i_data;
2120         p_data_sav = p_data;
2121
2122         i_data = i_length;
2123
2124         switch( i_tag )
2125         {
2126             case 0x03:
2127                 {
2128 #define es_descr    p_iod->es_descr[i_es_index]
2129                     int i_decoderConfigDescr_length;
2130 #ifdef TS_DEBUG
2131                     fprintf( stderr, "\n* - ES_Descriptor length:%d", i_length );
2132 #endif
2133                     es_descr.b_ok = 1;
2134
2135                     es_descr.i_es_id = IODGetWord( &i_data, &p_data );
2136                     i_flags = IODGetByte( &i_data, &p_data );
2137                     es_descr.b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
2138                     b_url = ( i_flags >> 6 )&0x01;
2139                     es_descr.b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
2140                     es_descr.i_streamPriority = i_flags & 0x1f;
2141 #ifdef TS_DEBUG
2142                     fprintf( stderr, "\n*   * streamDependenceFlag:%d", es_descr.b_streamDependenceFlag );
2143                     fprintf( stderr, "\n*   * OCRStreamFlag:%d", es_descr.b_OCRStreamFlag );
2144                     fprintf( stderr, "\n*   * streamPriority:%d", es_descr.i_streamPriority );
2145 #endif
2146                     if( es_descr.b_streamDependenceFlag )
2147                     {
2148                         es_descr.i_dependOn_es_id = IODGetWord( &i_data, &p_data );
2149 #ifdef TS_DEBUG
2150                         fprintf( stderr, "\n*   * dependOn_es_id:%d", es_descr.i_dependOn_es_id );
2151 #endif
2152                     }
2153
2154                     if( b_url )
2155                     {
2156                         es_descr.psz_url = IODGetURL( &i_data, &p_data );
2157 #ifdef TS_DEBUG
2158                         fprintf( stderr, "\n* url string:%s", es_descr.psz_url );
2159 #endif
2160                     }
2161                     else
2162                     {
2163                         es_descr.psz_url = NULL;
2164                     }
2165
2166                     if( es_descr.b_OCRStreamFlag )
2167                     {
2168                         es_descr.i_OCR_es_id = IODGetWord( &i_data, &p_data );
2169 #ifdef TS_DEBUG
2170                         fprintf( stderr, "\n*   * OCR_es_id:%d", es_descr.i_OCR_es_id );
2171 #endif
2172                     }
2173
2174                     if( IODGetByte( &i_data, &p_data ) != 0x04 )
2175                     {
2176 #ifdef TS_DEBUG
2177                         fprintf( stderr, "\n* ERR missing DecoderConfigDescr" );
2178 #endif
2179                         es_descr.b_ok = 0;
2180                         break;
2181                     }
2182                     i_decoderConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
2183 #ifdef TS_DEBUG
2184                     fprintf( stderr, "\n*   - DecoderConfigDesc length:%d", i_decoderConfigDescr_length );
2185 #endif
2186 #define dec_descr   es_descr.dec_descr
2187                     dec_descr.i_objectTypeIndication = IODGetByte( &i_data, &p_data );
2188                     i_flags = IODGetByte( &i_data, &p_data );
2189                     dec_descr.i_streamType = i_flags >> 2;
2190                     dec_descr.b_upStream = ( i_flags >> 1 )&0x01;
2191                     dec_descr.i_bufferSizeDB = IODGet3Bytes( &i_data, &p_data );
2192                     dec_descr.i_maxBitrate = IODGetDWord( &i_data, &p_data );
2193                     dec_descr.i_avgBitrate = IODGetDWord( &i_data, &p_data );
2194 #ifdef TS_DEBUG
2195                     fprintf( stderr, "\n*     * objectTypeIndication:0x%x", dec_descr.i_objectTypeIndication  );
2196                     fprintf( stderr, "\n*     * streamType:0x%x", dec_descr.i_streamType );
2197                     fprintf( stderr, "\n*     * upStream:%d", dec_descr.b_upStream );
2198                     fprintf( stderr, "\n*     * bufferSizeDB:%d", dec_descr.i_bufferSizeDB );
2199                     fprintf( stderr, "\n*     * maxBitrate:%d", dec_descr.i_maxBitrate );
2200                     fprintf( stderr, "\n*     * avgBitrate:%d", dec_descr.i_avgBitrate );
2201 #endif
2202                     if( i_decoderConfigDescr_length > 13 && IODGetByte( &i_data, &p_data ) == 0x05 )
2203                     {
2204                         int i;
2205                         dec_descr.i_decoder_specific_info_len =
2206                             IODDescriptorLength( &i_data, &p_data );
2207                         if( dec_descr.i_decoder_specific_info_len > 0 )
2208                         {
2209                             dec_descr.p_decoder_specific_info =
2210                                 malloc( dec_descr.i_decoder_specific_info_len );
2211                         }
2212                         for( i = 0; i < dec_descr.i_decoder_specific_info_len; i++ )
2213                         {
2214                             dec_descr.p_decoder_specific_info[i] = IODGetByte( &i_data, &p_data );
2215                         }
2216                     }
2217                     else
2218                     {
2219                         dec_descr.i_decoder_specific_info_len = 0;
2220                         dec_descr.p_decoder_specific_info = NULL;
2221                     }
2222                 }
2223 #undef  dec_descr
2224 #define sl_descr    es_descr.sl_descr
2225                 {
2226                     int i_SLConfigDescr_length;
2227                     int i_predefined;
2228
2229                     if( IODGetByte( &i_data, &p_data ) != 0x06 )
2230                     {
2231 #ifdef TS_DEBUG
2232                         fprintf( stderr, "\n* ERR missing SLConfigDescr" );
2233 #endif
2234                         es_descr.b_ok = 0;
2235                         break;
2236                     }
2237                     i_SLConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
2238 #ifdef TS_DEBUG
2239                     fprintf( stderr, "\n*   - SLConfigDescr length:%d", i_SLConfigDescr_length );
2240 #endif
2241                     i_predefined = IODGetByte( &i_data, &p_data );
2242 #ifdef TS_DEBUG
2243                     fprintf( stderr, "\n*     * i_predefined:0x%x", i_predefined  );
2244 #endif
2245                     switch( i_predefined )
2246                     {
2247                         case 0x01:
2248                             {
2249                                 sl_descr.b_useAccessUnitStartFlag   = 0;
2250                                 sl_descr.b_useAccessUnitEndFlag     = 0;
2251                                 sl_descr.b_useRandomAccessPointFlag = 0;
2252                                 //sl_descr.b_useRandomAccessUnitsOnlyFlag = 0;
2253                                 sl_descr.b_usePaddingFlag           = 0;
2254                                 sl_descr.b_useTimeStampsFlags       = 0;
2255                                 sl_descr.b_useIdleFlag              = 0;
2256                                 sl_descr.b_durationFlag     = 0;    // FIXME FIXME
2257                                 sl_descr.i_timeStampResolution      = 1000;
2258                                 sl_descr.i_OCRResolution    = 0;    // FIXME FIXME
2259                                 sl_descr.i_timeStampLength          = 32;
2260                                 sl_descr.i_OCRLength        = 0;    // FIXME FIXME
2261                                 sl_descr.i_AU_Length                = 0;
2262                                 sl_descr.i_instantBitrateLength= 0; // FIXME FIXME
2263                                 sl_descr.i_degradationPriorityLength= 0;
2264                                 sl_descr.i_AU_seqNumLength          = 0;
2265                                 sl_descr.i_packetSeqNumLength       = 0;
2266                                 if( sl_descr.b_durationFlag )
2267                                 {
2268                                     sl_descr.i_timeScale            = 0;    // FIXME FIXME
2269                                     sl_descr.i_accessUnitDuration   = 0;    // FIXME FIXME
2270                                     sl_descr.i_compositionUnitDuration= 0;    // FIXME FIXME
2271                                 }
2272                                 if( !sl_descr.b_useTimeStampsFlags )
2273                                 {
2274                                     sl_descr.i_startDecodingTimeStamp   = 0;    // FIXME FIXME
2275                                     sl_descr.i_startCompositionTimeStamp= 0;    // FIXME FIXME
2276                                 }
2277                             }
2278                             break;
2279                         default:
2280 #ifdef TS_DEBUG
2281                             fprintf( stderr, "\n* ERR unsupported SLConfigDescr predefined" );
2282 #endif
2283                             es_descr.b_ok = 0;
2284                             break;
2285                     }
2286                 }
2287                 break;
2288 #undef  sl_descr
2289 #undef  es_descr
2290             default:
2291 #ifdef TS_DEBUG
2292                 fprintf( stderr, "\n* - OD tag:0x%x length:%d (Unsupported)", i_tag, i_length );
2293 #endif
2294                 break;
2295         }
2296
2297         p_data = p_data_sav + i_length;
2298         i_data = i_data_sav - i_length;
2299         i_es_index++;
2300     }
2301 #ifdef TS_DEBUG
2302     fprintf( stderr, "\n*****************************\n" );
2303 #endif
2304     return p_iod;
2305 }
2306
2307 static void IODFree( iod_descriptor_t *p_iod )
2308 {
2309     int i;
2310
2311     if( p_iod->psz_url )
2312     {
2313         free( p_iod->psz_url );
2314         p_iod->psz_url = NULL;
2315         free( p_iod );
2316         return;
2317     }
2318
2319     for( i = 0; i < 255; i++ )
2320     {
2321 #define es_descr p_iod->es_descr[i]
2322         if( es_descr.b_ok )
2323         {
2324             if( es_descr.psz_url )
2325             {
2326                 free( es_descr.psz_url );
2327                 es_descr.psz_url = NULL;
2328             }
2329             else
2330             {
2331                 if( es_descr.dec_descr.p_decoder_specific_info != NULL )
2332                 {
2333                     free( es_descr.dec_descr.p_decoder_specific_info );
2334                     es_descr.dec_descr.p_decoder_specific_info = NULL;
2335                     es_descr.dec_descr.i_decoder_specific_info_len = 0;
2336                 }
2337             }
2338         }
2339         es_descr.b_ok = 0;
2340 #undef  es_descr
2341     }
2342     free( p_iod );
2343 }
2344
2345 /****************************************************************************
2346  ****************************************************************************
2347  ** libdvbpsi callbacks
2348  ****************************************************************************
2349  ****************************************************************************/
2350 static vlc_bool_t DVBProgramIsSelected( demux_t *p_demux, uint16_t i_pgrm )
2351 {
2352     demux_sys_t          *p_sys = p_demux->p_sys;
2353
2354     if ( !p_sys->b_dvb_control ) return VLC_FALSE;
2355     if ( (p_sys->i_dvb_program == -1 && p_sys->p_programs_list == NULL)
2356            || p_sys->i_dvb_program == 0 )
2357         return VLC_TRUE;
2358     if ( p_sys->i_dvb_program == i_pgrm ) return VLC_TRUE;
2359
2360     if ( p_sys->p_programs_list != NULL )
2361     {
2362         int i;
2363         for ( i = 0; i < p_sys->p_programs_list->i_count; i++ )
2364         {
2365             if ( i_pgrm == p_sys->p_programs_list->p_values[i].i_int )
2366                 return VLC_TRUE;
2367         }
2368     }
2369     return VLC_FALSE;
2370 }
2371
2372 #ifdef TS_USE_DVB_SI
2373 static void SDTCallBack( demux_t *p_demux, dvbpsi_sdt_t *p_sdt )
2374 {
2375     demux_sys_t          *p_sys = p_demux->p_sys;
2376     ts_pid_t             *sdt = &p_sys->pid[0x11];
2377     dvbpsi_sdt_service_t *p_srv;
2378
2379     msg_Dbg( p_demux, "SDTCallBack called" );
2380
2381     if( sdt->psi->i_sdt_version != -1 &&
2382         ( !p_sdt->b_current_next ||
2383           p_sdt->i_version == sdt->psi->i_sdt_version ) )
2384     {
2385         dvbpsi_DeleteSDT( p_sdt );
2386         return;
2387     }
2388
2389     msg_Dbg( p_demux, "new SDT ts_id=%d version=%d current_next=%d "
2390              "network_id=%d",
2391              p_sdt->i_ts_id, p_sdt->i_version, p_sdt->b_current_next,
2392              p_sdt->i_network_id );
2393
2394     for( p_srv = p_sdt->p_first_service; p_srv; p_srv = p_srv->p_next )
2395     {
2396         vlc_meta_t          *p_meta = vlc_meta_New();
2397         dvbpsi_descriptor_t *p_dr;
2398
2399         msg_Dbg( p_demux, "  * service id=%d eit schedule=%d present=%d "
2400                  "running=%d free_ca=%d",
2401                  p_srv->i_service_id, p_srv->b_eit_schedule,
2402                  p_srv->b_eit_present, p_srv->i_running_status,
2403                  p_srv->b_free_ca );
2404
2405         for( p_dr = p_srv->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
2406         {
2407             if( p_dr->i_tag == 0x48 )
2408             {
2409 #if 0
2410                 static const char *psz_type[0x11] = {
2411                     "Reserved",
2412                     "Digital television service",
2413                     "Digital radio sound service",
2414                     "Teletext service",
2415                     "NVOD reference service",
2416                     "NVOD time-shifted service",
2417                     "Mosaic service",
2418                     "PAL coded signal",
2419                     "SECAM coded signal",
2420                     "D/D2-MAC",
2421                     "FM Radio",
2422                     "NTSC coded signal",
2423                     "Data broadcast service",
2424                     "Reserved for Common Interface Usage",
2425                     "RCS Map (see EN 301 790 [35])",
2426                     "RCS FLS (see EN 301 790 [35])",
2427                     "DVB MHP service"
2428                 };
2429 #endif
2430                 dvbpsi_service_dr_t *pD = dvbpsi_DecodeServiceDr( p_dr );
2431                 char str1[257];
2432                 char str2[257];
2433
2434                 memcpy( str1, pD->i_service_provider_name,
2435                         pD->i_service_provider_name_length );
2436                 str1[pD->i_service_provider_name_length] = '\0';
2437                 memcpy( str2, pD->i_service_name, pD->i_service_name_length );
2438                 str2[pD->i_service_name_length] = '\0';
2439
2440                 msg_Dbg( p_demux, "    - type=%d provider=%s name=%s",
2441                         pD->i_service_type, str1, str2 );
2442
2443                 vlc_meta_SetTitle( p_meta, str2 );
2444                 vlc_meta_SetPublisher( p_meta, str1 );
2445                 if( pD->i_service_type >= 0x01 && pD->i_service_type <= 0x10 )
2446                     vlc_meta_Add( p_meta, "Type", psz_type[pD->i_service_type] );
2447             }
2448         }
2449
2450         if( p_srv->i_running_status == 0x01 )
2451             vlc_meta_Add( p_meta, "Status", "Not running" );
2452         else if( p_srv->i_running_status == 0x02 )
2453             vlc_meta_Add( p_meta, "Status", "Starts in a few seconds" );
2454         else if( p_srv->i_running_status == 0x03 )
2455             vlc_meta_Add( p_meta, "Status", "Pausing" );
2456         else if( p_srv->i_running_status == 0x04 )
2457             vlc_meta_Add( p_meta, "Status", "Running" );
2458         else
2459             vlc_meta_Add( p_meta, "Status", "Unknown" );
2460
2461         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_META,
2462                         p_srv->i_service_id, p_meta );
2463         vlc_meta_Delete( p_meta );
2464     }
2465
2466     sdt->psi->i_sdt_version = p_sdt->i_version;
2467     dvbpsi_DeleteSDT( p_sdt );
2468 }
2469 #if 0
2470 static void DecodeMjd( int i_mjd, int *p_y, int *p_m, int *p_d )
2471 {
2472     int yp = (int)( ( (double)i_mjd - 15078.2)/365.25 );
2473     int mp = (int)( ((double)i_mjd - 14956.1 - (int)(yp * 365.25)) / 30.6001 );
2474
2475     *p_d = i_mjd - 14956 - (int)(yp*365.25) - (int)(mp*30.6001);
2476
2477     if( mp == 14 || mp == 15 )
2478     {
2479         *p_y = yp + 1;
2480         *p_m = mp - 1 + 12;
2481     }
2482     else
2483     {
2484         *p_y = yp;
2485         *p_m = mp - 1;
2486     }
2487 }
2488 #endif
2489 static void EITEventFixString( unsigned char *psz )
2490 {
2491     int i_len;
2492     /* Sometimes the first char isn't a normal char but designed
2493      * caracters encoding, for now lets skip it */
2494     if( psz[0] >= 0x20 )
2495             return;
2496     if( ( i_len = strlen( (char *) psz ) ) > 0 )
2497         memmove( &psz[0], &psz[1], i_len ); /* Copy the \0 too */
2498 }
2499 static void EITCallBack( demux_t *p_demux, dvbpsi_eit_t *p_eit )
2500 {
2501     dvbpsi_eit_event_t *p_evt;
2502     vlc_meta_t         *p_meta;
2503     vlc_bool_t b_event_active = VLC_FALSE;
2504
2505     msg_Dbg( p_demux, "EITCallBack called" );
2506     if( !p_eit->b_current_next )
2507     {
2508         dvbpsi_DeleteEIT( p_eit );
2509         return;
2510     }
2511
2512     msg_Dbg( p_demux, "new EIT service_id=%d version=%d current_next=%d "
2513              "ts_id=%d network_id=%d segment_last_section_number=%d "
2514              "last_table_id=%d",
2515              p_eit->i_service_id, p_eit->i_version, p_eit->b_current_next,
2516              p_eit->i_ts_id, p_eit->i_network_id,
2517              p_eit->i_segment_last_section_number, p_eit->i_last_table_id );
2518
2519     p_meta = vlc_meta_New();
2520     for( p_evt = p_eit->p_first_event; p_evt; p_evt = p_evt->p_next )
2521     {
2522         dvbpsi_descriptor_t *p_dr;
2523         char                *psz_cat = malloc( strlen("Event")+10 );
2524         char                psz_start[15];
2525         char                psz_duration[15];
2526         char                psz_name[256];
2527         char                psz_text[256];
2528         char                *psz_extra = strdup("");
2529         char                *psz_value;
2530
2531         sprintf( psz_cat, "Event %d", p_evt->i_event_id );
2532         sprintf( psz_start, "%d%d:%d%d:%d%d",
2533                  (int)(p_evt->i_start_time >> 20)&0xf,
2534                  (int)(p_evt->i_start_time >> 16)&0xf,
2535                  (int)(p_evt->i_start_time >> 12)&0xf,
2536                  (int)(p_evt->i_start_time >>  8)&0xf,
2537                  (int)(p_evt->i_start_time >>  4)&0xf,
2538                  (int)(p_evt->i_start_time      )&0xf );
2539         sprintf( psz_duration, "%d%d:%d%d:%d%d",
2540                  (p_evt->i_duration >> 20)&0xf, (p_evt->i_duration >> 16)&0xf,
2541                  (p_evt->i_duration >> 12)&0xf, (p_evt->i_duration >>  8)&0xf,
2542                  (p_evt->i_duration >>  4)&0xf, (p_evt->i_duration      )&0xf );
2543         psz_name[0] = psz_text[0] = '\0';
2544
2545         msg_Dbg( p_demux, "  * event id=%d start_time:mjd=%d %s duration=%s "
2546                           "running=%d free_ca=%d",
2547                  p_evt->i_event_id,
2548                  (int)(p_evt->i_start_time >> 24),
2549                  psz_start, psz_duration,
2550                  p_evt->i_running_status, p_evt->b_free_ca );
2551
2552         for( p_dr = p_evt->p_first_descriptor; p_dr; p_dr = p_dr->p_next )
2553         {
2554             if( p_dr->i_tag == 0x4d )
2555             {
2556                 dvbpsi_short_event_dr_t *pE = dvbpsi_DecodeShortEventDr( p_dr );
2557
2558                 if( pE )
2559                 {
2560                     memcpy( psz_name, pE->i_event_name, pE->i_event_name_length);
2561                     psz_name[pE->i_event_name_length] = '\0';
2562                     memcpy( psz_text, pE->i_text, pE->i_text_length );
2563                     psz_text[pE->i_text_length] = '\0';
2564
2565                     EITEventFixString((unsigned char *)&psz_name);
2566                     EITEventFixString((unsigned char *)&psz_text);
2567                     msg_Dbg( p_demux, "    - short event lang=%3.3s '%s' : '%s'",
2568                              pE->i_iso_639_code, psz_name, psz_text );
2569                 }
2570             }
2571             else if( p_dr->i_tag == 0x4e )
2572             {
2573                 dvbpsi_extended_event_dr_t *pE = dvbpsi_DecodeExtendedEventDr( p_dr );
2574                 char str1[257];
2575                 char str2[257];
2576
2577                 if( pE )
2578                 {
2579                     int i;
2580                     msg_Dbg( p_demux, "    - extended event lang=%3.3s",
2581                              pE->i_iso_639_code );
2582                     for( i = 0; i < pE->i_entry_count; i++ )
2583                     {
2584                         memcpy( str1, pE->i_item_description[i],
2585                                 pE->i_item_description_length[i] );
2586                         str1[pE->i_item_description_length[i]] = '\0';
2587                         EITEventFixString((unsigned char *)&str1);
2588
2589                         memcpy( str2, pE->i_item[i],
2590                                 pE->i_item_length[i] );
2591                         str2[pE->i_item_length[i]] = '\0';
2592                         EITEventFixString((unsigned char *)&str2);
2593
2594                         msg_Dbg( p_demux, "       - desc='%s' item='%s'", str1, str2 );
2595                         psz_extra = realloc( psz_extra,
2596                                     strlen(psz_extra) +
2597                                     strlen(str1) +strlen(str2) + 1 + 3 );
2598                         strcat( psz_extra, str1 );
2599                         strcat( psz_extra, "(" );
2600                         strcat( psz_extra, str2 );
2601                         strcat( psz_extra, ") " );
2602                     }
2603
2604                     memcpy( str1, pE->i_text, pE->i_text_length );
2605                     str1[pE->i_text_length] = '\0';
2606                     EITEventFixString((unsigned char *)&str1);
2607
2608                     msg_Dbg( p_demux, "       - text='%s'", str1 );
2609                     psz_extra = realloc( psz_extra,
2610                                          strlen(psz_extra) + strlen(str1) + 2 );
2611                     strcat( psz_extra, str1 );
2612                     strcat( psz_extra, " " );
2613                 }
2614             }
2615             else
2616             {
2617                 msg_Dbg( p_demux, "    - tag=0x%x(%d)", p_dr->i_tag, p_dr->i_tag );
2618             }
2619         }
2620
2621         asprintf( &psz_value, "%s: %s (+%s) %s (%s)",
2622                   psz_start,
2623                   psz_name,
2624                   psz_duration,
2625                   psz_text, psz_extra );
2626         vlc_meta_Add( p_meta, psz_cat, psz_value );
2627         free( psz_value );
2628
2629         if( p_evt->i_running_status == 0x04 )
2630         {
2631             vlc_meta_SetNowPlaying( p_meta, psz_name );
2632             b_event_active = VLC_TRUE;
2633         }
2634
2635         free( psz_cat );
2636         free( psz_extra );
2637     }
2638
2639     if( !b_event_active )
2640         vlc_meta_SetNowPlaying( p_meta, "" );
2641     es_out_Control( p_demux->out, ES_OUT_SET_GROUP_META,
2642                     p_eit->i_service_id, p_meta );
2643     vlc_meta_Delete( p_meta );
2644
2645     dvbpsi_DeleteEIT( p_eit );
2646 }
2647
2648 static void PSINewTableCallBack( demux_t *p_demux, dvbpsi_handle h,
2649                                  uint8_t  i_table_id, uint16_t i_extension )
2650 {
2651 #if 0
2652     msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
2653              i_table_id, i_table_id, i_extension, i_extension );
2654 #endif
2655     if( p_demux->p_sys->pid[0].psi->i_pat_version == -1 )
2656         return;
2657
2658     if( i_table_id == 0x42 )
2659     {
2660         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
2661                  i_table_id, i_table_id, i_extension, i_extension );
2662
2663         dvbpsi_AttachSDT( h, i_table_id, i_extension,
2664                           (dvbpsi_sdt_callback)SDTCallBack, p_demux );
2665     }
2666     else if( i_table_id == 0x4e || /* Current/Following */
2667              ( i_table_id >= 0x50 && i_table_id <= 0x5f ) ) /* Schedule */
2668     {
2669         msg_Dbg( p_demux, "PSINewTableCallBack: table 0x%x(%d) ext=0x%x(%d)",
2670                  i_table_id, i_table_id, i_extension, i_extension );
2671
2672         dvbpsi_AttachEIT( h, i_table_id, i_extension,
2673                           (dvbpsi_eit_callback)EITCallBack, p_demux );
2674     }
2675 }
2676 #endif
2677
2678 static void PMTCallBack( demux_t *p_demux, dvbpsi_pmt_t *p_pmt )
2679 {
2680     demux_sys_t          *p_sys = p_demux->p_sys;
2681     dvbpsi_descriptor_t  *p_dr;
2682     dvbpsi_pmt_es_t      *p_es;
2683
2684     ts_pid_t             *pmt = NULL;
2685     ts_prg_psi_t         *prg = NULL;
2686
2687     ts_pid_t             **pp_clean = NULL;
2688     int                  i_clean = 0, i;
2689
2690     msg_Dbg( p_demux, "PMTCallBack called" );
2691
2692     /* First find this PMT declared in PAT */
2693     for( i = 0; i < p_sys->i_pmt; i++ )
2694     {
2695         int i_prg;
2696         for( i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
2697         {
2698             if( p_sys->pmt[i]->psi->prg[i_prg]->i_number ==
2699                 p_pmt->i_program_number )
2700             {
2701                 pmt = p_sys->pmt[i];
2702                 prg = p_sys->pmt[i]->psi->prg[i_prg];
2703                 break;
2704             }
2705         }
2706         if( pmt ) break;
2707     }
2708
2709     if( pmt == NULL )
2710     {
2711         msg_Warn( p_demux, "unreferenced program (broken stream)" );
2712         dvbpsi_DeletePMT(p_pmt);
2713         return;
2714     }
2715
2716     if( prg->i_version != -1 &&
2717         ( !p_pmt->b_current_next || prg->i_version == p_pmt->i_version ) )
2718     {
2719         dvbpsi_DeletePMT( p_pmt );
2720         return;
2721     }
2722
2723     /* Clean this program (remove all es) */
2724     for( i = 0; i < 8192; i++ )
2725     {
2726         ts_pid_t *pid = &p_sys->pid[i];
2727
2728         if( pid->b_valid && pid->p_owner == pmt->psi &&
2729             pid->i_owner_number == prg->i_number && pid->psi == NULL )
2730         {
2731             TAB_APPEND( i_clean, pp_clean, pid );
2732         }
2733     }
2734     if( prg->iod )
2735     {
2736         IODFree( prg->iod );
2737         prg->iod = NULL;
2738     }
2739
2740     msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
2741              p_pmt->i_program_number, p_pmt->i_version, p_pmt->i_pcr_pid );
2742     prg->i_pid_pcr = p_pmt->i_pcr_pid;
2743     prg->i_version = p_pmt->i_version;
2744
2745     if( DVBProgramIsSelected( p_demux, prg->i_number ) )
2746     {
2747         /* Set demux filter */
2748         stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
2749                         ACCESS_SET_PRIVATE_ID_STATE, prg->i_pid_pcr,
2750                         VLC_TRUE );
2751     }
2752     else if ( p_sys->b_dvb_control )
2753     {
2754         msg_Warn( p_demux, "skipping program (not selected)" );
2755         dvbpsi_DeletePMT(p_pmt);
2756         return;
2757     }
2758
2759     /* Parse descriptor */
2760     for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
2761     {
2762         if( p_dr->i_tag == 0x1d )
2763         {
2764             /* We have found an IOD descriptor */
2765             msg_Dbg( p_demux, " * descriptor : IOD (0x1d)" );
2766
2767             prg->iod = IODNew( p_dr->i_length, p_dr->p_data );
2768         }
2769         else if( p_dr->i_tag == 0x9 )
2770         {
2771             uint16_t i_sysid = ((uint16_t)p_dr->p_data[0] << 8)
2772                                 | p_dr->p_data[1];
2773             msg_Dbg( p_demux, " * descriptor : CA (0x9) SysID 0x%x", i_sysid );
2774         }
2775         else
2776         {
2777             msg_Dbg( p_demux, " * descriptor : unknown (0x%x)", p_dr->i_tag );
2778         }
2779     }
2780
2781     for( p_es = p_pmt->p_first_es; p_es != NULL; p_es = p_es->p_next )
2782     {
2783         ts_pid_t tmp_pid, *old_pid = 0, *pid = &tmp_pid;
2784
2785         /* Find out if the PID was already declared */
2786         for( i = 0; i < i_clean; i++ )
2787         {
2788             if( pp_clean[i] == &p_sys->pid[p_es->i_pid] )
2789             {
2790                 old_pid = pp_clean[i];
2791                 break;
2792             }
2793         }
2794
2795         if( !old_pid && p_sys->pid[p_es->i_pid].b_valid )
2796         {
2797             ts_pid_t *pid = &p_sys->pid[p_es->i_pid];
2798             if( ( pid->i_pid == 0x11 /* SDT */ ||
2799                   pid->i_pid == 0x12 /* EDT */ ) && pid->psi )
2800             {
2801                 /* This doesn't look like a DVB stream so don't try
2802                  * parsing the SDT/EDT */
2803                 dvbpsi_DetachDemux( pid->psi->handle );
2804                 free( pid->psi );
2805                 pid->psi = 0;
2806             }
2807             else
2808             {
2809                 msg_Warn( p_demux, "pmt error: pid=%d already defined",
2810                           p_es->i_pid );
2811                 continue;
2812             }
2813         }
2814
2815         PIDInit( pid, VLC_FALSE, pmt->psi );
2816         PIDFillFormat( pid, p_es->i_type );
2817         pid->i_owner_number = prg->i_number;
2818         pid->i_pid          = p_es->i_pid;
2819         pid->b_seen         = p_sys->pid[p_es->i_pid].b_seen;
2820
2821         if( p_es->i_type == 0x10 || p_es->i_type == 0x11 ||
2822             p_es->i_type == 0x12 )
2823         {
2824             /* MPEG-4 stream: search SL_DESCRIPTOR */
2825             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
2826
2827             while( p_dr && ( p_dr->i_tag != 0x1f ) ) p_dr = p_dr->p_next;
2828
2829             if( p_dr && p_dr->i_length == 2 )
2830             {
2831                 int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
2832
2833                 msg_Warn( p_demux, "found SL_descriptor es_id=%d", i_es_id );
2834
2835                 pid->es->p_mpeg4desc = NULL;
2836
2837                 for( i = 0; i < 255; i++ )
2838                 {
2839                     iod_descriptor_t *iod = prg->iod;
2840
2841                     if( iod->es_descr[i].b_ok &&
2842                         iod->es_descr[i].i_es_id == i_es_id )
2843                     {
2844                         pid->es->p_mpeg4desc = &iod->es_descr[i];
2845                         break;
2846                     }
2847                 }
2848             }
2849
2850             if( pid->es->p_mpeg4desc != NULL )
2851             {
2852                 decoder_config_descriptor_t *dcd =
2853                     &pid->es->p_mpeg4desc->dec_descr;
2854
2855                 if( dcd->i_streamType == 0x04 )    /* VisualStream */
2856                 {
2857                     pid->es->fmt.i_cat = VIDEO_ES;
2858                     switch( dcd->i_objectTypeIndication )
2859                     {
2860                     case 0x0B: /* mpeg4 sub */
2861                         pid->es->fmt.i_cat = SPU_ES;
2862                         pid->es->fmt.i_codec = VLC_FOURCC('s','u','b','t');
2863                         break;
2864
2865                     case 0x20: /* mpeg4 */
2866                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','v');
2867                         break;
2868                     case 0x21: /* h264 */
2869                         pid->es->fmt.i_codec = VLC_FOURCC('h','2','6','4');
2870                         break;
2871                     case 0x60:
2872                     case 0x61:
2873                     case 0x62:
2874                     case 0x63:
2875                     case 0x64:
2876                     case 0x65: /* mpeg2 */
2877                         pid->es->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
2878                         break;
2879                     case 0x6a: /* mpeg1 */
2880                         pid->es->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
2881                         break;
2882                     case 0x6c: /* mpeg1 */
2883                         pid->es->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
2884                         break;
2885                     default:
2886                         pid->es->fmt.i_cat = UNKNOWN_ES;
2887                         break;
2888                     }
2889                 }
2890                 else if( dcd->i_streamType == 0x05 )    /* AudioStream */
2891                 {
2892                     pid->es->fmt.i_cat = AUDIO_ES;
2893                     switch( dcd->i_objectTypeIndication )
2894                     {
2895                     case 0x40: /* mpeg4 */
2896                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','a');
2897                         break;
2898                     case 0x66:
2899                     case 0x67:
2900                     case 0x68: /* mpeg2 aac */
2901                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','a');
2902                         break;
2903                     case 0x69: /* mpeg2 */
2904                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','g','a');
2905                         break;
2906                     case 0x6b: /* mpeg1 */
2907                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','g','a');
2908                         break;
2909                     default:
2910                         pid->es->fmt.i_cat = UNKNOWN_ES;
2911                         break;
2912                     }
2913                 }
2914                 else
2915                 {
2916                     pid->es->fmt.i_cat = UNKNOWN_ES;
2917                 }
2918
2919                 if( pid->es->fmt.i_cat != UNKNOWN_ES )
2920                 {
2921                     pid->es->fmt.i_extra = dcd->i_decoder_specific_info_len;
2922                     if( pid->es->fmt.i_extra > 0 )
2923                     {
2924                         pid->es->fmt.p_extra = malloc( pid->es->fmt.i_extra );
2925                         memcpy( pid->es->fmt.p_extra,
2926                                 dcd->p_decoder_specific_info,
2927                                 pid->es->fmt.i_extra );
2928                     }
2929                 }
2930             }
2931         }
2932         else if( p_es->i_type == 0x06 )
2933         {
2934             dvbpsi_descriptor_t *p_dr;
2935
2936             for( p_dr = p_es->p_first_descriptor; p_dr != NULL;
2937                  p_dr = p_dr->p_next )
2938             {
2939                 msg_Dbg( p_demux, "  * es pid=%d type=%d dr->i_tag=0x%x",
2940                          p_es->i_pid, p_es->i_type, p_dr->i_tag );
2941
2942                 if( p_dr->i_tag == 0x05 )
2943                 {
2944                     /* Registration Descriptor */
2945                     if( p_dr->i_length != 4 )
2946                     {
2947                         msg_Warn( p_demux, "invalid Registration Descriptor" );
2948                     }
2949                     else
2950                     {
2951                         if( !memcmp( p_dr->p_data, "AC-3", 4 ) )
2952                         {
2953                             /* ATSC with stream_type 0x81 (but this descriptor
2954                              * is then not mandatory */
2955                             pid->es->fmt.i_cat = AUDIO_ES;
2956                             pid->es->fmt.i_codec = VLC_FOURCC('a','5','2',' ');
2957                         }
2958                         else if( !memcmp( p_dr->p_data, "DTS1", 4 ) ||
2959                                  !memcmp( p_dr->p_data, "DTS2", 4 ) ||
2960                                  !memcmp( p_dr->p_data, "DTS3", 4 ) )
2961                         {
2962                            /*registration descriptor(ETSI TS 101 154 Annex F)*/
2963                             pid->es->fmt.i_cat = AUDIO_ES;
2964                             pid->es->fmt.i_codec = VLC_FOURCC('d','t','s',' ');
2965                         }
2966                         else if( !memcmp( p_dr->p_data, "BSSD", 4 ) )
2967                         {
2968                             pid->es->fmt.i_cat = AUDIO_ES;
2969                             pid->es->fmt.i_codec = VLC_FOURCC('l','p','c','m');
2970                         }
2971                         else
2972                         {
2973                             msg_Warn( p_demux,
2974                                       "unknown Registration Descriptor (%4.4s)",
2975                                       p_dr->p_data );
2976                         }
2977                     }
2978
2979                 }
2980                 else if( p_dr->i_tag == 0x6a )
2981                 {
2982                     /* DVB with stream_type 0x06 */
2983                     pid->es->fmt.i_cat = AUDIO_ES;
2984                     pid->es->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
2985                 }
2986                 else if( p_dr->i_tag == 0x73 )
2987                 {
2988                     /* DTS audio descriptor (ETSI TS 101 154 Annex F) */
2989                     msg_Dbg( p_demux, "    * DTS audio descriptor not decoded" );
2990                     pid->es->fmt.i_cat = AUDIO_ES;
2991                     pid->es->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
2992                 }
2993                 else if( p_dr->i_tag == 0x45 )
2994                 {
2995                     msg_Dbg( p_demux, "    * VBI Data descriptor" );
2996                     /* FIXME : store the information somewhere */
2997                 }
2998                 else if( p_dr->i_tag == 0x46 )
2999                 {
3000                     msg_Dbg( p_demux, "    * VBI Teletext descriptor" );
3001                     /* FIXME : store the information somewhere */
3002                 }
3003 #ifdef _DVBPSI_DR_52_H_
3004                 else if( p_dr->i_tag == 0x52 )
3005                 {
3006                     dvbpsi_stream_identifier_dr_t *si;
3007                     si = dvbpsi_DecodeStreamIdentifierDr( p_dr );
3008
3009                     msg_Dbg( p_demux, "    * Stream Component Identifier: %d", si->i_component_tag );
3010                 }
3011 #endif
3012                 else if( p_dr->i_tag == 0x56 )
3013                 {
3014                     msg_Dbg( p_demux, "    * EBU Teletext descriptor" );
3015                     pid->es->fmt.i_cat = SPU_ES;
3016                     pid->es->fmt.i_codec = VLC_FOURCC( 't', 'e', 'l', 'x' );
3017                     pid->es->fmt.psz_description = strdup( "Teletext" );
3018                     pid->es->fmt.i_extra = p_dr->i_length;
3019                     pid->es->fmt.p_extra = malloc( p_dr->i_length );
3020                     memcpy( pid->es->fmt.p_extra, p_dr->p_data,
3021                             p_dr->i_length );
3022                 }
3023 #ifdef _DVBPSI_DR_59_H_
3024                 else if( p_dr->i_tag == 0x59 )
3025                 {
3026                     uint16_t n;
3027                     dvbpsi_subtitling_dr_t *sub;
3028
3029                     /* DVB subtitles */
3030                     pid->es->fmt.i_cat = SPU_ES;
3031                     pid->es->fmt.i_codec = VLC_FOURCC( 'd', 'v', 'b', 's' );
3032                     pid->es->fmt.i_group = p_pmt->i_program_number;
3033
3034                     sub = dvbpsi_DecodeSubtitlingDr( p_dr );
3035                     if( !sub ) continue;
3036
3037                     /* Each subtitle ES contains n languages,
3038                      * We are going to create n ES for the n tracks */
3039                     if( sub->i_subtitles_number > 0 )
3040                     {
3041                         pid->es->fmt.psz_language = malloc( 4 );
3042                         memcpy( pid->es->fmt.psz_language,
3043                                 sub->p_subtitle[0].i_iso6392_language_code, 3);
3044                         pid->es->fmt.psz_language[3] = 0;
3045
3046                         pid->es->fmt.subs.dvb.i_id =
3047                             sub->p_subtitle[0].i_composition_page_id;
3048                         /* Hack, FIXME */
3049                         pid->es->fmt.subs.dvb.i_id |=
3050                           ((int)sub->p_subtitle[0].i_ancillary_page_id << 16);
3051                     }
3052                     else pid->es->fmt.i_cat = UNKNOWN_ES;
3053
3054                     for( n = 1; n < sub->i_subtitles_number; n++ )
3055                     {
3056                         ts_es_t *p_es = malloc( sizeof( ts_es_t ) );
3057                         p_es->fmt = pid->es->fmt;
3058                         p_es->id = NULL;
3059                         p_es->p_pes = NULL;
3060                         p_es->i_pes_size = 0;
3061                         p_es->i_pes_gathered = 0;
3062                         p_es->pp_last = &p_es->p_pes;
3063                         p_es->p_mpeg4desc = NULL;
3064
3065                         p_es->fmt.psz_language = malloc( 4 );
3066                         memcpy( p_es->fmt.psz_language,
3067                                 sub->p_subtitle[n].i_iso6392_language_code, 3);
3068                         p_es->fmt.psz_language[3] = 0;
3069
3070                         p_es->fmt.subs.dvb.i_id =
3071                             sub->p_subtitle[n].i_composition_page_id;
3072                         /* Hack, FIXME */
3073                         p_es->fmt.subs.dvb.i_id |=
3074                           ((int)sub->p_subtitle[n].i_ancillary_page_id << 16);
3075
3076                         TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
3077                     }
3078                 }
3079 #endif /* _DVBPSI_DR_59_H_ */
3080             }
3081         }
3082         else if( p_es->i_type == 0xa0 )
3083         {
3084             /* MSCODEC sent by vlc */
3085             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;
3086
3087             while( p_dr && ( p_dr->i_tag != 0xa0 ) ) p_dr = p_dr->p_next;
3088
3089             if( p_dr && p_dr->i_length >= 8 )
3090             {
3091                 pid->es->fmt.i_cat = VIDEO_ES;
3092                 pid->es->fmt.i_codec =
3093                     VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
3094                                 p_dr->p_data[2], p_dr->p_data[3] );
3095                 pid->es->fmt.video.i_width =
3096                     ( p_dr->p_data[4] << 8 ) | p_dr->p_data[5];
3097                 pid->es->fmt.video.i_height =
3098                     ( p_dr->p_data[6] << 8 ) | p_dr->p_data[7];
3099                 pid->es->fmt.i_extra = 
3100                     (p_dr->p_data[8] << 8) | p_dr->p_data[9];
3101
3102                 if( pid->es->fmt.i_extra > 0 )
3103                 {
3104                     pid->es->fmt.p_extra = malloc( pid->es->fmt.i_extra );
3105                     memcpy( pid->es->fmt.p_extra, &p_dr->p_data[10],
3106                             pid->es->fmt.i_extra );
3107                 }
3108             }
3109             else
3110             {
3111                 msg_Warn( p_demux, "private MSCODEC (vlc) without bih private "
3112                           "descriptor" );
3113             }
3114             /* For such stream we will gather them ourself and don't launch a
3115              * packetizer.
3116              * Yes it's ugly but it's the only way to have DIV3 working */
3117             pid->es->fmt.b_packetized = VLC_TRUE;
3118         }
3119
3120         if( pid->es->fmt.i_cat == AUDIO_ES ||
3121             ( pid->es->fmt.i_cat == SPU_ES &&
3122               pid->es->fmt.i_codec != VLC_FOURCC('d','v','b','s') ) )
3123         {
3124             /* get language descriptor */
3125             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;
3126             while( p_dr && ( p_dr->i_tag != 0x0a ) ) p_dr = p_dr->p_next;
3127
3128             if( p_dr )
3129             {
3130                 dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
3131
3132                 if( p_decoded )
3133                 {
3134 #if DR_0A_API_VER >= 2
3135                     pid->es->fmt.psz_language = malloc( 4 );
3136                     memcpy( pid->es->fmt.psz_language,
3137                             p_decoded->code[0].iso_639_code, 3 );
3138                     pid->es->fmt.psz_language[3] = 0;
3139                     msg_Dbg( p_demux, "found language: %s", pid->es->fmt.psz_language);
3140                     switch( p_decoded->code[0].i_audio_type ) {
3141                     case 0:
3142                         pid->es->fmt.psz_description = NULL;
3143                         break;
3144                     case 1:
3145                         pid->es->fmt.psz_description =
3146                             strdup(_("clean effects"));
3147                         break;
3148                     case 2:
3149                         pid->es->fmt.psz_description =
3150                             strdup(_("hearing impaired"));
3151                         break;
3152                     case 3:
3153                         pid->es->fmt.psz_description =
3154                             strdup(_("visual impaired commentary"));
3155                         break;
3156                     default:
3157                         msg_Dbg( p_demux, "unknown audio type: %d",
3158                                  p_decoded->code[0].i_audio_type);
3159                         pid->es->fmt.psz_description = NULL;
3160                         break;
3161                     }
3162                     pid->es->fmt.i_extra_languages = p_decoded->i_code_count-1;
3163                     pid->es->fmt.p_extra_languages =
3164                         malloc( sizeof(*pid->es->fmt.p_extra_languages) *
3165                                 pid->es->fmt.i_extra_languages );
3166                     for( i = 0; i < pid->es->fmt.i_extra_languages; i++ ) {
3167                         msg_Dbg( p_demux, "bang" );
3168                         pid->es->fmt.p_extra_languages[i].psz_language =
3169                             malloc(4);
3170                         memcpy(pid->es->fmt.p_extra_languages[i].psz_language,
3171                                p_decoded->code[i+1].iso_639_code, 3 );
3172                         pid->es->fmt.p_extra_languages[i].psz_language[3] = '\0';
3173                         switch( p_decoded->code[i].i_audio_type ) {
3174                         case 0:
3175                             pid->es->fmt.p_extra_languages[i].psz_description =
3176                                 NULL;
3177                             break;
3178                         case 1:
3179                             pid->es->fmt.p_extra_languages[i].psz_description =
3180                                 strdup(_("clean effects"));
3181                             break;
3182                         case 2:
3183                             pid->es->fmt.p_extra_languages[i].psz_description =
3184                                 strdup(_("hearing impaired"));
3185                             break;
3186                         case 3:
3187                             pid->es->fmt.p_extra_languages[i].psz_description =
3188                                 strdup(_("visual impaired commentary"));
3189                             break;
3190                         default:
3191                             msg_Dbg( p_demux, "unknown audio type: %d",
3192                                      p_decoded->code[i].i_audio_type);
3193                             pid->es->fmt.psz_description = NULL;
3194                             break;
3195                         }
3196
3197                     }
3198 #else
3199                     pid->es->fmt.psz_language = malloc( 4 );
3200                     memcpy( pid->es->fmt.psz_language,
3201                             p_decoded->i_iso_639_code, 3 );
3202                     pid->es->fmt.psz_language[3] = 0;
3203 #endif
3204                 }
3205             }
3206         }
3207
3208         pid->es->fmt.i_group = p_pmt->i_program_number;
3209         if( pid->es->fmt.i_cat == UNKNOWN_ES )
3210         {
3211             msg_Dbg( p_demux, "  * es pid=%d type=%d *unknown*",
3212                      p_es->i_pid, p_es->i_type );
3213         }
3214         else if( !p_sys->b_udp_out )
3215         {
3216             msg_Dbg( p_demux, "  * es pid=%d type=%d fcc=%4.4s",
3217                      p_es->i_pid, p_es->i_type, (char*)&pid->es->fmt.i_codec );
3218
3219             if( p_sys->b_es_id_pid ) pid->es->fmt.i_id = p_es->i_pid;
3220
3221             /* Check if we can avoid restarting the ES */
3222             if( old_pid &&
3223                 pid->es->fmt.i_codec == old_pid->es->fmt.i_codec &&
3224                 pid->es->fmt.i_extra == old_pid->es->fmt.i_extra &&
3225                 pid->es->fmt.i_extra == 0 &&
3226                 pid->i_extra_es == old_pid->i_extra_es &&
3227                 ( ( !pid->es->fmt.psz_language &&
3228                     !old_pid->es->fmt.psz_language ) ||
3229                   ( pid->es->fmt.psz_language &&
3230                     old_pid->es->fmt.psz_language &&
3231                     !strcmp( pid->es->fmt.psz_language,
3232                              old_pid->es->fmt.psz_language ) ) ) )
3233             {
3234                 pid->es->id = old_pid->es->id;
3235                 old_pid->es->id = NULL;
3236                 for( i = 0; i < pid->i_extra_es; i++ )
3237                 {
3238                     pid->extra_es[i]->id = old_pid->extra_es[i]->id;
3239                     old_pid->extra_es[i]->id = NULL;
3240                 }
3241             }
3242             else
3243             {
3244                 if( old_pid )
3245                 {
3246                     PIDClean( p_demux->out, old_pid );
3247                     TAB_REMOVE( i_clean, pp_clean, old_pid );
3248                     old_pid = 0;
3249                 }
3250
3251                 pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
3252                 for( i = 0; i < pid->i_extra_es; i++ )
3253                 {
3254                     pid->extra_es[i]->id =
3255                         es_out_Add( p_demux->out, &pid->extra_es[i]->fmt );
3256                 }
3257             }
3258         }
3259
3260         /* Add ES to the list */
3261         if( old_pid )
3262         {
3263             PIDClean( p_demux->out, old_pid );
3264             TAB_REMOVE( i_clean, pp_clean, old_pid );
3265         }
3266         p_sys->pid[p_es->i_pid] = *pid;
3267
3268         for( p_dr = p_es->p_first_descriptor; p_dr != NULL;
3269              p_dr = p_dr->p_next )
3270         {
3271             if( p_dr->i_tag == 0x9 )
3272             {
3273                 uint16_t i_sysid = ((uint16_t)p_dr->p_data[0] << 8)
3274                                     | p_dr->p_data[1];
3275                 msg_Dbg( p_demux, "   * descriptor : CA (0x9) SysID 0x%x",
3276                          i_sysid );
3277             }
3278         }
3279
3280         if( DVBProgramIsSelected( p_demux, prg->i_number ) )
3281         {
3282             /* Set demux filter */
3283             stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
3284                             ACCESS_SET_PRIVATE_ID_STATE, p_es->i_pid,
3285                             VLC_TRUE );
3286         }
3287     }
3288
3289     if( DVBProgramIsSelected( p_demux, prg->i_number ) )
3290     {
3291         /* Set CAM descrambling */
3292         stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
3293                         ACCESS_SET_PRIVATE_ID_CA, p_pmt );
3294     }
3295     else
3296     {
3297         dvbpsi_DeletePMT( p_pmt );
3298     }
3299
3300     for ( i = 0; i < i_clean; i++ )
3301     {
3302         if( DVBProgramIsSelected( p_demux, prg->i_number ) )
3303         {
3304             stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
3305                             ACCESS_SET_PRIVATE_ID_STATE, pp_clean[i]->i_pid,
3306                             VLC_FALSE );
3307         }
3308
3309         PIDClean( p_demux->out, pp_clean[i] );
3310     }
3311     if( i_clean ) free( pp_clean );
3312 }
3313
3314 static void PATCallBack( demux_t *p_demux, dvbpsi_pat_t *p_pat )
3315 {
3316     demux_sys_t          *p_sys = p_demux->p_sys;
3317     dvbpsi_pat_program_t *p_program;
3318     ts_pid_t             *pat = &p_sys->pid[0];
3319     int                  i, j;
3320
3321     msg_Dbg( p_demux, "PATCallBack called" );
3322
3323     if( pat->psi->i_pat_version != -1 &&
3324         ( !p_pat->b_current_next ||
3325           p_pat->i_version == pat->psi->i_pat_version ) )
3326     {
3327         dvbpsi_DeletePAT( p_pat );
3328         return;
3329     }
3330
3331     msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
3332              p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
3333
3334     /* Clean old */
3335     if( p_sys->i_pmt > 0 )
3336     {
3337         int      i_pmt_rm = 0;
3338         ts_pid_t **pmt_rm = NULL;
3339
3340         /* Search pmt to be deleted */
3341         for( i = 0; i < p_sys->i_pmt; i++ )
3342         {
3343             ts_pid_t *pmt = p_sys->pmt[i];
3344             vlc_bool_t b_keep = VLC_FALSE;
3345
3346             for( p_program = p_pat->p_first_program; p_program != NULL;
3347                  p_program = p_program->p_next )
3348             {
3349                 if( p_program->i_pid == pmt->i_pid )
3350                 {
3351                     int i_prg;
3352                     for( i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
3353                     {
3354                         if( p_program->i_number ==
3355                             pmt->psi->prg[i_prg]->i_number )
3356                         {
3357                             b_keep = VLC_TRUE;
3358                             break;
3359                         }
3360                     }
3361                     if( b_keep ) break;
3362                 }
3363             }
3364
3365             if( !b_keep )
3366             {
3367                 TAB_APPEND( i_pmt_rm, pmt_rm, pmt );
3368             }
3369         }
3370
3371         /* Delete all ES attached to thoses PMT */
3372         for( i = 2; i < 8192; i++ )
3373         {
3374             ts_pid_t *pid = &p_sys->pid[i];
3375
3376             if( !pid->b_valid || pid->psi ) continue;
3377
3378             for( j = 0; j < i_pmt_rm; j++ )
3379             {
3380                 int i_prg;
3381                 for( i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
3382                 {
3383                     /* We only remove es that aren't defined by extra pmt */
3384                     if( pid->p_owner->prg[i_prg]->i_pid_pmt !=
3385                         pmt_rm[j]->i_pid ) continue;
3386
3387                     if( p_sys->b_dvb_control && pid->es->id )
3388                     {
3389                         if( stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
3390                                             ACCESS_SET_PRIVATE_ID_STATE, i,
3391                                             VLC_FALSE ) )
3392                             p_sys->b_dvb_control = VLC_FALSE;
3393                     }
3394
3395                     PIDClean( p_demux->out, pid );
3396                     break;
3397                 }
3398
3399                 if( !pid->b_valid ) break;
3400             }
3401         }
3402
3403         /* Delete PMT pid */
3404         for( i = 0; i < i_pmt_rm; i++ )
3405         {
3406             int i_prg;
3407             if( p_sys->b_dvb_control )
3408             {
3409                 if( stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
3410                                     ACCESS_SET_PRIVATE_ID_STATE,
3411                                     pmt_rm[i]->i_pid, VLC_FALSE ) )
3412                     p_sys->b_dvb_control = VLC_FALSE;
3413             }
3414
3415             for( i_prg = 0; i_prg < pmt_rm[i]->psi->i_prg; i_prg++ )
3416             {
3417                 const int i_number = pmt_rm[i]->psi->prg[i_prg]->i_number;
3418                 if( i_number != 0 )
3419                     es_out_Control( p_demux->out, ES_OUT_DEL_GROUP, i_number );
3420             }
3421
3422             PIDClean( p_demux->out, &p_sys->pid[pmt_rm[i]->i_pid] );
3423             TAB_REMOVE( p_sys->i_pmt, p_sys->pmt, pmt_rm[i] );
3424         }
3425
3426         if( pmt_rm ) free( pmt_rm );
3427     }
3428
3429     /* now create programs */
3430     for( p_program = p_pat->p_first_program; p_program != NULL;
3431          p_program = p_program->p_next )
3432     {
3433         msg_Dbg( p_demux, "  * number=%d pid=%d", p_program->i_number,
3434                  p_program->i_pid );
3435         if( p_program->i_number != 0 )
3436         {
3437             ts_pid_t *pmt = &p_sys->pid[p_program->i_pid];
3438             vlc_bool_t b_add = VLC_TRUE;
3439
3440             if( pmt->b_valid )
3441             {
3442                 int i_prg;
3443                 for( i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
3444                 {
3445                     if( pmt->psi->prg[i_prg]->i_number == p_program->i_number )
3446                     {
3447                         b_add = VLC_FALSE;
3448                         break;
3449                     }
3450                 }
3451             }
3452             else
3453             {
3454                 TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
3455             }
3456
3457             if( b_add )
3458             {
3459                 PIDInit( pmt, VLC_TRUE, pat->psi );
3460                 pmt->psi->prg[pmt->psi->i_prg-1]->handle =
3461                     dvbpsi_AttachPMT( p_program->i_number,
3462                                       (dvbpsi_pmt_callback)PMTCallBack,
3463                                       p_demux );
3464                 pmt->psi->prg[pmt->psi->i_prg-1]->i_number =
3465                     p_program->i_number;
3466                 pmt->psi->prg[pmt->psi->i_prg-1]->i_pid_pmt =
3467                     p_program->i_pid;
3468
3469                 /* Now select PID at access level */
3470                 if( p_sys->b_dvb_control )
3471                 {
3472                     if( DVBProgramIsSelected( p_demux, p_program->i_number ) )
3473                     {
3474                         if( p_sys->i_dvb_program == 0 )
3475                             p_sys->i_dvb_program = p_program->i_number;
3476
3477                         if( stream_Control( p_demux->s, STREAM_CONTROL_ACCESS, ACCESS_SET_PRIVATE_ID_STATE, p_program->i_pid, VLC_TRUE ) )
3478                             p_sys->b_dvb_control = VLC_FALSE;
3479                     }
3480                 }
3481             }
3482         }
3483     }
3484     pat->psi->i_pat_version = p_pat->i_version;
3485
3486     dvbpsi_DeletePAT( p_pat );
3487 }
3488