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