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