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