]> git.sesse.net Git - vlc/blob - modules/demux/ts.c
ts: fix --ts-extra-pmt.
[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( _("ISO 13818-1 MPEG Transport Stream input - new" ) );
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;
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 )
331     {
332         msg_Err( p_demux, "cannot peek" );
333         return VLC_EGENERIC;
334     }
335
336     /* Search first sync byte */
337     for( i_sync = 0; i_sync < TS_PACKET_SIZE_MAX; i_sync++ )
338     {
339         if( p_peek[i_sync] == 0x47 ) break;
340     }
341     if( i_sync >= TS_PACKET_SIZE_MAX )
342     {
343         if( strcmp( p_demux->psz_demux, "ts" ) )
344         {
345             msg_Warn( p_demux, "TS module discarded" );
346             return VLC_EGENERIC;
347         }
348         msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
349     }
350
351     /* Check next 3 sync bytes */
352     i_peek = TS_PACKET_SIZE_MAX * 3 + i_sync + 1;
353     if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
354     {
355         msg_Err( p_demux, "cannot peek" );
356         return VLC_EGENERIC;
357     }
358     if( p_peek[i_sync + TS_PACKET_SIZE_188] == 0x47 &&
359         p_peek[i_sync + 2 * TS_PACKET_SIZE_188] == 0x47 &&
360         p_peek[i_sync + 3 * TS_PACKET_SIZE_188] == 0x47 )
361     {
362         i_packet_size = TS_PACKET_SIZE_188;
363     }
364     else if( p_peek[i_sync + TS_PACKET_SIZE_192] == 0x47 &&
365              p_peek[i_sync + 2 * TS_PACKET_SIZE_192] == 0x47 &&
366              p_peek[i_sync + 3 * TS_PACKET_SIZE_192] == 0x47 )
367     {
368         i_packet_size = TS_PACKET_SIZE_192;
369     }
370     else if( p_peek[i_sync + TS_PACKET_SIZE_204] == 0x47 &&
371              p_peek[i_sync + 2 * TS_PACKET_SIZE_204] == 0x47 &&
372              p_peek[i_sync + 3 * TS_PACKET_SIZE_204] == 0x47 )
373     {
374         i_packet_size = TS_PACKET_SIZE_204;
375     }
376     else if( !strcmp( p_demux->psz_demux, "ts" ) )
377     {
378         i_packet_size = TS_PACKET_SIZE_188;
379     }
380     else
381     {
382         msg_Warn( p_demux, "TS module discarded (lost sync)" );
383         return VLC_EGENERIC;
384     }
385
386     /* Fill p_demux field */
387     p_demux->pf_demux = Demux;
388     p_demux->pf_control = Control;
389     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
390     memset( p_sys, 0, sizeof( demux_sys_t ) );
391
392     /* Init p_sys field */
393     p_sys->b_dvb_control = VLC_TRUE;
394     p_sys->i_dvb_program = 0;
395     for( i = 0; i < 8192; i++ )
396     {
397         ts_pid_t *pid = &p_sys->pid[i];
398
399         pid->i_pid      = i;
400         pid->b_seen     = VLC_FALSE;
401         pid->b_valid    = VLC_FALSE;
402     }
403     p_sys->i_packet_size = i_packet_size;
404     p_sys->b_udp_out = VLC_FALSE;
405     p_sys->i_ts_read = 50;
406     p_sys->csa = NULL;
407
408     /* Init PAT handler */
409     pat = &p_sys->pid[0];
410     PIDInit( pat, VLC_TRUE, NULL );
411     pat->psi->handle = dvbpsi_AttachPAT( (dvbpsi_pat_callback)PATCallBack,
412                                          p_demux );
413
414     /* Init PMT array */
415     p_sys->i_pmt = 0;
416     p_sys->pmt   = NULL;
417
418     /* Read config */
419     var_Create( p_demux, "ts-es-id-pid", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
420     var_Get( p_demux, "ts-es-id-pid", &val );
421     p_sys->b_es_id_pid = val.b_bool,
422
423     var_Create( p_demux, "ts-out", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
424     var_Get( p_demux, "ts-out", &val );
425     if( val.psz_string && *val.psz_string )
426     {
427         vlc_value_t mtu;
428         char *psz = strchr( val.psz_string, ':' );
429         int   i_port = 0;
430
431         p_sys->b_udp_out = VLC_TRUE;
432
433         if( psz )
434         {
435             *psz++ = '\0';
436             i_port = atoi( psz );
437         }
438         if( i_port <= 0 ) i_port  = 1234;
439         msg_Dbg( p_demux, "resend ts to '%s:%d'", val.psz_string, i_port );
440
441         p_sys->fd = net_OpenUDP( p_demux, "", 0, val.psz_string, i_port );
442         if( p_sys->fd < 0 )
443         {
444             msg_Err( p_demux, "failed to open udp socket, send disabled" );
445             p_sys->b_udp_out = VLC_FALSE;
446         }
447         else
448         {
449             var_Create( p_demux, "ts-out-mtu",
450                         VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
451             var_Get( p_demux, "ts-out-mtu", &mtu );
452             p_sys->i_ts_read = mtu.i_int / p_sys->i_packet_size;
453             if( p_sys->i_ts_read <= 0 )
454             {
455                 p_sys->i_ts_read = 1500 / p_sys->i_packet_size;
456             }
457             p_sys->buffer = malloc( p_sys->i_packet_size * p_sys->i_ts_read );
458         }
459     }
460     if( val.psz_string )
461     {
462         free( val.psz_string );
463     }
464
465
466     /* We handle description of an extra PMT */
467     var_Create( p_demux, "ts-extra-pmt", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
468     var_Get( p_demux, "ts-extra-pmt", &val );
469     if( val.psz_string && strchr( val.psz_string, '=' ) != NULL )
470     {
471         char *psz = val.psz_string;
472         int  i_pid = strtol( psz, &psz, 0 );
473
474         if( i_pid >= 2 && i_pid < 8192 )
475         {
476             ts_pid_t *pmt = &p_sys->pid[i_pid];
477
478             msg_Dbg( p_demux, "extra pmt specified (pid=%d)", i_pid );
479             PIDInit( pmt, VLC_TRUE, NULL );
480             pmt->psi->i_prg = 1;
481             pmt->psi->prg = malloc( sizeof(ts_prg_psi_t) );
482             /* FIXME we should also ask for a number */
483             pmt->psi->prg[0]->handle =
484                 dvbpsi_AttachPMT( 1, (dvbpsi_pmt_callback)PMTCallBack,
485                                   p_demux );
486             pmt->psi->prg[0]->i_number = 0; /* special one */
487
488             psz = strchr( psz, '=' ) + 1;   /* can't failed */
489             while( psz && *psz )
490             {
491                 char *psz_next = strchr( psz, ',' );
492                 int i_pid, i_stream_type;
493
494                 if( psz_next )
495                 {
496                     *psz_next++ = '\0';
497                 }
498
499                 i_pid = strtol( psz, &psz, 0 );
500                 if( *psz == ':' )
501                 {
502                     i_stream_type = strtol( psz + 1, &psz, 0 );
503                     if( i_pid >= 2 && i_pid < 8192 &&
504                         !p_sys->pid[i_pid].b_valid )
505                     {
506                         ts_pid_t *pid = &p_sys->pid[i_pid];
507
508                         PIDInit( pid, VLC_FALSE, pmt->psi);
509                         if( pmt->psi->prg[0]->i_pid_pcr <= 0 )
510                         {
511                             pmt->psi->prg[0]->i_pid_pcr = i_pid;
512                         }
513                         PIDFillFormat( pid, i_stream_type);
514                         if( pid->es->fmt.i_cat != UNKNOWN_ES )
515                         {
516                             if( p_sys->b_es_id_pid )
517                             {
518                                 pid->es->fmt.i_id = i_pid;
519                             }
520                             msg_Dbg( p_demux, "  * es pid=%d type=%d "
521                                      "fcc=%4.4s", i_pid, i_stream_type,
522                                      (char*)&pid->es->fmt.i_codec );
523                             pid->es->id = es_out_Add( p_demux->out,
524                                                       &pid->es->fmt );
525                         }
526                     }
527                 }
528                 psz = psz_next;
529             }
530         }
531     }
532     if( val.psz_string )
533     {
534         free( val.psz_string );
535     }
536
537     var_Create( p_demux, "ts-csa-ck", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
538     var_Get( p_demux, "ts-csa-ck", &val );
539     if( val.psz_string && *val.psz_string )
540     {
541         char *psz = val.psz_string;
542         if( psz[0] == '0' && ( psz[1] == 'x' || psz[1] == 'X' ) )
543         {
544             psz += 2;
545         }
546         if( strlen( psz ) != 16 )
547         {
548             msg_Warn( p_demux, "invalid csa ck (it must be 16 chars long)" );
549         }
550         else
551         {
552             uint64_t i_ck = strtoull( psz, NULL, 16 );
553             uint8_t ck[8];
554             int     i;
555             for( i = 0; i < 8; i++ )
556             {
557                 ck[i] = ( i_ck >> ( 56 - 8*i) )&0xff;
558             }
559
560             msg_Dbg( p_demux, "using CSA scrambling with "
561                      "ck=%x:%x:%x:%x:%x:%x:%x:%x",
562                      ck[0], ck[1], ck[2], ck[3], ck[4], ck[5], ck[6], ck[7] );
563
564             p_sys->csa = csa_New();
565             csa_SetCW( p_sys->csa, ck, ck );
566         }
567     }
568     if( val.psz_string )
569     {
570         free( val.psz_string );
571     }
572
573     var_Create( p_demux, "ts-silent", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
574     var_Get( p_demux, "ts-silent", &val );
575     p_sys->b_silent = val.b_bool;
576
577     var_Create( p_demux, "ts-capmt-sysid", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
578     var_Get( p_demux, "ts-capmt-sysid", &val );
579     p_sys->i_capmt_sysid = val.i_int;
580
581     return VLC_SUCCESS;
582 }
583
584 /*****************************************************************************
585  * Close
586  *****************************************************************************/
587 static void Close( vlc_object_t *p_this )
588 {
589     demux_t     *p_demux = (demux_t*)p_this;
590     demux_sys_t *p_sys = p_demux->p_sys;
591
592     int          i;
593
594     msg_Dbg( p_demux, "pid list:" );
595     for( i = 0; i < 8192; i++ )
596     {
597         ts_pid_t *pid = &p_sys->pid[i];
598
599         if( pid->b_valid && pid->psi )
600         {
601             switch( pid->i_pid )
602             {
603                 case 0: /* PAT */
604                     dvbpsi_DetachPAT( pid->psi->handle );
605                     free( pid->psi );
606                     break;
607                 case 1: /* CAT */
608                     free( pid->psi );
609                     break;
610                 default:
611                     PIDClean( p_demux->out, pid );
612                     break;
613             }
614         }
615         else if( pid->b_valid && pid->es )
616         {
617             PIDClean( p_demux->out, pid );
618         }
619
620         if( pid->b_seen )
621         {
622             msg_Dbg( p_demux, "  - pid[%d] seen", pid->i_pid );
623         }
624
625         if( p_sys->b_dvb_control && pid->i_pid > 0 )
626         {
627             /* too much */
628             stream_Control( p_demux->s, STREAM_CONTROL_ACCESS, ACCESS_SET_PRIVATE_ID_STATE, pid->i_pid, VLC_FALSE );
629         }
630
631     }
632
633     if( p_sys->b_udp_out )
634     {
635         net_Close( p_sys->fd );
636         free( p_sys->buffer );
637     }
638     if( p_sys->csa )
639     {
640         csa_Delete( p_sys->csa );
641     }
642
643     if( p_sys->i_pmt ) free( p_sys->pmt );
644
645     if ( p_sys->p_programs_list )
646     {
647         vlc_value_t val;
648         val.p_list = p_sys->p_programs_list;
649         var_Change( p_demux, "programs", VLC_VAR_FREELIST, &val, NULL );
650     }
651
652     free( p_sys );
653 }
654
655 /*****************************************************************************
656  * Demux:
657  *****************************************************************************/
658 static int Demux( demux_t *p_demux )
659 {
660     demux_sys_t *p_sys = p_demux->p_sys;
661     int          i_pkt;
662
663     /* We read at most 100 TS packet or until a frame is completed */
664     for( i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
665     {
666         vlc_bool_t  b_frame = VLC_FALSE;
667         block_t     *p_pkt;
668         ts_pid_t    *p_pid;
669
670         /* Get a new TS packet */
671         if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
672         {
673             msg_Dbg( p_demux, "eof ?" );
674             return 0;
675         }
676
677         /* Check sync byte and re-sync if needed */
678         if( p_pkt->p_buffer[0] != 0x47 )
679         {
680             msg_Warn( p_demux, "lost synchro" );
681             block_Release( p_pkt );
682
683             while( !p_demux->b_die )
684             {
685                 uint8_t *p_peek;
686                 int i_peek, i_skip = 0;
687
688                 i_peek = stream_Peek( p_demux->s, &p_peek,
689                                       p_sys->i_packet_size * 10 );
690                 if( i_peek < p_sys->i_packet_size + 1 )
691                 {
692                     msg_Dbg( p_demux, "eof ?" );
693                     return 0;
694                 }
695
696                 while( i_skip < i_peek - p_sys->i_packet_size )
697                 {
698                     if( p_peek[i_skip] == 0x47 &&
699                         p_peek[i_skip + p_sys->i_packet_size] == 0x47 )
700                     {
701                         break;
702                     }
703                     i_skip++;
704                 }
705
706                 msg_Dbg( p_demux, "skipping %d bytes of garbage", i_skip );
707                 stream_Read( p_demux->s, NULL, i_skip );
708
709                 if( i_skip < i_peek - p_sys->i_packet_size )
710                 {
711                     break;
712                 }
713             }
714
715             if( !( p_pkt = stream_Block( p_demux->s, p_sys->i_packet_size ) ) )
716             {
717                 msg_Dbg( p_demux, "eof ?" );
718                 return 0;
719             }
720         }
721
722         if( p_sys->b_udp_out )
723         {
724             memcpy( &p_sys->buffer[i_pkt * p_sys->i_packet_size],
725                     p_pkt->p_buffer, p_sys->i_packet_size );
726         }
727
728         /* Parse the TS packet */
729         p_pid = &p_sys->pid[PIDGet( p_pkt )];
730
731         if( p_pid->b_valid )
732         {
733             if( p_pid->psi )
734             {
735                 if( p_pid->i_pid == 0 )
736                 {
737                     dvbpsi_PushPacket( p_pid->psi->handle, p_pkt->p_buffer );
738                 }
739                 else
740                 {
741                     int i_prg;
742                     for( i_prg = 0; i_prg < p_pid->psi->i_prg; i_prg++ )
743                     {
744                         dvbpsi_PushPacket( p_pid->psi->prg[i_prg]->handle,
745                                            p_pkt->p_buffer );
746                     }
747                 }
748                 block_Release( p_pkt );
749             }
750             else if( !p_sys->b_udp_out )
751             {
752                 b_frame = GatherPES( p_demux, p_pid, p_pkt );
753             }
754             else
755             {
756                 PCRHandle( p_demux, p_pid, p_pkt );
757                 block_Release( p_pkt );
758             }
759         }
760         else
761         {
762             if( !p_pid->b_seen )
763             {
764                 msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid );
765             }
766             /* We have to handle PCR if present */
767             PCRHandle( p_demux, p_pid, p_pkt );
768             block_Release( p_pkt );
769         }
770         p_pid->b_seen = VLC_TRUE;
771
772         if( b_frame )
773         {
774             break;
775         }
776     }
777
778     if( p_sys->b_udp_out )
779     {
780         /* Send the complete block */
781         net_Write( p_demux, p_sys->fd, NULL, p_sys->buffer,
782                    p_sys->i_ts_read * p_sys->i_packet_size );
783     }
784
785     return 1;
786 }
787
788 /*****************************************************************************
789  * Control:
790  *****************************************************************************/
791 static int Control( demux_t *p_demux, int i_query, va_list args )
792 {
793     demux_sys_t *p_sys = p_demux->p_sys;
794     double f, *pf;
795     int64_t i64;
796     int i_int;
797
798     switch( i_query )
799     {
800         case DEMUX_GET_POSITION:
801             pf = (double*) va_arg( args, double* );
802             i64 = stream_Size( p_demux->s );
803             if( i64 > 0 )
804             {
805                 *pf = (double)stream_Tell( p_demux->s ) / (double)i64;
806             }
807             else
808             {
809                 *pf = 0.0;
810             }
811             return VLC_SUCCESS;
812         case DEMUX_SET_POSITION:
813             f = (double) va_arg( args, double );
814             i64 = stream_Size( p_demux->s );
815
816             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
817             if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
818             {
819                 return VLC_EGENERIC;
820             }
821             return VLC_SUCCESS;
822 #if 0
823
824         case DEMUX_GET_TIME:
825             pi64 = (int64_t*)va_arg( args, int64_t * );
826             if( p_sys->i_time < 0 )
827             {
828                 *pi64 = 0;
829                 return VLC_EGENERIC;
830             }
831             *pi64 = p_sys->i_time;
832             return VLC_SUCCESS;
833
834         case DEMUX_GET_LENGTH:
835             pi64 = (int64_t*)va_arg( args, int64_t * );
836             if( p_sys->i_mux_rate > 0 )
837             {
838                 *pi64 = I64C(1000000) * ( stream_Size( p_demux->s ) / 50 ) /
839                         p_sys->i_mux_rate;
840                 return VLC_SUCCESS;
841             }
842             *pi64 = 0;
843             return VLC_EGENERIC;
844 #endif
845         case DEMUX_SET_GROUP:
846         {
847             uint16_t i_vpid = 0, i_apid1 = 0, i_apid2 = 0, i_apid3 = 0;
848             ts_prg_psi_t *p_prg = NULL;
849             vlc_list_t *p_list;
850
851             i_int = (int)va_arg( args, int );
852             p_list = (vlc_list_t *)va_arg( args, vlc_list_t * );
853             msg_Dbg( p_demux, "DEMUX_SET_GROUP %d %p", i_int, p_list );
854
855             if( p_sys->b_dvb_control && i_int > 0 && i_int != p_sys->i_dvb_program )
856             {
857                 int i_pmt_pid = -1;
858                 int i;
859
860                 /* Search pmt to be unselected */
861                 for( i = 0; i < p_sys->i_pmt; i++ )
862                 {
863                     ts_pid_t *pmt = p_sys->pmt[i];
864                     int i_prg;
865
866                     for( i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
867                     {
868                         if( pmt->psi->prg[i_prg]->i_number == p_sys->i_dvb_program )
869                         {
870                             i_pmt_pid = p_sys->pmt[i]->i_pid;
871                             break;
872                         }
873                     }
874                     if( i_pmt_pid > 0 ) break;
875                 }
876
877                 if( i_pmt_pid > 0 )
878                 {
879                     stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
880                                     ACCESS_SET_PRIVATE_ID_STATE, i_pmt_pid,
881                                     VLC_FALSE );
882                     /* All ES */
883                     for( i = 2; i < 8192; i++ )
884                     {
885                         ts_pid_t *pid = &p_sys->pid[i];
886                         int i_prg;
887
888                         if( !pid->b_valid || pid->psi ) continue;
889
890                         for( i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
891                         {
892                             if( pid->p_owner->prg[i_prg]->i_pid_pmt == i_pmt_pid && pid->es->id )
893                             {
894                                 /* We only remove es that aren't defined by extra pmt */
895                                 stream_Control( p_demux->s,
896                                                 STREAM_CONTROL_ACCESS,
897                                                 ACCESS_SET_PRIVATE_ID_STATE,
898                                                 i, VLC_FALSE );
899                                 break;
900                             }
901                         }
902                     }
903                 }
904
905                 /* select new program */
906                 p_sys->i_dvb_program = i_int;
907                 i_pmt_pid = -1;
908                 for( i = 0; i < p_sys->i_pmt; i++ )
909                 {
910                     ts_pid_t *pmt = p_sys->pmt[i];
911                     int i_prg;
912
913                     for( i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
914                     {
915                         if( pmt->psi->prg[i_prg]->i_number == i_int )
916                         {
917                             i_pmt_pid = p_sys->pmt[i]->i_pid;
918                             p_prg = p_sys->pmt[i]->psi->prg[i_prg];
919                             break;
920                         }
921                     }
922                     if( i_pmt_pid > 0 ) break;
923                 }
924                 if( i_pmt_pid > 0 )
925                 {
926                     stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
927                                     ACCESS_SET_PRIVATE_ID_STATE, i_pmt_pid,
928                                     VLC_TRUE );
929                     stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
930                                     ACCESS_SET_PRIVATE_ID_STATE, p_prg->i_pid_pcr,
931                                     VLC_TRUE );
932
933                     for( i = 2; i < 8192; i++ )
934                     {
935                         ts_pid_t *pid = &p_sys->pid[i];
936                         int i_prg;
937
938                         if( !pid->b_valid || pid->psi ) continue;
939
940                         for( i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
941                         {
942                             if( pid->p_owner->prg[i_prg]->i_pid_pmt == i_pmt_pid && pid->es->id )
943                             {
944                                 if ( pid->es->fmt.i_cat == VIDEO_ES && !i_vpid )
945                                     i_vpid = i;
946                                 if ( pid->es->fmt.i_cat == AUDIO_ES && !i_apid1 )
947                                     i_apid1 = i;
948                                 else if ( pid->es->fmt.i_cat == AUDIO_ES && !i_apid2 )
949                                     i_apid2 = i;
950                                 else if ( pid->es->fmt.i_cat == AUDIO_ES && !i_apid3 )
951                                     i_apid3 = i;
952
953                                 stream_Control( p_demux->s,
954                                                 STREAM_CONTROL_ACCESS,
955                                                 ACCESS_SET_PRIVATE_ID_STATE,
956                                                 i, VLC_TRUE );
957                                 break;
958                             }
959                         }
960                     }
961                 }
962             }
963             else
964             {
965                 p_sys->i_dvb_program = -1;
966                 p_sys->p_programs_list = p_list;
967             }
968             return VLC_SUCCESS;
969         }
970
971         case DEMUX_GET_FPS:
972         case DEMUX_SET_TIME:
973         default:
974             return VLC_EGENERIC;
975     }
976 }
977
978 static void PIDInit( ts_pid_t *pid, vlc_bool_t b_psi, ts_psi_t *p_owner )
979 {
980     vlc_bool_t b_old_valid = pid->b_valid;
981
982     pid->b_valid    = VLC_TRUE;
983     pid->i_cc       = 0xff;
984     pid->p_owner    = p_owner;
985     pid->i_owner_number = 0;
986
987     pid->extra_es   = NULL;
988     pid->i_extra_es = 0;
989
990     if( b_psi )
991     {
992         pid->es  = NULL;
993
994         if( !b_old_valid )
995         {
996             pid->psi = malloc( sizeof( ts_psi_t ) );
997             pid->psi->i_prg = 0;
998             pid->psi->prg   = NULL;
999             pid->psi->handle= NULL;
1000         }
1001         pid->psi->i_pat_version  = -1;
1002         if( p_owner )
1003         {
1004             ts_prg_psi_t *prg = malloc( sizeof( ts_prg_psi_t ) );
1005             /* PMT */
1006             prg->i_version  = -1;
1007             prg->i_number   = -1;
1008             prg->i_pid_pcr  = -1;
1009             prg->i_pid_pmt  = -1;
1010             prg->iod        = NULL;
1011             prg->handle     = NULL;
1012
1013             TAB_APPEND( pid->psi->i_prg, pid->psi->prg, prg );
1014         }
1015     }
1016     else
1017     {
1018         pid->psi = NULL;
1019         pid->es  = malloc( sizeof( ts_es_t ) );
1020
1021         es_format_Init( &pid->es->fmt, UNKNOWN_ES, 0 );
1022         pid->es->id      = NULL;
1023         pid->es->p_pes   = NULL;
1024         pid->es->i_pes_size= 0;
1025         pid->es->i_pes_gathered= 0;
1026         pid->es->pp_last = &pid->es->p_pes;
1027         pid->es->p_mpeg4desc = NULL;
1028         pid->es->b_gather = VLC_FALSE;
1029     }
1030 }
1031
1032 static void PIDClean( es_out_t *out, ts_pid_t *pid )
1033 {
1034     if( pid->psi )
1035     {
1036         int i;
1037
1038         if( pid->psi->handle ) dvbpsi_DetachPMT( pid->psi->handle );
1039         for( i = 0; i < pid->psi->i_prg; i++ )
1040         {
1041             if( pid->psi->prg[i]->iod )
1042                 IODFree( pid->psi->prg[i]->iod );
1043             if( pid->psi->prg[i]->handle )
1044                 dvbpsi_DetachPMT( pid->psi->prg[i]->handle );
1045             free( pid->psi->prg[i] );
1046         }
1047         if( pid->psi->prg ) free( pid->psi->prg );
1048         free( pid->psi );
1049     }
1050     else
1051     {
1052         int i;
1053
1054         if( pid->es->id )
1055             es_out_Del( out, pid->es->id );
1056
1057         if( pid->es->p_pes )
1058             block_ChainRelease( pid->es->p_pes );
1059
1060         es_format_Clean( &pid->es->fmt );
1061
1062         free( pid->es );
1063
1064         for( i = 0; i < pid->i_extra_es; i++ )
1065         {
1066             if( pid->extra_es[i]->id )
1067                 es_out_Del( out, pid->extra_es[i]->id );
1068
1069             if( pid->extra_es[i]->p_pes )
1070                 block_ChainRelease( pid->extra_es[i]->p_pes );
1071
1072             es_format_Clean( &pid->extra_es[i]->fmt );
1073
1074             free( pid->extra_es[i] );
1075         }
1076         if( pid->i_extra_es ) free( pid->extra_es );
1077     }
1078
1079     pid->b_valid = VLC_FALSE;
1080 }
1081
1082 /****************************************************************************
1083  * gathering stuff
1084  ****************************************************************************/
1085 static void ParsePES( demux_t *p_demux, ts_pid_t *pid )
1086 {
1087     block_t *p_pes = pid->es->p_pes;
1088     uint8_t header[30];
1089     int     i_pes_size = 0;
1090     int     i_skip = 0;
1091     mtime_t i_dts = -1;
1092     mtime_t i_pts = -1;
1093     mtime_t i_length = 0;
1094     int i_max;
1095
1096     /* remove the pes from pid */
1097     pid->es->p_pes = NULL;
1098     pid->es->i_pes_size= 0;
1099     pid->es->i_pes_gathered= 0;
1100     pid->es->pp_last = &pid->es->p_pes;
1101
1102     /* FIXME find real max size */
1103     i_max = block_ChainExtract( p_pes, header, 30 );
1104
1105
1106     if( header[0] != 0 || header[1] != 0 || header[2] != 1 )
1107     {
1108         if( !p_demux->p_sys->b_silent )
1109             msg_Warn( p_demux, "invalid header [0x%x:%x:%x:%x] (pid: %d)",
1110                       header[0], header[1],header[2],header[3], pid->i_pid );
1111         block_ChainRelease( p_pes );
1112         return;
1113     }
1114
1115     /* TODO check size */
1116     switch( header[3] )
1117     {
1118         case 0xBC:  /* Program stream map */
1119         case 0xBE:  /* Padding */
1120         case 0xBF:  /* Private stream 2 */
1121         case 0xB0:  /* ECM */
1122         case 0xB1:  /* EMM */
1123         case 0xFF:  /* Program stream directory */
1124         case 0xF2:  /* DSMCC stream */
1125         case 0xF8:  /* ITU-T H.222.1 type E stream */
1126             i_skip = 6;
1127             break;
1128         default:
1129             if( ( header[6]&0xC0 ) == 0x80 )
1130             {
1131                 /* mpeg2 PES */
1132                 i_skip = header[8] + 9;
1133
1134                 if( header[7]&0x80 )    /* has pts */
1135                 {
1136                     i_pts = ((mtime_t)(header[ 9]&0x0e ) << 29)|
1137                              (mtime_t)(header[10] << 22)|
1138                             ((mtime_t)(header[11]&0xfe) << 14)|
1139                              (mtime_t)(header[12] << 7)|
1140                              (mtime_t)(header[13] >> 1);
1141
1142                     if( header[7]&0x40 )    /* has dts */
1143                     {
1144                          i_dts = ((mtime_t)(header[14]&0x0e ) << 29)|
1145                                  (mtime_t)(header[15] << 22)|
1146                                 ((mtime_t)(header[16]&0xfe) << 14)|
1147                                  (mtime_t)(header[17] << 7)|
1148                                  (mtime_t)(header[18] >> 1);
1149                     }
1150                 }
1151             }
1152             else
1153             {
1154                 i_skip = 6;
1155                 while( i_skip < 23 && header[i_skip] == 0xff )
1156                 {
1157                     i_skip++;
1158                 }
1159                 if( i_skip == 23 )
1160                 {
1161                     msg_Err( p_demux, "too much MPEG-1 stuffing" );
1162                     block_ChainRelease( p_pes );
1163                     return;
1164                 }
1165                 if( ( header[i_skip] & 0xC0 ) == 0x40 )
1166                 {
1167                     i_skip += 2;
1168                 }
1169
1170                 if(  header[i_skip]&0x20 )
1171                 {
1172                      i_pts = ((mtime_t)(header[i_skip]&0x0e ) << 29)|
1173                               (mtime_t)(header[i_skip+1] << 22)|
1174                              ((mtime_t)(header[i_skip+2]&0xfe) << 14)|
1175                               (mtime_t)(header[i_skip+3] << 7)|
1176                               (mtime_t)(header[i_skip+4] >> 1);
1177
1178                     if( header[i_skip]&0x10 )    /* has dts */
1179                     {
1180                          i_dts = ((mtime_t)(header[i_skip+5]&0x0e ) << 29)|
1181                                   (mtime_t)(header[i_skip+6] << 22)|
1182                                  ((mtime_t)(header[i_skip+7]&0xfe) << 14)|
1183                                   (mtime_t)(header[i_skip+8] << 7)|
1184                                   (mtime_t)(header[i_skip+9] >> 1);
1185                          i_skip += 10;
1186                     }
1187                     else
1188                     {
1189                         i_skip += 5;
1190                     }
1191                 }
1192                 else
1193                 {
1194                     i_skip += 1;
1195                 }
1196             }
1197             break;
1198     }
1199
1200     if( pid->es->fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
1201         pid->es->fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
1202     {
1203         i_skip += 4;
1204     }
1205     else if( pid->es->fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
1206              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
1207              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
1208     {
1209         i_skip += 1;
1210     }
1211     else if( pid->es->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) &&
1212              pid->es->p_mpeg4desc )
1213     {
1214         decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
1215
1216         if( dcd->i_decoder_specific_info_len > 2 &&
1217             dcd->p_decoder_specific_info[0] == 0x10 &&
1218             ( dcd->p_decoder_specific_info[1]&0x10 ) )
1219         {
1220             /* display length */
1221             if( p_pes->i_buffer + 2 <= i_skip )
1222             {
1223                 i_length = GetWBE( &p_pes->p_buffer[i_skip] );
1224             }
1225
1226             i_skip += 2;
1227         }
1228         if( p_pes->i_buffer + 2 <= i_skip )
1229         {
1230             i_pes_size = GetWBE( &p_pes->p_buffer[i_skip] );
1231         }
1232         /* */
1233         i_skip += 2;
1234     }
1235
1236     /* skip header */
1237     while( p_pes && i_skip > 0 )
1238     {
1239         if( p_pes->i_buffer <= i_skip )
1240         {
1241             block_t *p_next = p_pes->p_next;
1242
1243             i_skip -= p_pes->i_buffer;
1244             block_Release( p_pes );
1245             p_pes = p_next;
1246         }
1247         else
1248         {
1249             p_pes->i_buffer -= i_skip;
1250             p_pes->p_buffer += i_skip;
1251             break;
1252         }
1253     }
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_DISCONTINUITY;
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;
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     p_iod->i_iod_label = IODGetByte( &i_data, &p_data );
1649     fprintf( stderr, "\n* iod_label:%d", p_iod->i_iod_label );
1650     fprintf( stderr, "\n* ===========" );
1651     fprintf( stderr, "\n* tag:0x%x", p_data[0] );
1652
1653     if( IODGetByte( &i_data, &p_data ) != 0x02 )
1654     {
1655         fprintf( stderr, "\n ERR: tag != 0x02" );
1656         return p_iod;
1657     }
1658
1659     i_iod_length = IODDescriptorLength( &i_data, &p_data );
1660     fprintf( stderr, "\n* length:%d", i_iod_length );
1661     if( i_iod_length > i_data )
1662     {
1663         i_iod_length = i_data;
1664     }
1665
1666     p_iod->i_od_id = ( IODGetByte( &i_data, &p_data ) << 2 );
1667     i_flags = IODGetByte( &i_data, &p_data );
1668     p_iod->i_od_id |= i_flags >> 6;
1669     b_url = ( i_flags >> 5  )&0x01;
1670
1671     fprintf( stderr, "\n* od_id:%d", p_iod->i_od_id );
1672     fprintf( stderr, "\n* url flag:%d", b_url );
1673     fprintf( stderr, "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
1674
1675     if( b_url )
1676     {
1677         p_iod->psz_url = IODGetURL( &i_data, &p_data );
1678         fprintf( stderr, "\n* url string:%s", p_iod->psz_url );
1679         fprintf( stderr, "\n*****************************\n" );
1680         return p_iod;
1681     }
1682     else
1683     {
1684         p_iod->psz_url = NULL;
1685     }
1686
1687     p_iod->i_ODProfileLevelIndication = IODGetByte( &i_data, &p_data );
1688     p_iod->i_sceneProfileLevelIndication = IODGetByte( &i_data, &p_data );
1689     p_iod->i_audioProfileLevelIndication = IODGetByte( &i_data, &p_data );
1690     p_iod->i_visualProfileLevelIndication = IODGetByte( &i_data, &p_data );
1691     p_iod->i_graphicsProfileLevelIndication = IODGetByte( &i_data, &p_data );
1692
1693     fprintf( stderr, "\n* ODProfileLevelIndication:%d", p_iod->i_ODProfileLevelIndication );
1694     fprintf( stderr, "\n* sceneProfileLevelIndication:%d", p_iod->i_sceneProfileLevelIndication );
1695     fprintf( stderr, "\n* audioProfileLevelIndication:%d", p_iod->i_audioProfileLevelIndication );
1696     fprintf( stderr, "\n* visualProfileLevelIndication:%d", p_iod->i_visualProfileLevelIndication );
1697     fprintf( stderr, "\n* graphicsProfileLevelIndication:%d", p_iod->i_graphicsProfileLevelIndication );
1698
1699
1700     while( i_data > 0 && i_es_index < 255)
1701     {
1702         int i_tag, i_length;
1703         int     i_data_sav;
1704         uint8_t *p_data_sav;
1705
1706         i_tag = IODGetByte( &i_data, &p_data );
1707         i_length = IODDescriptorLength( &i_data, &p_data );
1708
1709         i_data_sav = i_data;
1710         p_data_sav = p_data;
1711
1712         i_data = i_length;
1713
1714         switch( i_tag )
1715         {
1716             case 0x03:
1717                 {
1718 #define es_descr    p_iod->es_descr[i_es_index]
1719                     int i_decoderConfigDescr_length;
1720                     fprintf( stderr, "\n* - ES_Descriptor length:%d", i_length );
1721                     es_descr.b_ok = 1;
1722
1723                     es_descr.i_es_id = IODGetWord( &i_data, &p_data );
1724                     i_flags = IODGetByte( &i_data, &p_data );
1725                     es_descr.b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
1726                     b_url = ( i_flags >> 6 )&0x01;
1727                     es_descr.b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
1728                     es_descr.i_streamPriority = i_flags & 0x1f;
1729                     fprintf( stderr, "\n*   * streamDependenceFlag:%d", es_descr.b_streamDependenceFlag );
1730                     fprintf( stderr, "\n*   * OCRStreamFlag:%d", es_descr.b_OCRStreamFlag );
1731                     fprintf( stderr, "\n*   * streamPriority:%d", es_descr.i_streamPriority );
1732
1733                     if( es_descr.b_streamDependenceFlag )
1734                     {
1735                         es_descr.i_dependOn_es_id = IODGetWord( &i_data, &p_data );
1736                         fprintf( stderr, "\n*   * dependOn_es_id:%d", es_descr.i_dependOn_es_id );
1737                     }
1738
1739                     if( b_url )
1740                     {
1741                         es_descr.psz_url = IODGetURL( &i_data, &p_data );
1742                         fprintf( stderr, "\n* url string:%s", es_descr.psz_url );
1743                     }
1744                     else
1745                     {
1746                         es_descr.psz_url = NULL;
1747                     }
1748
1749                     if( es_descr.b_OCRStreamFlag )
1750                     {
1751                         es_descr.i_OCR_es_id = IODGetWord( &i_data, &p_data );
1752                         fprintf( stderr, "\n*   * OCR_es_id:%d", es_descr.i_OCR_es_id );
1753                     }
1754
1755                     if( IODGetByte( &i_data, &p_data ) != 0x04 )
1756                     {
1757                         fprintf( stderr, "\n* ERR missing DecoderConfigDescr" );
1758                         es_descr.b_ok = 0;
1759                         break;
1760                     }
1761                     i_decoderConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
1762
1763                     fprintf( stderr, "\n*   - DecoderConfigDesc length:%d", i_decoderConfigDescr_length );
1764 #define dec_descr   es_descr.dec_descr
1765                     dec_descr.i_objectTypeIndication = IODGetByte( &i_data, &p_data );
1766                     i_flags = IODGetByte( &i_data, &p_data );
1767                     dec_descr.i_streamType = i_flags >> 2;
1768                     dec_descr.b_upStream = ( i_flags >> 1 )&0x01;
1769                     dec_descr.i_bufferSizeDB = IODGet3Bytes( &i_data, &p_data );
1770                     dec_descr.i_maxBitrate = IODGetDWord( &i_data, &p_data );
1771                     dec_descr.i_avgBitrate = IODGetDWord( &i_data, &p_data );
1772                     fprintf( stderr, "\n*     * objectTypeIndication:0x%x", dec_descr.i_objectTypeIndication  );
1773                     fprintf( stderr, "\n*     * streamType:0x%x", dec_descr.i_streamType );
1774                     fprintf( stderr, "\n*     * upStream:%d", dec_descr.b_upStream );
1775                     fprintf( stderr, "\n*     * bufferSizeDB:%d", dec_descr.i_bufferSizeDB );
1776                     fprintf( stderr, "\n*     * maxBitrate:%d", dec_descr.i_maxBitrate );
1777                     fprintf( stderr, "\n*     * avgBitrate:%d", dec_descr.i_avgBitrate );
1778                     if( i_decoderConfigDescr_length > 13 && IODGetByte( &i_data, &p_data ) == 0x05 )
1779                     {
1780                         int i;
1781                         dec_descr.i_decoder_specific_info_len =
1782                             IODDescriptorLength( &i_data, &p_data );
1783                         if( dec_descr.i_decoder_specific_info_len > 0 )
1784                         {
1785                             dec_descr.p_decoder_specific_info =
1786                                 malloc( dec_descr.i_decoder_specific_info_len );
1787                         }
1788                         for( i = 0; i < dec_descr.i_decoder_specific_info_len; i++ )
1789                         {
1790                             dec_descr.p_decoder_specific_info[i] = IODGetByte( &i_data, &p_data );
1791                         }
1792                     }
1793                     else
1794                     {
1795                         dec_descr.i_decoder_specific_info_len = 0;
1796                         dec_descr.p_decoder_specific_info = NULL;
1797                     }
1798                 }
1799 #undef  dec_descr
1800 #define sl_descr    es_descr.sl_descr
1801                 {
1802                     int i_SLConfigDescr_length;
1803                     int i_predefined;
1804
1805                     if( IODGetByte( &i_data, &p_data ) != 0x06 )
1806                     {
1807                         fprintf( stderr, "\n* ERR missing SLConfigDescr" );
1808                         es_descr.b_ok = 0;
1809                         break;
1810                     }
1811                     i_SLConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
1812
1813                     fprintf( stderr, "\n*   - SLConfigDescr length:%d", i_SLConfigDescr_length );
1814                     i_predefined = IODGetByte( &i_data, &p_data );
1815                     fprintf( stderr, "\n*     * i_predefined:0x%x", i_predefined  );
1816                     switch( i_predefined )
1817                     {
1818                         case 0x01:
1819                             {
1820                                 sl_descr.b_useAccessUnitStartFlag   = 0;
1821                                 sl_descr.b_useAccessUnitEndFlag     = 0;
1822                                 sl_descr.b_useRandomAccessPointFlag = 0;
1823                                 //sl_descr.b_useRandomAccessUnitsOnlyFlag = 0;
1824                                 sl_descr.b_usePaddingFlag           = 0;
1825                                 sl_descr.b_useTimeStampsFlags       = 0;
1826                                 sl_descr.b_useIdleFlag              = 0;
1827                                 sl_descr.b_durationFlag     = 0;    // FIXME FIXME
1828                                 sl_descr.i_timeStampResolution      = 1000;
1829                                 sl_descr.i_OCRResolution    = 0;    // FIXME FIXME
1830                                 sl_descr.i_timeStampLength          = 32;
1831                                 sl_descr.i_OCRLength        = 0;    // FIXME FIXME
1832                                 sl_descr.i_AU_Length                = 0;
1833                                 sl_descr.i_instantBitrateLength= 0; // FIXME FIXME
1834                                 sl_descr.i_degradationPriorityLength= 0;
1835                                 sl_descr.i_AU_seqNumLength          = 0;
1836                                 sl_descr.i_packetSeqNumLength       = 0;
1837                                 if( sl_descr.b_durationFlag )
1838                                 {
1839                                     sl_descr.i_timeScale            = 0;    // FIXME FIXME
1840                                     sl_descr.i_accessUnitDuration   = 0;    // FIXME FIXME
1841                                     sl_descr.i_compositionUnitDuration= 0;    // FIXME FIXME
1842                                 }
1843                                 if( !sl_descr.b_useTimeStampsFlags )
1844                                 {
1845                                     sl_descr.i_startDecodingTimeStamp   = 0;    // FIXME FIXME
1846                                     sl_descr.i_startCompositionTimeStamp= 0;    // FIXME FIXME
1847                                 }
1848                             }
1849                             break;
1850                         default:
1851                             fprintf( stderr, "\n* ERR unsupported SLConfigDescr predefined" );
1852                             es_descr.b_ok = 0;
1853                             break;
1854                     }
1855                 }
1856                 break;
1857 #undef  sl_descr
1858 #undef  es_descr
1859             default:
1860                 fprintf( stderr, "\n* - OD tag:0x%x length:%d (Unsupported)", i_tag, i_length );
1861                 break;
1862         }
1863
1864         p_data = p_data_sav + i_length;
1865         i_data = i_data_sav - i_length;
1866         i_es_index++;
1867     }
1868
1869
1870     fprintf( stderr, "\n*****************************\n" );
1871     return p_iod;
1872 }
1873
1874 static void IODFree( iod_descriptor_t *p_iod )
1875 {
1876     int i;
1877
1878     if( p_iod->psz_url )
1879     {
1880         free( p_iod->psz_url );
1881         p_iod->psz_url = NULL;
1882         free( p_iod );
1883         return;
1884     }
1885
1886     for( i = 0; i < 255; i++ )
1887     {
1888 #define es_descr p_iod->es_descr[i]
1889         if( es_descr.b_ok )
1890         {
1891             if( es_descr.psz_url )
1892             {
1893                 free( es_descr.psz_url );
1894                 es_descr.psz_url = NULL;
1895             }
1896             else
1897             {
1898                 if( es_descr.dec_descr.p_decoder_specific_info != NULL )
1899                 {
1900                     free( es_descr.dec_descr.p_decoder_specific_info );
1901                     es_descr.dec_descr.p_decoder_specific_info = NULL;
1902                     es_descr.dec_descr.i_decoder_specific_info_len = 0;
1903                 }
1904             }
1905         }
1906         es_descr.b_ok = 0;
1907 #undef  es_descr
1908     }
1909     free( p_iod );
1910 }
1911
1912 /****************************************************************************
1913  ****************************************************************************
1914  ** libdvbpsi callbacks
1915  ****************************************************************************
1916  ****************************************************************************/
1917 static vlc_bool_t DVBProgramIsSelected( demux_t *p_demux, uint16_t i_pgrm )
1918 {
1919     demux_sys_t          *p_sys = p_demux->p_sys;
1920
1921     if ( !p_sys->b_dvb_control ) return VLC_FALSE;
1922     if ( p_sys->i_dvb_program == -1 && p_sys->p_programs_list == NULL )
1923         return VLC_TRUE;
1924     if ( p_sys->i_dvb_program == i_pgrm ) return VLC_TRUE;
1925
1926     if ( p_sys->p_programs_list != NULL )
1927     {
1928         int i;
1929         for ( i = 0; i < p_sys->p_programs_list->i_count; i++ )
1930         {
1931             if ( i_pgrm == p_sys->p_programs_list->p_values[i].i_int )
1932                 return VLC_TRUE;
1933         }
1934     }
1935     return VLC_FALSE;
1936 }
1937
1938 static void PMTCallBack( demux_t *p_demux, dvbpsi_pmt_t *p_pmt )
1939 {
1940     demux_sys_t          *p_sys = p_demux->p_sys;
1941     dvbpsi_descriptor_t  *p_dr;
1942     dvbpsi_pmt_es_t      *p_es;
1943
1944     ts_pid_t             *pmt = NULL;
1945     ts_prg_psi_t         *prg = NULL;
1946
1947     ts_pid_t             **pp_clean = NULL;
1948     int                  i_clean = 0, i;
1949
1950     msg_Dbg( p_demux, "PMTCallBack called" );
1951
1952     /* First find this PMT declared in PAT */
1953     for( i = 0; i < p_sys->i_pmt; i++ )
1954     {
1955         int i_prg;
1956         for( i_prg = 0; i_prg < p_sys->pmt[i]->psi->i_prg; i_prg++ )
1957         {
1958             if( p_sys->pmt[i]->psi->prg[i_prg]->i_number ==
1959                 p_pmt->i_program_number )
1960             {
1961                 pmt = p_sys->pmt[i];
1962                 prg = p_sys->pmt[i]->psi->prg[i_prg];
1963                 break;
1964             }
1965         }
1966         if( pmt ) break;
1967     }
1968
1969     if( pmt == NULL )
1970     {
1971         msg_Warn( p_demux, "unreferenced program (broken stream)" );
1972         dvbpsi_DeletePMT(p_pmt);
1973         return;
1974     }
1975
1976     if( prg->i_version != -1 &&
1977         ( !p_pmt->b_current_next || prg->i_version == p_pmt->i_version ) )
1978     {
1979         dvbpsi_DeletePMT( p_pmt );
1980         return;
1981     }
1982
1983     /* Clean this program (remove all es) */
1984     for( i = 0; i < 8192; i++ )
1985     {
1986         ts_pid_t *pid = &p_sys->pid[i];
1987
1988         if( pid->b_valid && pid->p_owner == pmt->psi &&
1989             pid->i_owner_number == prg->i_number && pid->psi == NULL )
1990         {
1991             TAB_APPEND( i_clean, pp_clean, pid );
1992         }
1993     }
1994     if( prg->iod )
1995     {
1996         IODFree( prg->iod );
1997         prg->iod = NULL;
1998     }
1999
2000     msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=%d",
2001              p_pmt->i_program_number, p_pmt->i_version, p_pmt->i_pcr_pid );
2002     prg->i_pid_pcr = p_pmt->i_pcr_pid;
2003     prg->i_version = p_pmt->i_version;
2004
2005     if( DVBProgramIsSelected( p_demux, prg->i_number ) )
2006     {
2007         /* Set demux filter */
2008         stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
2009                         ACCESS_SET_PRIVATE_ID_STATE, prg->i_pid_pcr,
2010                         VLC_TRUE );
2011     }
2012     else if ( p_sys->b_dvb_control )
2013     {
2014         msg_Warn( p_demux, "skipping program (not selected)" );
2015         dvbpsi_DeletePMT(p_pmt);
2016         return;
2017     }
2018
2019     /* Parse descriptor */
2020     for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
2021     {
2022         if( p_dr->i_tag == 0x1d )
2023         {
2024             /* We have found an IOD descriptor */
2025             msg_Dbg( p_demux, " * descriptor : IOD (0x1d)" );
2026
2027             prg->iod = IODNew( p_dr->i_length, p_dr->p_data );
2028         }
2029         else if( p_dr->i_tag == 0x9 )
2030         {
2031             uint16_t i_sysid = ((uint16_t)p_dr->p_data[0] << 8)
2032                                 | p_dr->p_data[1];
2033             msg_Dbg( p_demux, " * descriptor : CA (0x9) SysID 0x%x", i_sysid );
2034         }
2035         else
2036         {
2037             msg_Dbg( p_demux, " * descriptor : unknown (0x%x)", p_dr->i_tag );
2038         }
2039     }
2040
2041     for( p_es = p_pmt->p_first_es; p_es != NULL; p_es = p_es->p_next )
2042     {
2043         ts_pid_t tmp_pid, *old_pid = 0, *pid = &tmp_pid;
2044
2045         /* Find out if the PID was already declared */
2046         for( i = 0; i < i_clean; i++ )
2047         {
2048             if( pp_clean[i] == &p_sys->pid[p_es->i_pid] )
2049             {
2050                 old_pid = pp_clean[i];
2051                 break;
2052             }
2053         }
2054
2055         if( !old_pid && p_sys->pid[p_es->i_pid].b_valid )
2056         {
2057             msg_Warn( p_demux, "pmt error: pid=%d already defined",
2058                       p_es->i_pid );
2059             continue;
2060         }
2061
2062         PIDInit( pid, VLC_FALSE, pmt->psi );
2063         PIDFillFormat( pid, p_es->i_type );
2064         pid->i_owner_number = prg->i_number;
2065         pid->i_pid          = p_es->i_pid;
2066         pid->b_seen         = p_sys->pid[p_es->i_pid].b_seen;
2067
2068         if( p_es->i_type == 0x10 || p_es->i_type == 0x11 ||
2069             p_es->i_type == 0x12 )
2070         {
2071             /* MPEG-4 stream: search SL_DESCRIPTOR */
2072             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
2073
2074             while( p_dr && ( p_dr->i_tag != 0x1f ) ) p_dr = p_dr->p_next;
2075
2076             if( p_dr && p_dr->i_length == 2 )
2077             {
2078                 int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
2079
2080                 msg_Warn( p_demux, "found SL_descriptor es_id=%d", i_es_id );
2081
2082                 pid->es->p_mpeg4desc = NULL;
2083
2084                 for( i = 0; i < 255; i++ )
2085                 {
2086                     iod_descriptor_t *iod = prg->iod;
2087
2088                     if( iod->es_descr[i].b_ok &&
2089                         iod->es_descr[i].i_es_id == i_es_id )
2090                     {
2091                         pid->es->p_mpeg4desc = &iod->es_descr[i];
2092                         break;
2093                     }
2094                 }
2095             }
2096
2097             if( pid->es->p_mpeg4desc != NULL )
2098             {
2099                 decoder_config_descriptor_t *dcd =
2100                     &pid->es->p_mpeg4desc->dec_descr;
2101
2102                 if( dcd->i_streamType == 0x04 )    /* VisualStream */
2103                 {
2104                     pid->es->fmt.i_cat = VIDEO_ES;
2105                     switch( dcd->i_objectTypeIndication )
2106                     {
2107                     case 0x0B: /* mpeg4 sub */
2108                         pid->es->fmt.i_cat = SPU_ES;
2109                         pid->es->fmt.i_codec = VLC_FOURCC('s','u','b','t');
2110                         break;
2111
2112                     case 0x20: /* mpeg4 */
2113                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','v');
2114                         break;
2115                     case 0x60:
2116                     case 0x61:
2117                     case 0x62:
2118                     case 0x63:
2119                     case 0x64:
2120                     case 0x65: /* mpeg2 */
2121                         pid->es->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
2122                         break;
2123                     case 0x6a: /* mpeg1 */
2124                         pid->es->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
2125                         break;
2126                     case 0x6c: /* mpeg1 */
2127                         pid->es->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
2128                         break;
2129                     default:
2130                         pid->es->fmt.i_cat = UNKNOWN_ES;
2131                         break;
2132                     }
2133                 }
2134                 else if( dcd->i_streamType == 0x05 )    /* AudioStream */
2135                 {
2136                     pid->es->fmt.i_cat = AUDIO_ES;
2137                     switch( dcd->i_objectTypeIndication )
2138                     {
2139                     case 0x40: /* mpeg4 */
2140                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','a');
2141                         break;
2142                     case 0x66:
2143                     case 0x67:
2144                     case 0x68: /* mpeg2 aac */
2145                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','a');
2146                         break;
2147                     case 0x69: /* mpeg2 */
2148                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','g','a');
2149                         break;
2150                     case 0x6b: /* mpeg1 */
2151                         pid->es->fmt.i_codec = VLC_FOURCC('m','p','g','a');
2152                         break;
2153                     default:
2154                         pid->es->fmt.i_cat = UNKNOWN_ES;
2155                         break;
2156                     }
2157                 }
2158                 else
2159                 {
2160                     pid->es->fmt.i_cat = UNKNOWN_ES;
2161                 }
2162
2163                 if( pid->es->fmt.i_cat != UNKNOWN_ES )
2164                 {
2165                     pid->es->fmt.i_extra = dcd->i_decoder_specific_info_len;
2166                     if( pid->es->fmt.i_extra > 0 )
2167                     {
2168                         pid->es->fmt.p_extra = malloc( pid->es->fmt.i_extra );
2169                         memcpy( pid->es->fmt.p_extra,
2170                                 dcd->p_decoder_specific_info,
2171                                 pid->es->fmt.i_extra );
2172                     }
2173                 }
2174             }
2175         }
2176         else if( p_es->i_type == 0x06 )
2177         {
2178             dvbpsi_descriptor_t *p_dr;
2179
2180             for( p_dr = p_es->p_first_descriptor; p_dr != NULL;
2181                  p_dr = p_dr->p_next )
2182             {
2183                 msg_Dbg( p_demux, "  * es pid=%d type=%d dr->i_tag=0x%x",
2184                          p_es->i_pid, p_es->i_type, p_dr->i_tag );
2185
2186                 if( p_dr->i_tag == 0x6a )
2187                 {
2188                     pid->es->fmt.i_cat = AUDIO_ES;
2189                     pid->es->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
2190                 }
2191                 else if( p_dr->i_tag == 0x05 )
2192                 {
2193
2194                     /* DTS registration descriptor (ETSI TS 101 154 Annex F) */
2195                     pid->es->fmt.i_cat = AUDIO_ES;
2196                     pid->es->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
2197                 }
2198                 else if( p_dr->i_tag == 0x73 )
2199                 {
2200                     /* DTS audio descriptor (ETSI TS 101 154 Annex F) */
2201                     msg_Dbg( p_demux, "   * DTS audio descriptor not decoded" );
2202                     pid->es->fmt.i_cat = AUDIO_ES;
2203                     pid->es->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
2204                 }
2205                 else if( p_dr->i_tag == 0x45 )
2206                 {
2207                     msg_Dbg( p_demux, "   * VBI Data descriptor" );
2208                     pid->es->fmt.i_cat = SPU_ES;
2209                     pid->es->fmt.i_codec = VLC_FOURCC( 'v', 'b', 'i', 'd' );
2210                     pid->es->fmt.psz_description = strdup( "VBI Data" );
2211                     pid->es->fmt.i_extra = p_dr->i_length;
2212                     pid->es->fmt.p_extra = malloc( p_dr->i_length );
2213                     memcpy( pid->es->fmt.p_extra, p_dr->p_data,
2214                             p_dr->i_length );
2215                 }
2216                 else if( p_dr->i_tag == 0x46 )
2217                 {
2218                     msg_Dbg( p_demux, "  * VBI Teletext descriptor" );
2219                     pid->es->fmt.i_cat = SPU_ES;
2220                     pid->es->fmt.i_codec = VLC_FOURCC( 'v', 'b', 'i', 't' );
2221                     pid->es->fmt.psz_description = strdup( "VBI Teletext" );
2222                     pid->es->fmt.i_extra = p_dr->i_length;
2223                     pid->es->fmt.p_extra = malloc( p_dr->i_length );
2224                     memcpy( pid->es->fmt.p_extra, p_dr->p_data,
2225                             p_dr->i_length );
2226                 }
2227                 else if( p_dr->i_tag == 0x56 )
2228                 {
2229                     msg_Dbg( p_demux, "   * EBU Teletext descriptor" );
2230                     pid->es->fmt.i_cat = SPU_ES;
2231                     pid->es->fmt.i_codec = VLC_FOURCC( 't', 'e', 'l', 'x' );
2232                     pid->es->fmt.psz_description = strdup( "Teletext" );
2233                     pid->es->fmt.i_extra = p_dr->i_length;
2234                     pid->es->fmt.p_extra = malloc( p_dr->i_length );
2235                     memcpy( pid->es->fmt.p_extra, p_dr->p_data,
2236                             p_dr->i_length );
2237                 }
2238 #ifdef _DVBPSI_DR_59_H_
2239                 else if( p_dr->i_tag == 0x59 )
2240                 {
2241                     uint16_t n;
2242                     dvbpsi_subtitling_dr_t *sub;
2243
2244                     /* DVB subtitles */
2245                     pid->es->fmt.i_cat = SPU_ES;
2246                     pid->es->fmt.i_codec = VLC_FOURCC( 'd', 'v', 'b', 's' );
2247                     pid->es->fmt.i_group = p_pmt->i_program_number;
2248
2249                     sub = dvbpsi_DecodeSubtitlingDr( p_dr );
2250                     if( !sub ) continue;
2251
2252                     /* Each subtitle ES contains n languages,
2253                      * We are going to create n ES for the n tracks */
2254                     if( sub->i_subtitles_number > 0 )
2255                     {
2256                         pid->es->fmt.psz_language = malloc( 4 );
2257                         memcpy( pid->es->fmt.psz_language,
2258                                 sub->p_subtitle[0].i_iso6392_language_code, 3);
2259                         pid->es->fmt.psz_language[3] = 0;
2260
2261                         pid->es->fmt.subs.dvb.i_id =
2262                             sub->p_subtitle[0].i_composition_page_id;
2263                         /* Hack, FIXME */
2264                         pid->es->fmt.subs.dvb.i_id |=
2265                           ((int)sub->p_subtitle[0].i_ancillary_page_id << 16);
2266                     }
2267                     else pid->es->fmt.i_cat = UNKNOWN_ES;
2268
2269                     for( n = 1; n < sub->i_subtitles_number; n++ )
2270                     {
2271                         ts_es_t *p_es = malloc( sizeof( ts_es_t ) );
2272                         p_es->fmt = pid->es->fmt;
2273                         p_es->id = NULL;
2274                         p_es->p_pes = NULL;
2275                         p_es->i_pes_size = 0;
2276                         p_es->i_pes_gathered = 0;
2277                         p_es->pp_last = &p_es->p_pes;
2278                         p_es->p_mpeg4desc = NULL;
2279
2280                         p_es->fmt.psz_language = malloc( 4 );
2281                         memcpy( p_es->fmt.psz_language,
2282                                 sub->p_subtitle[n].i_iso6392_language_code, 3);
2283                         p_es->fmt.psz_language[3] = 0;
2284
2285                         p_es->fmt.subs.dvb.i_id =
2286                             sub->p_subtitle[n].i_composition_page_id;
2287                         /* Hack, FIXME */
2288                         pid->es->fmt.subs.dvb.i_id |=
2289                           ((int)sub->p_subtitle[n].i_ancillary_page_id << 16);
2290
2291                         TAB_APPEND( pid->i_extra_es, pid->extra_es, p_es );
2292                     }
2293                 }
2294 #endif /* _DVBPSI_DR_59_H_ */
2295             }
2296         }
2297         else if( p_es->i_type == 0xa0 )
2298         {
2299             /* MSCODEC sent by vlc */
2300             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;
2301
2302             while( p_dr && ( p_dr->i_tag != 0xa0 ) ) p_dr = p_dr->p_next;
2303
2304             if( p_dr && p_dr->i_length >= 8 )
2305             {
2306                 pid->es->fmt.i_cat = VIDEO_ES;
2307                 pid->es->fmt.i_codec =
2308                     VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
2309                                 p_dr->p_data[2], p_dr->p_data[3] );
2310                 pid->es->fmt.video.i_width =
2311                     ( p_dr->p_data[4] << 8 ) | p_dr->p_data[5];
2312                 pid->es->fmt.video.i_height =
2313                     ( p_dr->p_data[6] << 8 ) | p_dr->p_data[7];
2314                 pid->es->fmt.i_extra = 
2315                     (p_dr->p_data[8] << 8) | p_dr->p_data[9];
2316
2317                 if( pid->es->fmt.i_extra > 0 )
2318                 {
2319                     pid->es->fmt.p_extra = malloc( pid->es->fmt.i_extra );
2320                     memcpy( pid->es->fmt.p_extra, &p_dr->p_data[10],
2321                             pid->es->fmt.i_extra );
2322                 }
2323             }
2324             else
2325             {
2326                 msg_Warn( p_demux, "private MSCODEC (vlc) without bih private "
2327                           "descriptor" );
2328             }
2329             /* For such stream we will gather them ourself and don't launch a
2330              * packetizer.
2331              * Yes it's ugly but it's the only way to have DIV3 working */
2332             pid->es->fmt.b_packetized = VLC_TRUE;
2333         }
2334
2335         if( pid->es->fmt.i_cat == AUDIO_ES ||
2336             ( pid->es->fmt.i_cat == SPU_ES &&
2337               pid->es->fmt.i_codec != VLC_FOURCC('d','v','b','s') ) )
2338         {
2339             /* get language descriptor */
2340             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;
2341             while( p_dr && ( p_dr->i_tag != 0x0a ) ) p_dr = p_dr->p_next;
2342
2343             if( p_dr )
2344             {
2345                 dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
2346
2347                 if( p_decoded )
2348                 {
2349                     pid->es->fmt.psz_language = malloc( 4 );
2350                     memcpy( pid->es->fmt.psz_language,
2351                             p_decoded->i_iso_639_code, 3 );
2352                     pid->es->fmt.psz_language[3] = 0;
2353                 }
2354             }
2355         }
2356
2357         pid->es->fmt.i_group = p_pmt->i_program_number;
2358         if( pid->es->fmt.i_cat == UNKNOWN_ES )
2359         {
2360             msg_Dbg( p_demux, "  * es pid=%d type=%d *unknown*",
2361                      p_es->i_pid, p_es->i_type );
2362         }
2363         else if( !p_sys->b_udp_out )
2364         {
2365             msg_Dbg( p_demux, "  * es pid=%d type=%d fcc=%4.4s",
2366                      p_es->i_pid, p_es->i_type, (char*)&pid->es->fmt.i_codec );
2367
2368             if( p_sys->b_es_id_pid ) pid->es->fmt.i_id = p_es->i_pid;
2369
2370             /* Check if we can avoid restarting the ES */
2371             if( old_pid &&
2372                 pid->es->fmt.i_codec == old_pid->es->fmt.i_codec &&
2373                 pid->es->fmt.i_extra == old_pid->es->fmt.i_extra &&
2374                 pid->es->fmt.i_extra == 0 &&
2375                 pid->i_extra_es == old_pid->i_extra_es &&
2376                 ( ( !pid->es->fmt.psz_language &&
2377                     !old_pid->es->fmt.psz_language ) ||
2378                   ( pid->es->fmt.psz_language &&
2379                     old_pid->es->fmt.psz_language &&
2380                     !strcmp( pid->es->fmt.psz_language,
2381                              old_pid->es->fmt.psz_language ) ) ) )
2382             {
2383                 pid->es->id = old_pid->es->id;
2384                 old_pid->es->id = NULL;
2385                 for( i = 0; i < pid->i_extra_es; i++ )
2386                 {
2387                     pid->extra_es[i]->id = old_pid->extra_es[i]->id;
2388                     old_pid->extra_es[i]->id = NULL;
2389                 }
2390             }
2391             else
2392             {
2393                 if( old_pid )
2394                 {
2395                     PIDClean( p_demux->out, old_pid );
2396                     TAB_REMOVE( i_clean, pp_clean, old_pid );
2397                     old_pid = 0;
2398                 }
2399
2400                 pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
2401                 for( i = 0; i < pid->i_extra_es; i++ )
2402                 {
2403                     pid->extra_es[i]->id =
2404                         es_out_Add( p_demux->out, &pid->extra_es[i]->fmt );
2405                 }
2406             }
2407         }
2408
2409         /* Add ES to the list */
2410         if( old_pid )
2411         {
2412             PIDClean( p_demux->out, old_pid );
2413             TAB_REMOVE( i_clean, pp_clean, old_pid );
2414         }
2415         p_sys->pid[p_es->i_pid] = *pid;
2416
2417         for( p_dr = p_es->p_first_descriptor; p_dr != NULL;
2418              p_dr = p_dr->p_next )
2419         {
2420             if( p_dr->i_tag == 0x9 )
2421             {
2422                 uint16_t i_sysid = ((uint16_t)p_dr->p_data[0] << 8)
2423                                     | p_dr->p_data[1];
2424                 msg_Dbg( p_demux, "   * descriptor : CA (0x9) SysID 0x%x",
2425                          i_sysid );
2426             }
2427         }
2428
2429         if( DVBProgramIsSelected( p_demux, prg->i_number ) )
2430         {
2431             /* Set demux filter */
2432             stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
2433                             ACCESS_SET_PRIVATE_ID_STATE, p_es->i_pid,
2434                             VLC_TRUE );
2435         }
2436     }
2437
2438     if( DVBProgramIsSelected( p_demux, prg->i_number ) )
2439     {
2440         /* Set CAM descrambling */
2441         stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
2442                         ACCESS_SET_PRIVATE_ID_CA, p_pmt );
2443     }
2444     else
2445     {
2446         dvbpsi_DeletePMT( p_pmt );
2447     }
2448
2449     for ( i = 0; i < i_clean; i++ )
2450     {
2451         if( DVBProgramIsSelected( p_demux, prg->i_number ) )
2452         {
2453             stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
2454                             ACCESS_SET_PRIVATE_ID_STATE, pp_clean[i]->i_pid,
2455                             VLC_FALSE );
2456         }
2457
2458         PIDClean( p_demux->out, pp_clean[i] );
2459     }
2460     if( i_clean ) free( pp_clean );
2461 }
2462
2463 static void PATCallBack( demux_t *p_demux, dvbpsi_pat_t *p_pat )
2464 {
2465     demux_sys_t          *p_sys = p_demux->p_sys;
2466     dvbpsi_pat_program_t *p_program;
2467     ts_pid_t             *pat = &p_sys->pid[0];
2468     int                  i, j;
2469
2470     msg_Dbg( p_demux, "PATCallBack called" );
2471
2472     if( pat->psi->i_pat_version != -1 &&
2473         ( !p_pat->b_current_next ||
2474           p_pat->i_version == pat->psi->i_pat_version ) )
2475     {
2476         dvbpsi_DeletePAT( p_pat );
2477         return;
2478     }
2479
2480     msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d",
2481              p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
2482
2483     /* Clean old */
2484     if( p_sys->i_pmt > 0 )
2485     {
2486         int      i_pmt_rm = 0;
2487         ts_pid_t **pmt_rm = NULL;
2488
2489         /* Search pmt to be deleted */
2490         for( i = 0; i < p_sys->i_pmt; i++ )
2491         {
2492             ts_pid_t *pmt = p_sys->pmt[i];
2493             vlc_bool_t b_keep = VLC_FALSE;
2494
2495             for( p_program = p_pat->p_first_program; p_program != NULL;
2496                  p_program = p_program->p_next )
2497             {
2498                 if( p_program->i_pid == pmt->i_pid )
2499                 {
2500                     int i_prg;
2501                     for( i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
2502                     {
2503                         if( p_program->i_number ==
2504                             pmt->psi->prg[i_prg]->i_number )
2505                         {
2506                             b_keep = VLC_TRUE;
2507                             break;
2508                         }
2509                     }
2510                     if( b_keep ) break;
2511                 }
2512             }
2513
2514             if( !b_keep )
2515             {
2516                 TAB_APPEND( i_pmt_rm, pmt_rm, pmt );
2517             }
2518         }
2519
2520         /* Delete all ES attached to thoses PMT */
2521         for( i = 2; i < 8192; i++ )
2522         {
2523             ts_pid_t *pid = &p_sys->pid[i];
2524
2525             if( !pid->b_valid || pid->psi ) continue;
2526
2527             for( j = 0; j < i_pmt_rm; j++ )
2528             {
2529                 int i_prg;
2530                 for( i_prg = 0; i_prg < pid->p_owner->i_prg; i_prg++ )
2531                 {
2532                     /* We only remove es that aren't defined by extra pmt */
2533                     if( pid->p_owner->prg[i_prg]->i_pid_pmt !=
2534                         pmt_rm[j]->i_pid ) continue;
2535
2536                     if( p_sys->b_dvb_control && pid->es->id )
2537                     {
2538                         if( stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
2539                                             ACCESS_SET_PRIVATE_ID_STATE, i,
2540                                             VLC_FALSE ) )
2541                             p_sys->b_dvb_control = VLC_FALSE;
2542                     }
2543
2544                     PIDClean( p_demux->out, pid );
2545                     break;
2546                 }
2547
2548                 if( !pid->b_valid ) break;
2549             }
2550         }
2551
2552         /* Delete PMT pid */
2553         for( i = 0; i < i_pmt_rm; i++ )
2554         {
2555             if( p_sys->b_dvb_control )
2556             {
2557                 if( stream_Control( p_demux->s, STREAM_CONTROL_ACCESS,
2558                                     ACCESS_SET_PRIVATE_ID_STATE,
2559                                     pmt_rm[i]->i_pid, VLC_FALSE ) )
2560                     p_sys->b_dvb_control = VLC_FALSE;
2561             }
2562
2563             PIDClean( p_demux->out, &p_sys->pid[pmt_rm[i]->i_pid] );
2564             TAB_REMOVE( p_sys->i_pmt, p_sys->pmt, pmt_rm[i] );
2565         }
2566
2567         if( pmt_rm ) free( pmt_rm );
2568     }
2569
2570     /* now create programs */
2571     for( p_program = p_pat->p_first_program; p_program != NULL;
2572          p_program = p_program->p_next )
2573     {
2574         msg_Dbg( p_demux, "  * number=%d pid=%d", p_program->i_number,
2575                  p_program->i_pid );
2576         if( p_program->i_number != 0 )
2577         {
2578             ts_pid_t *pmt = &p_sys->pid[p_program->i_pid];
2579             vlc_bool_t b_add = VLC_TRUE;
2580
2581             if( pmt->b_valid )
2582             {
2583                 int i_prg;
2584                 for( i_prg = 0; i_prg < pmt->psi->i_prg; i_prg++ )
2585                 {
2586                     if( pmt->psi->prg[i_prg]->i_number == p_program->i_number )
2587                     {
2588                         b_add = VLC_FALSE;
2589                         break;
2590                     }
2591                 }
2592             }
2593             else
2594             {
2595                 TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
2596             }
2597
2598             if( b_add )
2599             {
2600                 PIDInit( pmt, VLC_TRUE, pat->psi );
2601                 pmt->psi->prg[pmt->psi->i_prg-1]->handle =
2602                     dvbpsi_AttachPMT( p_program->i_number,
2603                                       (dvbpsi_pmt_callback)PMTCallBack,
2604                                       p_demux );
2605                 pmt->psi->prg[pmt->psi->i_prg-1]->i_number =
2606                     p_program->i_number;
2607                 pmt->psi->prg[pmt->psi->i_prg-1]->i_pid_pmt =
2608                     p_program->i_pid;
2609
2610                 /* Now select PID at access level */
2611                 if( p_sys->b_dvb_control )
2612                 {
2613                     if( DVBProgramIsSelected( p_demux, p_program->i_number ) )
2614                     {
2615                         if( p_sys->i_dvb_program == 0 )
2616                             p_sys->i_dvb_program = p_program->i_number;
2617
2618                         if( stream_Control( p_demux->s, STREAM_CONTROL_ACCESS, ACCESS_SET_PRIVATE_ID_STATE, p_program->i_pid, VLC_TRUE ) )
2619                             p_sys->b_dvb_control = VLC_FALSE;
2620                     }
2621                     else
2622                     {
2623                         if( stream_Control( p_demux->s, STREAM_CONTROL_ACCESS, ACCESS_SET_PRIVATE_ID_STATE, p_program->i_pid, VLC_FALSE ) )
2624                             p_sys->b_dvb_control = VLC_FALSE;
2625                     }
2626                 }
2627             }
2628         }
2629     }
2630     pat->psi->i_pat_version = p_pat->i_version;
2631
2632     dvbpsi_DeletePAT( p_pat );
2633 }
2634