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