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