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