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