]> git.sesse.net Git - vlc/blob - modules/demux/asf/asf.c
LGPL
[vlc] / modules / demux / asf / asf.c
1 /*****************************************************************************
2  * asf.c : ASF demux module
3  *****************************************************************************
4  * Copyright © 2002-2004, 2006-2008, 2010 VLC authors and VideoLAN
5  *
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU Lesser General Public License as published by
10  * the Free Software Foundation; either version 2.1 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_demux.h>
34 #include <vlc_dialog.h>
35
36 #include <vlc_meta.h>                  /* vlc_meta_Set*, vlc_meta_New */
37 #include <vlc_access.h>                /* GET_PRIVATE_ID_STATE */
38 #include <vlc_codecs.h>                /* VLC_BITMAPINFOHEADER, WAVEFORMATEX */
39
40 #include "libasf.h"
41
42 /* TODO
43  *  - add support for the newly added object: language, bitrate,
44  *                                            extended stream properties.
45  */
46
47 /*****************************************************************************
48  * Module descriptor
49  *****************************************************************************/
50 static int  Open  ( vlc_object_t * );
51 static void Close ( vlc_object_t * );
52
53 vlc_module_begin ()
54     set_category( CAT_INPUT )
55     set_subcategory( SUBCAT_INPUT_DEMUX )
56     set_description( N_("ASF/WMV demuxer") )
57     set_capability( "demux", 200 )
58     set_callbacks( Open, Close )
59     add_shortcut( "asf", "wmv" )
60 vlc_module_end ()
61
62
63 /*****************************************************************************
64  * Local prototypes
65  *****************************************************************************/
66 static int Demux  ( demux_t * );
67 static int Control( demux_t *, int i_query, va_list args );
68
69 typedef struct
70 {
71     int i_cat;
72
73     es_out_id_t     *p_es;
74
75     asf_object_stream_properties_t *p_sp;
76
77     mtime_t i_time;
78
79     block_t         *p_frame; /* use to gather complete frame */
80
81 } asf_track_t;
82
83 struct demux_sys_t
84 {
85     mtime_t             i_time;     /* s */
86     mtime_t             i_length;   /* length of file file */
87     int64_t             i_bitrate;  /* global file bitrate */
88
89     asf_object_root_t            *p_root;
90     asf_object_file_properties_t *p_fp;
91
92     unsigned int        i_track;
93     asf_track_t         *track[128]; /* track number is stored on 7 bits */
94
95     int64_t             i_data_begin;
96     int64_t             i_data_end;
97
98     bool                b_index;
99     unsigned int        i_seek_track;
100     unsigned int        i_wait_keyframe;
101
102     vlc_meta_t          *meta;
103 };
104
105 static mtime_t  GetMoviePTS( demux_sys_t * );
106 static int      DemuxInit( demux_t * );
107 static void     DemuxEnd( demux_t * );
108 static int      DemuxPacket( demux_t * );
109
110 /*****************************************************************************
111  * Open: check file and initializes ASF structures
112  *****************************************************************************/
113 static int Open( vlc_object_t * p_this )
114 {
115     demux_t     *p_demux = (demux_t *)p_this;
116     demux_sys_t *p_sys;
117     guid_t      guid;
118     const uint8_t     *p_peek;
119
120     /* A little test to see if it could be a asf stream */
121     if( stream_Peek( p_demux->s, &p_peek, 16 ) < 16 ) return VLC_EGENERIC;
122
123     ASF_GetGUID( &guid, p_peek );
124     if( !guidcmp( &guid, &asf_object_header_guid ) ) return VLC_EGENERIC;
125
126     /* Set p_demux fields */
127     p_demux->pf_demux = Demux;
128     p_demux->pf_control = Control;
129     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
130
131     /* Load the headers */
132     if( DemuxInit( p_demux ) )
133     {
134         free( p_sys );
135         return VLC_EGENERIC;
136     }
137     return VLC_SUCCESS;
138 }
139
140
141 /*****************************************************************************
142  * Demux: read packet and send them to decoders
143  *****************************************************************************/
144 static int Demux( demux_t *p_demux )
145 {
146     demux_sys_t *p_sys = p_demux->p_sys;
147
148     for( ;; )
149     {
150         const uint8_t *p_peek;
151         mtime_t i_length;
152         mtime_t i_time_begin = GetMoviePTS( p_sys );
153         int i_result;
154
155         if( !vlc_object_alive (p_demux) )
156             break;
157 #if 0
158         /* FIXME: returns EOF too early for some mms streams */
159         if( p_sys->i_data_end >= 0 &&
160                 stream_Tell( p_demux->s ) >= p_sys->i_data_end )
161             return 0; /* EOF */
162 #endif
163
164         /* Check if we have concatenated files */
165         if( stream_Peek( p_demux->s, &p_peek, 16 ) == 16 )
166         {
167             guid_t guid;
168
169             ASF_GetGUID( &guid, p_peek );
170             if( guidcmp( &guid, &asf_object_header_guid ) )
171             {
172                 msg_Warn( p_demux, "found a new ASF header" );
173                 /* We end this stream */
174                 DemuxEnd( p_demux );
175
176                 /* And we prepare to read the next one */
177                 if( DemuxInit( p_demux ) )
178                 {
179                     msg_Err( p_demux, "failed to load the new header" );
180                     dialog_Fatal( p_demux, _("Could not demux ASF stream"), "%s",
181                                     _("VLC failed to load the ASF header.") );
182                     return 0;
183                 }
184                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
185                 continue;
186             }
187         }
188
189         /* Read and demux a packet */
190         if( ( i_result = DemuxPacket( p_demux ) ) <= 0 )
191         {
192             return i_result;
193         }
194         if( i_time_begin == -1 )
195         {
196             i_time_begin = GetMoviePTS( p_sys );
197         }
198         else
199         {
200             i_length = GetMoviePTS( p_sys ) - i_time_begin;
201             if( i_length < 0 || i_length >= 40 * 1000 ) break;
202         }
203     }
204
205     /* Set the PCR */
206     p_sys->i_time = GetMoviePTS( p_sys );
207     if( p_sys->i_time >= 0 )
208     {
209         es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_time+1 );
210     }
211
212     return 1;
213 }
214
215 /*****************************************************************************
216  * Close: frees unused data
217  *****************************************************************************/
218 static void Close( vlc_object_t * p_this )
219 {
220     demux_t     *p_demux = (demux_t *)p_this;
221
222     DemuxEnd( p_demux );
223
224     free( p_demux->p_sys );
225 }
226
227 /*****************************************************************************
228  * SeekIndex: goto to i_date or i_percent
229  *****************************************************************************/
230 static int SeekPercent( demux_t *p_demux, int i_query, va_list args )
231 {
232     demux_sys_t *p_sys = p_demux->p_sys;
233     p_sys->i_wait_keyframe = p_sys->i_seek_track ? 50 : 0;
234     return demux_vaControlHelper( p_demux->s, p_sys->i_data_begin,
235                                    p_sys->i_data_end, p_sys->i_bitrate,
236                                    p_sys->p_fp->i_min_data_packet_size,
237                                    i_query, args );
238 }
239
240 static int SeekIndex( demux_t *p_demux, mtime_t i_date, float f_pos )
241 {
242     demux_sys_t *p_sys = p_demux->p_sys;
243     asf_object_index_t *p_index;
244
245     msg_Dbg( p_demux, "seek with index: %i seconds, position %f",
246              i_date >= 0 ? (int)(i_date/1000000) : -1, f_pos );
247
248     if( i_date < 0 )
249         i_date = p_sys->i_length * f_pos;
250
251     p_index = ASF_FindObject( p_sys->p_root, &asf_object_simple_index_guid, 0 );
252
253     uint64_t i_entry = i_date * 10 / p_index->i_index_entry_time_interval;
254     if( i_entry >= p_index->i_index_entry_count )
255     {
256         msg_Warn( p_demux, "Incomplete index" );
257         return VLC_EGENERIC;
258     }
259
260     p_sys->i_wait_keyframe = p_sys->i_seek_track ? 50 : 0;
261
262     uint64_t i_offset = (uint64_t)p_index->index_entry[i_entry].i_packet_number *
263                         p_sys->p_fp->i_min_data_packet_size;
264     return stream_Seek( p_demux->s, p_sys->i_data_begin + i_offset );
265 }
266
267 static void SeekPrepare( demux_t *p_demux )
268 {
269     demux_sys_t *p_sys = p_demux->p_sys;
270
271     p_sys->i_time = -1;
272     for( int i = 0; i < 128 ; i++ )
273     {
274         asf_track_t *tk = p_sys->track[i];
275         if( !tk )
276             continue;
277
278         tk->i_time = 1;
279         if( tk->p_frame )
280             block_ChainRelease( tk->p_frame );
281         tk->p_frame = NULL;
282     }
283 }
284
285 /*****************************************************************************
286  * Control:
287  *****************************************************************************/
288 static int Control( demux_t *p_demux, int i_query, va_list args )
289 {
290     demux_sys_t *p_sys = p_demux->p_sys;
291     vlc_meta_t  *p_meta;
292     int64_t     i64, *pi64;
293     double      f, *pf;
294
295     switch( i_query )
296     {
297     case DEMUX_GET_LENGTH:
298         pi64 = (int64_t*)va_arg( args, int64_t * );
299         *pi64 = p_sys->i_length;
300         return VLC_SUCCESS;
301
302     case DEMUX_GET_TIME:
303         pi64 = (int64_t*)va_arg( args, int64_t * );
304         if( p_sys->i_time < 0 ) return VLC_EGENERIC;
305         *pi64 = p_sys->i_time;
306         return VLC_SUCCESS;
307
308     case DEMUX_SET_TIME:
309         SeekPrepare( p_demux );
310
311         if( p_sys->b_index && p_sys->i_length > 0 )
312         {
313             va_list acpy;
314             va_copy( acpy, args );
315             i64 = (int64_t)va_arg( acpy, int64_t );
316             va_end( acpy );
317
318             if( !SeekIndex( p_demux, i64, -1 ) )
319                 return VLC_SUCCESS;
320         }
321         return SeekPercent( p_demux, i_query, args );
322
323     case DEMUX_GET_POSITION:
324         if( p_sys->i_time < 0 ) return VLC_EGENERIC;
325         if( p_sys->i_length > 0 )
326         {
327             pf = (double*)va_arg( args, double * );
328             *pf = p_sys->i_time / (double)p_sys->i_length;
329             return VLC_SUCCESS;
330         }
331         return demux_vaControlHelper( p_demux->s, p_sys->i_data_begin,
332                                        p_sys->i_data_end, p_sys->i_bitrate,
333                                        p_sys->p_fp->i_min_data_packet_size,
334                                        i_query, args );
335
336     case DEMUX_SET_POSITION:
337         SeekPrepare( p_demux );
338
339         if( p_sys->b_index && p_sys->i_length > 0 )
340         {
341             va_list acpy;
342             va_copy( acpy, args );
343             f = (double)va_arg( acpy, double );
344             va_end( acpy );
345
346             if( !SeekIndex( p_demux, -1, f ) )
347                 return VLC_SUCCESS;
348         }
349         return SeekPercent( p_demux, i_query, args );
350
351     case DEMUX_GET_META:
352         p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
353         vlc_meta_Merge( p_meta, p_sys->meta );
354         return VLC_SUCCESS;
355
356     default:
357         return demux_vaControlHelper( p_demux->s, p_sys->i_data_begin,
358                                        p_sys->i_data_end, p_sys->i_bitrate,
359                                        p_sys->p_fp->i_min_data_packet_size,
360                                        i_query, args );
361     }
362 }
363
364 /*****************************************************************************
365  *
366  *****************************************************************************/
367 static mtime_t GetMoviePTS( demux_sys_t *p_sys )
368 {
369     mtime_t i_time = -1;
370     int     i;
371
372     for( i = 0; i < 128 ; i++ )
373     {
374         asf_track_t *tk = p_sys->track[i];
375
376         if( tk && tk->p_es && tk->i_time > 0)
377         {
378             if( i_time < 0 ) i_time = tk->i_time;
379             else i_time = __MIN( i_time, tk->i_time );
380         }
381     }
382
383     return i_time;
384 }
385
386 #define GETVALUE2b( bits, var, def ) \
387     switch( (bits)&0x03 ) \
388     { \
389         case 1: var = p_peek[i_skip]; i_skip++; break; \
390         case 2: var = GetWLE( p_peek + i_skip );  i_skip+= 2; break; \
391         case 3: var = GetDWLE( p_peek + i_skip ); i_skip+= 4; break; \
392         case 0: \
393         default: var = def; break;\
394     }
395
396 static int DemuxPacket( demux_t *p_demux )
397 {
398     demux_sys_t *p_sys = p_demux->p_sys;
399     int         i_data_packet_min = p_sys->p_fp->i_min_data_packet_size;
400     const uint8_t *p_peek;
401     int         i_skip;
402
403     int         i_packet_size_left;
404     int         i_packet_flags;
405     int         i_packet_property;
406
407     int         b_packet_multiple_payload;
408     int         i_packet_length;
409     int         i_packet_sequence;
410     int         i_packet_padding_length;
411
412     uint32_t    i_packet_send_time;
413     uint16_t    i_packet_duration;
414     int         i_payload;
415     int         i_payload_count;
416     int         i_payload_length_type;
417
418
419     if( stream_Peek( p_demux->s, &p_peek,i_data_packet_min)<i_data_packet_min )
420     {
421         msg_Warn( p_demux, "cannot peek while getting new packet, EOF ?" );
422         return 0;
423     }
424     i_skip = 0;
425
426     /* *** parse error correction if present *** */
427     if( p_peek[0]&0x80 )
428     {
429         unsigned int i_error_correction_length_type;
430         unsigned int i_error_correction_data_length;
431         unsigned int i_opaque_data_present;
432
433         i_error_correction_data_length = p_peek[0] & 0x0f;  // 4bits
434         i_opaque_data_present = ( p_peek[0] >> 4 )& 0x01;    // 1bit
435         i_error_correction_length_type = ( p_peek[0] >> 5 ) & 0x03; // 2bits
436         i_skip += 1; // skip error correction flags
437
438         if( i_error_correction_length_type != 0x00 ||
439             i_opaque_data_present != 0 ||
440             i_error_correction_data_length != 0x02 )
441         {
442             goto loop_error_recovery;
443         }
444
445         i_skip += i_error_correction_data_length;
446     }
447     else
448     {
449         msg_Warn( p_demux, "p_peek[0]&0x80 != 0x80" );
450     }
451
452     /* sanity check */
453     if( i_skip + 2 >= i_data_packet_min )
454     {
455         goto loop_error_recovery;
456     }
457
458     i_packet_flags = p_peek[i_skip]; i_skip++;
459     i_packet_property = p_peek[i_skip]; i_skip++;
460
461     b_packet_multiple_payload = i_packet_flags&0x01;
462
463     /* read some value */
464     GETVALUE2b( i_packet_flags >> 5, i_packet_length, i_data_packet_min );
465     GETVALUE2b( i_packet_flags >> 1, i_packet_sequence, 0 );
466     GETVALUE2b( i_packet_flags >> 3, i_packet_padding_length, 0 );
467
468     if( i_packet_padding_length > i_packet_length )
469     {
470         msg_Warn( p_demux, "Too large padding: %d", i_packet_padding_length );
471         goto loop_error_recovery;
472     }
473
474     if( i_packet_length < i_data_packet_min )
475     {
476         /* if packet length too short, there is extra padding */
477         i_packet_padding_length += i_data_packet_min - i_packet_length;
478         i_packet_length = i_data_packet_min;
479     }
480
481     i_packet_send_time = GetDWLE( p_peek + i_skip ); i_skip += 4;
482     i_packet_duration  = GetWLE( p_peek + i_skip ); i_skip += 2;
483
484     i_packet_size_left = i_packet_length;
485
486     if( b_packet_multiple_payload )
487     {
488         i_payload_count = p_peek[i_skip] & 0x3f;
489         i_payload_length_type = ( p_peek[i_skip] >> 6 )&0x03;
490         i_skip++;
491     }
492     else
493     {
494         i_payload_count = 1;
495         i_payload_length_type = 0x02; // unused
496     }
497
498     for( i_payload = 0; i_payload < i_payload_count ; i_payload++ )
499     {
500         asf_track_t   *tk;
501
502         int i_packet_keyframe;
503         unsigned int i_stream_number;
504         int i_media_object_number;
505         int i_media_object_offset;
506         int i_replicated_data_length;
507         int i_payload_data_length;
508         int i_payload_data_pos;
509         int i_sub_payload_data_length;
510         int i_tmp;
511
512         mtime_t i_pts;
513         mtime_t i_pts_delta;
514
515         if( i_skip >= i_packet_size_left )
516         {
517             /* prevent some segfault with invalid file */
518             break;
519         }
520
521         i_packet_keyframe = p_peek[i_skip] >> 7;
522         i_stream_number = p_peek[i_skip++] & 0x7f;
523
524         GETVALUE2b( i_packet_property >> 4, i_media_object_number, 0 );
525         GETVALUE2b( i_packet_property >> 2, i_tmp, 0 );
526         GETVALUE2b( i_packet_property, i_replicated_data_length, 0 );
527
528         if( i_replicated_data_length > 1 ) // should be at least 8 bytes
529         {
530             i_pts = (mtime_t)GetDWLE( p_peek + i_skip + 4 ) * 1000;
531             i_skip += i_replicated_data_length;
532             i_pts_delta = 0;
533
534             i_media_object_offset = i_tmp;
535
536             if( i_skip >= i_packet_size_left )
537             {
538                 break;
539             }
540         }
541         else if( i_replicated_data_length == 1 )
542         {
543             /* msg_Dbg( p_demux, "found compressed payload" ); */
544
545             i_pts = (mtime_t)i_tmp * 1000;
546             i_pts_delta = (mtime_t)p_peek[i_skip] * 1000; i_skip++;
547
548             i_media_object_offset = 0;
549         }
550         else
551         {
552             i_pts = (mtime_t)i_packet_send_time * 1000;
553             i_pts_delta = 0;
554
555             i_media_object_offset = i_tmp;
556         }
557
558         i_pts = __MAX( i_pts - p_sys->p_fp->i_preroll * 1000, 0 );
559         if( b_packet_multiple_payload )
560         {
561             GETVALUE2b( i_payload_length_type, i_payload_data_length, 0 );
562         }
563         else
564         {
565             i_payload_data_length = i_packet_length -
566                                     i_packet_padding_length - i_skip;
567         }
568
569         if( i_payload_data_length < 0 || i_payload_data_length > i_packet_size_left )
570         {
571             break;
572         }
573 #ifdef ASF_DEBUG
574          msg_Dbg( p_demux,
575                   "payload(%d/%d) stream_number:%d media_object_number:%d media_object_offset:%d replicated_data_length:%d payload_data_length %d",
576                   i_payload + 1, i_payload_count, i_stream_number, i_media_object_number,
577                   i_media_object_offset, i_replicated_data_length, i_payload_data_length );
578 #endif
579
580         if( ( tk = p_sys->track[i_stream_number] ) == NULL )
581         {
582             msg_Warn( p_demux,
583                       "undeclared stream[Id 0x%x]", i_stream_number );
584             i_skip += i_payload_data_length;
585             continue;   // over payload
586         }
587
588         if( p_sys->i_wait_keyframe &&
589             !(i_stream_number == p_sys->i_seek_track && i_packet_keyframe &&
590               !i_media_object_offset) )
591         {
592             i_skip += i_payload_data_length;
593             p_sys->i_wait_keyframe--;
594             continue;   // over payload
595         }
596         p_sys->i_wait_keyframe = 0;
597
598         if( !tk->p_es )
599         {
600             i_skip += i_payload_data_length;
601             continue;
602         }
603
604
605         for( i_payload_data_pos = 0;
606              i_payload_data_pos < i_payload_data_length &&
607                     i_packet_size_left > 0;
608              i_payload_data_pos += i_sub_payload_data_length )
609         {
610             block_t *p_frag;
611             int i_read;
612
613             // read sub payload length
614             if( i_replicated_data_length == 1 )
615             {
616                 i_sub_payload_data_length = p_peek[i_skip]; i_skip++;
617                 i_payload_data_pos++;
618             }
619             else
620             {
621                 i_sub_payload_data_length = i_payload_data_length;
622             }
623
624             /* FIXME I don't use i_media_object_number, sould I ? */
625             if( tk->p_frame && i_media_object_offset == 0 )
626             {
627                 /* send complete packet to decoder */
628                 block_t *p_gather = block_ChainGather( tk->p_frame );
629
630                 if( p_gather->i_dts > VLC_TS_INVALID )
631                     tk->i_time = p_gather->i_dts - VLC_TS_0;
632
633                 if( p_sys->i_time < 0 )
634                     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + tk->i_time );
635
636                 es_out_Send( p_demux->out, tk->p_es, p_gather );
637
638                 tk->p_frame = NULL;
639             }
640
641             i_read = i_sub_payload_data_length + i_skip;
642             if( ( p_frag = stream_Block( p_demux->s, i_read ) ) == NULL )
643             {
644                 msg_Warn( p_demux, "cannot read data" );
645                 return 0;
646             }
647             i_packet_size_left -= i_read;
648
649             p_frag->p_buffer += i_skip;
650             p_frag->i_buffer -= i_skip;
651
652             if( tk->p_frame == NULL )
653             {
654                 p_frag->i_pts = VLC_TS_0 + i_pts + i_payload * (mtime_t)i_pts_delta;
655                 if( tk->i_cat != VIDEO_ES )
656                     p_frag->i_dts = VLC_TS_0 + p_frag->i_pts;
657                 else
658                 {
659                     p_frag->i_dts = VLC_TS_0 + p_frag->i_pts;
660                     p_frag->i_pts = VLC_TS_INVALID;
661                 }
662             }
663
664             block_ChainAppend( &tk->p_frame, p_frag );
665
666             i_skip = 0;
667             if( i_packet_size_left > 0 )
668             {
669                 if( stream_Peek( p_demux->s, &p_peek, i_packet_size_left )
670                                                          < i_packet_size_left )
671                 {
672                     msg_Warn( p_demux, "cannot peek, EOF ?" );
673                     return 0;
674                 }
675             }
676         }
677     }
678
679     if( i_packet_size_left > 0 )
680     {
681 #ifdef ASF_DEBUG
682         if( i_packet_size_left > i_packet_padding_length )
683             msg_Warn( p_demux, "Didn't read %d bytes in the packet",
684                             i_packet_size_left - i_packet_padding_length );
685         else if( i_packet_size_left < i_packet_padding_length )
686             msg_Warn( p_demux, "Read %d too much bytes in the packet",
687                             i_packet_padding_length - i_packet_size_left );
688 #endif
689         if( stream_Read( p_demux->s, NULL, i_packet_size_left )
690                                                          < i_packet_size_left )
691         {
692             msg_Err( p_demux, "cannot skip data, EOF ?" );
693             return 0;
694         }
695     }
696
697     return 1;
698
699 loop_error_recovery:
700     msg_Warn( p_demux, "unsupported packet header" );
701     if( p_sys->p_fp->i_min_data_packet_size != p_sys->p_fp->i_max_data_packet_size )
702     {
703         msg_Err( p_demux, "unsupported packet header, fatal error" );
704         return -1;
705     }
706     if( stream_Read( p_demux->s, NULL, i_data_packet_min ) != i_data_packet_min )
707     {
708         msg_Warn( p_demux, "cannot skip data, EOF ?" );
709         return 0;
710     }
711
712     return 1;
713 }
714
715 /*****************************************************************************
716  *
717  *****************************************************************************/
718 static int DemuxInit( demux_t *p_demux )
719 {
720     demux_sys_t *p_sys = p_demux->p_sys;
721
722     /* init context */
723     p_sys->i_time   = -1;
724     p_sys->i_length = 0;
725     p_sys->i_bitrate = 0;
726     p_sys->p_root   = NULL;
727     p_sys->p_fp     = NULL;
728     p_sys->b_index  = 0;
729     p_sys->i_track  = 0;
730     p_sys->i_seek_track = 0;
731     p_sys->i_wait_keyframe = 0;
732     for( int i = 0; i < 128; i++ )
733     {
734         p_sys->track[i] = NULL;
735     }
736     p_sys->i_data_begin = -1;
737     p_sys->i_data_end   = -1;
738     p_sys->meta         = NULL;
739
740     /* Now load all object ( except raw data ) */
741     bool b_seekable;
742     stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
743     if( !(p_sys->p_root = ASF_ReadObjectRoot(p_demux->s, b_seekable)) )
744     {
745         msg_Warn( p_demux, "ASF plugin discarded (not a valid file)" );
746         return VLC_EGENERIC;
747     }
748     p_sys->p_fp = p_sys->p_root->p_fp;
749
750     if( p_sys->p_fp->i_min_data_packet_size != p_sys->p_fp->i_max_data_packet_size )
751     {
752         msg_Warn( p_demux, "ASF plugin discarded (invalid file_properties object)" );
753         goto error;
754     }
755
756     p_sys->i_track = ASF_CountObject( p_sys->p_root->p_hdr,
757                                       &asf_object_stream_properties_guid );
758     if( p_sys->i_track <= 0 )
759     {
760         msg_Warn( p_demux, "ASF plugin discarded (cannot find any stream!)" );
761         goto error;
762     }
763     msg_Dbg( p_demux, "found %d streams", p_sys->i_track );
764
765     /* check if index is available */
766     asf_object_index_t *p_index = ASF_FindObject( p_sys->p_root,
767                                                   &asf_object_simple_index_guid, 0 );
768     const bool b_index = p_index && p_index->i_index_entry_count;
769
770     /* Find the extended header if any */
771     asf_object_t *p_hdr_ext = ASF_FindObject( p_sys->p_root->p_hdr,
772                                               &asf_object_header_extension_guid, 0 );
773
774     asf_object_language_list_t *p_languages = NULL;
775     if( p_hdr_ext )
776         p_languages = ASF_FindObject( p_hdr_ext, &asf_object_language_list, 0 );
777
778     for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
779     {
780         asf_track_t    *tk;
781         asf_object_stream_properties_t *p_sp;
782         asf_object_extended_stream_properties_t *p_esp;
783         bool b_access_selected;
784
785         p_sp = ASF_FindObject( p_sys->p_root->p_hdr,
786                                &asf_object_stream_properties_guid,
787                                i_stream );
788         p_esp = NULL;
789
790         tk = p_sys->track[p_sp->i_stream_number] = malloc( sizeof( asf_track_t ) );
791         memset( tk, 0, sizeof( asf_track_t ) );
792
793         tk->i_time = -1;
794         tk->p_sp = p_sp;
795         tk->p_es = NULL;
796         tk->p_frame = NULL;
797
798         /* Check (in case of mms) if this track is selected (ie will receive data) */
799         if( !stream_Control( p_demux->s, STREAM_CONTROL_ACCESS, ACCESS_GET_PRIVATE_ID_STATE,
800                              p_sp->i_stream_number, &b_access_selected ) &&
801             !b_access_selected )
802         {
803             tk->i_cat = UNKNOWN_ES;
804             msg_Dbg( p_demux, "ignoring not selected stream(ID:%d) (by access)",
805                      p_sp->i_stream_number );
806             continue;
807         }
808
809         /* Find the associated extended_stream_properties if any */
810         if( p_hdr_ext )
811         {
812             int i_ext_stream = ASF_CountObject( p_hdr_ext,
813                                                 &asf_object_extended_stream_properties_guid );
814             for( int i = 0; i < i_ext_stream; i++ )
815             {
816                 asf_object_t *p_tmp =
817                     ASF_FindObject( p_hdr_ext,
818                                     &asf_object_extended_stream_properties_guid, i );
819                 if( p_tmp->ext_stream.i_stream_number == p_sp->i_stream_number )
820                 {
821                     p_esp = &p_tmp->ext_stream;
822                     break;
823                 }
824             }
825         }
826
827         es_format_t fmt;
828
829         if( guidcmp( &p_sp->i_stream_type, &asf_object_stream_type_audio ) &&
830             p_sp->i_type_specific_data_length >= sizeof( WAVEFORMATEX ) - 2 )
831         {
832             uint8_t *p_data = p_sp->p_type_specific_data;
833             int i_format;
834
835             es_format_Init( &fmt, AUDIO_ES, 0 );
836             i_format = GetWLE( &p_data[0] );
837             wf_tag_to_fourcc( i_format, &fmt.i_codec, NULL );
838             fmt.audio.i_channels        = GetWLE(  &p_data[2] );
839             fmt.audio.i_rate            = GetDWLE( &p_data[4] );
840             fmt.i_bitrate               = GetDWLE( &p_data[8] ) * 8;
841             fmt.audio.i_blockalign      = GetWLE(  &p_data[12] );
842             fmt.audio.i_bitspersample   = GetWLE(  &p_data[14] );
843
844             if( p_sp->i_type_specific_data_length > sizeof( WAVEFORMATEX ) &&
845                 i_format != WAVE_FORMAT_MPEGLAYER3 &&
846                 i_format != WAVE_FORMAT_MPEG )
847             {
848                 fmt.i_extra = __MIN( GetWLE( &p_data[16] ),
849                                      p_sp->i_type_specific_data_length -
850                                      sizeof( WAVEFORMATEX ) );
851                 fmt.p_extra = malloc( fmt.i_extra );
852                 memcpy( fmt.p_extra, &p_data[sizeof( WAVEFORMATEX )],
853                         fmt.i_extra );
854             }
855
856             msg_Dbg( p_demux, "added new audio stream(codec:0x%x,ID:%d)",
857                     GetWLE( p_data ), p_sp->i_stream_number );
858         }
859         else if( guidcmp( &p_sp->i_stream_type,
860                               &asf_object_stream_type_video ) &&
861                  p_sp->i_type_specific_data_length >= 11 +
862                  sizeof( VLC_BITMAPINFOHEADER ) )
863         {
864             uint8_t      *p_data = &p_sp->p_type_specific_data[11];
865
866             es_format_Init( &fmt, VIDEO_ES,
867                             VLC_FOURCC( p_data[16], p_data[17],
868                                         p_data[18], p_data[19] ) );
869             fmt.video.i_width = GetDWLE( p_data + 4 );
870             fmt.video.i_height= GetDWLE( p_data + 8 );
871
872             if( p_esp && p_esp->i_average_time_per_frame > 0 )
873             {
874                 fmt.video.i_frame_rate = 10000000;
875                 fmt.video.i_frame_rate_base = p_esp->i_average_time_per_frame;
876             }
877
878             if( fmt.i_codec == VLC_FOURCC( 'D','V','R',' ') )
879             {
880                 /* DVR-MS special ASF */
881                 fmt.i_codec = VLC_FOURCC( 'm','p','g','2' ) ;
882                 fmt.b_packetized = false;
883             }
884
885             if( p_sp->i_type_specific_data_length > 11 +
886                 sizeof( VLC_BITMAPINFOHEADER ) )
887             {
888                 fmt.i_extra = __MIN( GetDWLE( p_data ),
889                                      p_sp->i_type_specific_data_length - 11 -
890                                      sizeof( VLC_BITMAPINFOHEADER ) );
891                 fmt.p_extra = malloc( fmt.i_extra );
892                 memcpy( fmt.p_extra, &p_data[sizeof( VLC_BITMAPINFOHEADER )],
893                         fmt.i_extra );
894             }
895
896             /* Look for an aspect ratio */
897             if( p_sys->p_root->p_metadata )
898             {
899                 asf_object_metadata_t *p_meta = p_sys->p_root->p_metadata;
900                 int i_aspect_x = 0, i_aspect_y = 0;
901                 unsigned int i;
902
903                 for( i = 0; i < p_meta->i_record_entries_count; i++ )
904                 {
905                     if( !strcmp( p_meta->record[i].psz_name, "AspectRatioX" ) )
906                     {
907                         if( (!i_aspect_x && !p_meta->record[i].i_stream) ||
908                             p_meta->record[i].i_stream ==
909                             p_sp->i_stream_number )
910                             i_aspect_x = p_meta->record[i].i_val;
911                     }
912                     if( !strcmp( p_meta->record[i].psz_name, "AspectRatioY" ) )
913                     {
914                         if( (!i_aspect_y && !p_meta->record[i].i_stream) ||
915                             p_meta->record[i].i_stream ==
916                             p_sp->i_stream_number )
917                             i_aspect_y = p_meta->record[i].i_val;
918                     }
919                 }
920
921                 if( i_aspect_x && i_aspect_y )
922                 {
923                     fmt.video.i_sar_num = i_aspect_x;
924                     fmt.video.i_sar_den = i_aspect_y;
925                 }
926             }
927
928             /* If there is a video track then use the index for seeking */
929             p_sys->b_index = b_index;
930
931             msg_Dbg( p_demux, "added new video stream(ID:%d)",
932                      p_sp->i_stream_number );
933         }
934         else if( guidcmp( &p_sp->i_stream_type, &asf_object_extended_stream_header ) &&
935             p_sp->i_type_specific_data_length >= 64 )
936         {
937             /* Now follows a 64 byte header of which we don't know much */
938             guid_t  *p_ref  = (guid_t *)p_sp->p_type_specific_data;
939             uint8_t *p_data = p_sp->p_type_specific_data + 64;
940             unsigned int i_data = p_sp->i_type_specific_data_length - 64;
941
942             msg_Dbg( p_demux, "Ext stream header detected. datasize = %d", p_sp->i_type_specific_data_length );
943             if( guidcmp( p_ref, &asf_object_extended_stream_type_audio ) &&
944                 i_data >= sizeof( WAVEFORMATEX ) - 2)
945             {
946                 int      i_format;
947                 es_format_Init( &fmt, AUDIO_ES, 0 );
948                 i_format = GetWLE( &p_data[0] );
949                 if( i_format == 0 )
950                     fmt.i_codec = VLC_CODEC_A52;
951                 else
952                     wf_tag_to_fourcc( i_format, &fmt.i_codec, NULL );
953                 fmt.audio.i_channels        = GetWLE(  &p_data[2] );
954                 fmt.audio.i_rate            = GetDWLE( &p_data[4] );
955                 fmt.i_bitrate               = GetDWLE( &p_data[8] ) * 8;
956                 fmt.audio.i_blockalign      = GetWLE(  &p_data[12] );
957                 fmt.audio.i_bitspersample   = GetWLE(  &p_data[14] );
958                 fmt.b_packetized = true;
959
960                 if( p_sp->i_type_specific_data_length > sizeof( WAVEFORMATEX ) &&
961                     i_format != WAVE_FORMAT_MPEGLAYER3 &&
962                     i_format != WAVE_FORMAT_MPEG )
963                 {
964                     fmt.i_extra = __MIN( GetWLE( &p_data[16] ),
965                                          p_sp->i_type_specific_data_length -
966                                          sizeof( WAVEFORMATEX ) );
967                     fmt.p_extra = malloc( fmt.i_extra );
968                     memcpy( fmt.p_extra, &p_data[sizeof( WAVEFORMATEX )],
969                         fmt.i_extra );
970                 }
971
972                 msg_Dbg( p_demux, "added new audio stream (codec:0x%x,ID:%d)",
973                     i_format, p_sp->i_stream_number );
974             }
975             else
976             {
977                 es_format_Init( &fmt, UNKNOWN_ES, 0 );
978             }
979         }
980         else
981         {
982             es_format_Init( &fmt, UNKNOWN_ES, 0 );
983         }
984
985         tk->i_cat = fmt.i_cat;
986         if( fmt.i_cat != UNKNOWN_ES )
987         {
988             if( p_esp && p_languages &&
989                 p_esp->i_language_index >= 0 &&
990                 p_esp->i_language_index < p_languages->i_language )
991             {
992                 fmt.psz_language = strdup( p_languages->ppsz_language[p_esp->i_language_index] );
993                 char *p;
994                 if( fmt.psz_language && (p = strchr( fmt.psz_language, '-' )) )
995                     *p = '\0';
996             }
997
998             /* Set the track on which we'll do our seeking to the first video track */
999             if(!p_sys->i_seek_track && fmt.i_cat == VIDEO_ES)
1000                 p_sys->i_seek_track = p_sp->i_stream_number;
1001
1002             tk->p_es = es_out_Add( p_demux->out, &fmt );
1003         }
1004         else
1005         {
1006             msg_Dbg( p_demux, "ignoring unknown stream(ID:%d)",
1007                      p_sp->i_stream_number );
1008         }
1009         es_format_Clean( &fmt );
1010     }
1011
1012     p_sys->i_data_begin = p_sys->p_root->p_data->i_object_pos + 50;
1013     if( p_sys->p_root->p_data->i_object_size != 0 )
1014     { /* local file */
1015         p_sys->i_data_end = p_sys->p_root->p_data->i_object_pos +
1016                                     p_sys->p_root->p_data->i_object_size;
1017     }
1018     else
1019     { /* live/broacast */
1020         p_sys->i_data_end = -1;
1021     }
1022
1023     /* go to first packet */
1024     stream_Seek( p_demux->s, p_sys->i_data_begin );
1025
1026     /* try to calculate movie time */
1027     if( p_sys->p_fp->i_data_packets_count > 0 )
1028     {
1029         int64_t i_count;
1030         int64_t i_size = stream_Size( p_demux->s );
1031
1032         if( p_sys->i_data_end > 0 && i_size > p_sys->i_data_end )
1033         {
1034             i_size = p_sys->i_data_end;
1035         }
1036
1037         /* real number of packets */
1038         i_count = ( i_size - p_sys->i_data_begin ) /
1039                   p_sys->p_fp->i_min_data_packet_size;
1040
1041         /* calculate the time duration in micro-s */
1042         p_sys->i_length = (mtime_t)p_sys->p_fp->i_play_duration / 10 *
1043                    (mtime_t)i_count /
1044                    (mtime_t)p_sys->p_fp->i_data_packets_count - p_sys->p_fp->i_preroll * 1000;
1045         if( p_sys->i_length < 0 )
1046             p_sys->i_length = 0;
1047
1048         if( p_sys->i_length > 0 )
1049         {
1050             p_sys->i_bitrate = 8 * i_size * (int64_t)1000000 / p_sys->i_length;
1051         }
1052     }
1053
1054     /* Create meta information */
1055     p_sys->meta = vlc_meta_New();
1056
1057     asf_object_content_description_t *p_cd;
1058     if( ( p_cd = ASF_FindObject( p_sys->p_root->p_hdr,
1059                                  &asf_object_content_description_guid, 0 ) ) )
1060     {
1061         if( p_cd->psz_title && *p_cd->psz_title )
1062         {
1063             vlc_meta_SetTitle( p_sys->meta, p_cd->psz_title );
1064         }
1065         if( p_cd->psz_artist && *p_cd->psz_artist )
1066         {
1067              vlc_meta_SetArtist( p_sys->meta, p_cd->psz_artist );
1068         }
1069         if( p_cd->psz_copyright && *p_cd->psz_copyright )
1070         {
1071             vlc_meta_SetCopyright( p_sys->meta, p_cd->psz_copyright );
1072         }
1073         if( p_cd->psz_description && *p_cd->psz_description )
1074         {
1075             vlc_meta_SetDescription( p_sys->meta, p_cd->psz_description );
1076         }
1077         if( p_cd->psz_rating && *p_cd->psz_rating )
1078         {
1079             vlc_meta_SetRating( p_sys->meta, p_cd->psz_rating );
1080         }
1081     }
1082     /// \tood Fix Child meta for ASF tracks
1083 #if 0
1084     for( i_stream = 0, i = 0; i < 128; i++ )
1085     {
1086         asf_object_codec_list_t *p_cl = ASF_FindObject( p_sys->p_root->p_hdr,
1087                                                         &asf_object_codec_list_guid, 0 );
1088
1089         if( p_sys->track[i] )
1090         {
1091             vlc_meta_t *tk = vlc_meta_New();
1092             TAB_APPEND( p_sys->meta->i_track, p_sys->meta->track, tk );
1093
1094             if( p_cl && i_stream < p_cl->i_codec_entries_count )
1095             {
1096                 if( p_cl->codec[i_stream].psz_name &&
1097                     *p_cl->codec[i_stream].psz_name )
1098                 {
1099                     vlc_meta_Add( tk, VLC_META_CODEC_NAME,
1100                                   p_cl->codec[i_stream].psz_name );
1101                 }
1102                 if( p_cl->codec[i_stream].psz_description &&
1103                     *p_cl->codec[i_stream].psz_description )
1104                 {
1105                     vlc_meta_Add( tk, VLC_META_CODEC_DESCRIPTION,
1106                                   p_cl->codec[i_stream].psz_description );
1107                 }
1108             }
1109             i_stream++;
1110         }
1111     }
1112 #endif
1113     return VLC_SUCCESS;
1114
1115 error:
1116     ASF_FreeObjectRoot( p_demux->s, p_sys->p_root );
1117     return VLC_EGENERIC;
1118 }
1119 /*****************************************************************************
1120  *
1121  *****************************************************************************/
1122 static void DemuxEnd( demux_t *p_demux )
1123 {
1124     demux_sys_t *p_sys = p_demux->p_sys;
1125
1126     if( p_sys->p_root )
1127     {
1128         ASF_FreeObjectRoot( p_demux->s, p_sys->p_root );
1129         p_sys->p_root = NULL;
1130     }
1131     if( p_sys->meta )
1132     {
1133         vlc_meta_Delete( p_sys->meta );
1134         p_sys->meta = NULL;
1135     }
1136
1137     for( int i = 0; i < 128; i++ )
1138     {
1139         asf_track_t *tk = p_sys->track[i];
1140
1141         if( tk )
1142         {
1143             if( tk->p_frame )
1144             {
1145                 block_ChainRelease( tk->p_frame );
1146             }
1147             if( tk->p_es )
1148             {
1149                 es_out_Del( p_demux->out, tk->p_es );
1150             }
1151             free( tk );
1152         }
1153         p_sys->track[i] = 0;
1154     }
1155 }
1156