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