6f9f0af248a0f4bb5cd0469b3ad8d4bdc238288f
[vlc.git] / 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 #include <vlc_vout.h>
40
41 #include <limits.h>
42
43 #include "asfpacket.h"
44 #include "libasf.h"
45 #include "assert.h"
46
47 /* TODO
48  *  - add support for the newly added object: language, bitrate,
49  *                                            extended stream properties.
50  */
51
52 /*****************************************************************************
53  * Module descriptor
54  *****************************************************************************/
55 static int  Open  ( vlc_object_t * );
56 static void Close ( vlc_object_t * );
57
58 vlc_module_begin ()
59     set_category( CAT_INPUT )
60     set_subcategory( SUBCAT_INPUT_DEMUX )
61     set_description( N_("ASF/WMV demuxer") )
62     set_capability( "demux", 200 )
63     set_callbacks( Open, Close )
64     add_shortcut( "asf", "wmv" )
65     add_file_extension("asf")
66     add_file_extension("wma")
67     add_file_extension("wmv")
68 vlc_module_end ()
69
70
71 /*****************************************************************************
72  * Local prototypes
73  *****************************************************************************/
74 static int Demux  ( demux_t * );
75 static int Control( demux_t *, int i_query, va_list args );
76
77 #define MAX_ASF_TRACKS (ASF_MAX_STREAMNUMBER + 1)
78 #define ASF_PREROLL_FROM_CURRENT -1
79
80 /* callbacks for packet parser */
81 static void Packet_UpdateTime( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number,
82                                vlc_tick_t i_time );
83 static void Packet_SetSendTime( asf_packet_sys_t *p_packetsys, vlc_tick_t i_time);
84 static bool Block_Dequeue( demux_t *p_demux, vlc_tick_t i_nexttime );
85 static asf_track_info_t * Packet_GetTrackInfo( asf_packet_sys_t *p_packetsys,
86                                                uint8_t i_stream_number );
87 static bool Packet_DoSkip( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, bool b_packet_keyframe );
88 static void Packet_Enqueue( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, block_t **pp_frame );
89 static void Packet_SetAR( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number,
90                           uint8_t i_ratio_x, uint8_t i_ratio_y );
91
92 typedef struct
93 {
94     int i_cat;
95
96     es_out_id_t     *p_es;
97     es_format_t     *p_fmt; /* format backup for video changes */
98     bool             b_selected;
99
100     vlc_tick_t       i_time; /* track time*/
101
102     asf_track_info_t info;
103
104     struct
105     {
106         block_t     *p_first;
107         block_t    **pp_last;
108     } queue;
109
110 } asf_track_t;
111
112 typedef struct
113 {
114     vlc_tick_t          i_time;     /* s */
115     vlc_tick_t          i_sendtime;
116     vlc_tick_t          i_length;   /* length of file */
117     uint64_t            i_bitrate;  /* global file bitrate */
118     bool                b_eos;      /* end of current stream */
119     bool                b_eof;      /* end of current media */
120
121     asf_object_root_t            *p_root;
122     asf_object_file_properties_t *p_fp;
123
124     unsigned int        i_track;
125     asf_track_t         *track[MAX_ASF_TRACKS]; /* track number is stored on 7 bits */
126
127     uint64_t            i_data_begin;
128     uint64_t            i_data_end;
129
130     bool                b_index;
131     bool                b_canfastseek;
132     bool                b_pcr_sent;
133     uint8_t             i_seek_track;
134     uint8_t             i_access_selected_track[ES_CATEGORY_COUNT]; /* mms, depends on access algorithm */
135     unsigned int        i_wait_keyframe;
136
137     vlc_tick_t          i_preroll_start;
138
139     asf_packet_sys_t    packet_sys;
140
141     vlc_meta_t          *meta;
142 } demux_sys_t;
143
144 static int      DemuxInit( demux_t * );
145 static void     DemuxEnd( demux_t * );
146
147 static void     FlushQueue( asf_track_t * );
148 static void     FlushQueues( demux_t *p_demux );
149
150 /*****************************************************************************
151  * Open: check file and initializes ASF structures
152  *****************************************************************************/
153 static int Open( vlc_object_t * p_this )
154 {
155     demux_t     *p_demux = (demux_t *)p_this;
156     demux_sys_t *p_sys;
157     vlc_guid_t      guid;
158     const uint8_t     *p_peek;
159
160     /* A little test to see if it could be a asf stream */
161     if( vlc_stream_Peek( p_demux->s, &p_peek, 16 ) < 16 ) return VLC_EGENERIC;
162
163     ASF_GetGUID( &guid, p_peek );
164     if( !guidcmp( &guid, &asf_object_header_guid ) ) return VLC_EGENERIC;
165
166     /* Set p_demux fields */
167     p_demux->pf_demux = Demux;
168     p_demux->pf_control = Control;
169     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
170
171     /* Load the headers */
172     if( DemuxInit( p_demux ) )
173     {
174         free( p_sys );
175         return VLC_EGENERIC;
176     }
177
178     p_sys->packet_sys.priv = p_demux;
179     p_sys->packet_sys.s = p_demux->s;
180     p_sys->packet_sys.logger = p_demux->obj.logger;
181     p_sys->packet_sys.b_deduplicate = false;
182     p_sys->packet_sys.b_can_hold_multiple_packets = false;
183     p_sys->packet_sys.pf_doskip = Packet_DoSkip;
184     p_sys->packet_sys.pf_send = Packet_Enqueue;
185     p_sys->packet_sys.pf_gettrackinfo = Packet_GetTrackInfo;
186     p_sys->packet_sys.pf_updatetime = Packet_UpdateTime;
187     p_sys->packet_sys.pf_updatesendtime = Packet_SetSendTime;
188     p_sys->packet_sys.pf_setaspectratio = Packet_SetAR;
189
190     return VLC_SUCCESS;
191 }
192
193 /*****************************************************************************
194  * Demux: read packet and send them to decoders
195  *****************************************************************************/
196 #define CHUNK VLC_TICK_FROM_MS(100)
197 static int Demux( demux_t *p_demux )
198 {
199     demux_sys_t *p_sys = p_demux->p_sys;
200
201     for( int i=0; i<ES_CATEGORY_COUNT; i++ )
202     {
203         if ( p_sys->i_access_selected_track[i] > 0 )
204         {
205             es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
206                             p_sys->track[p_sys->i_access_selected_track[i]]->p_es, true );
207             p_sys->i_access_selected_track[i] = 0;
208         }
209     }
210
211     /* Get selected tracks, especially for computing PCR */
212     for( int i=0; i<MAX_ASF_TRACKS; i++ )
213     {
214         asf_track_t *tk = p_sys->track[i];
215         if ( !tk ) continue;
216         if ( tk->p_es )
217             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, & tk->b_selected );
218         else
219             tk->b_selected = false;
220     }
221
222     while( !p_sys->b_eos && ( p_sys->i_sendtime - p_sys->i_time - CHUNK < 0 ||
223                             ( p_sys->i_sendtime - p_sys->i_time - CHUNK ) <
224                                                      p_sys->p_fp->i_preroll ) )
225     {
226         /* Read and demux a packet */
227         if( DemuxASFPacket( &p_sys->packet_sys,
228                              p_sys->p_fp->i_min_data_packet_size,
229                              p_sys->p_fp->i_max_data_packet_size,
230                              p_sys->i_data_begin, p_sys->i_data_end ) <= 0 )
231         {
232             p_sys->b_eos = true;
233             /* Check if we have concatenated files */
234             const uint8_t *p_peek;
235             if( vlc_stream_Peek( p_demux->s, &p_peek, 16 ) == 16 )
236             {
237                 vlc_guid_t guid;
238
239                 ASF_GetGUID( &guid, p_peek );
240                 p_sys->b_eof = !guidcmp( &guid, &asf_object_header_guid );
241                 if( !p_sys->b_eof )
242                     msg_Warn( p_demux, "found a new ASF header" );
243             }
244             else
245                 p_sys->b_eof = true;
246         }
247
248         if ( p_sys->i_time == VLC_TICK_INVALID )
249             p_sys->i_time = p_sys->i_sendtime;
250     }
251
252     if( p_sys->b_eos || ( p_sys->i_sendtime - p_sys->i_time - CHUNK >= 0 &&
253                         ( p_sys->i_sendtime - p_sys->i_time - CHUNK ) >=
254                                                      p_sys->p_fp->i_preroll ) )
255     {
256         bool b_data = Block_Dequeue( p_demux, p_sys->i_time + CHUNK );
257
258         if( p_sys->i_time != VLC_TICK_INVALID )
259         {
260             p_sys->i_time += CHUNK;
261             p_sys->b_pcr_sent = true;
262             es_out_SetPCR( p_demux->out, p_sys->i_time );
263 #ifdef ASF_DEBUG
264             msg_Dbg( p_demux, "Demux Loop Setting PCR to %"PRId64, p_sys->i_time );
265 #endif
266         }
267
268         if ( !b_data && p_sys->b_eos )
269         {
270             if( p_sys->i_time != VLC_TICK_INVALID )
271                 es_out_SetPCR( p_demux->out, p_sys->i_time );
272
273             /* We end this stream */
274             if( !p_sys->b_eof )
275             {
276                 DemuxEnd( p_demux );
277
278                 /* And we prepare to read the next one */
279                 if( DemuxInit( p_demux ) )
280                 {
281                     msg_Err( p_demux, "failed to load the new header" );
282                     return VLC_DEMUXER_EOF;
283                 }
284                 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
285             }
286             else
287                 return VLC_DEMUXER_EOF;
288         }
289     }
290
291     return 1;
292 }
293
294 /*****************************************************************************
295  * Close: frees unused data
296  *****************************************************************************/
297 static void Close( vlc_object_t * p_this )
298 {
299     demux_t     *p_demux = (demux_t *)p_this;
300
301     DemuxEnd( p_demux );
302
303     free( p_demux->p_sys );
304 }
305
306 /*****************************************************************************
307  * WaitKeyframe: computes the number of frames to wait for a keyframe
308  *****************************************************************************/
309 static void WaitKeyframe( demux_t *p_demux )
310 {
311     demux_sys_t *p_sys = p_demux->p_sys;
312     if ( ! p_sys->i_seek_track )
313     {
314         for ( int i=0; i<MAX_ASF_TRACKS; i++ )
315         {
316             asf_track_t *tk = p_sys->track[i];
317             if ( tk && tk->info.p_sp && tk->i_cat == VIDEO_ES && tk->b_selected )
318             {
319                 p_sys->i_seek_track = tk->info.p_sp->i_stream_number;
320                 break;
321             }
322         }
323     }
324
325     if ( p_sys->i_seek_track )
326     {
327         /* Skip forward at least 1 min */
328         asf_track_t *tk = p_sys->track[p_sys->i_seek_track];
329         if ( tk->info.p_esp && tk->info.p_esp->i_average_time_per_frame )
330         {
331             /* 1 min if fastseek, otherwise 5 sec */
332             /* That's a guess for bandwidth */
333             msftime_t i_maxwaittime = MSFTIME_FROM_SEC( p_sys->b_canfastseek ? 60 : 5);
334             uint64_t frames = i_maxwaittime / tk->info.p_esp->i_average_time_per_frame;
335             p_sys->i_wait_keyframe = __MIN( frames, UINT_MAX );
336         }
337         else
338         {
339             p_sys->i_wait_keyframe = ( p_sys->b_canfastseek ) ? 25 * 30 : 25 * 5;
340         }
341     }
342     else
343     {
344         p_sys->i_wait_keyframe = 0;
345     }
346
347 }
348
349 /*****************************************************************************
350  * SeekIndex: goto to i_date or i_percent
351  *****************************************************************************/
352 static int SeekPercent( demux_t *p_demux, int i_query, va_list args )
353 {
354     demux_sys_t *p_sys = p_demux->p_sys;
355
356     WaitKeyframe( p_demux );
357
358     msg_Dbg( p_demux, "seek with percent: waiting %i frames", p_sys->i_wait_keyframe );
359     return demux_vaControlHelper( p_demux->s, __MIN( INT64_MAX, p_sys->i_data_begin ),
360                                    __MIN( INT64_MAX, p_sys->i_data_end ),
361                                    __MIN( INT64_MAX, p_sys->i_bitrate ),
362                                    __MIN( INT16_MAX, p_sys->p_fp->i_min_data_packet_size ),
363                                    i_query, args );
364 }
365
366 static int SeekIndex( demux_t *p_demux, vlc_tick_t i_date, float f_pos )
367 {
368     demux_sys_t *p_sys = p_demux->p_sys;
369     asf_object_index_t *p_index;
370
371     msg_Dbg( p_demux, "seek with index: %i seconds, position %f",
372              i_date >= 0 ? (int)SEC_FROM_VLC_TICK(i_date) : -1, f_pos );
373
374     if( i_date < 0 )
375         i_date = p_sys->i_length * f_pos;
376
377     p_sys->i_preroll_start = i_date - p_sys->p_fp->i_preroll;
378     if ( p_sys->i_preroll_start < 0 ) p_sys->i_preroll_start = 0;
379
380     p_index = ASF_FindObject( p_sys->p_root, &asf_object_simple_index_guid, 0 );
381
382     uint64_t i_entry = MSFTIME_FROM_VLC_TICK(p_sys->i_preroll_start) / p_index->i_index_entry_time_interval;
383     if( i_entry >= p_index->i_index_entry_count )
384     {
385         msg_Warn( p_demux, "Incomplete index" );
386         return VLC_EGENERIC;
387     }
388
389     WaitKeyframe( p_demux );
390
391     uint64_t i_offset = (uint64_t)p_index->index_entry[i_entry].i_packet_number *
392                         p_sys->p_fp->i_min_data_packet_size;
393
394     if ( vlc_stream_Seek( p_demux->s, i_offset + p_sys->i_data_begin ) == VLC_SUCCESS )
395     {
396         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, VLC_TICK_0 + i_date );
397         return VLC_SUCCESS;
398     }
399     else return VLC_EGENERIC;
400 }
401
402 static void SeekPrepare( demux_t *p_demux )
403 {
404     demux_sys_t *p_sys = p_demux->p_sys;
405
406     p_sys->b_eof = false;
407     p_sys->b_eos = false;
408     p_sys->b_pcr_sent = false;
409     p_sys->i_time = VLC_TICK_INVALID;
410     p_sys->i_sendtime = VLC_TICK_INVALID;
411     p_sys->i_preroll_start = ASFPACKET_PREROLL_FROM_CURRENT;
412
413     for( int i = 0; i < MAX_ASF_TRACKS ; i++ )
414     {
415         asf_track_t *tk = p_sys->track[i];
416         if( tk )
417         {
418             FlushQueue( tk );
419             tk->i_time = VLC_TICK_INVALID;
420         }
421     }
422
423     es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
424 }
425
426 /*****************************************************************************
427  * Control:
428  *****************************************************************************/
429 static int Control( demux_t *p_demux, int i_query, va_list args )
430 {
431     demux_sys_t *p_sys = p_demux->p_sys;
432     vlc_meta_t  *p_meta;
433     vlc_tick_t  i64;
434     int         i;
435     double      f, *pf;
436
437     switch( i_query )
438     {
439     case DEMUX_GET_LENGTH:
440         *va_arg( args, vlc_tick_t * ) = p_sys->i_length;
441         return VLC_SUCCESS;
442
443     case DEMUX_GET_TIME:
444         if( p_sys->i_time == VLC_TICK_INVALID ) return VLC_EGENERIC;
445         *va_arg( args, vlc_tick_t * ) = p_sys->i_time;
446         return VLC_SUCCESS;
447
448     case DEMUX_SET_TIME:
449         if ( !p_sys->p_fp ||
450              ! ( p_sys->p_fp->i_flags & ASF_FILE_PROPERTIES_SEEKABLE ) )
451             return VLC_EGENERIC;
452
453         SeekPrepare( p_demux );
454
455         if( p_sys->b_index && p_sys->i_length != 0 )
456         {
457             va_list acpy;
458             va_copy( acpy, args );
459             i64 = va_arg( acpy, vlc_tick_t );
460             va_end( acpy );
461
462             if( !SeekIndex( p_demux, i64, -1 ) )
463                 return VLC_SUCCESS;
464         }
465         return SeekPercent( p_demux, i_query, args );
466
467     case DEMUX_SET_ES:
468     {
469         i = va_arg( args, int );
470         int i_ret;
471         if ( i >= 0 )
472         {
473             msg_Dbg( p_demux, "Requesting access to enable stream %d", i );
474             i_ret = vlc_stream_Control( p_demux->s,
475                                         STREAM_SET_PRIVATE_ID_STATE, i, true );
476         }
477         else
478         {  /* i contains -1 * es_category */
479             msg_Dbg( p_demux, "Requesting access to disable stream %d", i );
480             i_ret = vlc_stream_Control( p_demux->s,
481                                         STREAM_SET_PRIVATE_ID_STATE, i,
482                                         false );
483         }
484
485         if ( i_ret == VLC_SUCCESS )
486         {
487             asf_track_t *tk;
488             if( i >= 0 )
489             {
490                 tk = p_sys->track[i];
491             }
492             else
493             {
494                 for( int j = 0; j < MAX_ASF_TRACKS ; j++ )
495                 {
496                     tk = p_sys->track[j];
497                     if( !tk || !tk->p_fmt || tk->i_cat != -1 * i )
498                         continue;
499                     FlushQueue( tk );
500                     tk->i_time = VLC_TICK_INVALID;
501                 }
502             }
503
504             p_sys->i_seek_track = 0;
505             if ( ( tk && tk->i_cat == VIDEO_ES ) || i == -1 * VIDEO_ES )
506                 WaitKeyframe( p_demux );
507         }
508         return i_ret;
509     }
510
511     case DEMUX_SET_ES_LIST:
512         return VLC_EGENERIC; /* TODO */
513
514     case DEMUX_GET_POSITION:
515         if( p_sys->i_time == VLC_TICK_INVALID ) return VLC_EGENERIC;
516         if( p_sys->i_length != 0 )
517         {
518             pf = va_arg( args, double * );
519             *pf = p_sys->i_time / (double)p_sys->i_length;
520             return VLC_SUCCESS;
521         }
522         return demux_vaControlHelper( p_demux->s,
523                                        __MIN( INT64_MAX, p_sys->i_data_begin ),
524                                        __MIN( INT64_MAX, p_sys->i_data_end ),
525                                        __MIN( INT64_MAX, p_sys->i_bitrate ),
526                                        __MIN( INT16_MAX, p_sys->p_fp->i_min_data_packet_size ),
527                                        i_query, args );
528
529     case DEMUX_SET_POSITION:
530         if ( !p_sys->p_fp ||
531              ( !( p_sys->p_fp->i_flags & ASF_FILE_PROPERTIES_SEEKABLE ) && !p_sys->b_index ) )
532             return VLC_EGENERIC;
533
534         SeekPrepare( p_demux );
535
536         if( p_sys->b_index && p_sys->i_length != 0 )
537         {
538             va_list acpy;
539             va_copy( acpy, args );
540             f = va_arg( acpy, double );
541             va_end( acpy );
542
543             if( !SeekIndex( p_demux, -1, f ) )
544                 return VLC_SUCCESS;
545         }
546         return SeekPercent( p_demux, i_query, args );
547
548     case DEMUX_GET_META:
549         p_meta = va_arg( args, vlc_meta_t * );
550         vlc_meta_Merge( p_meta, p_sys->meta );
551         return VLC_SUCCESS;
552
553     case DEMUX_CAN_SEEK:
554         if ( !p_sys->p_fp ||
555              ( !( p_sys->p_fp->i_flags & ASF_FILE_PROPERTIES_SEEKABLE ) && !p_sys->b_index ) )
556         {
557             bool *pb_bool = va_arg( args, bool * );
558             *pb_bool = false;
559             return VLC_SUCCESS;
560         }
561         /* fall through */
562     default:
563         return demux_vaControlHelper( p_demux->s,
564                                       __MIN( INT64_MAX, p_sys->i_data_begin ),
565                                       __MIN( INT64_MAX, p_sys->i_data_end),
566                                       __MIN( INT64_MAX, p_sys->i_bitrate ),
567                     ( p_sys->p_fp ) ? __MIN( INT_MAX, p_sys->p_fp->i_min_data_packet_size ) : 1,
568                     i_query, args );
569     }
570 }
571
572 /*****************************************************************************
573  *
574  *****************************************************************************/
575 static void Packet_SetAR( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number,
576                           uint8_t i_ratio_x, uint8_t i_ratio_y )
577 {
578     demux_t *p_demux = p_packetsys->priv;
579     demux_sys_t *p_sys = p_demux->p_sys;
580     asf_track_t *tk = p_sys->track[i_stream_number];
581
582     if ( !tk->p_fmt || (tk->p_fmt->video.i_sar_num == i_ratio_x && tk->p_fmt->video.i_sar_den == i_ratio_y ) )
583         return;
584
585     tk->p_fmt->video.i_sar_num = i_ratio_x;
586     tk->p_fmt->video.i_sar_den = i_ratio_y;
587     if( tk->p_es )
588         es_out_Control( p_demux->out, ES_OUT_SET_ES_FMT, tk->p_es, tk->p_fmt );
589 }
590
591 static void Packet_SetSendTime( asf_packet_sys_t *p_packetsys, vlc_tick_t i_time )
592 {
593     demux_t *p_demux = p_packetsys->priv;
594     demux_sys_t *p_sys = p_demux->p_sys;
595
596     p_sys->i_sendtime = VLC_TICK_0 + i_time;
597 }
598
599 static void Packet_UpdateTime( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number,
600                                vlc_tick_t i_time )
601 {
602     demux_t *p_demux = p_packetsys->priv;
603     demux_sys_t *p_sys = p_demux->p_sys;
604     asf_track_t *tk = p_sys->track[i_stream_number];
605
606     if ( tk )
607         tk->i_time = VLC_TICK_0 + i_time;
608 }
609
610 static asf_track_info_t * Packet_GetTrackInfo( asf_packet_sys_t *p_packetsys,
611                                                uint8_t i_stream_number )
612 {
613     demux_t *p_demux = p_packetsys->priv;
614     demux_sys_t *p_sys = p_demux->p_sys;
615     asf_track_t *tk = p_sys->track[i_stream_number];
616
617     if (!tk)
618         return NULL;
619     else
620         return & tk->info;
621 }
622
623 static bool Packet_DoSkip( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, bool b_packet_keyframe )
624 {
625     demux_t *p_demux = p_packetsys->priv;
626     demux_sys_t *p_sys = p_demux->p_sys;
627     const asf_track_t *tk = p_sys->track[i_stream_number];
628
629     if( tk == NULL )
630     {
631         msg_Warn( p_demux, "undeclared stream[Id 0x%x]", i_stream_number );
632         return true;
633     }
634
635     if( p_sys->i_wait_keyframe )
636     {
637         if ( i_stream_number == p_sys->i_seek_track )
638         {
639             if ( !b_packet_keyframe )
640             {
641                 p_sys->i_wait_keyframe--;
642                 return true;
643             }
644             else
645                 p_sys->i_wait_keyframe = 0;
646         }
647         else
648             return true;
649     }
650
651     if( !tk->p_es )
652         return true;
653
654     return false;
655 }
656
657 static void Packet_Enqueue( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, block_t **pp_frame )
658 {
659     demux_t *p_demux = p_packetsys->priv;
660     demux_sys_t *p_sys = p_demux->p_sys;
661     asf_track_t *tk = p_sys->track[i_stream_number];
662     if ( !tk )
663         return;
664
665     block_t *p_gather = block_ChainGather( *pp_frame );
666     if( p_gather )
667     {
668         block_ChainLastAppend( & tk->queue.pp_last, p_gather );
669 #ifdef ASF_DEBUG
670         msg_Dbg( p_demux, "    enqueue packet dts %"PRId64" pts %"PRId64" pcr %"PRId64, p_gather->i_dts, p_gather->i_pts, p_sys->i_time );
671 #endif
672     }
673
674     *pp_frame = NULL;
675 }
676
677 static bool Block_Dequeue( demux_t *p_demux, vlc_tick_t i_nexttime )
678 {
679     demux_sys_t *p_sys = p_demux->p_sys;
680     bool b_tracks_have_data = false;
681     for( int i = 0; i < MAX_ASF_TRACKS; i++ )
682     {
683         asf_track_t *tk = p_sys->track[i];
684         if (!tk)
685             continue;
686         b_tracks_have_data |= (tk->queue.p_first != NULL);
687         while( tk->queue.p_first && tk->queue.p_first->i_dts <= i_nexttime )
688         {
689             block_t *p_block = tk->queue.p_first;
690             tk->queue.p_first = p_block->p_next;
691             if( tk->queue.p_first == NULL )
692                 tk->queue.pp_last = &tk->queue.p_first;
693             else
694                 p_block->p_next = NULL;
695
696             if( !p_sys->b_pcr_sent && p_sys->i_time != VLC_TICK_INVALID )
697             {
698                 p_sys->b_pcr_sent = true;
699                 es_out_SetPCR( p_demux->out, p_sys->i_time );
700 #ifdef ASF_DEBUG
701                 msg_Dbg( p_demux, "    dequeue setting PCR to %"PRId64, p_sys->i_time );
702 #endif
703             }
704
705 #ifdef ASF_DEBUG
706             msg_Dbg( p_demux, "    sending packet dts %"PRId64" pts %"PRId64" pcr %"PRId64, p_block->i_dts, p_block->i_pts, p_sys->i_time );
707 #endif
708             es_out_Send( p_demux->out, tk->p_es, p_block );
709         }
710     }
711     return b_tracks_have_data;
712 }
713
714 /*****************************************************************************
715  *
716  *****************************************************************************/
717 typedef struct asf_es_priorities_t
718 {
719     uint16_t *pi_stream_numbers;
720     uint16_t i_count;
721 } asf_es_priorities_t;
722
723 /* Fills up our exclusion list */
724 static void ASF_fillup_es_priorities_ex( demux_sys_t *p_sys, void *p_hdr,
725                                          asf_es_priorities_t *p_prios )
726 {
727     /* Find stream exclusions */
728     asf_object_advanced_mutual_exclusion_t *p_mutex =
729             ASF_FindObject( p_hdr, &asf_object_advanced_mutual_exclusion, 0 );
730     if (! p_mutex ) return;
731
732 #if ( UINT_MAX > SIZE_MAX / 2 )
733     if ( p_sys->i_track > (size_t)SIZE_MAX / sizeof(uint16_t) )
734         return;
735 #endif
736     p_prios->pi_stream_numbers = vlc_alloc( p_sys->i_track, sizeof(uint16_t) );
737     if ( !p_prios->pi_stream_numbers ) return;
738
739     if ( p_mutex->i_stream_number_count )
740     {
741         /* Just set highest prio on highest in the group */
742         for ( uint16_t i = 1; i < p_mutex->i_stream_number_count; i++ )
743         {
744             if ( p_prios->i_count > p_sys->i_track || i > p_sys->i_track ) break;
745             p_prios->pi_stream_numbers[ p_prios->i_count++ ] = p_mutex->pi_stream_number[ i ];
746         }
747     }
748 }
749
750 /* Fills up our bitrate exclusion list */
751 static void ASF_fillup_es_bitrate_priorities_ex( demux_sys_t *p_sys, void *p_hdr,
752                                                  asf_es_priorities_t *p_prios )
753 {
754     /* Find bitrate exclusions */
755     asf_object_bitrate_mutual_exclusion_t *p_bitrate_mutex =
756             ASF_FindObject( p_hdr, &asf_object_bitrate_mutual_exclusion_guid, 0 );
757     if (! p_bitrate_mutex ) return;
758
759 #if ( UINT_MAX > SIZE_MAX / 2 )
760     if ( p_sys->i_track > (size_t)SIZE_MAX / sizeof(uint16_t) )
761         return;
762 #endif
763     p_prios->pi_stream_numbers = vlc_alloc( p_sys->i_track, sizeof( uint16_t ) );
764     if ( !p_prios->pi_stream_numbers ) return;
765
766     if ( p_bitrate_mutex->i_stream_number_count )
767     {
768         /* Just remove < highest */
769         for ( uint16_t i = 1; i < p_bitrate_mutex->i_stream_number_count; i++ )
770         {
771             if ( p_prios->i_count > p_sys->i_track || i > p_sys->i_track ) break;
772             p_prios->pi_stream_numbers[ p_prios->i_count++ ] = p_bitrate_mutex->pi_stream_numbers[ i ];
773         }
774     }
775
776 }
777
778 #define GET_CHECKED( target, getter, maxtarget, temp ) \
779 {\
780     temp i_temp = getter;\
781     if ( i_temp > maxtarget ) {\
782         msg_Warn( p_demux, "rejecting stream %u : " #target " overflow", i_stream );\
783         es_format_Clean( &fmt );\
784         goto error;\
785     } else {\
786         target = i_temp;\
787     }\
788 }
789
790 static int DemuxInit( demux_t *p_demux )
791 {
792     demux_sys_t *p_sys = p_demux->p_sys;
793
794     /* init context */
795     p_sys->i_time   = VLC_TICK_INVALID;
796     p_sys->i_sendtime    = VLC_TICK_INVALID;
797     p_sys->i_length = 0;
798     p_sys->b_eos = false;
799     p_sys->b_eof = false;
800     p_sys->i_bitrate = 0;
801     p_sys->p_root   = NULL;
802     p_sys->p_fp     = NULL;
803     p_sys->b_index  = 0;
804     p_sys->i_track  = 0;
805     p_sys->i_seek_track = 0;
806     p_sys->b_pcr_sent = false;
807     p_sys->i_wait_keyframe = 0;
808     for( int i = 0; i < MAX_ASF_TRACKS; i++ )
809     {
810         p_sys->track[i] = NULL;
811     }
812     p_sys->i_data_begin = 0;
813     p_sys->i_data_end   = 0;
814     p_sys->i_preroll_start = 0;
815     p_sys->meta         = NULL;
816
817     /* Now load all object ( except raw data ) */
818     vlc_stream_Control( p_demux->s, STREAM_CAN_FASTSEEK,
819                         &p_sys->b_canfastseek );
820     if( !(p_sys->p_root = ASF_ReadObjectRoot(p_demux->s, p_sys->b_canfastseek)) )
821     {
822         msg_Warn( p_demux, "ASF plugin discarded (not a valid file)" );
823         return VLC_EGENERIC;
824     }
825     p_sys->p_fp = p_sys->p_root->p_fp;
826
827     if( p_sys->p_fp->i_min_data_packet_size != p_sys->p_fp->i_max_data_packet_size )
828     {
829         msg_Warn( p_demux, "ASF plugin discarded (invalid file_properties object)" );
830         goto error;
831     }
832
833     if ( ASF_FindObject( p_sys->p_root->p_hdr,
834                          &asf_object_content_encryption_guid, 0 ) != NULL
835          || ASF_FindObject( p_sys->p_root->p_hdr,
836                             &asf_object_extended_content_encryption_guid, 0 ) != NULL
837          || ASF_FindObject( p_sys->p_root->p_hdr,
838                          &asf_object_advanced_content_encryption_guid, 0 ) != NULL )
839     {
840         vlc_dialog_display_error( p_demux, _("Could not demux ASF stream"), "%s",
841             ("DRM protected streams are not supported.") );
842         goto error;
843     }
844
845     p_sys->i_track = ASF_CountObject( p_sys->p_root->p_hdr,
846                                       &asf_object_stream_properties_guid );
847     if( p_sys->i_track == 0 )
848     {
849         msg_Warn( p_demux, "ASF plugin discarded (cannot find any stream!)" );
850         goto error;
851     }
852     msg_Dbg( p_demux, "found %u streams", p_sys->i_track );
853
854     /* check if index is available */
855     asf_object_index_t *p_index = ASF_FindObject( p_sys->p_root,
856                                                   &asf_object_simple_index_guid, 0 );
857     const bool b_index = p_index && p_index->i_index_entry_count;
858
859     /* Find the extended header if any */
860     asf_object_t *p_hdr_ext = ASF_FindObject( p_sys->p_root->p_hdr,
861                                               &asf_object_header_extension_guid, 0 );
862
863     asf_object_language_list_t *p_languages = NULL;
864     asf_es_priorities_t fmt_priorities_ex = { NULL, 0 };
865     asf_es_priorities_t fmt_priorities_bitrate_ex = { NULL, 0 };
866
867     if( p_hdr_ext )
868     {
869         p_languages = ASF_FindObject( p_hdr_ext, &asf_object_language_list, 0 );
870
871         ASF_fillup_es_priorities_ex( p_sys, p_hdr_ext, &fmt_priorities_ex );
872         ASF_fillup_es_bitrate_priorities_ex( p_sys, p_hdr_ext, &fmt_priorities_bitrate_ex );
873     }
874
875     const bool b_mms = !strncasecmp( p_demux->psz_url, "mms:", 4 );
876     bool b_dvrms = false;
877
878     if( b_mms )
879     {
880         es_out_Control( p_demux->out, ES_OUT_SET_ES_CAT_POLICY,
881                         VIDEO_ES, ES_OUT_ES_POLICY_EXCLUSIVE );
882     }
883
884     for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
885     {
886         asf_track_t    *tk;
887         asf_object_stream_properties_t *p_sp;
888         asf_object_extended_stream_properties_t *p_esp;
889         bool b_access_selected;
890
891         p_sp = ASF_FindObject( p_sys->p_root->p_hdr,
892                                &asf_object_stream_properties_guid,
893                                i_stream );
894         p_esp = NULL;
895
896         /* Ignore duplicated streams numbers */
897         if (p_sys->track[p_sp->i_stream_number])
898             continue;
899
900         tk = p_sys->track[p_sp->i_stream_number] = malloc( sizeof( asf_track_t ) );
901         if (!tk)
902             goto error;
903         memset( tk, 0, sizeof( asf_track_t ) );
904
905         ASFPacketTrackInit( &tk->info );
906         tk->i_time = VLC_TICK_INVALID;
907         tk->info.p_sp = p_sp;
908         tk->p_es = NULL;
909         tk->queue.p_first = NULL;
910         tk->queue.pp_last = &tk->queue.p_first;
911         tk->info.i_pkt = 0;
912         tk->info.i_pktcount = 0;
913
914         if ( !b_mms )
915         {
916             /* Check (not mms) if this track is selected (ie will receive data) */
917             if( !vlc_stream_Control( p_demux->s, STREAM_GET_PRIVATE_ID_STATE,
918                                      (int) p_sp->i_stream_number,
919                                      &b_access_selected ) &&
920                 !b_access_selected )
921             {
922                 tk->i_cat = UNKNOWN_ES;
923                 msg_Dbg( p_demux, "ignoring not selected stream(ID:%u) (by access)",
924                          p_sp->i_stream_number );
925                 continue;
926             }
927         }
928
929         /* Find the associated extended_stream_properties if any */
930         if( p_hdr_ext )
931         {
932             int i_ext_stream = ASF_CountObject( p_hdr_ext,
933                                                 &asf_object_extended_stream_properties_guid );
934             for( int i = 0; i < i_ext_stream; i++ )
935             {
936                 asf_object_t *p_tmp =
937                     ASF_FindObject( p_hdr_ext,
938                                     &asf_object_extended_stream_properties_guid, i );
939                 if( p_tmp->ext_stream.i_stream_number == p_sp->i_stream_number )
940                 {
941                     p_esp = &p_tmp->ext_stream;
942                     tk->info.p_esp = p_esp;
943                     break;
944                 }
945             }
946         }
947
948         /* Check for DVR-MS */
949         if( p_esp )
950             for( uint16_t i=0; i<p_esp->i_payload_extension_system_count && !b_dvrms; i++ )
951                 b_dvrms = guidcmp( &p_esp->p_ext[i].i_extension_id, &asf_dvr_sampleextension_timing_rep_data_guid );
952
953         es_format_t fmt;
954
955         if( guidcmp( &p_sp->i_stream_type, &asf_object_stream_type_audio ) &&
956             p_sp->i_type_specific_data_length >= sizeof( WAVEFORMATEX ) - 2 )
957         {
958             uint8_t *p_data = p_sp->p_type_specific_data;
959             int i_format;
960
961             es_format_Init( &fmt, AUDIO_ES, 0 );
962             i_format = GetWLE( &p_data[0] );
963             wf_tag_to_fourcc( i_format, &fmt.i_codec, NULL );
964
965             GET_CHECKED( fmt.audio.i_channels,      GetWLE( &p_data[2] ),
966                                                         255, uint16_t );
967             GET_CHECKED( fmt.audio.i_rate,          GetDWLE( &p_data[4] ),
968                                                         UINT_MAX, uint32_t );
969             GET_CHECKED( fmt.i_bitrate,             GetDWLE( &p_data[8] ) * 8,
970                                                         UINT_MAX, uint32_t );
971             fmt.audio.i_blockalign      = GetWLE(  &p_data[12] );
972             fmt.audio.i_bitspersample   = GetWLE(  &p_data[14] );
973
974             if( p_sp->i_type_specific_data_length > sizeof( WAVEFORMATEX ) &&
975                 i_format != WAVE_FORMAT_MPEGLAYER3 &&
976                 i_format != WAVE_FORMAT_MPEG )
977             {
978                 GET_CHECKED( fmt.i_extra, __MIN( GetWLE( &p_data[16] ),
979                                      p_sp->i_type_specific_data_length -
980                                      sizeof( WAVEFORMATEX ) ),
981                              INT_MAX, uint32_t );
982                 fmt.p_extra = malloc( fmt.i_extra );
983                 memcpy( fmt.p_extra, &p_data[sizeof( WAVEFORMATEX )],
984                         fmt.i_extra );
985             }
986             msg_Dbg( p_demux, "added new audio stream (codec:%4.4s(0x%x),ID:%d)",
987                 (char*)&fmt.i_codec, GetWLE( p_data ), p_sp->i_stream_number );
988         }
989         else if( guidcmp( &p_sp->i_stream_type,
990                               &asf_object_stream_type_video ) &&
991                  p_sp->i_type_specific_data_length >= 11 +
992                  sizeof( VLC_BITMAPINFOHEADER ) )
993         {
994             uint8_t      *p_data = &p_sp->p_type_specific_data[11];
995
996             es_format_Init( &fmt, VIDEO_ES,
997                             VLC_FOURCC( p_data[16], p_data[17],
998                                         p_data[18], p_data[19] ) );
999
1000             GET_CHECKED( fmt.video.i_width,      GetDWLE( p_data + 4 ),
1001                                                      UINT_MAX, uint32_t );
1002             GET_CHECKED( fmt.video.i_height,     GetDWLE( p_data + 8 ),
1003                                                      UINT_MAX, uint32_t );
1004             fmt.video.i_visible_width = fmt.video.i_width;
1005             fmt.video.i_visible_height = fmt.video.i_height;
1006
1007             if( p_esp && p_esp->i_average_time_per_frame > 0 )
1008             {
1009                 fmt.video.i_frame_rate = 10000000;
1010                 GET_CHECKED( fmt.video.i_frame_rate_base,
1011                              p_esp->i_average_time_per_frame,
1012                              UINT_MAX, uint64_t );
1013             }
1014
1015             if( fmt.i_codec == VLC_FOURCC( 'D','V','R',' ') )
1016             {
1017                 /* DVR-MS special ASF */
1018                 fmt.i_codec = VLC_CODEC_MPGV;
1019             }
1020
1021             if( p_sp->i_type_specific_data_length > 11 +
1022                 sizeof( VLC_BITMAPINFOHEADER ) )
1023             {
1024                 GET_CHECKED( fmt.i_extra, __MIN( GetDWLE( p_data ),
1025                                      p_sp->i_type_specific_data_length - 11 -
1026                                      sizeof( VLC_BITMAPINFOHEADER ) ),
1027                              UINT_MAX, uint32_t );
1028                 fmt.p_extra = malloc( fmt.i_extra );
1029                 memcpy( fmt.p_extra, &p_data[sizeof( VLC_BITMAPINFOHEADER )],
1030                         fmt.i_extra );
1031             }
1032
1033             /* Look for an aspect ratio */
1034             if( p_sys->p_root->p_metadata )
1035             {
1036                 asf_object_metadata_t *p_meta = p_sys->p_root->p_metadata;
1037                 unsigned int i_aspect_x = 0, i_aspect_y = 0;
1038                 uint32_t i;
1039                 for( i = 0; i < p_meta->i_record_entries_count; i++ )
1040                 {
1041                     if( !p_meta->record[i].psz_name )
1042                         continue;
1043                     if( !strcmp( p_meta->record[i].psz_name, "AspectRatioX" ) )
1044                     {
1045                         if( (!i_aspect_x && !p_meta->record[i].i_stream) ||
1046                             p_meta->record[i].i_stream ==
1047                             p_sp->i_stream_number )
1048                             GET_CHECKED( i_aspect_x, p_meta->record[i].i_val,
1049                                          UINT_MAX, uint64_t );
1050                     }
1051                     if( !strcmp( p_meta->record[i].psz_name, "AspectRatioY" ) )
1052                     {
1053                         if( (!i_aspect_y && !p_meta->record[i].i_stream) ||
1054                             p_meta->record[i].i_stream ==
1055                             p_sp->i_stream_number )
1056                             GET_CHECKED( i_aspect_y, p_meta->record[i].i_val,
1057                                          UINT_MAX, uint64_t );
1058                     }
1059                 }
1060
1061                 if( i_aspect_x && i_aspect_y )
1062                 {
1063                     fmt.video.i_sar_num = i_aspect_x;
1064                     fmt.video.i_sar_den = i_aspect_y;
1065                 }
1066             }
1067
1068             /* If there is a video track then use the index for seeking */
1069             p_sys->b_index = b_index;
1070
1071             msg_Dbg( p_demux, "added new video stream(codec:%4.4s,ID:%d)",
1072                      (char*)&fmt.i_codec, p_sp->i_stream_number );
1073         }
1074         else if( guidcmp( &p_sp->i_stream_type, &asf_object_stream_type_binary ) &&
1075             p_sp->i_type_specific_data_length >= 64 )
1076         {
1077             vlc_guid_t i_major_media_type;
1078             ASF_GetGUID( &i_major_media_type, p_sp->p_type_specific_data );
1079             msg_Dbg( p_demux, "stream(ID:%d) major type " GUID_FMT, p_sp->i_stream_number,
1080                      GUID_PRINT(i_major_media_type) );
1081
1082             vlc_guid_t i_media_subtype;
1083             ASF_GetGUID( &i_media_subtype, &p_sp->p_type_specific_data[16] );
1084             msg_Dbg( p_demux, "stream(ID:%d) subtype " GUID_FMT, p_sp->i_stream_number,
1085                      GUID_PRINT(i_media_subtype) );
1086
1087             //uint32_t i_fixed_size_samples = GetDWBE( &p_sp->p_type_specific_data[32] );
1088             //uint32_t i_temporal_compression = GetDWBE( &p_sp->p_type_specific_data[36] );
1089             //uint32_t i_sample_size = GetDWBE( &p_sp->p_type_specific_data[40] );
1090
1091             vlc_guid_t i_format_type;
1092             ASF_GetGUID( &i_format_type, &p_sp->p_type_specific_data[44] );
1093             msg_Dbg( p_demux, "stream(ID:%d) format type " GUID_FMT, p_sp->i_stream_number,
1094                      GUID_PRINT(i_format_type) );
1095
1096             //uint32_t i_format_data_size = GetDWBE( &p_sp->p_type_specific_data[60] );
1097             uint8_t *p_data = p_sp->p_type_specific_data + 64;
1098             unsigned int i_data = p_sp->i_type_specific_data_length - 64;
1099
1100             msg_Dbg( p_demux, "Ext stream header detected. datasize = %d", p_sp->i_type_specific_data_length );
1101             if( guidcmp( &i_major_media_type, &asf_object_extended_stream_type_audio ) &&
1102                 i_data >= sizeof( WAVEFORMATEX ) - 2)
1103             {
1104                 uint16_t i_format;
1105                 es_format_Init( &fmt, AUDIO_ES, 0 );
1106
1107                 i_format = GetWLE( &p_data[0] );
1108                 if( i_format == 0 )
1109                     fmt.i_codec = VLC_CODEC_A52;
1110                 else
1111                     wf_tag_to_fourcc( i_format, &fmt.i_codec, NULL );
1112
1113                 GET_CHECKED( fmt.audio.i_channels,      GetWLE( &p_data[2] ),
1114                                                             255, uint16_t );
1115                 GET_CHECKED( fmt.audio.i_rate,          GetDWLE( &p_data[4] ),
1116                                                             UINT_MAX, uint32_t );
1117                 GET_CHECKED( fmt.i_bitrate,             GetDWLE( &p_data[8] ) * 8,
1118                                                             UINT_MAX, uint32_t );
1119                 fmt.audio.i_blockalign      = GetWLE(  &p_data[12] );
1120                 fmt.audio.i_bitspersample   = GetWLE(  &p_data[14] );
1121
1122                 if( p_sp->i_type_specific_data_length > sizeof( WAVEFORMATEX ) &&
1123                     i_format != WAVE_FORMAT_MPEGLAYER3 &&
1124                     i_format != WAVE_FORMAT_MPEG && i_data >= 19 )
1125                 {
1126                     GET_CHECKED( fmt.i_extra, __MIN( GetWLE( &p_data[16] ),
1127                                          p_sp->i_type_specific_data_length -
1128                                          sizeof( WAVEFORMATEX ) - 64),
1129                                  INT_MAX, uint32_t );
1130                     fmt.p_extra = malloc( fmt.i_extra );
1131                     if ( fmt.p_extra )
1132                         memcpy( fmt.p_extra, &p_data[sizeof( WAVEFORMATEX )], fmt.i_extra );
1133                     else
1134                         fmt.i_extra = 0;
1135                 }
1136
1137                 msg_Dbg( p_demux, "added new audio stream (codec:%4.4s(0x%x),ID:%d)",
1138                     (char*)&fmt.i_codec, i_format, p_sp->i_stream_number );
1139             }
1140             else
1141             {
1142                 es_format_Init( &fmt, UNKNOWN_ES, 0 );
1143             }
1144         }
1145         else
1146         {
1147             es_format_Init( &fmt, UNKNOWN_ES, 0 );
1148         }
1149
1150         if( b_dvrms )
1151         {
1152             fmt.i_original_fourcc = VLC_FOURCC( 'D','V','R',' ');
1153             fmt.b_packetized = false;
1154         }
1155
1156         if( fmt.i_codec == VLC_CODEC_MP4A )
1157             fmt.b_packetized = false;
1158
1159         tk->i_cat = tk->info.i_cat = fmt.i_cat;
1160         if( fmt.i_cat != UNKNOWN_ES )
1161         {
1162             if( p_esp && p_languages &&
1163                 p_esp->i_language_index < p_languages->i_language &&
1164                 p_languages->ppsz_language[p_esp->i_language_index] )
1165             {
1166                 fmt.psz_language = strdup( p_languages->ppsz_language[p_esp->i_language_index] );
1167                 char *p;
1168                 if( fmt.psz_language && (p = strchr( fmt.psz_language, '-' )) )
1169                     *p = '\0';
1170             }
1171
1172             /* Set our priority so we won't get multiple videos */
1173             int i_priority = ES_PRIORITY_SELECTABLE_MIN;
1174             for( uint16_t i = 0; i < fmt_priorities_ex.i_count; i++ )
1175             {
1176                 if ( fmt_priorities_ex.pi_stream_numbers[i] == p_sp->i_stream_number )
1177                 {
1178                     i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
1179                     break;
1180                 }
1181             }
1182             for( uint16_t i = 0; i < fmt_priorities_bitrate_ex.i_count; i++ )
1183             {
1184                 if ( fmt_priorities_bitrate_ex.pi_stream_numbers[i] == p_sp->i_stream_number )
1185                 {
1186                     i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
1187                     break;
1188                 }
1189             }
1190             fmt.i_priority = i_priority;
1191
1192             if ( i_stream <= INT_MAX )
1193                 fmt.i_id = i_stream;
1194             else
1195                 msg_Warn( p_demux, "Can't set fmt.i_id to match stream id %u", i_stream );
1196
1197             if ( fmt.i_cat == VIDEO_ES )
1198             {
1199                 /* Backup our video format */
1200                 tk->p_fmt = malloc( sizeof( es_format_t ) );
1201                 if ( tk->p_fmt )
1202                     es_format_Copy( tk->p_fmt, &fmt );
1203             }
1204
1205             fmt.i_id = tk->info.p_sp->i_stream_number;
1206
1207             tk->p_es = es_out_Add( p_demux->out, &fmt );
1208
1209             if( !vlc_stream_Control( p_demux->s, STREAM_GET_PRIVATE_ID_STATE,
1210                                      (int) p_sp->i_stream_number,
1211                                      &b_access_selected ) &&
1212                 b_access_selected )
1213             {
1214                 p_sys->i_access_selected_track[fmt.i_cat] = p_sp->i_stream_number;
1215             }
1216
1217         }
1218         else
1219         {
1220             msg_Dbg( p_demux, "ignoring unknown stream(ID:%d)",
1221                      p_sp->i_stream_number );
1222         }
1223
1224         es_format_Clean( &fmt );
1225     }
1226
1227     free( fmt_priorities_ex.pi_stream_numbers );
1228     free( fmt_priorities_bitrate_ex.pi_stream_numbers );
1229
1230     p_sys->i_data_begin = p_sys->p_root->p_data->i_object_pos + 50;
1231     if( p_sys->p_root->p_data->i_object_size != 0 )
1232     { /* local file */
1233         p_sys->i_data_end = p_sys->p_root->p_data->i_object_pos +
1234                                     p_sys->p_root->p_data->i_object_size;
1235         p_sys->i_data_end = __MIN( (uint64_t)stream_Size( p_demux->s ), p_sys->i_data_end );
1236     }
1237     else
1238     { /* live/broacast */
1239         p_sys->i_data_end = 0;
1240     }
1241
1242     /* go to first packet */
1243     if( vlc_stream_Seek( p_demux->s, p_sys->i_data_begin ) != VLC_SUCCESS )
1244         goto error;
1245
1246     /* try to calculate movie time */
1247     if( p_sys->p_fp->i_data_packets_count > 0 )
1248     {
1249         uint64_t i_count;
1250         uint64_t i_size = stream_Size( p_demux->s );
1251
1252         if( p_sys->i_data_end > 0 && i_size > p_sys->i_data_end )
1253         {
1254             i_size = p_sys->i_data_end;
1255         }
1256
1257         /* real number of packets */
1258         i_count = ( i_size - p_sys->i_data_begin ) /
1259                   p_sys->p_fp->i_min_data_packet_size;
1260
1261         /* calculate the time duration in micro-s */
1262         p_sys->i_length = VLC_TICK_FROM_MSFTIME(p_sys->p_fp->i_play_duration) *
1263                    (vlc_tick_t)i_count /
1264                    (vlc_tick_t)p_sys->p_fp->i_data_packets_count;
1265         if( p_sys->i_length <= p_sys->p_fp->i_preroll )
1266             p_sys->i_length = 0;
1267         else
1268         {
1269             p_sys->i_length  -= p_sys->p_fp->i_preroll;
1270             p_sys->i_bitrate = 8 * i_size * CLOCK_FREQ / p_sys->i_length;
1271         }
1272     }
1273
1274     /* Create meta information */
1275     p_sys->meta = vlc_meta_New();
1276
1277     asf_object_content_description_t *p_cd;
1278     if( ( p_cd = ASF_FindObject( p_sys->p_root->p_hdr,
1279                                  &asf_object_content_description_guid, 0 ) ) )
1280     {
1281         if( p_cd->psz_title && *p_cd->psz_title )
1282         {
1283             vlc_meta_SetTitle( p_sys->meta, p_cd->psz_title );
1284         }
1285         if( p_cd->psz_artist && *p_cd->psz_artist )
1286         {
1287              vlc_meta_SetArtist( p_sys->meta, p_cd->psz_artist );
1288         }
1289         if( p_cd->psz_copyright && *p_cd->psz_copyright )
1290         {
1291             vlc_meta_SetCopyright( p_sys->meta, p_cd->psz_copyright );
1292         }
1293         if( p_cd->psz_description && *p_cd->psz_description )
1294         {
1295             vlc_meta_SetDescription( p_sys->meta, p_cd->psz_description );
1296         }
1297         if( p_cd->psz_rating && *p_cd->psz_rating )
1298         {
1299             vlc_meta_SetRating( p_sys->meta, p_cd->psz_rating );
1300         }
1301     }
1302     asf_object_extended_content_description_t *p_ecd;
1303     if( ( p_ecd = ASF_FindObject( p_sys->p_root->p_hdr,
1304                                  &asf_object_extended_content_description, 0 ) ) )
1305     {
1306         for( int i = 0; i < p_ecd->i_count; i++ )
1307         {
1308
1309 #define set_meta( name, vlc_type ) \
1310             if( p_ecd->ppsz_name[i] && !strncmp( p_ecd->ppsz_name[i], name, strlen(name) ) ) \
1311                 vlc_meta_Set( p_sys->meta, vlc_type, p_ecd->ppsz_value[i] );
1312
1313             set_meta( "WM/AlbumTitle",   vlc_meta_Album )
1314             else set_meta( "WM/TrackNumber",  vlc_meta_TrackNumber )
1315             else set_meta( "WM/Year",         vlc_meta_Date )
1316             else set_meta( "WM/Genre",        vlc_meta_Genre )
1317             else set_meta( "WM/Genre",        vlc_meta_Genre )
1318             else set_meta( "WM/AlbumArtist",  vlc_meta_AlbumArtist )
1319             else set_meta( "WM/Publisher",    vlc_meta_Publisher )
1320             else set_meta( "WM/PartOfSet",    vlc_meta_DiscNumber )
1321             else if( p_ecd->ppsz_value[i] != NULL && p_ecd->ppsz_name[i] &&
1322                     *p_ecd->ppsz_value[i] != '\0' && /* no empty value */
1323                     *p_ecd->ppsz_value[i] != '{'  && /* no guid value */
1324                     *p_ecd->ppsz_name[i] != '{' )    /* no guid name */
1325                     vlc_meta_AddExtra( p_sys->meta, p_ecd->ppsz_name[i], p_ecd->ppsz_value[i] );
1326             /* TODO map WM/Composer, WM/Provider, WM/PartOfSet, PeakValue, AverageLevel  */
1327 #undef set_meta
1328         }
1329     }
1330
1331     /// \tood Fix Child meta for ASF tracks
1332 #if 0
1333     for( i_stream = 0, i = 0; i < MAX_ASF_TRACKS; i++ )
1334     {
1335         asf_object_codec_list_t *p_cl = ASF_FindObject( p_sys->p_root->p_hdr,
1336                                                         &asf_object_codec_list_guid, 0 );
1337
1338         if( p_sys->track[i] )
1339         {
1340             vlc_meta_t *tk = vlc_meta_New();
1341             TAB_APPEND( p_sys->meta->i_track, p_sys->meta->track, tk );
1342
1343             if( p_cl && i_stream < p_cl->i_codec_entries_count )
1344             {
1345                 if( p_cl->codec[i_stream].psz_name &&
1346                     *p_cl->codec[i_stream].psz_name )
1347                 {
1348                     vlc_meta_Add( tk, VLC_META_CODEC_NAME,
1349                                   p_cl->codec[i_stream].psz_name );
1350                 }
1351                 if( p_cl->codec[i_stream].psz_description &&
1352                     *p_cl->codec[i_stream].psz_description )
1353                 {
1354                     vlc_meta_Add( tk, VLC_META_CODEC_DESCRIPTION,
1355                                   p_cl->codec[i_stream].psz_description );
1356                 }
1357             }
1358             i_stream++;
1359         }
1360     }
1361 #endif
1362
1363     p_sys->packet_sys.pi_preroll = &p_sys->p_fp->i_preroll;
1364     p_sys->packet_sys.pi_preroll_start = &p_sys->i_preroll_start;
1365     p_sys->packet_sys.b_can_hold_multiple_packets = false;
1366
1367     return VLC_SUCCESS;
1368
1369 error:
1370     DemuxEnd( p_demux );
1371     return VLC_EGENERIC;
1372 }
1373
1374 /*****************************************************************************
1375  * FlushQueues: flushes tail packets and send queues
1376  *****************************************************************************/
1377 static void FlushQueue( asf_track_t *tk )
1378 {
1379     ASFPacketTrackReset( &tk->info );
1380     if( tk->queue.p_first )
1381     {
1382         block_ChainRelease( tk->queue.p_first );
1383         tk->queue.p_first = NULL;
1384         tk->queue.pp_last = &tk->queue.p_first;
1385     }
1386 }
1387
1388 static void FlushQueues( demux_t *p_demux )
1389 {
1390     demux_sys_t *p_sys = p_demux->p_sys;
1391     for ( unsigned int i = 0; i < MAX_ASF_TRACKS; i++ )
1392     {
1393         asf_track_t *tk = p_sys->track[i];
1394         if( !tk )
1395             continue;
1396         FlushQueue( tk );
1397     }
1398 }
1399
1400 /*****************************************************************************
1401  *
1402  *****************************************************************************/
1403 static void DemuxEnd( demux_t *p_demux )
1404 {
1405     demux_sys_t *p_sys = p_demux->p_sys;
1406
1407     if( p_sys->p_root )
1408     {
1409         ASF_FreeObjectRoot( p_demux->s, p_sys->p_root );
1410         p_sys->p_root = NULL;
1411         p_sys->p_fp = NULL;
1412     }
1413     if( p_sys->meta )
1414     {
1415         vlc_meta_Delete( p_sys->meta );
1416         p_sys->meta = NULL;
1417     }
1418
1419     FlushQueues( p_demux );
1420
1421     for( int i = 0; i < MAX_ASF_TRACKS; i++ )
1422     {
1423         asf_track_t *tk = p_sys->track[i];
1424
1425         if( tk )
1426         {
1427             if( tk->p_es )
1428             {
1429                 es_out_Del( p_demux->out, tk->p_es );
1430             }
1431             if ( tk->p_fmt )
1432             {
1433                 es_format_Clean( tk->p_fmt );
1434                 free( tk->p_fmt );
1435             }
1436             free( tk );
1437         }
1438         p_sys->track[i] = 0;
1439     }
1440 }
1441