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