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