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