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