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