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