]> git.sesse.net Git - vlc/blob - modules/demux/ts.c
* modules/demux/ts.c: added support for transport streams with Reed-Solomon (204...
[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/descriptor.h>
41 #   include <dvbpsi/pat.h>
42 #   include <dvbpsi/pmt.h>
43 #   include <dvbpsi/dr.h>
44 #   include <dvbpsi/psi.h>
45 #else
46 #   include "dvbpsi.h"
47 #   include "descriptor.h"
48 #   include "tables/pat.h"
49 #   include "tables/pmt.h"
50 #   include "descriptors/dr.h"
51 #   include "psi.h"
52 #endif
53
54 /* TODO:
55  *  - XXX: do not mark options message to be translated, they are too osbcure for now ...
56  *  - test it
57  *  - ...
58  */
59
60 /*****************************************************************************
61  * Module descriptor
62  *****************************************************************************/
63 static int  Open  ( vlc_object_t * );
64 static void Close ( vlc_object_t * );
65
66 #define PMT_TEXT N_("Extra PMT")
67 #define PMT_LONGTEXT N_( \
68   "Allows a user to specify an extra pmt (pmt_pid=pid:stream_type[,...])" )
69
70 #define PID_TEXT N_("Set id of ES to PID")
71 #define PID_LONGTEXT N_("set id of es to pid")
72
73 #define TSOUT_TEXT N_("Fast udp streaming")
74 #define TSOUT_LONGTEXT N_( \
75   "Sends TS to specific ip:port by udp (you must know what you are doing)")
76
77 #define MTUOUT_TEXT N_("MTU for out mode")
78 #define MTUOUT_LONGTEXT N_("MTU for out mode")
79
80 #define CSA_TEXT N_("CSA ck")
81 #define CSA_LONGTEXT N_("CSA ck")
82
83 #define SILENT_TEXT N_("Silent mode")
84 #define SILENT_LONGTEXT N_("do not complain on encrypted PES")
85
86 vlc_module_begin();
87     set_description( _("ISO 13818-1 MPEG Transport Stream input - new" ) );
88
89     add_string( "ts-extra-pmt", NULL, NULL, PMT_TEXT, PMT_LONGTEXT, VLC_TRUE );
90     add_bool( "ts-es-id-pid", 0, NULL, PID_TEXT, PID_LONGTEXT, VLC_TRUE );
91     add_string( "ts-out", NULL, NULL, TSOUT_TEXT, TSOUT_LONGTEXT, VLC_TRUE );
92     add_integer( "ts-out-mtu", 1500, NULL, MTUOUT_TEXT,
93                  MTUOUT_LONGTEXT, VLC_TRUE );
94     add_string( "ts-csa-ck", NULL, NULL, CSA_TEXT, CSA_LONGTEXT, VLC_TRUE );
95     add_bool( "ts-silent", 0, NULL, SILENT_TEXT, SILENT_LONGTEXT, VLC_TRUE );
96
97     set_capability( "demux2", 10 );
98     set_callbacks( Open, Close );
99     add_shortcut( "ts" );
100 vlc_module_end();
101
102 /*****************************************************************************
103  * Local prototypes
104  *****************************************************************************/
105
106 typedef struct
107 {
108     uint8_t                 i_objectTypeIndication;
109     uint8_t                 i_streamType;
110     vlc_bool_t              b_upStream;
111     uint32_t                i_bufferSizeDB;
112     uint32_t                i_maxBitrate;
113     uint32_t                i_avgBitrate;
114
115     int                     i_decoder_specific_info_len;
116     uint8_t                 *p_decoder_specific_info;
117
118 } decoder_config_descriptor_t;
119
120 typedef struct
121 {
122     vlc_bool_t              b_useAccessUnitStartFlag;
123     vlc_bool_t              b_useAccessUnitEndFlag;
124     vlc_bool_t              b_useRandomAccessPointFlag;
125     vlc_bool_t              b_useRandomAccessUnitsOnlyFlag;
126     vlc_bool_t              b_usePaddingFlag;
127     vlc_bool_t              b_useTimeStampsFlags;
128     vlc_bool_t              b_useIdleFlag;
129     vlc_bool_t              b_durationFlag;
130     uint32_t                i_timeStampResolution;
131     uint32_t                i_OCRResolution;
132     uint8_t                 i_timeStampLength;
133     uint8_t                 i_OCRLength;
134     uint8_t                 i_AU_Length;
135     uint8_t                 i_instantBitrateLength;
136     uint8_t                 i_degradationPriorityLength;
137     uint8_t                 i_AU_seqNumLength;
138     uint8_t                 i_packetSeqNumLength;
139
140     uint32_t                i_timeScale;
141     uint16_t                i_accessUnitDuration;
142     uint16_t                i_compositionUnitDuration;
143
144     uint64_t                i_startDecodingTimeStamp;
145     uint64_t                i_startCompositionTimeStamp;
146
147 } sl_config_descriptor_t;
148
149 typedef struct
150 {
151     vlc_bool_t              b_ok;
152     uint16_t                i_es_id;
153
154     vlc_bool_t              b_streamDependenceFlag;
155     vlc_bool_t              b_OCRStreamFlag;
156     uint8_t                 i_streamPriority;
157
158     char                    *psz_url;
159
160     uint16_t                i_dependOn_es_id;
161     uint16_t                i_OCR_es_id;
162
163     decoder_config_descriptor_t    dec_descr;
164     sl_config_descriptor_t         sl_descr;
165
166 } es_mpeg4_descriptor_t;
167
168 typedef struct
169 {
170     uint8_t                i_iod_label;
171
172     /* IOD */
173     uint16_t                i_od_id;
174     char                    *psz_url;
175
176     uint8_t                 i_ODProfileLevelIndication;
177     uint8_t                 i_sceneProfileLevelIndication;
178     uint8_t                 i_audioProfileLevelIndication;
179     uint8_t                 i_visualProfileLevelIndication;
180     uint8_t                 i_graphicsProfileLevelIndication;
181
182     es_mpeg4_descriptor_t   es_descr[255];
183
184 } iod_descriptor_t;
185
186 typedef struct
187 {
188     dvbpsi_handle   handle;
189
190     int             i_version;
191     int             i_number;
192     int             i_pid_pcr;
193     /* IOD stuff (mpeg4) */
194     iod_descriptor_t *iod;
195
196 } ts_prg_psi_t;
197
198 typedef struct
199 {
200     /* for special PAT case */
201     dvbpsi_handle   handle;
202     int             i_pat_version;
203
204     /* For PMT */
205     int             i_prg;
206     ts_prg_psi_t    **prg;
207
208 } ts_psi_t;
209
210 typedef struct
211 {
212     es_format_t  fmt;
213     es_out_id_t *id;
214     int         i_pes_size;
215     int         i_pes_gathered;
216     block_t     *p_pes;
217     block_t     **pp_last;
218
219     es_mpeg4_descriptor_t *p_mpeg4desc;
220     int         b_gather;
221
222 } ts_es_t;
223
224 typedef struct
225 {
226     int         i_pid;
227
228     vlc_bool_t  b_seen;
229     vlc_bool_t  b_valid;
230     int         i_cc;   /* countinuity counter */
231
232     /* PSI owner (ie PMT -> PAT, ES -> PMT */
233     ts_psi_t   *p_owner;
234     int         i_owner_number;
235
236     /* */
237     ts_psi_t    *psi;
238     ts_es_t     *es;
239
240     /* Some private streams encapsulate several ES (eg. DVB subtitles)*/
241     ts_es_t     **extra_es;
242     int         i_extra_es;
243
244 } ts_pid_t;
245
246 struct demux_sys_t
247 {
248     /* TS packet size (188, 192, 204) */
249     int         i_packet_size;
250
251     /* how many TS packet we read at once */
252     int         i_ts_read;
253
254     /* All pid */
255     ts_pid_t    pid[8192];
256
257     /* All PMT */
258     int         i_pmt;
259     ts_pid_t    **pmt;
260
261     /* */
262     vlc_bool_t  b_es_id_pid;
263     csa_t       *csa;
264     vlc_bool_t  b_silent;
265
266     vlc_bool_t  b_udp_out;
267     int         fd; /* udp socket */
268     uint8_t     *buffer;
269 };
270
271 static int Demux  ( demux_t *p_demux );
272 static int Control( demux_t *p_demux, int i_query, va_list args );
273
274
275 static void PIDInit ( ts_pid_t *pid, vlc_bool_t b_psi, ts_psi_t *p_owner );
276 static void PIDClean( es_out_t *out, ts_pid_t *pid );
277 static int  PIDFillFormat( ts_pid_t *pid, int i_stream_type );
278
279 static void PATCallBack( demux_t *, dvbpsi_pat_t * );
280 static void PMTCallBack( demux_t *p_demux, dvbpsi_pmt_t *p_pmt );
281
282 static inline int PIDGet( block_t *p )
283 {
284     return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
285 }
286
287 static vlc_bool_t GatherPES( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
288
289 static void PCRHandle( demux_t *p_demux, ts_pid_t *, block_t * );
290
291 static iod_descriptor_t *IODNew( int , uint8_t * );
292 static void              IODFree( iod_descriptor_t * );
293
294 #define TS_PACKET_SIZE_188 188
295 #define TS_PACKET_SIZE_192 192
296 #define TS_PACKET_SIZE_204 204
297 #define TS_PACKET_SIZE_MAX 204
298
299 /*****************************************************************************
300  * Open
301  *****************************************************************************/
302 static int Open( vlc_object_t *p_this )
303 {
304     demux_t     *p_demux = (demux_t*)p_this;
305     demux_sys_t *p_sys;
306
307     uint8_t     *p_peek;
308     int          i_sync, i_peek, i;
309     int          i_packet_size;
310
311     ts_pid_t     *pat;
312
313     vlc_value_t  val;
314
315     if( stream_Peek( p_demux->s, &p_peek, TS_PACKET_SIZE_MAX ) <
316         TS_PACKET_SIZE_MAX )
317     {
318         msg_Err( p_demux, "cannot peek" );
319         return VLC_EGENERIC;
320     }
321
322     /* Search first sync byte */
323     for( i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
324     {
325         if( p_peek[i_sync] == 0x47 ) break;
326     }
327     if( i_sync >= TS_PACKET_SIZE_MAX )
328     {
329         if( strcmp( p_demux->psz_demux, "ts" ) )
330         {
331             msg_Warn( p_demux, "TS module discarded" );
332             return VLC_EGENERIC;
333         }
334         msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
335     }
336
337     /* Check next 3 sync bytes */
338     i_peek = TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
339     if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
340     {
341         msg_Err( p_demux, "cannot peek" );
342         return VLC_EGENERIC;
343     }
344     if( p_peek[i_sync + TS_PACKET_SIZE_188] == 0x47 &&
345         p_peek[i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
346         p_peek[i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
347     {
348         i_packet_size = TS_PACKET_SIZE_188;
349     }
350     else if( p_peek[i_sync + TS_PACKET_SIZE_192] == 0x47 &&
351              p_peek[i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
352              p_peek[i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
353     {
354         i_packet_size = TS_PACKET_SIZE_192;
355     }
356     else if( p_peek[i_sync + TS_PACKET_SIZE_204] == 0x47 &&
357              p_peek[i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
358              p_peek[i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
359     {
360         i_packet_size = TS_PACKET_SIZE_204;
361     }
362     else if( !strcmp( p_demux->psz_demux, "ts" ) )
363     {
364         i_packet_size = TS_PACKET_SIZE_188;
365     }
366     else
367     {
368         msg_Warn( p_demux, "TS module discarded (lost sync)" );
369         return VLC_EGENERIC;
370     }
371
372     /* Fill p_demux field */
373     p_demux->pf_demux = Demux;
374     p_demux->pf_control = Control;
375     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
376     memset( p_sys, 0, sizeof( demux_sys_t ) );
377
378     /* Init p_sys field */
379     for( i = 0; i < 8192; i++ )
380     {
381         ts_pid_t *pid = &p_sys->pid[i];
382
383         pid->i_pid      = i;
384         pid->b_seen     = VLC_FALSE;
385         pid->b_valid    = VLC_FALSE;
386     }
387     p_sys->i_packet_size = i_packet_size;
388     p_sys->b_udp_out = VLC_FALSE;
389     p_sys->i_ts_read = 50;
390     p_sys->csa = NULL;
391
392     /* Init PAT handler */
393     pat = &p_sys->pid[0];
394     PIDInit( pat, VLC_TRUE, NULL );
395     pat->psi->handle = dvbpsi_AttachPAT( (dvbpsi_pat_callback)PATCallBack,
396                                          p_demux );
397
398     /* Init PMT array */
399     p_sys->i_pmt = 0;
400     p_sys->pmt   = NULL;
401
402     /* Read config */
403     var_Create( p_demux, "ts-es-id-pid", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
404     var_Get( p_demux, "ts-es-id-pid", &val );
405     p_sys->b_es_id_pid = val.b_bool,
406
407     var_Create( p_demux, "ts-out", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
408     var_Get( p_demux, "ts-out", &val );
409     if( val.psz_string && *val.psz_string )
410     {
411         vlc_value_t mtu;
412         char *psz = strchr( val.psz_string, ':' );
413         int   i_port = 0;
414
415         p_sys->b_udp_out = VLC_TRUE;
416
417         if( psz )
418         {
419             *psz++ = '\0';
420             i_port = atoi( psz );
421         }
422         if( i_port <= 0 ) i_port  = 1234;
423         msg_Dbg( p_demux, "resend ts to '%s:%d'", val.psz_string, i_port );
424
425         p_sys->fd = net_OpenUDP( p_demux, "", 0, val.psz_string, i_port );
426         if( p_sys->fd < 0 )
427         {
428             msg_Err( p_demux, "failed to open udp socket, send disabled" );
429             p_sys->b_udp_out = VLC_FALSE;
430         }
431         else
432         {
433             var_Create( p_demux, "ts-out-mtu",
434                         VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
435             var_Get( p_demux, "ts-out-mtu", &mtu );
436             p_sys->i_ts_read = mtu.i_int / p_sys->i_packet_size;
437             if( p_sys->i_ts_read <= 0 )
438             {
439                 p_sys->i_ts_read = 1500 / p_sys->i_packet_size;
440             }
441             p_sys->buffer = malloc( p_sys->i_packet_size * p_sys->i_ts_read );
442         }
443     }
444     if( val.psz_string )
445     {
446         free( val.psz_string );
447     }
448
449
450     /* We handle description of an extra PMT */
451     var_Create( p_demux, "ts-extra-pmt", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
452     var_Get( p_demux, "ts-extra-pmt", &val );
453     if( val.psz_string && strchr( val.psz_string, '=' ) != NULL )
454     {
455         char *psz = val.psz_string;
456         int  i_pid = strtol( psz, &psz, 0 );
457
458         if( i_pid >= 2 && i_pid < 8192 )
459         {
460             ts_pid_t *pmt = &p_sys->pid[i_pid];
461
462             msg_Dbg( p_demux, "extra pmt specified (pid=0x%x)", i_pid );
463             PIDInit( pmt, VLC_TRUE, NULL );
464             /* FIXME we should also ask for a number */
465             pmt->psi->prg[0]->handle =
466                 dvbpsi_AttachPMT( 1, (dvbpsi_pmt_callback)PMTCallBack,
467                                   p_demux );
468             pmt->psi->prg[0]->i_number = 0; /* special one */
469
470             psz = strchr( psz, '=' ) + 1;   /* can't failed */
471             while( psz && *psz )
472             {
473                 char *psz_next = strchr( psz, ',' );
474                 int i_pid, i_stream_type;
475
476                 if( psz_next )
477                 {
478                     *psz_next++ = '\0';
479                 }
480
481                 i_pid = strtol( psz, &psz, 0 );
482                 if( *psz == ':' )
483                 {
484                     i_stream_type = strtol( psz + 1, &psz, 0 );
485                     if( i_pid >= 2 && i_pid < 8192 &&
486                         !p_sys->pid[i_pid].b_valid )
487                     {
488                         ts_pid_t *pid = &p_sys->pid[i_pid];
489
490                         PIDInit( pid, VLC_FALSE, pmt->psi);
491                         if( pmt->psi->prg[0]->i_pid_pcr <= 0 )
492                         {
493                             pmt->psi->prg[0]->i_pid_pcr = i_pid;
494                         }
495                         PIDFillFormat( pid, i_stream_type);
496                         if( pid->es->fmt.i_cat != UNKNOWN_ES )
497                         {
498                             if( p_sys->b_es_id_pid )
499                             {
500                                 pid->es->fmt.i_id = i_pid;
501                             }
502                             msg_Dbg( p_demux, "  * es pid=0x%x type=0x%x "
503                                      "fcc=%4.4s", i_pid, i_stream_type,
504                                      (char*)&pid->es->fmt.i_codec );
505                             pid->es->id = es_out_Add( p_demux->out,
506                                                       &pid->es->fmt );
507                         }
508                     }
509                 }
510                 psz = psz_next;
511             }
512         }
513     }
514     if( val.psz_string )
515     {
516         free( val.psz_string );
517     }
518
519     var_Create( p_demux, "ts-csa-ck", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
520     var_Get( p_demux, "ts-csa-ck", &val );
521     if( val.psz_string && *val.psz_string )
522     {
523         char *psz = val.psz_string;
524         if( psz[0] == '0' && ( psz[1] == 'x' || psz[1] == 'X' ) )
525         {
526             psz += 2;
527         }
528         if( strlen( psz ) != 16 )
529         {
530             msg_Warn( p_demux, "invalid csa ck (it must be 16 chars long)" );
531         }
532         else
533         {
534             uint64_t i_ck = strtoll( psz, NULL, 16 );
535             uint8_t ck[8];
536             int     i;
537             for( i = 0; i < 8; i++ )
538             {
539                 ck[i] = ( i_ck >> ( 56 - 8*i) )&0xff;
540             }
541
542             msg_Dbg( p_demux, "using CSA scrambling with "
543                      "ck=%x:%x:%x:%x:%x:%x:%x:%x",
544                      ck[0], ck[1], ck[2], ck[3], ck[4], ck[5], ck[6], ck[7] );
545
546             p_sys->csa = csa_New();
547             csa_SetCW( p_sys->csa, ck, ck );
548         }
549     }
550     if( val.psz_string )
551     {
552         free( val.psz_string );
553     }
554
555     var_Create( p_demux, "ts-silent", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
556     var_Get( p_demux, "ts-silent", &val );
557     p_sys->b_silent = val.b_bool;
558
559     return VLC_SUCCESS;
560 }
561
562 /*****************************************************************************
563  * Close
564  *****************************************************************************/
565 static void Close( vlc_object_t *p_this )
566 {
567     demux_t     *p_demux = (demux_t*)p_this;
568     demux_sys_t *p_sys = p_demux->p_sys;
569
570     int          i;
571
572     msg_Dbg( p_demux, "pid list:" );
573     for( i = 0; i < 8192; i++ )
574     {
575         ts_pid_t *pid = &p_sys->pid[i];
576
577         if( pid->b_valid && pid->psi )
578         {
579             switch( pid->i_pid )
580             {
581                 case 0: /* PAT */
582                     dvbpsi_DetachPAT( pid->psi->handle );
583                     free( pid->psi );
584                     break;
585                 case 1: /* CAT */
586                     free( pid->psi );
587                     break;
588                 default:
589                     PIDClean( p_demux->out, pid );
590                     break;
591             }
592         }
593         else if( pid->b_valid && pid->es )
594         {
595             PIDClean( p_demux->out, pid );
596         }
597
598         if( pid->b_seen )
599         {
600             msg_Dbg( p_demux, "  - pid[0x%x] seen", pid->i_pid );
601         }
602     }
603
604     if( p_sys->b_udp_out )
605     {
606         net_Close( p_sys->fd );
607         free( p_sys->buffer );
608     }
609     if( p_sys->csa )
610     {
611         csa_Delete( p_sys->csa );
612     }
613
614     if( p_sys->i_pmt ) free( p_sys->pmt );
615     free( p_sys );
616 }
617
618 /*****************************************************************************
619  * Demux:
620  *****************************************************************************/
621 static int Demux( demux_t *p_demux )
622 {
623     demux_sys_t *p_sys = p_demux->p_sys;
624     int          i_pkt;
625
626     /* We read at most 100 TS packet or until a frame is completed */
627     for( i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
628     {
629         vlc_bool_t  b_frame = VLC_FALSE;
630         block_t     *p_pkt;
631         ts_pid_t    *p_pid;
632
633         /* Get a new TS packet */
634         if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
635         {
636             msg_Dbg( p_demux, "eof ?" );
637             return 0;
638         }
639
640         /* Check sync byte and re-sync if needed */
641         if( p_pkt->p_buffer[0] != 0x47 )
642         {
643             msg_Warn( p_demux, "lost synchro" );
644             block_Release( p_pkt );
645
646             while( !p_demux->b_die )
647             {
648                 uint8_t *p_peek;
649                 int i_peek, i_skip = 0;
650
651                 i_peek = stream_Peek( p_demux->s, &p_peek,
652                                       p_sys->i_packet_size * 10 );
653                 if( i_peek < p_sys->i_packet_size + 1 )
654                 {
655                     msg_Dbg( p_demux, "eof ?" );
656                     return 0;
657                 }
658
659                 while( i_skip < i_peek - p_sys->i_packet_size )
660                 {
661                     if( p_peek[i_skip] == 0x47 &&
662                         p_peek[i_skip + p_sys->i_packet_size] == 0x47 )
663                     {
664                         break;
665                     }
666                     i_skip++;
667                 }
668
669                 msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
670                 stream_Read( p_demux->s, NULL, i_skip );
671
672                 if( i_skip < i_peek - p_sys->i_packet_size )
673                 {
674                     break;
675                 }
676             }
677
678             if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
679             {
680                 msg_Dbg( p_demux, "eof ?" );
681                 return 0;
682             }
683         }
684
685         if( p_sys->b_udp_out )
686         {
687             memcpy( &p_sys->buffer[i_pkt * p_sys->i_packet_size],
688                     p_pkt->p_buffer, p_sys->i_packet_size );
689         }
690
691         /* Parse the TS packet */
692         p_pid = &p_sys->pid[PIDGet( p_pkt )];
693
694         if( p_pid->b_valid )
695         {
696             if( p_pid->psi )
697             {
698                 if( p_pid->i_pid == 0 )
699                 {
700                     dvbpsi_PushPacket( p_pid->psi->handle, p_pkt->p_buffer );
701                 }
702                 else
703                 {
704                     int i_prg;
705                     for( i_prg = 0; i_prg < p_pid->psi->i_prg; i_prg++ )
706                     {
707                         dvbpsi_PushPacket( p_pid->psi->prg[i_prg]->handle,
708                                            p_pkt->p_buffer );
709                     }
710                 }
711                 block_Release( p_pkt );
712             }
713             else if( !p_sys->b_udp_out )
714             {
715                 b_frame = GatherPES( p_demux, p_pid, p_pkt );
716             }
717             else
718             {
719                 block_Release( p_pkt );
720             }
721         }
722         else
723         {
724             if( !p_pid->b_seen )
725             {
726                 msg_Dbg( p_demux, "pid[0x%x] unknown", p_pid->i_pid );
727             }
728             /* We have to handle PCR if present */
729             PCRHandle( p_demux, p_pid, p_pkt );
730             block_Release( p_pkt );
731         }
732         p_pid->b_seen = VLC_TRUE;
733
734         if( b_frame )
735         {
736             break;
737         }
738     }
739
740     if( p_sys->b_udp_out )
741     {
742         /* Send the complete block */
743         net_Write( p_demux, p_sys->fd, p_sys->buffer,
744                    p_sys->i_ts_read * p_sys->i_packet_size );
745     }
746
747     return 1;
748 }
749
750 /*****************************************************************************
751  * Control:
752  *****************************************************************************/
753 static int Control( demux_t *p_demux, int i_query, va_list args )
754 {
755     /* demux_sys_t *p_sys = p_demux->p_sys; */
756     double f, *pf;
757     int64_t i64;
758
759     switch( i_query )
760     {
761         case DEMUX_GET_POSITION:
762             pf = (double*) va_arg( args, double* );
763             i64 = stream_Size( p_demux->s );
764             if( i64 > 0 )
765             {
766                 *pf = (double)stream_Tell( p_demux->s ) / (double)i64;
767             }
768             else
769             {
770                 *pf = 0.0;
771             }
772             return VLC_SUCCESS;
773         case DEMUX_SET_POSITION:
774             f = (double) va_arg( args, double );
775             i64 = stream_Size( p_demux->s );
776
777             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
778             if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
779             {
780                 return VLC_EGENERIC;
781             }
782             return VLC_SUCCESS;
783 #if 0
784
785         case DEMUX_GET_TIME:
786             pi64 = (int64_t*)va_arg( args, int64_t * );
787             if( p_sys->i_time < 0 )
788             {
789                 *pi64 = 0;
790                 return VLC_EGENERIC;
791             }
792             *pi64 = p_sys->i_time;
793             return VLC_SUCCESS;
794
795         case DEMUX_GET_LENGTH:
796             pi64 = (int64_t*)va_arg( args, int64_t * );
797             if( p_sys->i_mux_rate > 0 )
798             {
799                 *pi64 = I64C(1000000) * ( stream_Size( p_demux->s ) / 50 ) /
800                         p_sys->i_mux_rate;
801                 return VLC_SUCCESS;
802             }
803             *pi64 = 0;
804             return VLC_EGENERIC;
805 #endif
806         case DEMUX_GET_FPS:
807         case DEMUX_SET_TIME:
808         default:
809             return VLC_EGENERIC;
810     }
811 }
812
813 static void PIDInit( ts_pid_t *pid, vlc_bool_t b_psi, ts_psi_t *p_owner )
814 {
815     vlc_bool_t b_old_valid = pid->b_valid;
816
817     pid->b_valid    = VLC_TRUE;
818     pid->i_cc       = 0xff;
819     pid->p_owner    = p_owner;
820     pid->i_owner_number = 0;
821
822     pid->extra_es   = NULL;
823     pid->i_extra_es = 0;
824
825     if( b_psi )
826     {
827         pid->es  = NULL;
828
829         if( !b_old_valid )
830         {
831             pid->psi = malloc( sizeof( ts_psi_t ) );
832             pid->psi->i_prg = 0;
833             pid->psi->prg   = NULL;
834             pid->psi->handle= NULL;
835         }
836         pid->psi->i_pat_version  = -1;
837         if( p_owner )
838         {
839             ts_prg_psi_t *prg = malloc( sizeof( ts_prg_psi_t ) );
840             /* PMT */
841             prg->i_version  = -1;
842             prg->i_number   = -1;
843             prg->i_pid_pcr  = -1;
844             prg->iod        = NULL;
845             prg->handle     = NULL;
846
847             TAB_APPEND( pid->psi->i_prg, pid->psi->prg, prg );
848         }
849     }
850     else
851     {
852         pid->psi = NULL;
853         pid->es  = malloc( sizeof( ts_es_t ) );
854
855         es_format_Init( &pid->es->fmt, UNKNOWN_ES, 0 );
856         pid->es->id      = NULL;
857         pid->es->p_pes   = NULL;
858         pid->es->i_pes_size= 0;
859         pid->es->i_pes_gathered= 0;
860         pid->es->pp_last = &pid->es->p_pes;
861         pid->es->p_mpeg4desc = NULL;
862         pid->es->b_gather = VLC_FALSE;
863     }
864 }
865
866 static void PIDClean( es_out_t *out, ts_pid_t *pid )
867 {
868     if( pid->psi )
869     {
870         int i;
871
872         if( pid->psi->handle ) dvbpsi_DetachPMT( pid->psi->handle );
873         for( i = 0; i < pid->psi->i_prg; i++ )
874         {
875             if( pid->psi->prg[i]->iod )
876                 IODFree( pid->psi->prg[i]->iod );
877             if( pid->psi->prg[i]->handle )
878                 dvbpsi_DetachPMT( pid->psi->prg[i]->handle );
879             free( pid->psi->prg[i] );
880         }
881         if( pid->psi->prg ) free( pid->psi->prg );
882         free( pid->psi );
883     }
884     else
885     {
886         int i;
887
888         if( pid->es->id )
889             es_out_Del( out, pid->es->id );
890
891         if( pid->es->p_pes )
892             block_ChainRelease( pid->es->p_pes );
893
894         es_format_Clean( &pid->es->fmt );
895
896         free( pid->es );
897
898         for( i = 0; i < pid->i_extra_es; i++ )
899         {
900             if( pid->extra_es[i]->id )
901                 es_out_Del( out, pid->extra_es[i]->id );
902
903             if( pid->extra_es[i]->p_pes )
904                 block_ChainRelease( pid->extra_es[i]->p_pes );
905
906             es_format_Clean( &pid->extra_es[i]->fmt );
907
908             free( pid->extra_es[i] );
909         }
910         if( pid->i_extra_es ) free( pid->extra_es );
911     }
912
913     pid->b_valid = VLC_FALSE;
914 }
915
916 /****************************************************************************
917  * gathering stuff
918  ****************************************************************************/
919 static void ParsePES( demux_t *p_demux, ts_pid_t *pid )
920 {
921     block_t *p_pes = pid->es->p_pes;
922     uint8_t header[30];
923     int     i_pes_size = 0;
924     int     i_skip = 0;
925     mtime_t i_dts = -1;
926     mtime_t i_pts = -1;
927     mtime_t i_length = 0;
928     int i_max;
929
930     /* remove the pes from pid */
931     pid->es->p_pes = NULL;
932     pid->es->i_pes_size= 0;
933     pid->es->i_pes_gathered= 0;
934     pid->es->pp_last = &pid->es->p_pes;
935
936     /* FIXME find real max size */
937     i_max = block_ChainExtract( p_pes, header, 30 );
938
939
940     if( header[0] != 0 || header[1] != 0 || header[2] != 1 )
941     {
942         if( !p_demux->p_sys->b_silent )
943             msg_Warn( p_demux, "invalid header [0x%x:%x:%x:%x] (pid: 0x%x)",
944                       header[0], header[1],header[2],header[3], pid->i_pid );
945         block_ChainRelease( p_pes );
946         return;
947     }
948
949     /* TODO check size */
950     switch( header[3] )
951     {
952         case 0xBC:  /* Program stream map */
953         case 0xBE:  /* Padding */
954         case 0xBF:  /* Private stream 2 */
955         case 0xB0:  /* ECM */
956         case 0xB1:  /* EMM */
957         case 0xFF:  /* Program stream directory */
958         case 0xF2:  /* DSMCC stream */
959         case 0xF8:  /* ITU-T H.222.1 type E stream */
960             i_skip = 6;
961             break;
962         default:
963             if( ( header[6]&0xC0 ) == 0x80 )
964             {
965                 /* mpeg2 PES */
966                 i_skip = header[8] + 9;
967
968                 if( header[7]&0x80 )    /* has pts */
969                 {
970                     i_pts = ((mtime_t)(header[ 9]&0x0e ) << 29)|
971                              (mtime_t)(header[10] << 22)|
972                             ((mtime_t)(header[11]&0xfe) << 14)|
973                              (mtime_t)(header[12] << 7)|
974                              (mtime_t)(header[13] >> 1);
975
976                     if( header[7]&0x40 )    /* has dts */
977                     {
978                          i_dts = ((mtime_t)(header[14]&0x0e ) << 29)|
979                                  (mtime_t)(header[15] << 22)|
980                                 ((mtime_t)(header[16]&0xfe) << 14)|
981                                  (mtime_t)(header[17] << 7)|
982                                  (mtime_t)(header[18] >> 1);
983                     }
984                 }
985             }
986             else
987             {
988                 i_skip = 6;
989                 while( i_skip < 23 && header[i_skip] == 0xff )
990                 {
991                     i_skip++;
992                 }
993                 if( i_skip == 23 )
994                 {
995                     msg_Err( p_demux, "too much MPEG-1 stuffing" );
996                     block_ChainRelease( p_pes );
997                     return;
998                 }
999                 if( ( header[i_skip] & 0xC0 ) == 0x40 )
1000                 {
1001                     i_skip += 2;
1002                 }
1003
1004                 if(  header[i_skip]&0x20 )
1005                 {
1006                      i_pts = ((mtime_t)(header[i_skip]&0x0e ) << 29)|
1007                               (mtime_t)(header[i_skip+1] << 22)|
1008                              ((mtime_t)(header[i_skip+2]&0xfe) << 14)|
1009                               (mtime_t)(header[i_skip+3] << 7)|
1010                               (mtime_t)(header[i_skip+4] >> 1);
1011
1012                     if( header[i_skip]&0x10 )    /* has dts */
1013                     {
1014                          i_dts = ((mtime_t)(header[i_skip+5]&0x0e ) << 29)|
1015                                   (mtime_t)(header[i_skip+6] << 22)|
1016                                  ((mtime_t)(header[i_skip+7]&0xfe) << 14)|
1017                                   (mtime_t)(header[i_skip+8] << 7)|
1018                                   (mtime_t)(header[i_skip+9] >> 1);
1019                          i_skip += 10;
1020                     }
1021                     else
1022                     {
1023                         i_skip += 5;
1024                     }
1025                 }
1026                 else
1027                 {
1028                     i_skip += 1;
1029                 }
1030             }
1031             break;
1032     }
1033
1034     if( pid->es->fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
1035         pid->es->fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
1036     {
1037         i_skip += 4;
1038     }
1039     else if( pid->es->fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
1040              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
1041              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
1042     {
1043         i_skip += 1;
1044     }
1045     else if( pid->es->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) &&
1046              pid->es->p_mpeg4desc )
1047     {
1048         decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
1049
1050         if( dcd->i_decoder_specific_info_len > 2 &&
1051             dcd->p_decoder_specific_info[0] == 0x10 &&
1052             ( dcd->p_decoder_specific_info[1]&0x10 ) )
1053         {
1054             /* display length */
1055             if( p_pes->i_buffer + 2 <= i_skip )
1056             {
1057                 i_length = GetWBE( &p_pes->p_buffer[i_skip] );
1058             }
1059
1060             i_skip += 2;
1061         }
1062         if( p_pes->i_buffer + 2 <= i_skip )
1063         {
1064             i_pes_size = GetWBE( &p_pes->p_buffer[i_skip] );
1065         }
1066         /* */
1067         i_skip += 2;
1068     }
1069
1070     /* skip header */
1071     while( p_pes && i_skip > 0 )
1072     {
1073         if( p_pes->i_buffer <= i_skip )
1074         {
1075             block_t *p_next = p_pes->p_next;
1076
1077             i_skip -= p_pes->i_buffer;
1078             block_Release( p_pes );
1079             p_pes = p_next;
1080         }
1081         else
1082         {
1083             p_pes->i_buffer -= i_skip;
1084             p_pes->p_buffer += i_skip;
1085             break;
1086         }
1087     }
1088
1089     if( p_pes )
1090     {
1091         block_t *p_block;
1092         int i;
1093
1094         if( i_dts >= 0 )
1095         {
1096             p_pes->i_dts = i_dts * 100 / 9;
1097         }
1098         if( i_pts >= 0 )
1099         {
1100             p_pes->i_pts = i_pts * 100 / 9;
1101         }
1102         p_pes->i_length = i_length * 100 / 9;
1103
1104         p_block = block_ChainGather( p_pes );
1105         if( pid->es->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) )
1106         {
1107             if( i_pes_size > 0 && p_block->i_buffer > i_pes_size )
1108             {
1109                 p_block->i_buffer = i_pes_size;
1110             }
1111             /* Append a \0 */
1112             p_block = block_Realloc( p_block, 0, p_block->i_buffer + 1 );
1113             p_block->p_buffer[p_block->i_buffer -1] = '\0';
1114         }
1115
1116         for( i = 0; i < pid->i_extra_es; i++ )
1117         {
1118             es_out_Send( p_demux->out, pid->extra_es[i]->id,
1119                          block_Duplicate( p_block ) );
1120         }
1121
1122         es_out_Send( p_demux->out, pid->es->id, p_block );
1123     }
1124     else
1125     {
1126         msg_Warn( p_demux, "empty pes" );
1127     }
1128 }
1129
1130 static void PCRHandle( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
1131 {
1132     demux_sys_t   *p_sys = p_demux->p_sys;
1133     const uint8_t *p = p_bk->p_buffer;
1134
1135     if( ( p[3]&0x20 ) && /* adaptation */
1136         ( p[5]&0x10 ) &&
1137         ( p[4] >= 7 ) )
1138     {
1139         int i;
1140         mtime_t i_pcr;  /* 33 bits */
1141
1142         i_pcr = ( (mtime_t)p[6] << 25 ) |
1143                 ( (mtime_t)p[7] << 17 ) |
1144                 ( (mtime_t)p[8] << 9 ) |
1145                 ( (mtime_t)p[9] << 1 ) |
1146                 ( (mtime_t)p[10] >> 7 );
1147
1148         /* Search program and set the PCR */
1149         for( i = 0; i < p_sys->i_pmt; i++ )
1150         {
1151             int i_prg;
1152             for( i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
1153             {
1154                 if( pid->i_pid == p_sys->pmt[i]->psi->prg[i_prg]->i_pid_pcr )
1155                 {
1156                     es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR,
1157                                     (int)p_sys->pmt[i]->psi->prg[i_prg]->i_number,
1158                                     (int64_t)(i_pcr * 100 / 9) );
1159                 }
1160             }
1161         }
1162     }
1163 }
1164
1165 static vlc_bool_t GatherPES( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
1166 {
1167     const uint8_t    *p = p_bk->p_buffer;
1168     const vlc_bool_t b_unit_start = p[1]&0x40;
1169     const vlc_bool_t b_adaptation = p[3]&0x20;
1170     const vlc_bool_t b_payload    = p[3]&0x10;
1171     const int        i_cc         = p[3]&0x0f;   /* continuity counter */
1172
1173     /* transport_scrambling_control is ignored */
1174
1175     int         i_skip = 0;
1176     vlc_bool_t  i_ret  = VLC_FALSE;
1177     int         i_diff;
1178
1179 #if 0
1180     msg_Dbg( p_demux, "pid=0x%x unit_start=%d adaptation=%d payload=%d "
1181              "cc=0x%x", pid->i_pid, b_unit_start, b_adaptation,
1182              b_payload, i_cc );
1183 #endif
1184
1185     /* For now, ignore additional error correction
1186      * TODO: handle Reed-Solomon 204,188 error correction */
1187     p_bk->i_buffer = TS_PACKET_SIZE_188;
1188
1189     if( p[1]&0x80 )
1190     {
1191         msg_Dbg( p_demux, "transport_error_indicator set (pid=0x%x)",
1192                  pid->i_pid );
1193     }
1194
1195     if( p_demux->p_sys->csa )
1196     {
1197         csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer );
1198     }
1199
1200     if( !b_adaptation )
1201     {
1202         /* We don't have any adaptation_field, so payload starts
1203          * immediately after the 4 byte TS header */
1204         i_skip = 4;
1205     }
1206     else
1207     {
1208         /* p[4] is adaptation_field_length minus one */
1209         i_skip = 5 + p[4];
1210         if( p[4] > 0 )
1211         {
1212             if( p[5]&0x80 )
1213             {
1214                 msg_Warn( p_demux, "discontinuity_indicator (pid=0x%x) "
1215                           "ignored", pid->i_pid );
1216             }
1217         }
1218     }
1219
1220     /* Test continuity counter */
1221     /* continuous when (one of this):
1222         * diff == 1
1223         * diff == 0 and payload == 0
1224         * diff == 0 and duplicate packet (playload != 0) <- should we
1225         *   test the content ?
1226      */
1227
1228     i_diff = ( i_cc - pid->i_cc )&0x0f;
1229     if( b_payload && i_diff == 1 )
1230     {
1231         pid->i_cc++;
1232     }
1233     else
1234     {
1235         if( pid->i_cc == 0xff )
1236         {
1237             msg_Warn( p_demux, "first packet for pid=0x%x cc=0x%x",
1238                       pid->i_pid, i_cc );
1239             pid->i_cc = i_cc;
1240         }
1241         else if( i_diff != 0 )
1242         {
1243             /* FIXME what to do when discontinuity_indicator is set ? */
1244             msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x",
1245                       i_cc, ( pid->i_cc + 1 )&0x0f );
1246
1247             pid->i_cc = i_cc;
1248
1249             if( pid->es->p_pes )
1250             {
1251                 pid->es->p_pes->i_flags |= BLOCK_FLAG_DISCONTINUITY;
1252             }
1253         }
1254     }
1255
1256     PCRHandle( p_demux, pid, p_bk );
1257
1258     if( i_skip >= 188 || pid->es->id == NULL || p_demux->p_sys->b_udp_out )
1259     {
1260         block_Release( p_bk );
1261         return i_ret;
1262     }
1263
1264     /* We have to gather it */
1265     p_bk->p_buffer += i_skip;
1266     p_bk->i_buffer -= i_skip;
1267
1268     if( b_unit_start )
1269     {
1270         if( pid->es->p_pes )
1271         {
1272             ParsePES( p_demux, pid );
1273             i_ret = VLC_TRUE;
1274         }
1275
1276         block_ChainLastAppend( &pid->es->pp_last, p_bk );
1277         if( p_bk->i_buffer > 6 )
1278         {
1279             pid->es->i_pes_size = GetWBE( &p_bk->p_buffer[4] );
1280             if( pid->es->i_pes_size > 0 )
1281             {
1282                 pid->es->i_pes_size += 6;
1283             }
1284         }
1285         pid->es->i_pes_gathered += p_bk->i_buffer;
1286         if( pid->es->i_pes_size > 0 &&
1287             pid->es->i_pes_gathered >= pid->es->i_pes_size )
1288         {
1289             ParsePES( p_demux, pid );
1290             i_ret = VLC_TRUE;
1291         }
1292     }
1293     else
1294     {
1295         if( pid->es->p_pes == NULL )
1296         {
1297             /* msg_Dbg( p_demux, "broken packet" ); */
1298             block_Release( p_bk );
1299         }
1300         else
1301         {
1302             block_ChainLastAppend( &pid->es->pp_last, p_bk );
1303             pid->es->i_pes_gathered += p_bk->i_buffer;
1304             if( pid->es->i_pes_size > 0 &&
1305                 pid->es->i_pes_gathered >= pid->es->i_pes_size )
1306             {
1307                 ParsePES( p_demux, pid );
1308                 i_ret = VLC_TRUE;
1309             }
1310         }
1311     }
1312
1313     return i_ret;
1314 }
1315
1316 static int PIDFillFormat( ts_pid_t *pid, int i_stream_type )
1317 {
1318     es_format_t *fmt = &pid->es->fmt;
1319
1320     switch( i_stream_type )
1321     {
1322         case 0x01:  /* MPEG-1 video */
1323         case 0x02:  /* MPEG-2 video */
1324         case 0x80:  /* MPEG-2 MOTO video */
1325             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'm', 'p', 'g', 'v' ) );
1326             break;
1327         case 0x03:  /* MPEG-1 audio */
1328         case 0x04:  /* MPEG-2 audio */
1329             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'm', 'p', 'g', 'a' ) );
1330             break;
1331         case 0x11:  /* MPEG4 (audio) */
1332         case 0x0f:  /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
1333             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'm', 'p', '4', 'a' ) );
1334             break;
1335         case 0x10:  /* MPEG4 (video) */
1336             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'm', 'p', '4', 'v' ) );
1337             pid->es->b_gather = VLC_TRUE;
1338             break;
1339         case 0x1B:  /* H264 <- check transport syntax/needed descriptor */
1340             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'h', '2', '6', '4' ) );
1341             break;
1342
1343         case 0x81:  /* A52 (audio) */
1344             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', ' ' ) );
1345             break;
1346         case 0x82:  /* DVD_SPU (sub) */
1347             es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', ' ' ) );
1348             break;
1349         case 0x83:  /* LPCM (audio) */
1350             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'l', 'p', 'c', 'm' ) );
1351             break;
1352         case 0x84:  /* SDDS (audio) */
1353             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 's' ) );
1354             break;
1355         case 0x85:  /* DTS (audio) */
1356             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'd', 't', 's', ' ' ) );
1357             break;
1358
1359         case 0x91:  /* A52 vls (audio) */
1360             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
1361             break;
1362         case 0x92:  /* DVD_SPU vls (sub) */
1363             es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
1364             break;
1365         case 0x93:  /* LPCM vls (audio) */
1366             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'l', 'p', 'c', 'b' ) );
1367             break;
1368         case 0x94:  /* SDDS (audio) */
1369             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
1370             break;
1371
1372         case 0xa0:  /* MSCODEC vlc (video) (fixed later) */
1373             es_format_Init( fmt, UNKNOWN_ES, 0 );
1374             pid->es->b_gather = VLC_TRUE;
1375             break;
1376
1377         case 0x06:  /* PES_PRIVATE  (fixed later) */
1378         case 0x12:  /* MPEG-4 generic (sub/scene/...) (fixed later) */
1379         default:
1380             es_format_Init( fmt, UNKNOWN_ES, 0 );
1381             break;
1382     }
1383
1384     /* PES packets usually contain truncated frames */
1385     fmt->b_packetized = VLC_FALSE;
1386
1387     return fmt->i_cat == UNKNOWN_ES ? VLC_EGENERIC : VLC_SUCCESS ;
1388 }
1389
1390 /*****************************************************************************
1391  * MP4 specific functions (IOD parser)
1392  *****************************************************************************/
1393 static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
1394 {
1395     unsigned int i_b;
1396     unsigned int i_len = 0;
1397     do
1398     {
1399         i_b = **pp_data;
1400         (*pp_data)++;
1401         (*pi_data)--;
1402         i_len = ( i_len << 7 ) + ( i_b&0x7f );
1403
1404     } while( i_b&0x80 );
1405
1406     return( i_len );
1407 }
1408 static int IODGetByte( int *pi_data, uint8_t **pp_data )
1409 {
1410     if( *pi_data > 0 )
1411     {
1412         const int i_b = **pp_data;
1413         (*pp_data)++;
1414         (*pi_data)--;
1415         return( i_b );
1416     }
1417     return( 0 );
1418 }
1419 static int IODGetWord( int *pi_data, uint8_t **pp_data )
1420 {
1421     const int i1 = IODGetByte( pi_data, pp_data );
1422     const int i2 = IODGetByte( pi_data, pp_data );
1423     return( ( i1 << 8 ) | i2 );
1424 }
1425 static int IODGet3Bytes( int *pi_data, uint8_t **pp_data )
1426 {
1427     const int i1 = IODGetByte( pi_data, pp_data );
1428     const int i2 = IODGetByte( pi_data, pp_data );
1429     const int i3 = IODGetByte( pi_data, pp_data );
1430
1431     return( ( i1 << 16 ) | ( i2 << 8) | i3 );
1432 }
1433
1434 static uint32_t IODGetDWord( int *pi_data, uint8_t **pp_data )
1435 {
1436     const uint32_t i1 = IODGetWord( pi_data, pp_data );
1437     const uint32_t i2 = IODGetWord( pi_data, pp_data );
1438     return( ( i1 << 16 ) | i2 );
1439 }
1440
1441 static char* IODGetURL( int *pi_data, uint8_t **pp_data )
1442 {
1443     char *url;
1444     int i_url_len, i;
1445
1446     i_url_len = IODGetByte( pi_data, pp_data );
1447     url = malloc( i_url_len + 1 );
1448     for( i = 0; i < i_url_len; i++ )
1449     {
1450         url[i] = IODGetByte( pi_data, pp_data );
1451     }
1452     url[i_url_len] = '\0';
1453     return( url );
1454 }
1455
1456 static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
1457 {
1458     iod_descriptor_t *p_iod;
1459     int i;
1460     int i_es_index;
1461     uint8_t     i_flags;
1462     vlc_bool_t  b_url;
1463     int         i_iod_length;
1464
1465     p_iod = malloc( sizeof( iod_descriptor_t ) );
1466     memset( p_iod, 0, sizeof( iod_descriptor_t ) );
1467
1468     fprintf( stderr, "\n************ IOD ************" );
1469     for( i = 0; i < 255; i++ )
1470     {
1471         p_iod->es_descr[i].b_ok = 0;
1472     }
1473     i_es_index = 0;
1474
1475     if( i_data < 3 )
1476     {
1477         return p_iod;
1478     }
1479
1480     p_iod->i_iod_label = IODGetByte( &i_data, &p_data );
1481     fprintf( stderr, "\n* iod_label:%d", p_iod->i_iod_label );
1482     fprintf( stderr, "\n* ===========" );
1483     fprintf( stderr, "\n* tag:0x%x", p_data[0] );
1484
1485     if( IODGetByte( &i_data, &p_data ) != 0x02 )
1486     {
1487         fprintf( stderr, "\n ERR: tag != 0x02" );
1488         return p_iod;
1489     }
1490
1491     i_iod_length = IODDescriptorLength( &i_data, &p_data );
1492     fprintf( stderr, "\n* length:%d", i_iod_length );
1493     if( i_iod_length > i_data )
1494     {
1495         i_iod_length = i_data;
1496     }
1497
1498     p_iod->i_od_id = ( IODGetByte( &i_data, &p_data ) << 2 );
1499     i_flags = IODGetByte( &i_data, &p_data );
1500     p_iod->i_od_id |= i_flags >> 6;
1501     b_url = ( i_flags >> 5  )&0x01;
1502
1503     fprintf( stderr, "\n* od_id:%d", p_iod->i_od_id );
1504     fprintf( stderr, "\n* url flag:%d", b_url );
1505     fprintf( stderr, "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
1506
1507     if( b_url )
1508     {
1509         p_iod->psz_url = IODGetURL( &i_data, &p_data );
1510         fprintf( stderr, "\n* url string:%s", p_iod->psz_url );
1511         fprintf( stderr, "\n*****************************\n" );
1512         return p_iod;
1513     }
1514     else
1515     {
1516         p_iod->psz_url = NULL;
1517     }
1518
1519     p_iod->i_ODProfileLevelIndication = IODGetByte( &i_data, &p_data );
1520     p_iod->i_sceneProfileLevelIndication = IODGetByte( &i_data, &p_data );
1521     p_iod->i_audioProfileLevelIndication = IODGetByte( &i_data, &p_data );
1522     p_iod->i_visualProfileLevelIndication = IODGetByte( &i_data, &p_data );
1523     p_iod->i_graphicsProfileLevelIndication = IODGetByte( &i_data, &p_data );
1524
1525     fprintf( stderr, "\n* ODProfileLevelIndication:%d", p_iod->i_ODProfileLevelIndication );
1526     fprintf( stderr, "\n* sceneProfileLevelIndication:%d", p_iod->i_sceneProfileLevelIndication );
1527     fprintf( stderr, "\n* audioProfileLevelIndication:%d", p_iod->i_audioProfileLevelIndication );
1528     fprintf( stderr, "\n* visualProfileLevelIndication:%d", p_iod->i_visualProfileLevelIndication );
1529     fprintf( stderr, "\n* graphicsProfileLevelIndication:%d", p_iod->i_graphicsProfileLevelIndication );
1530
1531
1532     while( i_data > 0 && i_es_index < 255)
1533     {
1534         int i_tag, i_length;
1535         int     i_data_sav;
1536         uint8_t *p_data_sav;
1537
1538         i_tag = IODGetByte( &i_data, &p_data );
1539         i_length = IODDescriptorLength( &i_data, &p_data );
1540
1541         i_data_sav = i_data;
1542         p_data_sav = p_data;
1543
1544         i_data = i_length;
1545
1546         switch( i_tag )
1547         {
1548             case 0x03:
1549                 {
1550 #define es_descr    p_iod->es_descr[i_es_index]
1551                     int i_decoderConfigDescr_length;
1552                     fprintf( stderr, "\n* - ES_Descriptor length:%d", i_length );
1553                     es_descr.b_ok = 1;
1554
1555                     es_descr.i_es_id = IODGetWord( &i_data, &p_data );
1556                     i_flags = IODGetByte( &i_data, &p_data );
1557                     es_descr.b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
1558                     b_url = ( i_flags >> 6 )&0x01;
1559                     es_descr.b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
1560                     es_descr.i_streamPriority = i_flags & 0x1f;
1561                     fprintf( stderr, "\n*   * streamDependenceFlag:%d", es_descr.b_streamDependenceFlag );
1562                     fprintf( stderr, "\n*   * OCRStreamFlag:%d", es_descr.b_OCRStreamFlag );
1563                     fprintf( stderr, "\n*   * streamPriority:%d", es_descr.i_streamPriority );
1564
1565                     if( es_descr.b_streamDependenceFlag )
1566                     {
1567                         es_descr.i_dependOn_es_id = IODGetWord( &i_data, &p_data );
1568                         fprintf( stderr, "\n*   * dependOn_es_id:%d", es_descr.i_dependOn_es_id );
1569                     }
1570
1571                     if( b_url )
1572                     {
1573                         es_descr.psz_url = IODGetURL( &i_data, &p_data );
1574                         fprintf( stderr, "\n* url string:%s", es_descr.psz_url );
1575                     }
1576                     else
1577                     {
1578                         es_descr.psz_url = NULL;
1579                     }
1580
1581                     if( es_descr.b_OCRStreamFlag )
1582                     {
1583                         es_descr.i_OCR_es_id = IODGetWord( &i_data, &p_data );
1584                         fprintf( stderr, "\n*   * OCR_es_id:%d", es_descr.i_OCR_es_id );
1585                     }
1586
1587                     if( IODGetByte( &i_data, &p_data ) != 0x04 )
1588                     {
1589                         fprintf( stderr, "\n* ERR missing DecoderConfigDescr" );
1590                         es_descr.b_ok = 0;
1591                         break;
1592                     }
1593                     i_decoderConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
1594
1595                     fprintf( stderr, "\n*   - DecoderConfigDesc length:%d", i_decoderConfigDescr_length );
1596 #define dec_descr   es_descr.dec_descr
1597                     dec_descr.i_objectTypeIndication = IODGetByte( &i_data, &p_data );
1598                     i_flags = IODGetByte( &i_data, &p_data );
1599                     dec_descr.i_streamType = i_flags >> 2;
1600                     dec_descr.b_upStream = ( i_flags >> 1 )&0x01;
1601                     dec_descr.i_bufferSizeDB = IODGet3Bytes( &i_data, &p_data );
1602                     dec_descr.i_maxBitrate = IODGetDWord( &i_data, &p_data );
1603                     dec_descr.i_avgBitrate = IODGetDWord( &i_data, &p_data );
1604                     fprintf( stderr, "\n*     * objectTypeIndication:0x%x", dec_descr.i_objectTypeIndication  );
1605                     fprintf( stderr, "\n*     * streamType:0x%x", dec_descr.i_streamType );
1606                     fprintf( stderr, "\n*     * upStream:%d", dec_descr.b_upStream );
1607                     fprintf( stderr, "\n*     * bufferSizeDB:%d", dec_descr.i_bufferSizeDB );
1608                     fprintf( stderr, "\n*     * maxBitrate:%d", dec_descr.i_maxBitrate );
1609                     fprintf( stderr, "\n*     * avgBitrate:%d", dec_descr.i_avgBitrate );
1610                     if( i_decoderConfigDescr_length > 13 && IODGetByte( &i_data, &p_data ) == 0x05 )
1611                     {
1612                         int i;
1613                         dec_descr.i_decoder_specific_info_len =
1614                             IODDescriptorLength( &i_data, &p_data );
1615                         if( dec_descr.i_decoder_specific_info_len > 0 )
1616                         {
1617                             dec_descr.p_decoder_specific_info =
1618                                 malloc( dec_descr.i_decoder_specific_info_len );
1619                         }
1620                         for( i = 0; i < dec_descr.i_decoder_specific_info_len; i++ )
1621                         {
1622                             dec_descr.p_decoder_specific_info[i] = IODGetByte( &i_data, &p_data );
1623                         }
1624                     }
1625                     else
1626                     {
1627                         dec_descr.i_decoder_specific_info_len = 0;
1628                         dec_descr.p_decoder_specific_info = NULL;
1629                     }
1630                 }
1631 #undef  dec_descr
1632 #define sl_descr    es_descr.sl_descr
1633                 {
1634                     int i_SLConfigDescr_length;
1635                     int i_predefined;
1636
1637                     if( IODGetByte( &i_data, &p_data ) != 0x06 )
1638                     {
1639                         fprintf( stderr, "\n* ERR missing SLConfigDescr" );
1640                         es_descr.b_ok = 0;
1641                         break;
1642                     }
1643                     i_SLConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
1644
1645                     fprintf( stderr, "\n*   - SLConfigDescr length:%d", i_SLConfigDescr_length );
1646                     i_predefined = IODGetByte( &i_data, &p_data );
1647                     fprintf( stderr, "\n*     * i_predefined:0x%x", i_predefined  );
1648                     switch( i_predefined )
1649                     {
1650                         case 0x01:
1651                             {
1652                                 sl_descr.b_useAccessUnitStartFlag   = 0;
1653                                 sl_descr.b_useAccessUnitEndFlag     = 0;
1654                                 sl_descr.b_useRandomAccessPointFlag = 0;
1655                                 //sl_descr.b_useRandomAccessUnitsOnlyFlag = 0;
1656                                 sl_descr.b_usePaddingFlag           = 0;
1657                                 sl_descr.b_useTimeStampsFlags       = 0;
1658                                 sl_descr.b_useIdleFlag              = 0;
1659                                 sl_descr.b_durationFlag     = 0;    // FIXME FIXME
1660                                 sl_descr.i_timeStampResolution      = 1000;
1661                                 sl_descr.i_OCRResolution    = 0;    // FIXME FIXME
1662                                 sl_descr.i_timeStampLength          = 32;
1663                                 sl_descr.i_OCRLength        = 0;    // FIXME FIXME
1664                                 sl_descr.i_AU_Length                = 0;
1665                                 sl_descr.i_instantBitrateLength= 0; // FIXME FIXME
1666                                 sl_descr.i_degradationPriorityLength= 0;
1667                                 sl_descr.i_AU_seqNumLength          = 0;
1668                                 sl_descr.i_packetSeqNumLength       = 0;
1669                                 if( sl_descr.b_durationFlag )
1670                                 {
1671                                     sl_descr.i_timeScale            = 0;    // FIXME FIXME
1672                                     sl_descr.i_accessUnitDuration   = 0;    // FIXME FIXME
1673                                     sl_descr.i_compositionUnitDuration= 0;    // FIXME FIXME
1674                                 }
1675                                 if( !sl_descr.b_useTimeStampsFlags )
1676                                 {
1677                                     sl_descr.i_startDecodingTimeStamp   = 0;    // FIXME FIXME
1678                                     sl_descr.i_startCompositionTimeStamp= 0;    // FIXME FIXME
1679                                 }
1680                             }
1681                             break;
1682                         default:
1683                             fprintf( stderr, "\n* ERR unsupported SLConfigDescr predefined" );
1684                             es_descr.b_ok = 0;
1685                             break;
1686                     }
1687                 }
1688                 break;
1689 #undef  sl_descr
1690 #undef  es_descr
1691             default:
1692                 fprintf( stderr, "\n* - OD tag:0x%x length:%d (Unsupported)", i_tag, i_length );
1693                 break;
1694         }
1695
1696         p_data = p_data_sav + i_length;
1697         i_data = i_data_sav - i_length;
1698         i_es_index++;
1699     }
1700
1701
1702     fprintf( stderr, "\n*****************************\n" );
1703     return p_iod;
1704 }
1705
1706 static void IODFree( iod_descriptor_t *p_iod )
1707 {
1708     int i;
1709
1710     if( p_iod->psz_url )
1711     {
1712         free( p_iod->psz_url );
1713         p_iod->psz_url = NULL;
1714         free( p_iod );
1715         return;
1716     }
1717
1718     for( i = 0; i < 255; i++ )
1719     {
1720 #define es_descr p_iod->es_descr[i]
1721         if( es_descr.b_ok )
1722         {
1723             if( es_descr.psz_url )
1724             {
1725                 free( es_descr.psz_url );
1726                 es_descr.psz_url = NULL;
1727             }
1728             else
1729             {
1730                 if( es_descr.dec_descr.p_decoder_specific_info != NULL )
1731                 {
1732                     free( es_descr.dec_descr.p_decoder_specific_info );
1733                     es_descr.dec_descr.p_decoder_specific_info = NULL;
1734                     es_descr.dec_descr.i_decoder_specific_info_len = 0;
1735                 }
1736             }
1737         }
1738         es_descr.b_ok = 0;
1739 #undef  es_descr
1740     }
1741     free( p_iod );
1742 }
1743
1744 /****************************************************************************
1745  ****************************************************************************
1746  ** libdvbpsi callbacks
1747  ****************************************************************************
1748  ****************************************************************************/
1749 static void PMTCallBack( demux_t *p_demux, dvbpsi_pmt_t *p_pmt )
1750 {
1751     demux_sys_t          *p_sys = p_demux->p_sys;
1752     dvbpsi_descriptor_t  *p_dr;
1753     dvbpsi_pmt_es_t      *p_es;
1754
1755     ts_pid_t             *pmt = NULL;
1756     ts_prg_psi_t         *prg = NULL;
1757     int                  i;
1758
1759     msg_Dbg( p_demux, "PMTCallBack called" );
1760
1761     /* First find this PMT declared in PAT */
1762     for( i = 0; i < p_sys->i_pmt; i++ )
1763     {
1764         int i_prg;
1765         for( i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
1766         {
1767             if( p_sys->pmt[i]->psi->prg[i_prg]->i_number ==
1768                 p_pmt->i_program_number )
1769             {
1770                 pmt = p_sys->pmt[i];
1771                 prg = p_sys->pmt[i]->psi->prg[i_prg];
1772                 break;
1773             }
1774         }
1775         if( pmt )
1776             break;
1777     }
1778
1779     if( pmt == NULL )
1780     {
1781         msg_Warn( p_demux, "unreferenced program (broken stream)" );
1782         dvbpsi_DeletePMT(p_pmt);
1783         return;
1784     }
1785
1786     if( prg->i_version != -1 &&
1787         ( !p_pmt->b_current_next || prg->i_version == p_pmt->i_version ) )
1788     {
1789         dvbpsi_DeletePMT( p_pmt );
1790         return;
1791     }
1792
1793     /* Clean this program (remove all es) */
1794     for( i = 0; i < 8192; i++ )
1795     {
1796         ts_pid_t *pid = &p_sys->pid[i];
1797
1798         if( pid->b_valid && pid->p_owner == pmt->psi &&
1799             pid->i_owner_number == prg->i_number && pid->psi == NULL )
1800         {
1801             PIDClean( p_demux->out, pid );
1802         }
1803     }
1804     if( prg->iod )
1805     {
1806         IODFree( prg->iod );
1807         prg->iod = NULL;
1808     }
1809
1810     msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=0x%x",
1811              p_pmt->i_program_number, p_pmt->i_version, p_pmt->i_pcr_pid );
1812     prg->i_pid_pcr = p_pmt->i_pcr_pid;
1813     prg->i_version = p_pmt->i_version;
1814
1815     /* Parse descriptor */
1816     for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
1817     {
1818         if( p_dr->i_tag == 0x1d )
1819         {
1820             /* We have found an IOD descriptor */
1821             msg_Warn( p_demux, " * descriptor : IOD (0x1d)" );
1822
1823             prg->iod = IODNew( p_dr->i_length, p_dr->p_data );
1824         }
1825         else
1826         {
1827             msg_Dbg( p_demux, " * descriptor : unknown (0x%x)", p_dr->i_tag );
1828         }
1829     }
1830
1831     for( p_es = p_pmt->p_first_es; p_es != NULL; p_es = p_es->p_next )
1832     {
1833         ts_pid_t *pid = &p_sys->pid[p_es->i_pid];
1834
1835         if( pid->b_valid )
1836         {
1837             msg_Warn( p_demux, "pmt error: pid=0x%x already defined",
1838                       p_es->i_pid );
1839             continue;
1840         }
1841
1842         PIDInit( pid, VLC_FALSE, pmt->psi );
1843         PIDFillFormat( pid, p_es->i_type );
1844         pid->i_owner_number = prg->i_number;
1845
1846         if( p_es->i_type == 0x10 || p_es->i_type == 0x11 ||
1847             p_es->i_type == 0x12 )
1848         {
1849             /* MPEG-4 stream: search SL_DESCRIPTOR */
1850             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
1851
1852             while( p_dr && ( p_dr->i_tag != 0x1f ) ) p_dr = p_dr->p_next;
1853
1854             if( p_dr && p_dr->i_length == 2 )
1855             {
1856                 int i;
1857                 int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
1858
1859                 msg_Warn( p_demux, "found SL_descriptor es_id=%d", i_es_id );
1860
1861                 pid->es->p_mpeg4desc = NULL;
1862
1863                 for( i = 0; i < 255; i++ )
1864                 {
1865                     iod_descriptor_t *iod = prg->iod;
1866
1867                     if( iod->es_descr[i].b_ok &&
1868                         iod->es_descr[i].i_es_id == i_es_id )
1869                     {
1870                         pid->es->p_mpeg4desc = &iod->es_descr[i];
1871                         break;
1872                     }
1873                 }
1874             }
1875
1876             if( pid->es->p_mpeg4desc != NULL )
1877             {
1878                 decoder_config_descriptor_t *dcd =
1879                     &pid->es->p_mpeg4desc->dec_descr;
1880
1881                 if( dcd->i_streamType == 0x04 )    /* VisualStream */
1882                 {
1883                     pid->es->fmt.i_cat = VIDEO_ES;
1884                     switch( dcd->i_objectTypeIndication )
1885                     {
1886                     case 0x0B: /* mpeg4 sub */
1887                         pid->es->fmt.i_cat = SPU_ES;
1888                         pid->es->fmt.i_codec = VLC_FOURCC('s','u','b','t');
1889                         break;
1890
1891                     case 0x20: /* mpeg4 */
1892                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','v');
1893                         break;
1894                     case 0x60:
1895                     case 0x61:
1896                     case 0x62:
1897                     case 0x63:
1898                     case 0x64:
1899                     case 0x65: /* mpeg2 */
1900                         pid->es->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1901                         break;
1902                     case 0x6a: /* mpeg1 */
1903                         pid->es->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1904                         break;
1905                     case 0x6c: /* mpeg1 */
1906                         pid->es->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
1907                         break;
1908                     default:
1909                         pid->es->fmt.i_cat = UNKNOWN_ES;
1910                         break;
1911                     }
1912                 }
1913                 else if( dcd->i_streamType == 0x05 )    /* AudioStream */
1914                 {
1915                     pid->es->fmt.i_cat = AUDIO_ES;
1916                     switch( dcd->i_objectTypeIndication )
1917                     {
1918                     case 0x40: /* mpeg4 */
1919                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','a');
1920                         break;
1921                     case 0x66:
1922                     case 0x67:
1923                     case 0x68: /* mpeg2 aac */
1924                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','a');
1925                         break;
1926                     case 0x69: /* mpeg2 */
1927                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','g','a');
1928                         break;
1929                     case 0x6b: /* mpeg1 */
1930                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','g','a');
1931                         break;
1932                     default:
1933                         pid->es->fmt.i_cat = UNKNOWN_ES;
1934                         break;
1935                     }
1936                 }
1937                 else
1938                 {
1939                     pid->es->fmt.i_cat = UNKNOWN_ES;
1940                 }
1941
1942                 if( pid->es->fmt.i_cat != UNKNOWN_ES )
1943                 {
1944                     pid->es->fmt.i_extra = dcd->i_decoder_specific_info_len;
1945                     if( pid->es->fmt.i_extra > 0 )
1946                     {
1947                         pid->es->fmt.p_extra = malloc( pid->es->fmt.i_extra );
1948                         memcpy( pid->es->fmt.p_extra,
1949                                 dcd->p_decoder_specific_info,
1950                                 pid->es->fmt.i_extra );
1951                     }
1952                 }
1953             }
1954         }
1955         else if( p_es->i_type == 0x06 )
1956         {
1957             dvbpsi_descriptor_t *p_dr;
1958
1959             for( p_dr = p_es->p_first_descriptor; p_dr != NULL;
1960                  p_dr = p_dr->p_next )
1961             {
1962                 msg_Dbg( p_demux, "  * es pid=0x%x type=0x%x dr->i_tag=0x%x",
1963                          p_es->i_pid, p_es->i_type, p_dr->i_tag );
1964
1965                 if( p_dr->i_tag == 0x6a )
1966                 {
1967                     pid->es->fmt.i_cat = AUDIO_ES;
1968                     pid->es->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1969                 }
1970                 else if( p_dr->i_tag == 0x05 )
1971                 {
1972
1973                     /* DTS registration descriptor (ETSI TS 101 154 Annex F) */
1974                     pid->es->fmt.i_cat = AUDIO_ES;
1975                     pid->es->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1976                 }
1977                 else if( p_dr->i_tag == 0x73 )
1978                 {
1979                     /* DTS audio descriptor (ETSI TS 101 154 Annex F) */
1980                     msg_Dbg( p_demux, "  * DTS audio descriptor not decoded" );
1981                     pid->es->fmt.i_cat = AUDIO_ES;
1982                     pid->es->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1983                 }
1984                 else if( p_dr->i_tag == 0x56 )
1985                 {
1986                     msg_Dbg( p_demux, "  * Teletext descriptor" );
1987                     pid->es->fmt.i_cat = SPU_ES;
1988                     pid->es->fmt.i_codec = VLC_FOURCC( 't', 'e', 'l', 'x' );
1989                 }
1990 #ifdef _DVBPSI_DR_59_H_
1991                 else if( p_dr->i_tag == 0x59 )
1992                 {
1993                     uint16_t n;
1994                     dvbpsi_subtitling_dr_t *sub;
1995
1996                     /* DVB subtitles */
1997                     pid->es->fmt.i_cat = SPU_ES;
1998                     pid->es->fmt.i_codec = VLC_FOURCC( 'd', 'v', 'b', 's' );
1999                     pid->es->fmt.i_group = p_pmt->i_program_number;
2000
2001                     sub = dvbpsi_DecodeSubtitlingDr( p_dr );
2002                     if( !sub ) continue;
2003
2004                     /* Each subtitle ES contains n languages,
2005                      * We are going to create n ES for the n tracks */
2006                     if( sub->i_subtitles_number > 0 )
2007                     {
2008                         pid->es->fmt.psz_language = malloc( 4 );
2009                         memcpy( pid->es->fmt.psz_language,
2010                                 sub->p_subtitle[0].i_iso6392_language_code, 3);
2011                         pid->es->fmt.psz_language[3] = 0;
2012
2013                         pid->es->fmt.subs.dvb.i_id =
2014                             sub->p_subtitle[0].i_composition_page_id;
2015                         /* Hack, FIXME */
2016                         pid->es->fmt.subs.dvb.i_id |=
2017                           ((int)sub->p_subtitle[0].i_ancillary_page_id << 16);
2018                     }
2019                     else pid->es->fmt.i_cat = UNKNOWN_ES;
2020
2021                     for( n = 1; n < sub->i_subtitles_number; n++ )
2022                     {
2023                         ts_es_t *p_es = malloc( sizeof( ts_es_t ) );
2024                         p_es->fmt = pid->es->fmt;
2025                         p_es->id = NULL;
2026                         p_es->p_pes = NULL;
2027                         p_es->i_pes_size = 0;
2028                         p_es->i_pes_gathered = 0;
2029                         p_es->pp_last = &p_es->p_pes;
2030                         p_es->p_mpeg4desc = NULL;
2031
2032                         p_es->fmt.psz_language = malloc( 4 );
2033                         memcpy( p_es->fmt.psz_language,
2034                                 sub->p_subtitle[n].i_iso6392_language_code, 3);
2035                         p_es->fmt.psz_language[3] = 0;
2036
2037                         p_es->fmt.subs.dvb.i_id =
2038                             sub->p_subtitle[n].i_composition_page_id;
2039                         /* Hack, FIXME */
2040                         pid->es->fmt.subs.dvb.i_id |=
2041                           ((int)sub->p_subtitle[n].i_ancillary_page_id << 16);
2042
2043                         TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
2044                     }
2045                 }
2046 #endif /* _DVBPSI_DR_59_H_ */
2047             }
2048         }
2049         else if( p_es->i_type == 0xa0 )
2050         {
2051             /* MSCODEC sent by vlc */
2052             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;
2053
2054             while( p_dr && ( p_dr->i_tag != 0xa0 ) ) p_dr = p_dr->p_next;
2055
2056             if( p_dr && p_dr->i_length >= 8 )
2057             {
2058                 pid->es->fmt.i_cat = VIDEO_ES;
2059                 pid->es->fmt.i_codec =
2060                     VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
2061                                 p_dr->p_data[2], p_dr->p_data[3] );
2062                 pid->es->fmt.video.i_width =
2063                     ( p_dr->p_data[4] << 8 ) | p_dr->p_data[5];
2064                 pid->es->fmt.video.i_height =
2065                     ( p_dr->p_data[6] << 8 ) | p_dr->p_data[7];
2066                 pid->es->fmt.i_extra = 
2067                     (p_dr->p_data[8] << 8) | p_dr->p_data[9];
2068
2069                 if( pid->es->fmt.i_extra > 0 )
2070                 {
2071                     pid->es->fmt.p_extra = malloc( pid->es->fmt.i_extra );
2072                     memcpy( pid->es->fmt.p_extra, &p_dr->p_data[10],
2073                             pid->es->fmt.i_extra );
2074                 }
2075             }
2076             else
2077             {
2078                 msg_Warn( p_demux, "private MSCODEC (vlc) without bih private "
2079                           "descriptor" );
2080             }
2081             /* For such stream we will gather them ourself and don't launch a
2082              * packetizer.
2083              * Yes it's ugly but it's the only way to have DIV3 working */
2084             pid->es->fmt.b_packetized = VLC_TRUE;
2085         }
2086
2087         if( pid->es->fmt.i_cat == AUDIO_ES ||
2088             ( pid->es->fmt.i_cat == SPU_ES &&
2089               pid->es->fmt.i_codec != VLC_FOURCC('d','v','b','s') ) )
2090         {
2091             /* get language descriptor */
2092             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;
2093             while( p_dr && ( p_dr->i_tag != 0x0a ) ) p_dr = p_dr->p_next;
2094
2095             if( p_dr )
2096             {
2097                 dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
2098
2099                 if( p_decoded )
2100                 {
2101                     pid->es->fmt.psz_language = malloc( 4 );
2102                     memcpy( pid->es->fmt.psz_language,
2103                             p_decoded->i_iso_639_code, 3 );
2104                     pid->es->fmt.psz_language[3] = 0;
2105                 }
2106             }
2107         }
2108
2109         pid->es->fmt.i_group = p_pmt->i_program_number;
2110         if( pid->es->fmt.i_cat == UNKNOWN_ES )
2111         {
2112             msg_Dbg( p_demux, "  * es pid=0x%x type=0x%x *unknown*",
2113                      p_es->i_pid, p_es->i_type );
2114         }
2115         else if( !p_sys->b_udp_out )
2116         {
2117             int i;
2118
2119             msg_Dbg( p_demux, "  * es pid=0x%x type=0x%x fcc=%4.4s",
2120                      p_es->i_pid, p_es->i_type, (char*)&pid->es->fmt.i_codec );
2121
2122             if( p_sys->b_es_id_pid )
2123             {
2124                 pid->es->fmt.i_id = p_es->i_pid;
2125             }
2126
2127             pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
2128
2129             for( i = 0; i < pid->i_extra_es; i++ )
2130             {
2131                 pid->extra_es[i]->id =
2132                     es_out_Add( p_demux->out, &pid->extra_es[i]->fmt);
2133             }
2134         }
2135     }
2136     dvbpsi_DeletePMT(p_pmt);
2137 }
2138
2139 static void PATCallBack( demux_t *p_demux, dvbpsi_pat_t *p_pat )
2140 {
2141     demux_sys_t          *p_sys = p_demux->p_sys;
2142     dvbpsi_pat_program_t *p_program;
2143     ts_pid_t             *pat = &p_sys->pid[0];
2144     int                  i, j;
2145
2146     msg_Dbg( p_demux, "PATCallBack called" );
2147
2148     if( pat->psi->i_pat_version != -1 &&
2149         ( !p_pat->b_current_next ||
2150           p_pat->i_version == pat->psi->i_pat_version ) )
2151     {
2152         dvbpsi_DeletePAT( p_pat );
2153         return;
2154     }
2155
2156     msg_Dbg( p_demux, "new PAT ts_id=0x%x version=%d current_next=%d",
2157              p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
2158
2159     /* Clean old */
2160     if( p_sys->i_pmt > 0 )
2161     {
2162         int      i_pmt_rm = 0;
2163         ts_pid_t **pmt_rm = NULL;
2164
2165         /* Search pmt to be deleted */
2166         for( i = 0; i < p_sys->i_pmt; i++ )
2167         {
2168             ts_pid_t *pmt = p_sys->pmt[i];
2169             vlc_bool_t b_keep = VLC_FALSE;
2170
2171             for( p_program = p_pat->p_first_program; p_program != NULL;
2172                  p_program = p_program->p_next )
2173             {
2174                 if( p_program->i_pid == pmt->i_pid )
2175                 {
2176                     int i_prg;
2177                     for( i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
2178                     {
2179                         if( p_program->i_number ==
2180                             pmt->psi->prg[i_prg]->i_number )
2181                         {
2182                             b_keep = VLC_TRUE;
2183                             break;
2184                         }
2185                     }
2186                     if( b_keep )
2187                         break;
2188                 }
2189             }
2190             if( !b_keep )
2191             {
2192                 TAB_APPEND( i_pmt_rm, pmt_rm, pmt );
2193             }
2194         }
2195
2196         /* Delete all ES attached to thoses PMT */
2197         for( i = 2; i < 8192; i++ )
2198         {
2199             ts_pid_t *pid = &p_sys->pid[i];
2200
2201             if( !pid->b_valid || pid->psi ) continue;
2202
2203             for( j = 0; j < i_pmt_rm; j++ )
2204             {
2205                 int i_prg;
2206                 for( i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
2207                 {
2208                     if( pid->p_owner->prg[i_prg]->i_pid_pcr ==
2209                         pmt_rm[j]->i_pid && pid->es->id )
2210                     {
2211                         /* We only remove es that aren't defined by extra pmt */
2212                         PIDClean( p_demux->out, pid );
2213                         break;
2214                     }
2215                 }
2216                 if( !pid->b_valid )
2217                     break;
2218             }
2219         }
2220
2221         /* Delete PMT pid */
2222         for( i = 0; i < i_pmt_rm; i++ )
2223         {
2224             PIDClean( p_demux->out, &p_sys->pid[pmt_rm[i]->i_pid] );
2225             TAB_REMOVE( p_sys->i_pmt, p_sys->pmt, pmt_rm[i] );
2226         }
2227         if( pmt_rm )
2228         {
2229             free( pmt_rm );
2230         }
2231     }
2232
2233     /* now create programs */
2234     for( p_program = p_pat->p_first_program; p_program != NULL;
2235          p_program = p_program->p_next )
2236     {
2237         msg_Dbg( p_demux, "  * number=%d pid=0x%x", p_program->i_number,
2238                  p_program->i_pid );
2239         if( p_program->i_number != 0 )
2240         {
2241             ts_pid_t *pmt = &p_sys->pid[p_program->i_pid];
2242             vlc_bool_t b_add = VLC_TRUE;
2243
2244             if( pmt->b_valid )
2245             {
2246                 int i_prg;
2247                 for( i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
2248                 {
2249                     if( pmt->psi->prg[i_prg]->i_number == p_program->i_number )
2250                     {
2251                         b_add = VLC_FALSE;
2252                         break;
2253                     }
2254                 }
2255             }
2256             else
2257             {
2258                 TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
2259             }
2260
2261             if( b_add )
2262             {
2263                 PIDInit( pmt, VLC_TRUE, pat->psi );
2264                 pmt->psi->prg[pmt->psi->i_prg-1]->handle =
2265                     dvbpsi_AttachPMT( p_program->i_number,
2266                                       (dvbpsi_pmt_callback)PMTCallBack,
2267                                       p_demux );
2268                 pmt->psi->prg[pmt->psi->i_prg-1]->i_number =
2269                     p_program->i_number;
2270             }
2271         }
2272     }
2273     pat->psi->i_pat_version = p_pat->i_version;
2274
2275     dvbpsi_DeletePAT( p_pat );
2276 }