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