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