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