]> git.sesse.net Git - vlc/blob - modules/demux/ts.c
2b2d39472df6efa81960cd66a26a57474bea2667
[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                 pid->es->p_pes->i_flags |= BLOCK_FLAG_DISCONTINUITY;
1036             }
1037         }
1038     }
1039
1040     PCRHandle( p_demux, pid, p_bk );
1041
1042     if( i_skip >= 188 || pid->es->id == NULL || p_demux->p_sys->b_udp_out )
1043     {
1044         block_Release( p_bk );
1045     }
1046     else
1047     {
1048         const vlc_bool_t b_unit_start= p[1]&0x40;
1049
1050         /* we have to gather it */
1051         p_bk->p_buffer += i_skip;
1052         p_bk->i_buffer -= i_skip;
1053
1054         if( b_unit_start )
1055         {
1056             if( pid->es->p_pes )
1057             {
1058                 ParsePES( p_demux, pid );
1059                 i_ret = VLC_TRUE;
1060             }
1061
1062             pid->es->p_pes = p_bk;
1063         }
1064         else
1065         {
1066             if( pid->es->p_pes == NULL )
1067             {
1068                 /* msg_Dbg( p_demux, "broken packet" ); */
1069                 block_Release( p_bk );
1070             }
1071             else
1072             {
1073                 /* TODO check if when have gather enough packet to form a PES (ie read PES size)*/
1074                 block_ChainAppend( &pid->es->p_pes, p_bk );
1075             }
1076         }
1077     }
1078
1079     return i_ret;
1080 }
1081
1082 static int PIDFillFormat( ts_pid_t *pid, int i_stream_type )
1083 {
1084     es_format_t *fmt = &pid->es->fmt;
1085
1086     switch( i_stream_type )
1087     {
1088         case 0x01:  /* MPEG-1 video */
1089         case 0x02:  /* MPEG-2 video */
1090         case 0x80:  /* MPEG-2 MOTO video */
1091             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'm', 'p', 'g', 'v' ) );
1092             break;
1093         case 0x03:  /* MPEG-1 audio */
1094         case 0x04:  /* MPEG-2 audio */
1095             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'm', 'p', 'g', 'a' ) );
1096             break;
1097         case 0x11:  /* MPEG4 (audio) */
1098         case 0x0f:  /* ISO/IEC 13818-7 Audio with ADTS transport syntax */
1099             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'm', 'p', '4', 'a' ) );
1100             break;
1101         case 0x10:  /* MPEG4 (video) */
1102             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'm', 'p', '4', 'v' ) );
1103             break;
1104         case 0x1B:  /* H264 <- check transport syntax/needed descriptor */
1105             es_format_Init( fmt, VIDEO_ES, VLC_FOURCC( 'h', '2', '6', '4' ) );
1106             break;
1107
1108         case 0x81:  /* A52 (audio) */
1109             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', ' ' ) );
1110             break;
1111         case 0x82:  /* DVD_SPU (sub) */
1112             es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', ' ' ) );
1113             break;
1114         case 0x83:  /* LPCM (audio) */
1115             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'l', 'p', 'c', 'm' ) );
1116             break;
1117         case 0x84:  /* SDDS (audio) */
1118             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 's' ) );
1119             break;
1120         case 0x85:  /* DTS (audio) */
1121             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'd', 't', 's', ' ' ) );
1122             break;
1123
1124         case 0x91:  /* A52 vls (audio) */
1125             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', 'b' ) );
1126             break;
1127         case 0x92:  /* DVD_SPU vls (sub) */
1128             es_format_Init( fmt, SPU_ES, VLC_FOURCC( 's', 'p', 'u', 'b' ) );
1129             break;
1130         case 0x93:  /* LPCM vls (audio) */
1131             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 'l', 'p', 'c', 'b' ) );
1132             break;
1133         case 0x94:  /* SDDS (audio) */
1134             es_format_Init( fmt, AUDIO_ES, VLC_FOURCC( 's', 'd', 'd', 'b' ) );
1135             break;
1136
1137         case 0x06:  /* PES_PRIVATE  (fixed later) */
1138         case 0xa0:  /* MSCODEC vlc (video) (fixed later) */
1139         default:
1140             es_format_Init( fmt, UNKNOWN_ES, 0 );
1141             break;
1142     }
1143
1144     /* PES packets usually contain truncated frames */
1145     fmt->b_packetized = VLC_FALSE;
1146
1147     return fmt->i_cat == UNKNOWN_ES ? VLC_EGENERIC : VLC_SUCCESS ;
1148 }
1149
1150 /*****************************************************************************
1151  * MP4 specific functions (IOD parser)
1152  *****************************************************************************/
1153 static int  IODDescriptorLength( int *pi_data, uint8_t **pp_data )
1154 {
1155     unsigned int i_b;
1156     unsigned int i_len = 0;
1157     do
1158     {
1159         i_b = **pp_data;
1160         (*pp_data)++;
1161         (*pi_data)--;
1162         i_len = ( i_len << 7 ) + ( i_b&0x7f );
1163
1164     } while( i_b&0x80 );
1165
1166     return( i_len );
1167 }
1168 static int IODGetByte( int *pi_data, uint8_t **pp_data )
1169 {
1170     if( *pi_data > 0 )
1171     {
1172         const int i_b = **pp_data;
1173         (*pp_data)++;
1174         (*pi_data)--;
1175         return( i_b );
1176     }
1177     return( 0 );
1178 }
1179 static int IODGetWord( int *pi_data, uint8_t **pp_data )
1180 {
1181     const int i1 = IODGetByte( pi_data, pp_data );
1182     const int i2 = IODGetByte( pi_data, pp_data );
1183     return( ( i1 << 8 ) | i2 );
1184 }
1185 static int IODGet3Bytes( int *pi_data, uint8_t **pp_data )
1186 {
1187     const int i1 = IODGetByte( pi_data, pp_data );
1188     const int i2 = IODGetByte( pi_data, pp_data );
1189     const int i3 = IODGetByte( pi_data, pp_data );
1190
1191     return( ( i1 << 16 ) | ( i2 << 8) | i3 );
1192 }
1193
1194 static uint32_t IODGetDWord( int *pi_data, uint8_t **pp_data )
1195 {
1196     const uint32_t i1 = IODGetWord( pi_data, pp_data );
1197     const uint32_t i2 = IODGetWord( pi_data, pp_data );
1198     return( ( i1 << 16 ) | i2 );
1199 }
1200
1201 static char* IODGetURL( int *pi_data, uint8_t **pp_data )
1202 {
1203     char *url;
1204     int i_url_len, i;
1205
1206     i_url_len = IODGetByte( pi_data, pp_data );
1207     url = malloc( i_url_len + 1 );
1208     for( i = 0; i < i_url_len; i++ )
1209     {
1210         url[i] = IODGetByte( pi_data, pp_data );
1211     }
1212     url[i_url_len] = '\0';
1213     return( url );
1214 }
1215
1216 static iod_descriptor_t *IODNew( int i_data, uint8_t *p_data )
1217 {
1218     iod_descriptor_t *p_iod;
1219     int i;
1220     int i_es_index;
1221     uint8_t     i_flags;
1222     vlc_bool_t  b_url;
1223     int         i_iod_length;
1224
1225     p_iod = malloc( sizeof( iod_descriptor_t ) );
1226     memset( p_iod, 0, sizeof( iod_descriptor_t ) );
1227
1228     fprintf( stderr, "\n************ IOD ************" );
1229     for( i = 0; i < 255; i++ )
1230     {
1231         p_iod->es_descr[i].b_ok = 0;
1232     }
1233     i_es_index = 0;
1234
1235     if( i_data < 3 )
1236     {
1237         return p_iod;
1238     }
1239
1240     p_iod->i_iod_label = IODGetByte( &i_data, &p_data );
1241     fprintf( stderr, "\n* iod_label:%d", p_iod->i_iod_label );
1242     fprintf( stderr, "\n* ===========" );
1243     fprintf( stderr, "\n* tag:0x%x", p_data[0] );
1244
1245     if( IODGetByte( &i_data, &p_data ) != 0x02 )
1246     {
1247         fprintf( stderr, "\n ERR: tag != 0x02" );
1248         return p_iod;
1249     }
1250
1251     i_iod_length = IODDescriptorLength( &i_data, &p_data );
1252     fprintf( stderr, "\n* length:%d", i_iod_length );
1253     if( i_iod_length > i_data )
1254     {
1255         i_iod_length = i_data;
1256     }
1257
1258     p_iod->i_od_id = ( IODGetByte( &i_data, &p_data ) << 2 );
1259     i_flags = IODGetByte( &i_data, &p_data );
1260     p_iod->i_od_id |= i_flags >> 6;
1261     b_url = ( i_flags >> 5  )&0x01;
1262
1263     fprintf( stderr, "\n* od_id:%d", p_iod->i_od_id );
1264     fprintf( stderr, "\n* url flag:%d", b_url );
1265     fprintf( stderr, "\n* includeInlineProfileLevel flag:%d", ( i_flags >> 4 )&0x01 );
1266
1267     if( b_url )
1268     {
1269         p_iod->psz_url = IODGetURL( &i_data, &p_data );
1270         fprintf( stderr, "\n* url string:%s", p_iod->psz_url );
1271         fprintf( stderr, "\n*****************************\n" );
1272         return p_iod;
1273     }
1274     else
1275     {
1276         p_iod->psz_url = NULL;
1277     }
1278
1279     p_iod->i_ODProfileLevelIndication = IODGetByte( &i_data, &p_data );
1280     p_iod->i_sceneProfileLevelIndication = IODGetByte( &i_data, &p_data );
1281     p_iod->i_audioProfileLevelIndication = IODGetByte( &i_data, &p_data );
1282     p_iod->i_visualProfileLevelIndication = IODGetByte( &i_data, &p_data );
1283     p_iod->i_graphicsProfileLevelIndication = IODGetByte( &i_data, &p_data );
1284
1285     fprintf( stderr, "\n* ODProfileLevelIndication:%d", p_iod->i_ODProfileLevelIndication );
1286     fprintf( stderr, "\n* sceneProfileLevelIndication:%d", p_iod->i_sceneProfileLevelIndication );
1287     fprintf( stderr, "\n* audioProfileLevelIndication:%d", p_iod->i_audioProfileLevelIndication );
1288     fprintf( stderr, "\n* visualProfileLevelIndication:%d", p_iod->i_visualProfileLevelIndication );
1289     fprintf( stderr, "\n* graphicsProfileLevelIndication:%d", p_iod->i_graphicsProfileLevelIndication );
1290
1291
1292     while( i_data > 0 && i_es_index < 255)
1293     {
1294         int i_tag, i_length;
1295         int     i_data_sav;
1296         uint8_t *p_data_sav;
1297
1298         i_tag = IODGetByte( &i_data, &p_data );
1299         i_length = IODDescriptorLength( &i_data, &p_data );
1300
1301         i_data_sav = i_data;
1302         p_data_sav = p_data;
1303
1304         i_data = i_length;
1305
1306         switch( i_tag )
1307         {
1308             case 0x03:
1309                 {
1310 #define es_descr    p_iod->es_descr[i_es_index]
1311                     int i_decoderConfigDescr_length;
1312                     fprintf( stderr, "\n* - ES_Descriptor length:%d", i_length );
1313                     es_descr.b_ok = 1;
1314
1315                     es_descr.i_es_id = IODGetWord( &i_data, &p_data );
1316                     i_flags = IODGetByte( &i_data, &p_data );
1317                     es_descr.b_streamDependenceFlag = ( i_flags >> 7 )&0x01;
1318                     b_url = ( i_flags >> 6 )&0x01;
1319                     es_descr.b_OCRStreamFlag = ( i_flags >> 5 )&0x01;
1320                     es_descr.i_streamPriority = i_flags & 0x1f;
1321                     fprintf( stderr, "\n*   * streamDependenceFlag:%d", es_descr.b_streamDependenceFlag );
1322                     fprintf( stderr, "\n*   * OCRStreamFlag:%d", es_descr.b_OCRStreamFlag );
1323                     fprintf( stderr, "\n*   * streamPriority:%d", es_descr.i_streamPriority );
1324
1325                     if( es_descr.b_streamDependenceFlag )
1326                     {
1327                         es_descr.i_dependOn_es_id = IODGetWord( &i_data, &p_data );
1328                         fprintf( stderr, "\n*   * dependOn_es_id:%d", es_descr.i_dependOn_es_id );
1329                     }
1330
1331                     if( b_url )
1332                     {
1333                         es_descr.psz_url = IODGetURL( &i_data, &p_data );
1334                         fprintf( stderr, "\n* url string:%s", es_descr.psz_url );
1335                     }
1336                     else
1337                     {
1338                         es_descr.psz_url = NULL;
1339                     }
1340
1341                     if( es_descr.b_OCRStreamFlag )
1342                     {
1343                         es_descr.i_OCR_es_id = IODGetWord( &i_data, &p_data );
1344                         fprintf( stderr, "\n*   * OCR_es_id:%d", es_descr.i_OCR_es_id );
1345                     }
1346
1347                     if( IODGetByte( &i_data, &p_data ) != 0x04 )
1348                     {
1349                         fprintf( stderr, "\n* ERR missing DecoderConfigDescr" );
1350                         es_descr.b_ok = 0;
1351                         break;
1352                     }
1353                     i_decoderConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
1354
1355                     fprintf( stderr, "\n*   - DecoderConfigDesc length:%d", i_decoderConfigDescr_length );
1356 #define dec_descr   es_descr.dec_descr
1357                     dec_descr.i_objectTypeIndication = IODGetByte( &i_data, &p_data );
1358                     i_flags = IODGetByte( &i_data, &p_data );
1359                     dec_descr.i_streamType = i_flags >> 2;
1360                     dec_descr.b_upStream = ( i_flags >> 1 )&0x01;
1361                     dec_descr.i_bufferSizeDB = IODGet3Bytes( &i_data, &p_data );
1362                     dec_descr.i_maxBitrate = IODGetDWord( &i_data, &p_data );
1363                     dec_descr.i_avgBitrate = IODGetDWord( &i_data, &p_data );
1364                     fprintf( stderr, "\n*     * objectTypeIndication:0x%x", dec_descr.i_objectTypeIndication  );
1365                     fprintf( stderr, "\n*     * streamType:0x%x", dec_descr.i_streamType );
1366                     fprintf( stderr, "\n*     * upStream:%d", dec_descr.b_upStream );
1367                     fprintf( stderr, "\n*     * bufferSizeDB:%d", dec_descr.i_bufferSizeDB );
1368                     fprintf( stderr, "\n*     * maxBitrate:%d", dec_descr.i_maxBitrate );
1369                     fprintf( stderr, "\n*     * avgBitrate:%d", dec_descr.i_avgBitrate );
1370                     if( i_decoderConfigDescr_length > 13 && IODGetByte( &i_data, &p_data ) == 0x05 )
1371                     {
1372                         int i;
1373                         dec_descr.i_decoder_specific_info_len =
1374                             IODDescriptorLength( &i_data, &p_data );
1375                         if( dec_descr.i_decoder_specific_info_len > 0 )
1376                         {
1377                             dec_descr.p_decoder_specific_info =
1378                                 malloc( dec_descr.i_decoder_specific_info_len );
1379                         }
1380                         for( i = 0; i < dec_descr.i_decoder_specific_info_len; i++ )
1381                         {
1382                             dec_descr.p_decoder_specific_info[i] = IODGetByte( &i_data, &p_data );
1383                         }
1384                     }
1385                     else
1386                     {
1387                         dec_descr.i_decoder_specific_info_len = 0;
1388                         dec_descr.p_decoder_specific_info = NULL;
1389                     }
1390                 }
1391 #undef  dec_descr
1392 #define sl_descr    es_descr.sl_descr
1393                 {
1394                     int i_SLConfigDescr_length;
1395                     int i_predefined;
1396
1397                     if( IODGetByte( &i_data, &p_data ) != 0x06 )
1398                     {
1399                         fprintf( stderr, "\n* ERR missing SLConfigDescr" );
1400                         es_descr.b_ok = 0;
1401                         break;
1402                     }
1403                     i_SLConfigDescr_length = IODDescriptorLength( &i_data, &p_data );
1404
1405                     fprintf( stderr, "\n*   - SLConfigDescr length:%d", i_SLConfigDescr_length );
1406                     i_predefined = IODGetByte( &i_data, &p_data );
1407                     fprintf( stderr, "\n*     * i_predefined:0x%x", i_predefined  );
1408                     switch( i_predefined )
1409                     {
1410                         case 0x01:
1411                             {
1412                                 sl_descr.b_useAccessUnitStartFlag   = 0;
1413                                 sl_descr.b_useAccessUnitEndFlag     = 0;
1414                                 sl_descr.b_useRandomAccessPointFlag = 0;
1415                                 //sl_descr.b_useRandomAccessUnitsOnlyFlag = 0;
1416                                 sl_descr.b_usePaddingFlag           = 0;
1417                                 sl_descr.b_useTimeStampsFlags       = 0;
1418                                 sl_descr.b_useIdleFlag              = 0;
1419                                 sl_descr.b_durationFlag     = 0;    // FIXME FIXME
1420                                 sl_descr.i_timeStampResolution      = 1000;
1421                                 sl_descr.i_OCRResolution    = 0;    // FIXME FIXME
1422                                 sl_descr.i_timeStampLength          = 32;
1423                                 sl_descr.i_OCRLength        = 0;    // FIXME FIXME
1424                                 sl_descr.i_AU_Length                = 0;
1425                                 sl_descr.i_instantBitrateLength= 0; // FIXME FIXME
1426                                 sl_descr.i_degradationPriorityLength= 0;
1427                                 sl_descr.i_AU_seqNumLength          = 0;
1428                                 sl_descr.i_packetSeqNumLength       = 0;
1429                                 if( sl_descr.b_durationFlag )
1430                                 {
1431                                     sl_descr.i_timeScale            = 0;    // FIXME FIXME
1432                                     sl_descr.i_accessUnitDuration   = 0;    // FIXME FIXME
1433                                     sl_descr.i_compositionUnitDuration= 0;    // FIXME FIXME
1434                                 }
1435                                 if( !sl_descr.b_useTimeStampsFlags )
1436                                 {
1437                                     sl_descr.i_startDecodingTimeStamp   = 0;    // FIXME FIXME
1438                                     sl_descr.i_startCompositionTimeStamp= 0;    // FIXME FIXME
1439                                 }
1440                             }
1441                             break;
1442                         default:
1443                             fprintf( stderr, "\n* ERR unsupported SLConfigDescr predefined" );
1444                             es_descr.b_ok = 0;
1445                             break;
1446                     }
1447                 }
1448                 break;
1449 #undef  sl_descr
1450 #undef  es_descr
1451             default:
1452                 fprintf( stderr, "\n* - OD tag:0x%x length:%d (Unsupported)", i_tag, i_length );
1453                 break;
1454         }
1455
1456         p_data = p_data_sav + i_length;
1457         i_data = i_data_sav - i_length;
1458         i_es_index++;
1459     }
1460
1461
1462     fprintf( stderr, "\n*****************************\n" );
1463     return p_iod;
1464 }
1465
1466 static void IODFree( iod_descriptor_t *p_iod )
1467 {
1468     int i;
1469
1470     if( p_iod->psz_url )
1471     {
1472         free( p_iod->psz_url );
1473         p_iod->psz_url = NULL;
1474         free( p_iod );
1475         return;
1476     }
1477
1478     for( i = 0; i < 255; i++ )
1479     {
1480 #define es_descr p_iod->es_descr[i]
1481         if( es_descr.b_ok )
1482         {
1483             if( es_descr.psz_url )
1484             {
1485                 free( es_descr.psz_url );
1486                 es_descr.psz_url = NULL;
1487             }
1488             else
1489             {
1490                 if( es_descr.dec_descr.p_decoder_specific_info != NULL )
1491                 {
1492                     free( es_descr.dec_descr.p_decoder_specific_info );
1493                     es_descr.dec_descr.p_decoder_specific_info = NULL;
1494                     es_descr.dec_descr.i_decoder_specific_info_len = 0;
1495                 }
1496             }
1497         }
1498         es_descr.b_ok = 0;
1499 #undef  es_descr
1500     }
1501     free( p_iod );
1502 }
1503
1504 /****************************************************************************
1505  ****************************************************************************
1506  ** libdvbpsi callbacks
1507  ****************************************************************************
1508  ****************************************************************************/
1509 static void PMTCallBack( demux_t *p_demux, dvbpsi_pmt_t *p_pmt )
1510 {
1511     demux_sys_t          *p_sys = p_demux->p_sys;
1512     dvbpsi_descriptor_t  *p_dr;
1513     dvbpsi_pmt_es_t      *p_es;
1514
1515     ts_pid_t             *pmt = NULL;
1516     int                  i;
1517
1518     msg_Dbg( p_demux, "PMTCallBack called" );
1519     /* First find this PMT declared in PAT */
1520     for( i = 0; i < p_sys->i_pmt; i++ )
1521     {
1522         if( p_sys->pmt[i]->psi->i_number == p_pmt->i_program_number )
1523         {
1524             pmt = p_sys->pmt[i];
1525         }
1526     }
1527     if( pmt == NULL )
1528     {
1529         msg_Warn( p_demux, "unreferenced program (broken stream)" );
1530         dvbpsi_DeletePMT(p_pmt);
1531         return;
1532     }
1533
1534     if( pmt->psi->i_version != -1 && ( !p_pmt->b_current_next || pmt->psi->i_version == p_pmt->i_version ) )
1535     {
1536         dvbpsi_DeletePMT( p_pmt );
1537         return;
1538     }
1539
1540     /* Clean this program (remove all es) */
1541     for( i = 0; i < 8192; i++ )
1542     {
1543         ts_pid_t *pid = &p_sys->pid[i];
1544
1545         if( pid->b_valid && pid->p_owner == pmt->psi && pid->psi == NULL )
1546         {
1547             PIDClean( p_demux->out, pid );
1548         }
1549     }
1550     if( pmt->psi->iod )
1551     {
1552         IODFree( pmt->psi->iod );
1553         pmt->psi->iod = NULL;
1554     }
1555
1556     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 );
1557     pmt->psi->i_pid_pcr = p_pmt->i_pcr_pid;
1558     pmt->psi->i_version = p_pmt->i_version;
1559
1560     /* Parse descriptor */
1561     for( p_dr = p_pmt->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
1562     {
1563         if( p_dr->i_tag == 0x1d )
1564         {
1565             /* We have found an IOD descriptor */
1566             msg_Warn( p_demux, " * descriptor : IOD (0x1d)" );
1567
1568             pmt->psi->iod = IODNew( p_dr->i_length, p_dr->p_data );
1569         }
1570         else
1571         {
1572             msg_Dbg( p_demux, " * descriptor : unknown (0x%x)", p_dr->i_tag );
1573         }
1574     }
1575
1576     for( p_es = p_pmt->p_first_es; p_es != NULL; p_es = p_es->p_next )
1577     {
1578         ts_pid_t *pid = &p_sys->pid[p_es->i_pid];
1579
1580         if( pid->b_valid )
1581         {
1582             msg_Warn( p_demux, "pmt error: pid=0x%x already defined", p_es->i_pid );
1583             continue;
1584         }
1585
1586         PIDInit( pid, VLC_FALSE, pmt->psi );
1587         PIDFillFormat( pid, p_es->i_type );
1588
1589         if( p_es->i_type == 0x10 || p_es->i_type == 0x11 )
1590         {
1591             /* MPEG-4 stream: search SL_DESCRIPTOR */
1592             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
1593
1594             while( p_dr && ( p_dr->i_tag != 0x1f ) ) p_dr = p_dr->p_next;
1595
1596             if( p_dr && p_dr->i_length == 2 )
1597             {
1598                 int i;
1599                 int i_es_id = ( p_dr->p_data[0] << 8 ) | p_dr->p_data[1];
1600
1601                 msg_Warn( p_demux, "found SL_descriptor es_id=%d", i_es_id );
1602
1603                 pid->es->p_mpeg4desc = NULL;
1604
1605                 for( i = 0; i < 255; i++ )
1606                 {
1607                     iod_descriptor_t *iod = pmt->psi->iod;
1608
1609                     if( iod->es_descr[i].b_ok &&
1610                         iod->es_descr[i].i_es_id == i_es_id )
1611                     {
1612                         pid->es->p_mpeg4desc = &iod->es_descr[i];
1613                         break;
1614                     }
1615                 }
1616             }
1617
1618             if( pid->es->p_mpeg4desc != NULL )
1619             {
1620                 decoder_config_descriptor_t *dcd = &pid->es->p_mpeg4desc->dec_descr;
1621
1622                 if( dcd->i_streamType == 0x04 )    /* VisualStream */
1623                 {
1624                     pid->es->fmt.i_cat = VIDEO_ES;
1625                     switch( dcd->i_objectTypeIndication )
1626                     {
1627                         case 0x20:
1628                             pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','v');    // mpeg4
1629                             break;
1630                         case 0x60:
1631                         case 0x61:
1632                         case 0x62:
1633                         case 0x63:
1634                         case 0x64:
1635                         case 0x65:
1636                             pid->es->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );  // mpeg2
1637                             break;
1638                         case 0x6a:
1639                             pid->es->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );  // mpeg1
1640                             break;
1641                         case 0x6c:
1642                             pid->es->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );  // mpeg1
1643                             break;
1644
1645                         default:
1646                             pid->es->fmt.i_cat = UNKNOWN_ES;
1647                             break;
1648                     }
1649                 }
1650                 else if( dcd->i_streamType == 0x05 )    /* AudioStream */
1651                 {
1652                     pid->es->fmt.i_cat = AUDIO_ES;
1653                     switch( dcd->i_objectTypeIndication )
1654                     {
1655                         case 0x40:
1656                             pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','a');    // mpeg4
1657                             break;
1658                         case 0x66:
1659                         case 0x67:
1660                         case 0x68:
1661                             pid->es->fmt.i_codec = VLC_FOURCC('m','p','4','a');// mpeg2 aac
1662                             break;
1663                         case 0x69:
1664                             pid->es->fmt.i_codec = VLC_FOURCC('m','p','g','a');    // mpeg2
1665                             break;
1666                         case 0x6b:
1667                             pid->es->fmt.i_codec = VLC_FOURCC('m','p','g','a');    // mpeg1
1668                             break;
1669                         default:
1670                             pid->es->fmt.i_cat = UNKNOWN_ES;
1671                             break;
1672                     }
1673                 }
1674                 else
1675                 {
1676                     pid->es->fmt.i_cat = UNKNOWN_ES;
1677                 }
1678
1679                 if( pid->es->fmt.i_cat != UNKNOWN_ES )
1680                 {
1681                     pid->es->fmt.i_extra = dcd->i_decoder_specific_info_len;
1682                     if( pid->es->fmt.i_extra > 0 )
1683                     {
1684                         pid->es->fmt.p_extra = malloc( pid->es->fmt.i_extra );
1685                         memcpy( pid->es->fmt.p_extra,
1686                                 dcd->p_decoder_specific_info,
1687                                 pid->es->fmt.i_extra );
1688                     }
1689                 }
1690             }
1691         }
1692         else if( p_es->i_type == 0x06 )
1693         {
1694             dvbpsi_descriptor_t *p_dr;
1695
1696             for( p_dr = p_es->p_first_descriptor; p_dr != NULL; p_dr = p_dr->p_next )
1697             {
1698                 msg_Dbg( p_demux, "  * es pid=0x%x type=0x%x dr->i_tag=0x%x",
1699                          p_es->i_pid, p_es->i_type, p_dr->i_tag );
1700
1701                 if( p_dr->i_tag == 0x6a )
1702                 {
1703                     pid->es->fmt.i_cat = AUDIO_ES;
1704                     pid->es->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1705                 }
1706 #ifdef _DVBPSI_DR_59_H_
1707                 else if( p_dr->i_tag == 0x59 )
1708                 {
1709                     /* DVB subtitle */
1710                     /* TODO */
1711                 }
1712 #endif
1713             }
1714         }
1715         else if( p_es->i_type == 0xa0 )
1716         {
1717             /* MSCODEC send by vlc */
1718             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;;
1719
1720             while( p_dr && ( p_dr->i_tag != 0xa0 ) ) p_dr = p_dr->p_next;
1721
1722             if( p_dr && p_dr->i_length >= 8 )
1723             {
1724                 pid->es->fmt.i_cat = VIDEO_ES;
1725                 pid->es->fmt.i_codec = VLC_FOURCC( p_dr->p_data[0], p_dr->p_data[1],
1726                                                    p_dr->p_data[2], p_dr->p_data[3] );
1727                 pid->es->fmt.video.i_width = ( p_dr->p_data[4] << 8 )|p_dr->p_data[5];
1728                 pid->es->fmt.video.i_height= ( p_dr->p_data[6] << 8 )|p_dr->p_data[7];
1729                 pid->es->fmt.i_extra = (p_dr->p_data[8] << 8) | p_dr->p_data[9];
1730
1731                 if( pid->es->fmt.i_extra > 0 )
1732                 {
1733                     pid->es->fmt.p_extra = malloc( pid->es->fmt.i_extra );
1734                     memcpy( pid->es->fmt.p_extra, &p_dr->p_data[10], pid->es->fmt.i_extra );
1735                 }
1736             }
1737             else
1738             {
1739                 msg_Warn( p_demux, "private MSCODEC (vlc) without bih private descriptor" );
1740             }
1741             /* For such stream we will gather them ourself and don't launch a packetize,
1742              * Yes it's ugly but it's the only way to make DIV3 working */
1743             pid->es->fmt.b_packetized = VLC_TRUE;
1744         }
1745
1746         if( pid->es->fmt.i_cat == AUDIO_ES || pid->es->fmt.i_cat == SPU_ES )
1747         {
1748             /* get language descriptor */
1749             dvbpsi_descriptor_t *p_dr = p_es->p_first_descriptor;
1750             while( p_dr && ( p_dr->i_tag != 0x0a ) ) p_dr = p_dr->p_next;
1751
1752             if( p_dr )
1753             {
1754                 dvbpsi_iso639_dr_t *p_decoded = dvbpsi_DecodeISO639Dr( p_dr );
1755
1756                 if( p_decoded )
1757                 {
1758                     pid->es->fmt.psz_language = malloc( 4 );
1759                     memcpy( pid->es->fmt.psz_language, p_decoded->i_iso_639_code, 3 );
1760                     pid->es->fmt.psz_language[3] = 0;
1761                 }
1762             }
1763         }
1764
1765         pid->es->fmt.i_group = p_pmt->i_program_number;
1766         if( pid->es->fmt.i_cat == UNKNOWN_ES )
1767         {
1768             msg_Dbg( p_demux, "  * es pid=0x%x type=0x%x *unknown*", p_es->i_pid, p_es->i_type );
1769         }
1770         else if( !p_sys->b_udp_out )
1771         {
1772             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 );
1773             if( p_sys->b_es_id_pid )
1774             {
1775                 pid->es->fmt.i_id = p_es->i_pid;
1776             }
1777             pid->es->id = es_out_Add( p_demux->out, &pid->es->fmt );
1778         }
1779     }
1780     dvbpsi_DeletePMT(p_pmt);
1781 }
1782
1783 static void PATCallBack( demux_t *p_demux, dvbpsi_pat_t *p_pat )
1784 {
1785     demux_sys_t          *p_sys = p_demux->p_sys;
1786     dvbpsi_pat_program_t *p_program;
1787     ts_pid_t             *pat = &p_sys->pid[0];
1788     int                  i;
1789
1790     msg_Dbg( p_demux, "PATCallBack called" );
1791
1792     if( pat->psi->i_version != -1 &&
1793         ( !p_pat->b_current_next || p_pat->i_version == pat->psi->i_version ) )
1794     {
1795         dvbpsi_DeletePAT( p_pat );
1796         return;
1797     }
1798
1799     msg_Dbg( p_demux, "new PAT ts_id=0x%x version=%d current_next=%d",
1800              p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
1801
1802     /* Clean old */
1803     if( p_sys->i_pmt > 0 )
1804     {
1805         int      i_pmt_rm = 0;
1806         ts_pid_t **pmt_rm = NULL;
1807
1808         /* Search pmt to be deleted */
1809         for( i = 0; i < p_sys->i_pmt; i++ )
1810         {
1811             ts_pid_t *pmt = p_sys->pmt[i];
1812             vlc_bool_t b_keep = VLC_FALSE;
1813
1814             for( p_program = p_pat->p_first_program; p_program != NULL; p_program = p_program->p_next )
1815             {
1816                 if( p_program->i_pid == pmt->i_pid && p_program->i_number == pmt->psi->i_number )
1817                 {
1818                     b_keep = VLC_TRUE;
1819                     break;
1820                 }
1821             }
1822             if( !b_keep )
1823             {
1824                 TAB_APPEND( i_pmt_rm, pmt_rm, pmt );
1825             }
1826         }
1827
1828         /* Delete all ES attached to thoses PMT */
1829         for( i = 2; i < 8192; i++ )
1830         {
1831             ts_pid_t *pid = &p_sys->pid[i];
1832             if( pid->b_valid && !pid->psi )
1833             {
1834                 for( i = 0; i < i_pmt_rm; i++ )
1835                 {
1836                     if( pid->p_owner->i_pid_pcr == pmt_rm[i]->i_pid && pid->es->id )
1837                     {
1838                         /* We only remove es that aren't defined by extra pmt */
1839                         PIDClean( p_demux->out, pid );
1840                         break;
1841                     }
1842                 }
1843             }
1844         }
1845
1846         /* Delete PMT pid */
1847         for( i = 0; i < i_pmt_rm; i++ )
1848         {
1849             PIDClean( p_demux->out, &p_sys->pid[pmt_rm[i]->i_pid] );
1850             TAB_REMOVE( p_sys->i_pmt, p_sys->pmt, pmt_rm[i] );
1851         }
1852         if( pmt_rm )
1853         {
1854             free( pmt_rm );
1855         }
1856     }
1857
1858     /* now create programs */
1859     for( p_program = p_pat->p_first_program; p_program != NULL;
1860          p_program = p_program->p_next )
1861     {
1862         msg_Dbg( p_demux, "  * number=%d pid=0x%x", p_program->i_number,
1863                  p_program->i_pid );
1864         if( p_program->i_number != 0 )
1865         {
1866             ts_pid_t *pmt = &p_sys->pid[p_program->i_pid];
1867
1868             if( !pmt->b_valid )
1869             {
1870                 PIDInit( pmt, VLC_TRUE, pat->psi );
1871                 pmt->psi->handle =
1872                     dvbpsi_AttachPMT( p_program->i_number,
1873                                       (dvbpsi_pmt_callback)PMTCallBack, p_demux );
1874                 pmt->psi->i_number = p_program->i_number;
1875
1876                 TAB_APPEND( p_sys->i_pmt, p_sys->pmt, pmt );
1877             }
1878         }
1879     }
1880     pat->psi->i_version = p_pat->i_version;
1881
1882     dvbpsi_DeletePAT( p_pat );
1883 }