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