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