]> git.sesse.net Git - vlc/blob - modules/demux/ts.c
* ts: implemented the same detection than mpeg/ts.c
[vlc] / modules / demux / ts.c
1 /*****************************************************************************
2  * ts.c: Transport Stream input module for VLC.
3  *****************************************************************************
4  * Copyright (C) 2004 VideoLAN
5  * $Id: ts.c,v 1.10 2004/02/01 04:50:13 fenrir Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>                                      /* malloc(), free() */
28
29 #include <vlc/vlc.h>
30 #include <vlc/input.h>
31
32 #include "iso_lang.h"
33 #include "network.h"
34
35 #include "../mux/mpeg/csa.h"
36
37 /* Include dvbpsi headers */
38 #ifdef HAVE_DVBPSI_DR_H
39 #   include <dvbpsi/dvbpsi.h>
40 #   include <dvbpsi/descriptor.h>
41 #   include <dvbpsi/pat.h>
42 #   include <dvbpsi/pmt.h>
43 #   include <dvbpsi/dr.h>
44 #   include <dvbpsi/psi.h>
45 #else
46 #   include "dvbpsi.h"
47 #   include "descriptor.h"
48 #   include "tables/pat.h"
49 #   include "tables/pmt.h"
50 #   include "descriptors/dr.h"
51 #   include "psi.h"
52 #endif
53
54 /* TODO:
55  *  - XXX: do not mark options message to be translated, they are too osbcure for now ...
56  *  - test it
57  *  - ...
58  */
59
60 /*****************************************************************************
61  * Module descriptor
62  *****************************************************************************/
63 static int  Open    ( vlc_object_t * );
64 static void Close  ( vlc_object_t * );
65
66 vlc_module_begin();
67     set_description( _("ISO 13818-1 MPEG Transport Stream input - new" ) );
68     add_string( "ts-extra-pmt", NULL, NULL, "extra PMT", "allow user to specify an extra pmt (pmt_pid=pid:stream_type[,...])", VLC_TRUE );
69     add_bool( "ts-es-id-pid", 0, NULL, "set id of es to pid", "set id of es to pid", VLC_TRUE );
70     add_string( "ts-out", NULL, NULL, "fast udp streaming", "send TS to specific ip:port by udp (you must know what you are doing)", VLC_TRUE );
71     add_integer( "ts-out-mtu", 1500, NULL, "MTU for out mode", "MTU for out mode", VLC_TRUE );
72     add_string( "ts-csa-ck", NULL, NULL, "CSA ck", "CSA ck", VLC_TRUE );
73     set_capability( "demux2", 10 );
74     set_callbacks( Open, Close );
75     add_shortcut( "ts2" );
76 vlc_module_end();
77
78 /*****************************************************************************
79  * Local prototypes
80  *****************************************************************************/
81
82 typedef struct
83 {
84     uint8_t                 i_objectTypeIndication;
85     uint8_t                 i_streamType;
86     vlc_bool_t              b_upStream;
87     uint32_t                i_bufferSizeDB;
88     uint32_t                i_maxBitrate;
89     uint32_t                i_avgBitrate;
90
91     int                     i_decoder_specific_info_len;
92     uint8_t                 *p_decoder_specific_info;
93
94 } decoder_config_descriptor_t;
95
96 typedef struct
97 {
98     vlc_bool_t              b_useAccessUnitStartFlag;
99     vlc_bool_t              b_useAccessUnitEndFlag;
100     vlc_bool_t              b_useRandomAccessPointFlag;
101     vlc_bool_t              b_useRandomAccessUnitsOnlyFlag;
102     vlc_bool_t              b_usePaddingFlag;
103     vlc_bool_t              b_useTimeStampsFlags;
104     vlc_bool_t              b_useIdleFlag;
105     vlc_bool_t              b_durationFlag;
106     uint32_t                i_timeStampResolution;
107     uint32_t                i_OCRResolution;
108     uint8_t                 i_timeStampLength;
109     uint8_t                 i_OCRLength;
110     uint8_t                 i_AU_Length;
111     uint8_t                 i_instantBitrateLength;
112     uint8_t                 i_degradationPriorityLength;
113     uint8_t                 i_AU_seqNumLength;
114     uint8_t                 i_packetSeqNumLength;
115
116     uint32_t                i_timeScale;
117     uint16_t                i_accessUnitDuration;
118     uint16_t                i_compositionUnitDuration;
119
120     uint64_t                i_startDecodingTimeStamp;
121     uint64_t                i_startCompositionTimeStamp;
122
123 } sl_config_descriptor_t;
124
125 typedef struct
126 {
127     vlc_bool_t              b_ok;
128     uint16_t                i_es_id;
129
130     vlc_bool_t              b_streamDependenceFlag;
131     vlc_bool_t              b_OCRStreamFlag;
132     uint8_t                 i_streamPriority;
133
134     char                    *psz_url;
135
136     uint16_t                i_dependOn_es_id;
137     uint16_t                i_OCR_es_id;
138
139     decoder_config_descriptor_t    dec_descr;
140     sl_config_descriptor_t         sl_descr;
141 } es_mpeg4_descriptor_t;
142
143 typedef struct
144 {
145     uint8_t                i_iod_label;
146
147     /* IOD */
148     uint16_t                i_od_id;
149     char                    *psz_url;
150
151     uint8_t                 i_ODProfileLevelIndication;
152     uint8_t                 i_sceneProfileLevelIndication;
153     uint8_t                 i_audioProfileLevelIndication;
154     uint8_t                 i_visualProfileLevelIndication;
155     uint8_t                 i_graphicsProfileLevelIndication;
156
157     es_mpeg4_descriptor_t   es_descr[255];
158
159 } iod_descriptor_t;
160
161 typedef struct
162 {
163     int             i_version;
164     int             i_number;
165     int             i_pid_pcr;
166     dvbpsi_handle   handle;
167
168     /* IOD stuff (mpeg4) */
169     iod_descriptor_t *iod;
170
171 } ts_psi_t;
172
173 typedef struct
174 {
175     es_format_t  fmt;
176     es_out_id_t *id;
177     block_t     *p_pes;
178
179     es_mpeg4_descriptor_t *p_mpeg4desc;
180 } ts_es_t;
181
182 typedef struct
183 {
184     int         i_pid;
185
186     vlc_bool_t  b_seen;
187     vlc_bool_t  b_valid;
188     int         i_cc;   /* countinuity counter */
189
190     /* PSI owner (ie PMT -> PAT, ES -> PMT */
191     ts_psi_t   *p_owner;
192
193     /* */
194     ts_psi_t    *psi;
195     ts_es_t     *es;
196
197 } ts_pid_t;
198
199 struct demux_sys_t
200 {
201     /* how many TS packet we read at once */
202     int         i_ts_read;
203
204     /* All pid */
205     ts_pid_t    pid[8192];
206
207     /* All PMT */
208     int         i_pmt;
209     ts_pid_t    **pmt;
210
211     /* */
212     vlc_bool_t  b_es_id_pid;
213     csa_t       *csa;
214
215     vlc_bool_t  b_udp_out;
216     int         fd; /* udp socket */
217     uint8_t     *buffer;
218 };
219
220 static int Demux  ( demux_t *p_demux );
221 static int Control( demux_t *p_demux, int i_query, va_list args );
222
223
224 static void PIDInit ( ts_pid_t *pid, vlc_bool_t b_psi, ts_psi_t *p_owner );
225 static void PIDClean( es_out_t *out, ts_pid_t *pid );
226 static int  PIDFillFormat( ts_pid_t *pid, int i_stream_type );
227
228 static void PATCallBack( demux_t *, dvbpsi_pat_t * );
229 static void PMTCallBack( demux_t *p_demux, dvbpsi_pmt_t *p_pmt );
230
231 static inline int PIDGet( block_t *p )
232 {
233     return ( (p->p_buffer[1]&0x1f)<<8 )|p->p_buffer[2];
234 }
235
236 static vlc_bool_t GatherPES( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk );
237
238 static iod_descriptor_t *IODNew( int , uint8_t * );
239 static void              IODFree( iod_descriptor_t * );
240
241
242 /*****************************************************************************
243  * Open
244  *****************************************************************************/
245 static int Open( vlc_object_t *p_this )
246 {
247     demux_t     *p_demux = (demux_t*)p_this;
248     demux_sys_t *p_sys;
249
250     uint8_t     *p_peek;
251     int          i_peek;
252     int          i_sync;
253     int          i;
254
255     ts_pid_t     *pat;
256
257     vlc_value_t  val;
258
259     if( ( i_peek = stream_Peek( p_demux->s, &p_peek, 189 ) ) < 1 )
260     {
261         msg_Err( p_demux, "cannot peek" );
262         return VLC_EGENERIC;
263     }
264
265     /* Search first synch */
266     for( i_sync = 0; i_sync < i_peek; i_sync++ )
267     {
268         if( p_peek[i_sync] == 0x47 ) break;
269     }
270     if( i_sync >= i_peek )
271     {
272         if( strcmp( p_demux->psz_demux, "ts2" ) )
273         {
274             msg_Warn( p_demux, "TS module discarded" );
275             return VLC_EGENERIC;
276         }
277         msg_Warn( p_demux, "this does not look like a TS stream, continuing" );
278     }
279     if( strcmp( p_demux->psz_demux, "ts2" ) )
280     {
281         /* Check next 3 sync points */
282         i_peek = 188*3 + 1 + i_sync;
283         if( ( stream_Peek( p_demux->s, &p_peek, i_peek ) ) < i_peek )
284         {
285             msg_Err( p_demux, "cannot peek" );
286             return VLC_EGENERIC;
287         }
288         if( p_peek[i_sync+  188] != 0x47 || p_peek[i_sync+2*188] != 0x47 ||
289             p_peek[i_sync+3*188] != 0x47 )
290         {
291             msg_Warn( p_demux, "TS module discarded (lost sync)" );
292             return VLC_EGENERIC;
293         }
294     }
295
296     /* Fill p_demux field */
297     p_demux->pf_demux = Demux;
298     p_demux->pf_control = Control;
299     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
300     memset( p_sys, 0, sizeof( demux_sys_t ) );
301
302     /* Init p_sys field */
303     for( i = 0; i < 8192; i++ )
304     {
305         ts_pid_t *pid = &p_sys->pid[i];
306
307         pid->i_pid      = i;
308         pid->b_seen     = VLC_FALSE;
309         pid->b_valid    = VLC_FALSE;
310     }
311     p_sys->b_udp_out = VLC_FALSE;
312     p_sys->i_ts_read = 50;
313     p_sys->csa = NULL;
314
315     /* Init PAT handler */
316     pat = &p_sys->pid[0];
317     PIDInit( pat, VLC_TRUE, NULL );
318     pat->psi->handle = dvbpsi_AttachPAT( (dvbpsi_pat_callback)PATCallBack, p_demux );
319
320     /* Init PMT array */
321     p_sys->i_pmt = 0;
322     p_sys->pmt   = NULL;
323
324     /* Read config */
325     var_Create( p_demux, "ts-es-id-pid", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
326     var_Get( p_demux, "ts-es-id-pid", &val );
327     p_sys->b_es_id_pid = val.b_bool,
328
329     var_Create( p_demux, "ts-out", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
330     var_Get( p_demux, "ts-out", &val );
331     if( val.psz_string && *val.psz_string )
332     {
333         vlc_value_t mtu;
334         char *psz = strchr( val.psz_string, ':' );
335         int   i_port = 0;
336
337         p_sys->b_udp_out = VLC_TRUE;
338
339         if( psz )
340         {
341             *psz++ = '\0';
342             i_port = atoi( psz );
343         }
344         if( i_port <= 0 ) i_port  = 1234;
345         msg_Dbg( p_demux, "resend ts to '%s:%d'", val.psz_string, i_port );
346
347         p_sys->fd = net_OpenUDP( p_demux, "", 0, val.psz_string, i_port );
348         if( p_sys->fd < 0 )
349         {
350             msg_Err( p_demux, "failed to open udp socket, send disabled" );
351             p_sys->b_udp_out = VLC_FALSE;
352         }
353         else
354         {
355             var_Create( p_demux, "ts-out-mtu", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
356             var_Get( p_demux, "ts-out-mtu", &mtu );
357             p_sys->i_ts_read = mtu.i_int / 188;
358             if( p_sys->i_ts_read <= 0 )
359             {
360                 p_sys->i_ts_read = 1500 / 188;
361             }
362             p_sys->buffer = malloc( 188 * p_sys->i_ts_read );
363         }
364     }
365     if( val.psz_string )
366     {
367         free( val.psz_string );
368     }
369
370
371     /* We handle description of an extra PMT */
372     var_Create( p_demux, "ts-extra-pmt", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
373     var_Get( p_demux, "ts-extra-pmt", &val );
374     if( val.psz_string && strchr( val.psz_string, '=' ) != NULL )
375     {
376         char *psz = val.psz_string;
377         int  i_pid = strtol( psz, &psz, 0 );
378
379         if( i_pid >= 2 && i_pid < 8192 )
380         {
381             ts_pid_t *pmt = &p_sys->pid[i_pid];
382
383             msg_Dbg( p_demux, "extra pmt specified (pid=0x%x)", i_pid );
384             PIDInit( pmt, VLC_TRUE, NULL );
385             /* FIXME we should also ask for a number */
386             pmt->psi->handle = dvbpsi_AttachPMT( 1, (dvbpsi_pmt_callback)PMTCallBack, p_demux );
387             pmt->psi->i_number = 0; /* special one */
388
389             psz = strchr( psz, '=' ) + 1;   /* can't failed */
390             while( psz && *psz )
391             {
392                 char *psz_next = strchr( psz, ',' );
393                 int i_pid, i_stream_type;
394
395                 if( psz_next )
396                 {
397                     *psz_next++ = '\0';
398                 }
399
400                 i_pid = strtol( psz, &psz, 0 );
401                 if( *psz == ':' )
402                 {
403                     i_stream_type = strtol( psz + 1, &psz, 0 );
404                     if( i_pid >= 2 && i_pid < 8192 && !p_sys->pid[i_pid].b_valid )
405                     {
406                         ts_pid_t *pid = &p_sys->pid[i_pid];
407
408                         PIDInit( pid, VLC_FALSE, pmt->psi);
409                         if( pmt->psi->i_pid_pcr <= 0 )
410                         {
411                             pmt->psi->i_pid_pcr = i_pid;
412                         }
413                         PIDFillFormat( pid, i_stream_type);
414                         if( pid->es->fmt.i_cat != UNKNOWN_ES )
415                         {
416                             if( p_sys->b_es_id_pid )
417                             {
418                                 pid->es->fmt.i_id = i_pid;
419                             }
420                             msg_Dbg( p_demux, "  * es pid=0x%x type=0x%x fcc=%4.4s", i_pid, i_stream_type, (char*)&pid->es->fmt.i_codec );
421                             pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
422                         }
423                     }
424                 }
425                 psz = psz_next;
426             }
427         }
428     }
429     if( val.psz_string )
430     {
431         free( val.psz_string );
432     }
433
434     var_Create( p_demux, "ts-csa-ck", VLC_VAR_STRING | VLC_VAR_DOINHERIT );
435     var_Get( p_demux, "ts-csa-ck", &val );
436     if( val.psz_string && *val.psz_string )
437     {
438         char *psz = val.psz_string;
439         if( psz[0] == '0' && ( psz[1] == 'x' || psz[1] == 'X' ) )
440         {
441             psz += 2;
442         }
443         if( strlen( psz ) != 16 )
444         {
445             msg_Warn( p_demux, "invalid csa ck (it must be 16 chars long)" );
446         }
447         else
448         {
449             uint64_t i_ck = strtoll( psz, NULL, 16 );
450             uint8_t ck[8];
451             int     i;
452             for( i = 0; i < 8; i++ )
453             {
454                 ck[i] = ( i_ck >> ( 56 - 8*i) )&0xff;
455             }
456
457             msg_Dbg( p_demux, "using CSA scrambling with ck=%x:%x:%x:%x:%x:%x:%x:%x",
458                      ck[0], ck[1], ck[2], ck[3], ck[4], ck[5], ck[6], ck[7] );
459
460             p_sys->csa = csa_New();
461             csa_SetCW( p_sys->csa, ck, ck );
462         }
463     }
464     if( val.psz_string )
465     {
466         free( val.psz_string );
467     }
468
469
470     return VLC_SUCCESS;
471 }
472
473 /*****************************************************************************
474  * Close
475  *****************************************************************************/
476 static void Close( vlc_object_t *p_this )
477 {
478     demux_t     *p_demux = (demux_t*)p_this;
479     demux_sys_t *p_sys = p_demux->p_sys;
480
481     int          i;
482
483     msg_Dbg( p_demux, "pid list:" );
484     for( i = 0; i < 8192; i++ )
485     {
486         ts_pid_t *pid = &p_sys->pid[i];
487
488         if( pid->b_valid && pid->psi )
489         {
490             switch( pid->i_pid )
491             {
492                 case 0: /* PAT */
493                     dvbpsi_DetachPAT( pid->psi->handle );
494                     break;
495                 case 1: /* CAT */
496                     break;
497                 default:
498                     dvbpsi_DetachPMT( pid->psi->handle );
499                     if( pid->psi->iod )
500                     {
501                         IODFree( pid->psi->iod );
502                     }
503                     break;
504             }
505             free( pid->psi );
506         }
507         else if( pid->b_valid && pid->es )
508         {
509             if( pid->es->p_pes )
510             {
511                 block_ChainRelease( pid->es->p_pes );
512             }
513             free( pid->es );
514         }
515         if( pid->b_seen )
516         {
517             msg_Dbg( p_demux, "  - pid[0x%x] seen", pid->i_pid );
518         }
519     }
520
521     if( p_sys->b_udp_out )
522     {
523         net_Close( p_sys->fd );
524         free( p_sys->buffer );
525     }
526     if( p_sys->csa )
527     {
528         csa_Delete( p_sys->csa );
529     }
530
531     free( p_sys );
532 }
533
534
535 /*****************************************************************************
536  * Demux:
537  *****************************************************************************/
538 static int Demux( demux_t *p_demux )
539 {
540     demux_sys_t *p_sys = p_demux->p_sys;
541     int          i_pkt;
542
543     /* We read at most 100 TS packet or until a frame is completed */
544     for( i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
545     {
546         vlc_bool_t  b_frame = VLC_FALSE;
547         block_t     *p_pkt;
548         ts_pid_t    *p_pid;
549
550         /* Get a new TS packet */
551         if( ( p_pkt = stream_Block( p_demux->s, 188 ) ) == NULL )
552         {
553             msg_Dbg( p_demux, "eof ?" );
554             return 0;
555         }
556         if( p_pkt->p_buffer[0] != 0x47 )
557         {
558             msg_Warn( p_demux, "lost synchro" );
559             block_Release( p_pkt );
560
561             /* Resynch */
562             while( !p_demux->b_die )
563             {
564                 uint8_t    *p_peek;
565                 int         i_peek = stream_Peek( p_demux->s, &p_peek, 1880 );
566                 int         i_skip = 0;
567                 vlc_bool_t  b_ok = VLC_FALSE;
568
569                 if( i_peek < 189 )
570                 {
571                     msg_Dbg( p_demux, "eof ?" );
572                     return 0;
573                 }
574
575                 while( i_skip < i_peek - 188 )
576                 {
577                     if( p_peek[i_skip] == 0x47 && p_peek[i_skip+188] == 0x47 )
578                     {
579                         b_ok = VLC_TRUE;
580                         break;
581                     }
582                     i_skip++;
583                 }
584                 stream_Read( p_demux->s, NULL, i_skip );
585                 msg_Dbg( p_demux, "%d bytes of garbage", i_skip );
586                 if( b_ok )
587                 {
588                     break;
589                 }
590             }
591             if( ( p_pkt = stream_Block( p_demux->s, 188 ) ) == NULL )
592             {
593                 msg_Dbg( p_demux, "eof ?" );
594                 return 0;
595             }
596         }
597
598         if( p_sys->b_udp_out )
599         {
600             memcpy( &p_sys->buffer[i_pkt*188], p_pkt->p_buffer, 188 );
601         }
602
603         /* Parse the TS packet */
604         p_pid = &p_sys->pid[PIDGet( p_pkt )];
605
606         if( p_pid->b_valid )
607         {
608             if( p_pid->psi )
609             {
610                 dvbpsi_PushPacket( p_pid->psi->handle, p_pkt->p_buffer );
611                 block_Release( p_pkt );
612             }
613             else if( !p_sys->b_udp_out )
614             {
615                 b_frame = GatherPES( p_demux, p_pid, p_pkt );
616             }
617             else
618             {
619                 block_Release( p_pkt );
620             }
621         }
622         else
623         {
624             if( !p_pid->b_seen )
625             {
626                 msg_Dbg( p_demux, "pid[0x%x] unknown", p_pid->i_pid );
627             }
628             block_Release( p_pkt );
629         }
630         p_pid->b_seen = VLC_TRUE;
631
632         if( b_frame )
633         {
634             break;
635         }
636     }
637
638     if( p_sys->b_udp_out )
639     {
640         /* Send the complete block */
641         net_Write( p_demux, p_sys->fd, p_sys->buffer, p_sys->i_ts_read * 188 );
642     }
643
644     return 1;
645 }
646
647 /*****************************************************************************
648  * Control:
649  *****************************************************************************/
650 static int Control( demux_t *p_demux, int i_query, va_list args )
651 {
652     /* demux_sys_t *p_sys = p_demux->p_sys; */
653     double f, *pf;
654     int64_t i64;
655
656     switch( i_query )
657     {
658         case DEMUX_GET_POSITION:
659             pf = (double*) va_arg( args, double* );
660             i64 = stream_Size( p_demux->s );
661             if( i64 > 0 )
662             {
663                 *pf = (double)stream_Tell( p_demux->s ) / (double)i64;
664             }
665             else
666             {
667                 *pf = 0.0;
668             }
669             return VLC_SUCCESS;
670         case DEMUX_SET_POSITION:
671             f = (double) va_arg( args, double );
672             i64 = stream_Size( p_demux->s );
673
674             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
675             if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
676             {
677                 return VLC_EGENERIC;
678             }
679             return VLC_SUCCESS;
680 #if 0
681
682         case DEMUX_GET_TIME:
683             pi64 = (int64_t*)va_arg( args, int64_t * );
684             if( p_sys->i_time < 0 )
685             {
686                 *pi64 = 0;
687                 return VLC_EGENERIC;
688             }
689             *pi64 = p_sys->i_time;
690             return VLC_SUCCESS;
691
692 #if 0
693         case DEMUX_GET_LENGTH:
694             pi64 = (int64_t*)va_arg( args, int64_t * );
695             if( p_sys->i_mux_rate > 0 )
696             {
697                 *pi64 = (int64_t)1000000 * ( stream_Size( p_demux->s ) / 50 ) / p_sys->i_mux_rate;
698                 return VLC_SUCCESS;
699             }
700             *pi64 = 0;
701             return VLC_EGENERIC;
702
703         case DEMUX_SET_TIME:
704 #endif
705         case DEMUX_GET_FPS:
706             pf = (double*)va_arg( args, double * );
707             *pf = (double)1000000.0 / (double)p_sys->i_pcr_inc;
708             return VLC_SUCCESS;
709 #endif
710         default:
711             return VLC_EGENERIC;
712     }
713 }
714
715 static void PIDInit( ts_pid_t *pid, vlc_bool_t b_psi, ts_psi_t *p_owner )
716 {
717     pid->b_valid    = VLC_TRUE;
718     pid->i_cc       = 0xff;
719     pid->p_owner    = p_owner;
720
721     if( b_psi )
722     {
723         pid->psi = malloc( sizeof( ts_psi_t ) );
724         pid->es  = NULL;
725
726         pid->psi->i_version  = -1;
727         pid->psi->i_number   = -1;
728         pid->psi->i_pid_pcr  = -1;
729         pid->psi->handle     = NULL;
730         pid->psi->iod        = NULL;
731     }
732     else
733     {
734         pid->psi = NULL;
735         pid->es  = malloc( sizeof( ts_es_t ) );
736
737         es_format_Init( &pid->es->fmt, UNKNOWN_ES, 0 );
738         pid->es->id      = NULL;
739         pid->es->p_pes   = NULL;
740         pid->es->p_mpeg4desc = NULL;
741     }
742 }
743
744 static void PIDClean( es_out_t *out, ts_pid_t *pid )
745 {
746     if( pid->psi )
747     {
748         if( pid->psi->handle )
749         {
750             dvbpsi_DetachPMT( pid->psi->handle );
751         }
752         if( pid->psi->iod )
753         {
754             IODFree( pid->psi->iod );
755         }
756         free( pid->psi );
757     }
758     else
759     {
760         if( pid->es->id )
761         {
762             es_out_Del( out, pid->es->id );
763         }
764         if( pid->es->p_pes )
765         {
766             block_ChainRelease( pid->es->p_pes );
767         }
768         free( pid->es );
769     }
770     pid->b_valid = VLC_FALSE;
771 }
772
773 /****************************************************************************
774  * gathering stuff
775  ****************************************************************************/
776 static void ParsePES ( demux_t *p_demux, ts_pid_t *pid )
777 {
778     block_t *p_pes = pid->es->p_pes;
779     uint8_t header[30];
780     int     i_pes_size;
781     int     i_skip = 0;
782     mtime_t i_dts = -1;
783     mtime_t i_pts = -1;
784     int i_max;
785
786     /* remove the pes from pid */
787     pid->es->p_pes = NULL;
788
789     /* FIXME find real max size */
790     i_max = block_ChainExtract( p_pes, header, 30 );
791
792     if( header[0] != 0 || header[1] != 0 || header[2] != 1 )
793     {
794         msg_Warn( p_demux, "invalid header [0x%x:%x:%x:%x]", header[0], header[1],header[2],header[3] );
795         block_ChainRelease( p_pes );
796         return;
797     }
798
799     i_pes_size = (header[4] << 8)|header[5];
800
801     /* TODO check size */
802
803     switch( header[3] )
804     {
805         case 0xBC:  /* Program stream map */
806         case 0xBE:  /* Padding */
807         case 0xBF:  /* Private stream 2 */
808         case 0xB0:  /* ECM */
809         case 0xB1:  /* EMM */
810         case 0xFF:  /* Program stream directory */
811         case 0xF2:  /* DSMCC stream */
812         case 0xF8:  /* ITU-T H.222.1 type E stream */
813             i_skip = 6;
814             break;
815         default:
816             if( ( header[6]&0xC0 ) == 0x80 )
817             {
818                 /* mpeg2 PES */
819                 i_skip = header[8] + 9;
820
821                 if( header[7]&0x80 )    /* has pts */
822                 {
823                     i_pts = ((mtime_t)(header[ 9]&0x0e ) << 29)|
824                              (mtime_t)(header[10] << 22)|
825                             ((mtime_t)(header[11]&0xfe) << 14)|
826                              (mtime_t)(header[12] << 7)|
827                              (mtime_t)(header[12] >> 1);
828
829                     if( header[7]&0x40 )    /* has dts */
830                     {
831                          i_dts = ((mtime_t)(header[14]&0x0e ) << 29)|
832                                  (mtime_t)(header[15] << 22)|
833                                 ((mtime_t)(header[16]&0xfe) << 14)|
834                                  (mtime_t)(header[17] << 7)|
835                                  (mtime_t)(header[18] >> 1);
836                     }
837                 }
838             }
839             else
840             {
841                 i_skip = 6;
842                 while( i_skip < 23 && header[i_skip] == 0xff )
843                 {
844                     i_skip++;
845                 }
846                 if( i_skip == 23 )
847                 {
848                     msg_Err( p_demux, "too much MPEG-1 stuffing" );
849                     block_ChainRelease( p_pes );
850                     return;
851                 }
852                 if( ( header[i_skip] & 0xC0 ) == 0x40 )
853                 {
854                     i_skip += 2;
855                 }
856
857                 if(  header[i_skip]&0x20 )
858                 {
859                      p_pes->i_pts = ((mtime_t)(header[i_skip]&0x0e ) << 29)|
860                                      (mtime_t)(header[i_skip+1] << 22)|
861                                     ((mtime_t)(header[i_skip+2]&0xfe) << 14)|
862                                      (mtime_t)(header[i_skip+3] << 7)|
863                                      (mtime_t)(header[i_skip+4] >> 1);
864
865                     if( header[i_skip]&0x10 )    /* has dts */
866                     {
867                          p_pes->i_dts = ((mtime_t)(header[i_skip+5]&0x0e ) << 29)|
868                                          (mtime_t)(header[i_skip+6] << 22)|
869                                         ((mtime_t)(header[i_skip+7]&0xfe) << 14)|
870                                          (mtime_t)(header[i_skip+8] << 7)|
871                                          (mtime_t)(header[i_skip+9] >> 1);
872                          i_skip += 10;
873                     }
874                     else
875                     {
876                         i_skip += 5;
877                     }
878                 }
879                 else
880                 {
881                     i_skip += 1;
882                 }
883             }
884             break;
885     }
886
887     if( pid->es->fmt.i_codec == VLC_FOURCC( 'a', '5', '2', 'b' ) ||
888         pid->es->fmt.i_codec == VLC_FOURCC( 'd', 't', 's', 'b' ) )
889     {
890         i_skip += 4;
891     }
892     else if( pid->es->fmt.i_codec == VLC_FOURCC( 'l', 'p', 'c', 'b' ) ||
893              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'p', 'u', 'b' ) ||
894              pid->es->fmt.i_codec == VLC_FOURCC( 's', 'd', 'd', 'b' ) )
895     {
896         i_skip += 1;
897     }
898
899     /* skip header */
900     while( p_pes && i_skip > 0 )
901     {
902         if( p_pes->i_buffer <= i_skip )
903         {
904             block_t *p_next = p_pes->p_next;
905
906             i_skip -= p_pes->i_buffer;
907             block_Release( p_pes );
908             p_pes = p_next;
909         }
910         else
911         {
912             p_pes->i_buffer -= i_skip;
913             p_pes->p_buffer += i_skip;
914             break;
915         }
916     }
917     if( p_pes )
918     {
919         if( i_dts >= 0 )
920         {
921             p_pes->i_dts = i_dts * 100 / 9;
922         }
923         if( i_pts >= 0 )
924         {
925             p_pes->i_pts = i_pts * 100 / 9;
926         }
927
928         /* For mpeg4/mscodec we first gather the packet -> will make ffmpeg happier */
929         es_out_Send( p_demux->out, pid->es->id, block_ChainGather( p_pes ) );
930     }
931     else
932     {
933         msg_Warn( p_demux, "empty pes" );
934     }
935 };
936
937 static vlc_bool_t GatherPES( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
938 {
939     const uint8_t    *p = p_bk->p_buffer;
940     const vlc_bool_t  b_adaptation= p[3]&0x20;
941     const vlc_bool_t  b_payload   = p[3]&0x10;
942     const int         i_cc        = p[3]&0x0f;   /* continuity counter */
943     /* transport_scrambling_control is ignored */
944
945     int         i_skip = 0;
946     vlc_bool_t  i_ret   = VLC_FALSE;
947
948     int         i_diff;
949
950     //msg_Dbg( p_demux, "pid=0x%x unit_start=%d adaptation=%d payload=%d cc=0x%x", i_pid, b_unit_start, b_adaptation, b_payload, i_continuity_counter);
951     if( p[1]&0x80 )
952     {
953         msg_Dbg( p_demux, "transport_error_indicator set (pid=0x%x)", pid->i_pid );
954     }
955
956     if( p_demux->p_sys->csa )
957     {
958         csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer );
959     }
960
961     if( !b_adaptation )
962     {
963         i_skip = 4;
964     }
965     else
966     {
967         /* p[4] is adaptation length */
968         i_skip = 5 + p[4];
969         if( p[4] > 0 )
970         {
971             if( p[5]&0x80 )
972             {
973                 msg_Warn( p_demux, "discontinuity_indicator (pid=0x%x) ignored", pid->i_pid );
974             }
975         }
976     }
977     /* test continuity counter */
978     /* continuous when (one of this):
979         * diff == 1
980         * diff == 0 and payload == 0
981         * diff == 0 and duplicate packet (playload != 0) <- do we should test the content ?
982      */
983
984     i_diff = ( i_cc - pid->i_cc )&0x0f;
985     if( b_payload && i_diff == 1 )
986     {
987         pid->i_cc++;
988     }
989     else
990     {
991         if( pid->i_cc == 0xff )
992         {
993             msg_Warn( p_demux, "first packet for pid=0x%x cc=0x%x", pid->i_pid, i_cc );
994             pid->i_cc = i_cc;
995         }
996         else if( i_diff != 0 )
997         {
998             /* FIXME what to do when discontinuity_indicator is set ? */
999             msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x",
1000                       i_cc, ( pid->i_cc + 1 )&0x0f );
1001
1002             pid->i_cc = i_cc;
1003
1004             if( pid->es->p_pes )
1005             {
1006                 block_ChainRelease( pid->es->p_pes );
1007                 pid->es->p_pes = NULL;
1008             }
1009         }
1010     }
1011
1012     if( b_adaptation &&
1013         (p[5] & 0x10) && p[4]>=7 && pid->p_owner && pid->p_owner->i_pid_pcr == pid->i_pid )
1014     {
1015         mtime_t i_pcr;  /* 33 bits */
1016
1017         i_pcr = ( (mtime_t)p[6] << 25 ) |
1018                 ( (mtime_t)p[7] << 17 ) |
1019                 ( (mtime_t)p[8] << 9 ) |
1020                 ( (mtime_t)p[9] << 1 ) |
1021                 ( (mtime_t)p[10] >> 7 );
1022
1023         es_out_Control( p_demux->out, ES_OUT_SET_GROUP_PCR, (int)pid->p_owner->i_number, (int64_t)(i_pcr * 100 / 9) );
1024     }
1025
1026
1027     if( i_skip >= 188 || pid->es->id == NULL || p_demux->p_sys->b_udp_out )
1028     {
1029         block_Release( p_bk );
1030     }
1031     else
1032     {
1033         const vlc_bool_t b_unit_start= p[1]&0x40;
1034
1035         /* we have to gather it */
1036         p_bk->p_buffer += i_skip;
1037         p_bk->i_buffer -= i_skip;
1038
1039         if( b_unit_start )
1040         {
1041             if( pid->es->p_pes )
1042             {
1043                 ParsePES( p_demux, pid );
1044                 i_ret = VLC_TRUE;
1045             }
1046
1047             pid->es->p_pes = p_bk;
1048         }
1049         else
1050         {
1051             if( pid->es->p_pes == NULL )
1052             {
1053                 /* msg_Dbg( p_demux, "broken packet" ); */
1054                 block_Release( p_bk );
1055             }
1056             else
1057             {
1058                 /* TODO check if when have gather enough packet to form a PES (ie read PES size)*/
1059                 block_ChainAppend( &pid->es->p_pes, p_bk );
1060             }
1061         }
1062     }
1063
1064     return i_ret;
1065 }
1066
1067 static int PIDFillFormat( ts_pid_t *pid, int i_stream_type )
1068 {
1069     es_format_t *fmt = &pid->es->fmt;
1070
1071     switch( i_stream_type )
1072     {
1073         case 0x01:  /* MPEG-1 video */
1074         case 0x02:  /* MPEG-2 video */
1075         case 0x80:  /* MPEG-2 MOTO video */
1076             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'm', 'p', 'g', 'v' ) );
1077             break;
1078         case 0x03:  /* MPEG-1 audio */
1079         case 0x04:  /* MPEG-2 audio */
1080             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'm', 'p', 'g', 'a' ) );
1081             break;
1082         case 0x11:  /* MPEG4 (audio) */
1083         case 0x0f:  /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
1084             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'm', 'p', '4', 'a' ) );
1085             break;
1086         case 0x10:  /* MPEG4 (video) */
1087             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'm', 'p', '4', 'v' ) );
1088             break;
1089         case 0x1B:  /* H264 <- check transport syntax/needed descriptor */
1090             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'h', '2', '6', '4' ) );
1091             break;
1092
1093         case 0x81:  /* A52 (audio) */
1094             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', ' ' ) );
1095             break;
1096         case 0x82:  /* DVD_SPU (sub) */
1097             es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', ' ' ) );
1098             break;
1099         case 0x83:  /* LPCM (audio) */
1100             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'l', 'p', 'c', 'm' ) );
1101             break;
1102         case 0x84:  /* SDDS (audio) */
1103             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 's' ) );
1104             break;
1105         case 0x85:  /* DTS (audio) */
1106             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'd', 't', 's', ' ' ) );
1107             break;
1108
1109         case 0x91:  /* A52 vls (audio) */
1110             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
1111             break;
1112         case 0x92:  /* DVD_SPU vls (sub) */
1113             es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
1114             break;
1115         case 0x93:  /* LPCM vls (audio) */
1116             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'l', 'p', 'c', 'b' ) );
1117             break;
1118         case 0x94:  /* SDDS (audio) */
1119             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
1120             break;
1121
1122         case 0x06:  /* PES_PRIVATE  (fixed later) */
1123         case 0xa0:  /* MSCODEC vlc (video) (fixed later) */
1124         default:
1125             es_format_Init( fmt, UNKNOWN_ES, 0 );
1126             break;
1127     }
1128
1129     return fmt->i_cat == UNKNOWN_ES ? VLC_EGENERIC : VLC_SUCCESS ;
1130 }
1131
1132 /*****************************************************************************
1133  * MP4 specific functions (IOD parser)
1134  *****************************************************************************/
1135 static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
1136 {
1137     unsigned int i_b;
1138     unsigned int i_len = 0;
1139     do
1140     {
1141         i_b = **pp_data;
1142         (*pp_data)++;
1143         (*pi_data)--;
1144         i_len = ( i_len << 7 ) + ( i_b&0x7f );
1145
1146     } while( i_b&0x80 );
1147
1148     return( i_len );
1149 }
1150 static int IODGetByte( int *pi_data, uint8_t **pp_data )
1151 {
1152     if( *pi_data > 0 )
1153     {
1154         const int i_b = **pp_data;
1155         (*pp_data)++;
1156         (*pi_data)--;
1157         return( i_b );
1158     }
1159     return( 0 );
1160 }
1161 static int IODGetWord( int *pi_data, uint8_t **pp_data )
1162 {
1163     const int i1 = IODGetByte( pi_data, pp_data );
1164     const int i2 = IODGetByte( pi_data, pp_data );
1165     return( ( i1 << 8 ) | i2 );
1166 }
1167 static int IODGet3Bytes( int *pi_data, uint8_t **pp_data )
1168 {
1169     const int i1 = IODGetByte( pi_data, pp_data );
1170     const int i2 = IODGetByte( pi_data, pp_data );
1171     const int i3 = IODGetByte( pi_data, pp_data );
1172
1173     return( ( i1 << 16 ) | ( i2 << 8) | i3 );
1174 }
1175
1176 static uint32_t IODGetDWord( int *pi_data, uint8_t **pp_data )
1177 {
1178     const uint32_t i1 = IODGetWord( pi_data, pp_data );
1179     const uint32_t i2 = IODGetWord( pi_data, pp_data );
1180     return( ( i1 << 16 ) | i2 );
1181 }
1182
1183 static char* IODGetURL( int *pi_data, uint8_t **pp_data )
1184 {
1185     char *url;
1186     int i_url_len, i;
1187
1188     i_url_len = IODGetByte( pi_data, pp_data );
1189     url = malloc( i_url_len + 1 );
1190     for( i = 0; i < i_url_len; i++ )
1191     {
1192         url[i] = IODGetByte( pi_data, pp_data );
1193     }
1194     url[i_url_len] = '\0';
1195     return( url );
1196 }
1197
1198 static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
1199 {
1200     iod_descriptor_t *p_iod;
1201     int i;
1202     int i_es_index;
1203     uint8_t     i_flags;
1204     vlc_bool_t  b_url;
1205     int         i_iod_length;
1206
1207     p_iod = malloc( sizeof( iod_descriptor_t ) );
1208     memset( p_iod, 0, sizeof( iod_descriptor_t ) );
1209
1210     fprintf( stderr, "\n************ IOD ************" );
1211     for( i = 0; i < 255; i++ )
1212     {
1213         p_iod->es_descr[i].b_ok = 0;
1214     }
1215     i_es_index = 0;
1216
1217     if( i_data < 3 )
1218     {
1219         return p_iod;
1220     }
1221
1222     p_iod->i_iod_label = IODGetByte( &i_data, &p_data );
1223     fprintf( stderr, "\n* iod_label:%d", p_iod->i_iod_label );
1224     fprintf( stderr, "\n* ===========" );
1225     fprintf( stderr, "\n* tag:0x%x", p_data[0] );
1226
1227     if( IODGetByte( &i_data, &p_data ) != 0x02 )
1228     {
1229         fprintf( stderr, "\n ERR: tag != 0x02" );
1230         return p_iod;
1231     }
1232
1233     i_iod_length = IODDescriptorLength( &i_data, &p_data );
1234     fprintf( stderr, "\n* length:%d", i_iod_length );
1235     if( i_iod_length > i_data )
1236     {
1237         i_iod_length = i_data;
1238     }
1239
1240     p_iod->i_od_id = ( IODGetByte( &i_data, &p_data ) << 2 );
1241     i_flags = IODGetByte( &i_data, &p_data );
1242     p_iod->i_od_id |= i_flags >> 6;
1243     b_url = ( i_flags >> 5  )&0x01;
1244
1245     fprintf( stderr, "\n* od_id:%d", p_iod->i_od_id );
1246     fprintf( stderr, "\n* url flag:%d", b_url );
1247     fprintf( stderr, "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
1248
1249     if( b_url )
1250     {
1251         p_iod->psz_url = IODGetURL( &i_data, &p_data );
1252         fprintf( stderr, "\n* url string:%s", p_iod->psz_url );
1253         fprintf( stderr, "\n*****************************\n" );
1254         return p_iod;
1255     }
1256     else
1257     {
1258         p_iod->psz_url = NULL;
1259     }
1260
1261     p_iod->i_ODProfileLevelIndication = IODGetByte( &i_data, &p_data );
1262     p_iod->i_sceneProfileLevelIndication = IODGetByte( &i_data, &p_data );
1263     p_iod->i_audioProfileLevelIndication = IODGetByte( &i_data, &p_data );
1264     p_iod->i_visualProfileLevelIndication = IODGetByte( &i_data, &p_data );
1265     p_iod->i_graphicsProfileLevelIndication = IODGetByte( &i_data, &p_data );
1266
1267     fprintf( stderr, "\n* ODProfileLevelIndication:%d", p_iod->i_ODProfileLevelIndication );
1268     fprintf( stderr, "\n* sceneProfileLevelIndication:%d", p_iod->i_sceneProfileLevelIndication );
1269     fprintf( stderr, "\n* audioProfileLevelIndication:%d", p_iod->i_audioProfileLevelIndication );
1270     fprintf( stderr, "\n* visualProfileLevelIndication:%d", p_iod->i_visualProfileLevelIndication );
1271     fprintf( stderr, "\n* graphicsProfileLevelIndication:%d", p_iod->i_graphicsProfileLevelIndication );
1272
1273
1274     while( i_data > 0 && i_es_index < 255)
1275     {
1276         int i_tag, i_length;
1277         int     i_data_sav;
1278         uint8_t *p_data_sav;
1279
1280         i_tag = IODGetByte( &i_data, &p_data );
1281         i_length = IODDescriptorLength( &i_data, &p_data );
1282
1283         i_data_sav = i_data;
1284         p_data_sav = p_data;
1285
1286         i_data = i_length;
1287
1288         switch( i_tag )
1289         {
1290             case 0x03:
1291                 {
1292 #define es_descr    p_iod->es_descr[i_es_index]
1293                     int i_decoderConfigDescr_length;
1294                     fprintf( stderr, "\n* - ES_Descriptor length:%d", i_length );
1295                     es_descr.b_ok = 1;
1296
1297                     es_descr.i_es_id = IODGetWord( &i_data, &p_data );
1298                     i_flags = IODGetByte( &i_data, &p_data );
1299                     es_descr.b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
1300                     b_url = ( i_flags >> 6 )&0x01;
1301                     es_descr.b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
1302                     es_descr.i_streamPriority = i_flags & 0x1f;
1303                     fprintf( stderr, "\n*   * streamDependenceFlag:%d", es_descr.b_streamDependenceFlag );
1304                     fprintf( stderr, "\n*   * OCRStreamFlag:%d", es_descr.b_OCRStreamFlag );
1305                     fprintf( stderr, "\n*   * streamPriority:%d", es_descr.i_streamPriority );
1306
1307                     if( es_descr.b_streamDependenceFlag )
1308                     {
1309                         es_descr.i_dependOn_es_id = IODGetWord( &i_data, &p_data );
1310                         fprintf( stderr, "\n*   * dependOn_es_id:%d", es_descr.i_dependOn_es_id );
1311                     }
1312
1313                     if( b_url )
1314                     {
1315                         es_descr.psz_url = IODGetURL( &i_data, &p_data );
1316                         fprintf( stderr, "\n* url string:%s", es_descr.psz_url );
1317                     }
1318                     else
1319                     {
1320                         es_descr.psz_url = NULL;
1321                     }
1322
1323                     if( es_descr.b_OCRStreamFlag )
1324                     {
1325                         es_descr.i_OCR_es_id = IODGetWord( &i_data, &p_data );
1326                         fprintf( stderr, "\n*   * OCR_es_id:%d", es_descr.i_OCR_es_id );
1327                     }
1328
1329                     if( IODGetByte( &i_data, &p_data ) != 0x04 )
1330                     {
1331                         fprintf( stderr, "\n* ERR missing DecoderConfigDescr" );
1332                         es_descr.b_ok = 0;
1333                         break;
1334                     }
1335                     i_decoderConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
1336
1337                     fprintf( stderr, "\n*   - DecoderConfigDesc length:%d", i_decoderConfigDescr_length );
1338 #define dec_descr   es_descr.dec_descr
1339                     dec_descr.i_objectTypeIndication = IODGetByte( &i_data, &p_data );
1340                     i_flags = IODGetByte( &i_data, &p_data );
1341                     dec_descr.i_streamType = i_flags >> 2;
1342                     dec_descr.b_upStream = ( i_flags >> 1 )&0x01;
1343                     dec_descr.i_bufferSizeDB = IODGet3Bytes( &i_data, &p_data );
1344                     dec_descr.i_maxBitrate = IODGetDWord( &i_data, &p_data );
1345                     dec_descr.i_avgBitrate = IODGetDWord( &i_data, &p_data );
1346                     fprintf( stderr, "\n*     * objectTypeIndication:0x%x", dec_descr.i_objectTypeIndication  );
1347                     fprintf( stderr, "\n*     * streamType:0x%x", dec_descr.i_streamType );
1348                     fprintf( stderr, "\n*     * upStream:%d", dec_descr.b_upStream );
1349                     fprintf( stderr, "\n*     * bufferSizeDB:%d", dec_descr.i_bufferSizeDB );
1350                     fprintf( stderr, "\n*     * maxBitrate:%d", dec_descr.i_maxBitrate );
1351                     fprintf( stderr, "\n*     * avgBitrate:%d", dec_descr.i_avgBitrate );
1352                     if( i_decoderConfigDescr_length > 13 && IODGetByte( &i_data, &p_data ) == 0x05 )
1353                     {
1354                         int i;
1355                         dec_descr.i_decoder_specific_info_len =
1356                             IODDescriptorLength( &i_data, &p_data );
1357                         if( dec_descr.i_decoder_specific_info_len > 0 )
1358                         {
1359                             dec_descr.p_decoder_specific_info =
1360                                 malloc( dec_descr.i_decoder_specific_info_len );
1361                         }
1362                         for( i = 0; i < dec_descr.i_decoder_specific_info_len; i++ )
1363                         {
1364                             dec_descr.p_decoder_specific_info[i] = IODGetByte( &i_data, &p_data );
1365                         }
1366                     }
1367                     else
1368                     {
1369                         dec_descr.i_decoder_specific_info_len = 0;
1370                         dec_descr.p_decoder_specific_info = NULL;
1371                     }
1372                 }
1373 #undef  dec_descr
1374 #define sl_descr    es_descr.sl_descr
1375                 {
1376                     int i_SLConfigDescr_length;
1377                     int i_predefined;
1378
1379                     if( IODGetByte( &i_data, &p_data ) != 0x06 )
1380                     {
1381                         fprintf( stderr, "\n* ERR missing SLConfigDescr" );
1382                         es_descr.b_ok = 0;
1383                         break;
1384                     }
1385                     i_SLConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
1386
1387                     fprintf( stderr, "\n*   - SLConfigDescr length:%d", i_SLConfigDescr_length );
1388                     i_predefined = IODGetByte( &i_data, &p_data );
1389                     fprintf( stderr, "\n*     * i_predefined:0x%x", i_predefined  );
1390                     switch( i_predefined )
1391                     {
1392                         case 0x01:
1393                             {
1394                                 sl_descr.b_useAccessUnitStartFlag   = 0;
1395                                 sl_descr.b_useAccessUnitEndFlag     = 0;
1396                                 sl_descr.b_useRandomAccessPointFlag = 0;
1397                                 //sl_descr.b_useRandomAccessUnitsOnlyFlag = 0;
1398                                 sl_descr.b_usePaddingFlag           = 0;
1399                                 sl_descr.b_useTimeStampsFlags       = 0;
1400                                 sl_descr.b_useIdleFlag              = 0;
1401                                 sl_descr.b_durationFlag     = 0;    // FIXME FIXME
1402                                 sl_descr.i_timeStampResolution      = 1000;
1403                                 sl_descr.i_OCRResolution    = 0;    // FIXME FIXME
1404                                 sl_descr.i_timeStampLength          = 32;
1405                                 sl_descr.i_OCRLength        = 0;    // FIXME FIXME
1406                                 sl_descr.i_AU_Length                = 0;
1407                                 sl_descr.i_instantBitrateLength= 0; // FIXME FIXME
1408                                 sl_descr.i_degradationPriorityLength= 0;
1409                                 sl_descr.i_AU_seqNumLength          = 0;
1410                                 sl_descr.i_packetSeqNumLength       = 0;
1411                                 if( sl_descr.b_durationFlag )
1412                                 {
1413                                     sl_descr.i_timeScale            = 0;    // FIXME FIXME
1414                                     sl_descr.i_accessUnitDuration   = 0;    // FIXME FIXME
1415                                     sl_descr.i_compositionUnitDuration= 0;    // FIXME FIXME
1416                                 }
1417                                 if( !sl_descr.b_useTimeStampsFlags )
1418                                 {
1419                                     sl_descr.i_startDecodingTimeStamp   = 0;    // FIXME FIXME
1420                                     sl_descr.i_startCompositionTimeStamp= 0;    // FIXME FIXME
1421                                 }
1422                             }
1423                             break;
1424                         default:
1425                             fprintf( stderr, "\n* ERR unsupported SLConfigDescr predefined" );
1426                             es_descr.b_ok = 0;
1427                             break;
1428                     }
1429                 }
1430                 break;
1431 #undef  sl_descr
1432 #undef  es_descr
1433             default:
1434                 fprintf( stderr, "\n* - OD tag:0x%x length:%d (Unsupported)", i_tag, i_length );
1435                 break;
1436         }
1437
1438         p_data = p_data_sav + i_length;
1439         i_data = i_data_sav - i_length;
1440         i_es_index++;
1441     }
1442
1443
1444     fprintf( stderr, "\n*****************************\n" );
1445     return p_iod;
1446 }
1447
1448 static void IODFree( iod_descriptor_t *p_iod )
1449 {
1450     int i;
1451
1452     if( p_iod->psz_url )
1453     {
1454         free( p_iod->psz_url );
1455         p_iod->psz_url = NULL;
1456         free( p_iod );
1457         return;
1458     }
1459
1460     for( i = 0; i < 255; i++ )
1461     {
1462 #define es_descr p_iod->es_descr[i]
1463         if( es_descr.b_ok )
1464         {
1465             if( es_descr.psz_url )
1466             {
1467                 free( es_descr.psz_url );
1468                 es_descr.psz_url = NULL;
1469             }
1470             else
1471             {
1472                 if( es_descr.dec_descr.p_decoder_specific_info != NULL )
1473                 {
1474                     free( es_descr.dec_descr.p_decoder_specific_info );
1475                     es_descr.dec_descr.p_decoder_specific_info = NULL;
1476                     es_descr.dec_descr.i_decoder_specific_info_len = 0;
1477                 }
1478             }
1479         }
1480         es_descr.b_ok = 0;
1481 #undef  es_descr
1482     }
1483     free( p_iod );
1484 }
1485
1486 /****************************************************************************
1487  ****************************************************************************
1488  ** libdvbpsi callbacks
1489  ****************************************************************************
1490  ****************************************************************************/
1491 static void PMTCallBack( demux_t *p_demux, dvbpsi_pmt_t *p_pmt )
1492 {
1493     demux_sys_t          *p_sys = p_demux->p_sys;
1494     dvbpsi_descriptor_t  *p_dr;
1495     dvbpsi_pmt_es_t      *p_es;
1496
1497     ts_pid_t             *pmt = NULL;
1498     int                  i;
1499
1500     msg_Dbg( p_demux, "PMTCallBack called" );
1501     /* First find this PMT declared in PAT */
1502     for( i = 0; i < p_sys->i_pmt; i++ )
1503     {
1504         if( p_sys->pmt[i]->psi->i_number == p_pmt->i_program_number )
1505         {
1506             pmt = p_sys->pmt[i];
1507         }
1508     }
1509     if( pmt == NULL )
1510     {
1511         msg_Warn( p_demux, "unreferenced program (broken stream)" );
1512         dvbpsi_DeletePMT(p_pmt);
1513         return;
1514     }
1515
1516     if( pmt->psi->i_version != -1 && ( !p_pmt->b_current_next || pmt->psi->i_version == p_pmt->i_version ) )
1517     {
1518         dvbpsi_DeletePMT( p_pmt );
1519         return;
1520     }
1521
1522     /* Clean this program (remove all es) */
1523     for( i = 0; i < 8192; i++ )
1524     {
1525         ts_pid_t *pid = &p_sys->pid[i];
1526
1527         if( pid->b_valid && pid->p_owner == pmt->psi && pid->psi == NULL )
1528         {
1529             PIDClean( p_demux->out, pid );
1530         }
1531     }
1532     if( pmt->psi->iod )
1533     {
1534         IODFree( pmt->psi->iod );
1535         pmt->psi->iod = NULL;
1536     }
1537
1538     msg_Dbg( p_demux, "new PMT program number=%d version=%d pid_pcr=0x%x", p_pmt->i_program_number, p_pmt->i_version, p_pmt->i_pcr_pid );
1539     pmt->psi->i_pid_pcr = p_pmt->i_pcr_pid;
1540     pmt->psi->i_version = p_pmt->i_version;
1541
1542     /* Parse descriptor */
1543     for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
1544     {
1545         if( p_dr->i_tag == 0x1d )
1546         {
1547             /* We have found an IOD descriptor */
1548             msg_Warn( p_demux, "found IOD descriptor" );
1549
1550             pmt->psi->iod = IODNew( p_dr->i_length, p_dr->p_data );
1551         }
1552     }
1553
1554     for( p_es = p_pmt->p_first_es; p_es != NULL; p_es = p_es->p_next )
1555     {
1556         ts_pid_t *pid = &p_sys->pid[p_es->i_pid];
1557
1558         if( pid->b_valid )
1559         {
1560             msg_Warn( p_demux, "pmt error: pid=0x%x already defined", p_es->i_pid );
1561             continue;
1562         }
1563
1564         PIDInit( pid, VLC_FALSE, pmt->psi );
1565         PIDFillFormat( pid, p_es->i_type );
1566
1567         if( p_es->i_type == 0x10 || p_es->i_type == 0x11 )
1568         {
1569             /* MPEG-4 stream: search SL_DESCRIPTOR */
1570             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
1571
1572             while( p_dr && ( p_dr->i_tag != 0x1f ) ) p_dr = p_dr->p_next;
1573
1574             if( p_dr && p_dr->i_length == 2 )
1575             {
1576                 int i;
1577                 int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
1578
1579                 msg_Warn( p_demux, "found SL_descriptor es_id=%d", i_es_id );
1580
1581                 pid->es->p_mpeg4desc = NULL;
1582
1583                 for( i = 0; i < 255; i++ )
1584                 {
1585                     iod_descriptor_t *iod = pmt->psi->iod;
1586
1587                     if( iod->es_descr[i].b_ok &&
1588                         iod->es_descr[i].i_es_id == i_es_id )
1589                     {
1590                         pid->es->p_mpeg4desc = &iod->es_descr[i];
1591                         break;
1592                     }
1593                 }
1594             }
1595
1596             if( pid->es->p_mpeg4desc != NULL )
1597             {
1598                 decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
1599
1600                 if( dcd->i_streamType == 0x04 )    /* VisualStream */
1601                 {
1602                     pid->es->fmt.i_cat = VIDEO_ES;
1603                     switch( dcd->i_objectTypeIndication )
1604                     {
1605                         case 0x20:
1606                             pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','v');    // mpeg4
1607                             break;
1608                         case 0x60:
1609                         case 0x61:
1610                         case 0x62:
1611                         case 0x63:
1612                         case 0x64:
1613                         case 0x65:
1614                             pid->es->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );  // mpeg2
1615                             break;
1616                         case 0x6a:
1617                             pid->es->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );  // mpeg1
1618                             break;
1619                         case 0x6c:
1620                             pid->es->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );  // mpeg1
1621                             break;
1622
1623                         default:
1624                             pid->es->fmt.i_cat = UNKNOWN_ES;
1625                             break;
1626                     }
1627                 }
1628                 else if( dcd->i_streamType == 0x05 )    /* AudioStream */
1629                 {
1630                     pid->es->fmt.i_cat = AUDIO_ES;
1631                     switch( dcd->i_objectTypeIndication )
1632                     {
1633                         case 0x40:
1634                             pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','a');    // mpeg4
1635                             break;
1636                         case 0x66:
1637                         case 0x67:
1638                         case 0x68:
1639                             pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','a');// mpeg2 aac
1640                             break;
1641                         case 0x69:
1642                             pid->es->fmt.i_codec = VLC_FOURCC('m','p','g','a');    // mpeg2
1643                             break;
1644                         case 0x6b:
1645                             pid->es->fmt.i_codec = VLC_FOURCC('m','p','g','a');    // mpeg1
1646                             break;
1647                         default:
1648                             pid->es->fmt.i_cat = UNKNOWN_ES;
1649                             break;
1650                     }
1651                 }
1652                 else
1653                 {
1654                     pid->es->fmt.i_cat = UNKNOWN_ES;
1655                 }
1656
1657                 if( pid->es->fmt.i_cat != UNKNOWN_ES )
1658                 {
1659                     pid->es->fmt.i_extra = dcd->i_decoder_specific_info_len;
1660                     if( pid->es->fmt.i_extra > 0 )
1661                     {
1662                         pid->es->fmt.p_extra = malloc( pid->es->fmt.i_extra );
1663                         memcpy( pid->es->fmt.p_extra,
1664                                 dcd->p_decoder_specific_info,
1665                                 pid->es->fmt.i_extra );
1666                     }
1667                 }
1668             }
1669         }
1670         else if( p_es->i_type == 0x06 )
1671         {
1672             dvbpsi_descriptor_t *p_dr;
1673
1674             for( p_dr = p_es->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
1675             {
1676                 if( p_dr->i_tag == 0x6a )
1677                 {
1678                     pid->es->fmt.i_cat = AUDIO_ES;
1679                     pid->es->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1680                 }
1681 #ifdef _DVBPSI_DR_59_H_
1682                 else if( p_dr->i_tag == 0x59 )
1683                 {
1684                     /* DVB subtitle */
1685                     /* TODO */
1686                 }
1687 #endif
1688             }
1689         }
1690         else if( p_es->i_type == 0xa0 )
1691         {
1692             /* MSCODEC send by vlc */
1693             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
1694
1695             while( p_dr && ( p_dr->i_tag != 0xa0 ) ) p_dr = p_dr->p_next;
1696
1697             if( p_dr && p_dr->i_length >= 8 )
1698             {
1699                 pid->es->fmt.i_cat = VIDEO_ES;
1700                 pid->es->fmt.i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
1701                                                    p_dr->p_data[2], p_dr->p_data[3] );
1702                 pid->es->fmt.video.i_width = ( p_dr->p_data[4] << 8 )|p_dr->p_data[5];
1703                 pid->es->fmt.video.i_height= ( p_dr->p_data[6] << 8 )|p_dr->p_data[7];
1704                 pid->es->fmt.i_extra = (p_dr->p_data[8] << 8) | p_dr->p_data[9];
1705
1706                 if( pid->es->fmt.i_extra > 0 )
1707                 {
1708                     pid->es->fmt.p_extra = malloc( pid->es->fmt.i_extra );
1709                     memcpy( pid->es->fmt.p_extra, &p_dr->p_data[10], pid->es->fmt.i_extra );
1710                 }
1711             }
1712             else
1713             {
1714                 msg_Warn( p_demux, "private MSCODEC (vlc) without bih private descriptor" );
1715             }
1716         }
1717
1718         if( pid->es->fmt.i_cat == AUDIO_ES || pid->es->fmt.i_cat == SPU_ES )
1719         {
1720             /* get language descriptor */
1721             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;
1722             while( p_dr && ( p_dr->i_tag != 0x0a ) ) p_dr = p_dr->p_next;
1723
1724             if( p_dr )
1725             {
1726                 dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
1727
1728                 if( p_decoded )
1729                 {
1730                     pid->es->fmt.psz_language = malloc( 4 );
1731                     memcpy( pid->es->fmt.psz_language, p_decoded->i_iso_639_code, 3 );
1732                     pid->es->fmt.psz_language[3] = 0;
1733                 }
1734             }
1735         }
1736
1737         pid->es->fmt.i_group = p_pmt->i_program_number;
1738         if( pid->es->fmt.i_cat == UNKNOWN_ES )
1739         {
1740             msg_Dbg( p_demux, "  * es pid=0x%x type=0x%x *unknown*", p_es->i_pid, p_es->i_type );
1741         }
1742         else if( !p_sys->b_udp_out )
1743         {
1744             msg_Dbg( p_demux, "  * es pid=0x%x type=0x%x fcc=%4.4s", p_es->i_pid, p_es->i_type, (char*)&pid->es->fmt.i_codec );
1745             if( p_sys->b_es_id_pid )
1746             {
1747                 pid->es->fmt.i_id = p_es->i_pid;
1748             }
1749             pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
1750         }
1751     }
1752     dvbpsi_DeletePMT(p_pmt);
1753 }
1754
1755 static void PATCallBack( demux_t *p_demux, dvbpsi_pat_t *p_pat )
1756 {
1757     demux_sys_t          *p_sys = p_demux->p_sys;
1758     dvbpsi_pat_program_t *p_program;
1759     ts_pid_t             *pat = &p_sys->pid[0];
1760     int                  i;
1761
1762     msg_Dbg( p_demux, "PATCallBack called" );
1763
1764     if( pat->psi->i_version != -1 && ( !p_pat->b_current_next || p_pat->i_version == pat->psi->i_version ) )
1765     {
1766         dvbpsi_DeletePAT( p_pat );
1767         return;
1768     }
1769
1770     msg_Dbg( p_demux, "new PAT ts_id=0x%x version=%d current_next=%d", p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
1771
1772     /* Clean old */
1773     for( i = 2; i < 8192; i++ )
1774     {
1775         ts_pid_t *pid = &p_sys->pid[i];
1776
1777         if( pid->b_valid )
1778         {
1779             if( pid->psi )
1780             {
1781                 if( pid->p_owner == pat->psi )
1782                 {
1783                     PIDClean( p_demux->out, pid );
1784                     TAB_REMOVE( p_sys->i_pmt, p_sys->pmt, pid );
1785                 }
1786             }
1787             else if( pid->p_owner && pid->p_owner->i_number != 0 && pid->es->id )
1788             {
1789                 /* We only remove es that aren't defined by extra pmt */
1790                 PIDClean( p_demux->out, pid );
1791             }
1792         }
1793     }
1794
1795     /* now create programs */
1796     for( p_program = p_pat->p_first_program; p_program != NULL; p_program = p_program->p_next )
1797     {
1798         msg_Dbg( p_demux, "  * number=%d pid=0x%x", p_program->i_number, p_program->i_pid );
1799         if( p_program->i_number != 0 )
1800         {
1801             ts_pid_t *pmt = &p_sys->pid[p_program->i_pid];
1802
1803             PIDInit( pmt, VLC_TRUE, pat->psi );
1804             pmt->psi->handle = dvbpsi_AttachPMT( p_program->i_number, (dvbpsi_pmt_callback)PMTCallBack, p_demux );
1805             pmt->psi->i_number = p_program->i_number;
1806
1807             TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
1808         }
1809     }
1810     pat->psi->i_version = p_pat->i_version;
1811
1812     dvbpsi_DeletePAT( p_pat );
1813 }
1814