]> git.sesse.net Git - vlc/blobdiff - modules/demux/asf/asf.c
demux: mp4: fix heap read ofw in extra bytes
[vlc] / modules / demux / asf / asf.c
index f169d37bc34994016f4bad26414d99e5f6ed157d..0622ff81a3bb1e0d9774efd6f254ef47b12fb91f 100644 (file)
 #include <vlc_meta.h>                  /* vlc_meta_Set*, vlc_meta_New */
 #include <vlc_access.h>                /* GET_PRIVATE_ID_STATE */
 #include <vlc_codecs.h>                /* VLC_BITMAPINFOHEADER, WAVEFORMATEX */
+#include <vlc_input.h>
+#include <vlc_vout.h>
 
 #include <limits.h>
 
+#include "asfpacket.h"
 #include "libasf.h"
+#include "assert.h"
 
 /* TODO
  *  - add support for the newly added object: language, bitrate,
@@ -67,19 +71,32 @@ vlc_module_end ()
  *****************************************************************************/
 static int Demux  ( demux_t * );
 static int Control( demux_t *, int i_query, va_list args );
+static void FlushRemainingPackets( demux_t *p_demux );
+
+#define MAX_ASF_TRACKS (ASF_MAX_STREAMNUMBER + 1)
+#define ASF_PREROLL_FROM_CURRENT -1
+
+/* callbacks for packet parser */
+static void Packet_UpdateTime( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number,
+                               mtime_t i_time );
+static asf_track_info_t * Packet_GetTrackInfo( asf_packet_sys_t *p_packetsys,
+                                               uint8_t i_stream_number );
+static bool Packet_DoSkip( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, bool b_packet_keyframe );
+static void Packet_Send(asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, block_t **pp_frame);
+static void Packet_SetAR( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number,
+                          uint8_t i_ratio_x, uint8_t i_ratio_y );
 
 typedef struct
 {
     int i_cat;
 
     es_out_id_t     *p_es;
+    es_format_t     *p_fmt; /* format backup for video changes */
+    bool             b_selected;
 
-    asf_object_stream_properties_t *p_sp;
-    asf_object_extended_stream_properties_t *p_esp;
-
-    mtime_t i_time;
+    mtime_t          i_time; /* track time*/
 
-    block_t         *p_frame; /* use to gather complete frame */
+    asf_track_info_t info;
 
 } asf_track_t;
 
@@ -87,29 +104,33 @@ struct demux_sys_t
 {
     mtime_t             i_time;     /* s */
     mtime_t             i_length;   /* length of file file */
-    int64_t             i_bitrate;  /* global file bitrate */
+    uint64_t            i_bitrate;  /* global file bitrate */
 
     asf_object_root_t            *p_root;
     asf_object_file_properties_t *p_fp;
 
     unsigned int        i_track;
-    asf_track_t         *track[128]; /* track number is stored on 7 bits */
+    asf_track_t         *track[MAX_ASF_TRACKS]; /* track number is stored on 7 bits */
 
-    int64_t             i_data_begin;
-    int64_t             i_data_end;
+    uint64_t            i_data_begin;
+    uint64_t            i_data_end;
 
     bool                b_index;
     bool                b_canfastseek;
     uint8_t             i_seek_track;
+    uint8_t             i_access_selected_track[ES_CATEGORY_COUNT]; /* mms, depends on access algorithm */
     unsigned int        i_wait_keyframe;
 
+    mtime_t             i_preroll_start;
+
+    asf_packet_sys_t    packet_sys;
+
     vlc_meta_t          *meta;
 };
 
 static mtime_t  GetMoviePTS( demux_sys_t * );
 static int      DemuxInit( demux_t * );
 static void     DemuxEnd( demux_t * );
-static int      DemuxPacket( demux_t * );
 
 /*****************************************************************************
  * Open: check file and initializes ASF structures
@@ -138,10 +159,17 @@ static int Open( vlc_object_t * p_this )
         free( p_sys );
         return VLC_EGENERIC;
     }
+
+    p_sys->packet_sys.p_demux = p_demux;
+    p_sys->packet_sys.pf_doskip = Packet_DoSkip;
+    p_sys->packet_sys.pf_send = Packet_Send;
+    p_sys->packet_sys.pf_gettrackinfo = Packet_GetTrackInfo;
+    p_sys->packet_sys.pf_updatetime = Packet_UpdateTime;
+    p_sys->packet_sys.pf_setaspectratio = Packet_SetAR;
+
     return VLC_SUCCESS;
 }
 
-
 /*****************************************************************************
  * Demux: read packet and send them to decoders
  *****************************************************************************/
@@ -149,6 +177,27 @@ static int Demux( demux_t *p_demux )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
 
+    for( int i=0; i<ES_CATEGORY_COUNT; i++ )
+    {
+        if ( p_sys->i_access_selected_track[i] > 0 )
+        {
+            es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
+                            p_sys->track[p_sys->i_access_selected_track[i]]->p_es, true );
+            p_sys->i_access_selected_track[i] = 0;
+        }
+    }
+
+    /* Get selected tracks, especially for computing PCR */
+    for( int i=0; i<MAX_ASF_TRACKS; i++ )
+    {
+        asf_track_t *tk = p_sys->track[i];
+        if ( !tk ) continue;
+        if ( tk->p_es )
+            es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, & tk->b_selected );
+        else
+            tk->b_selected = false;
+    }
+
     for( ;; )
     {
         const uint8_t *p_peek;
@@ -191,8 +240,11 @@ static int Demux( demux_t *p_demux )
         }
 
         /* Read and demux a packet */
-        if( ( i_result = DemuxPacket( p_demux ) ) <= 0 )
+        if( ( i_result = DemuxASFPacket( &p_sys->packet_sys,
+                                      p_sys->p_fp->i_min_data_packet_size,
+                                      p_sys->p_fp->i_max_data_packet_size ) ) <= 0 )
         {
+            FlushRemainingPackets( p_demux );
             return i_result;
         }
         if( i_time_begin == -1 )
@@ -207,10 +259,14 @@ static int Demux( demux_t *p_demux )
     }
 
     /* Set the PCR */
+    /* WARN: Don't move it before the end of the whole chunk */
     p_sys->i_time = GetMoviePTS( p_sys );
     if( p_sys->i_time >= 0 )
     {
-        es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_time+1 );
+#ifdef ASF_DEBUG
+        msg_Dbg( p_demux, "Demux Loop Setting PCR to %"PRId64, VLC_TS_0 + p_sys->i_time );
+#endif
+        es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
     }
 
     return 1;
@@ -236,19 +292,13 @@ static void WaitKeyframe( demux_t *p_demux )
     demux_sys_t *p_sys = p_demux->p_sys;
     if ( ! p_sys->i_seek_track )
     {
-        for ( int i=0; i<128; i++ )
+        for ( int i=0; i<MAX_ASF_TRACKS; i++ )
         {
             asf_track_t *tk = p_sys->track[i];
-            if ( tk && tk->p_sp && tk->i_cat == VIDEO_ES )
+            if ( tk && tk->info.p_sp && tk->i_cat == VIDEO_ES && tk->b_selected )
             {
-                bool b_selected = false;
-                es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
-                                tk->p_es, &b_selected );
-                if ( b_selected )
-                {
-                    p_sys->i_seek_track = tk->p_sp->i_stream_number;
-                    break;
-                }
+                p_sys->i_seek_track = tk->info.p_sp->i_stream_number;
+                break;
             }
         }
     }
@@ -257,12 +307,12 @@ static void WaitKeyframe( demux_t *p_demux )
     {
         /* Skip forward at least 1 min */
         asf_track_t *tk = p_sys->track[p_sys->i_seek_track];
-        if ( tk->p_esp && tk->p_esp->i_average_time_per_frame )
+        if ( tk->info.p_esp && tk->info.p_esp->i_average_time_per_frame )
         {
             /* 1 min if fastseek, otherwise 5 sec */
             /* That's a guess for bandwidth */
             uint64_t i_maxwaittime = ( p_sys->b_canfastseek ) ? 600000000 : 50000000;
-            i_maxwaittime /= tk->p_esp->i_average_time_per_frame;
+            i_maxwaittime /= tk->info.p_esp->i_average_time_per_frame;
             p_sys->i_wait_keyframe = __MIN( i_maxwaittime, UINT_MAX );
         }
         else
@@ -287,9 +337,10 @@ static int SeekPercent( demux_t *p_demux, int i_query, va_list args )
     WaitKeyframe( p_demux );
 
     msg_Dbg( p_demux, "seek with percent: waiting %i frames", p_sys->i_wait_keyframe );
-    return demux_vaControlHelper( p_demux->s, p_sys->i_data_begin,
-                                   p_sys->i_data_end, p_sys->i_bitrate,
-                                   p_sys->p_fp->i_min_data_packet_size,
+    return demux_vaControlHelper( p_demux->s, __MIN( INT64_MAX, p_sys->i_data_begin ),
+                                   __MIN( INT64_MAX, p_sys->i_data_end ),
+                                   __MIN( INT64_MAX, p_sys->i_bitrate ),
+                                   __MIN( INT16_MAX, p_sys->p_fp->i_min_data_packet_size ),
                                    i_query, args );
 }
 
@@ -304,9 +355,12 @@ static int SeekIndex( demux_t *p_demux, mtime_t i_date, float f_pos )
     if( i_date < 0 )
         i_date = p_sys->i_length * f_pos;
 
+    p_sys->i_preroll_start = i_date - (int64_t) p_sys->p_fp->i_preroll;
+    if ( p_sys->i_preroll_start < 0 ) p_sys->i_preroll_start = 0;
+
     p_index = ASF_FindObject( p_sys->p_root, &asf_object_simple_index_guid, 0 );
 
-    uint64_t i_entry = i_date * 10 / p_index->i_index_entry_time_interval;
+    uint64_t i_entry = p_sys->i_preroll_start * 10 / p_index->i_index_entry_time_interval;
     if( i_entry >= p_index->i_index_entry_count )
     {
         msg_Warn( p_demux, "Incomplete index" );
@@ -331,19 +385,20 @@ static void SeekPrepare( demux_t *p_demux )
     demux_sys_t *p_sys = p_demux->p_sys;
 
     p_sys->i_time = VLC_TS_INVALID;
-    for( int i = 0; i < 128 ; i++ )
+    p_sys->i_preroll_start = ASFPACKET_PREROLL_FROM_CURRENT;
+    for( int i = 0; i < MAX_ASF_TRACKS ; i++ )
     {
         asf_track_t *tk = p_sys->track[i];
         if( !tk )
             continue;
 
-        tk->i_time = VLC_TS_INVALID;
-        if( tk->p_frame )
-            block_ChainRelease( tk->p_frame );
-        tk->p_frame = NULL;
+        tk->i_time = -1;
+        if( tk->info.p_frame )
+            block_ChainRelease( tk->info.p_frame );
+        tk->info.p_frame = NULL;
     }
 
-    es_out_Control( p_demux->out, ES_OUT_RESET_PCR, VLC_TS_INVALID );
+    es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
 }
 
 /*****************************************************************************
@@ -354,6 +409,7 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
     demux_sys_t *p_sys = p_demux->p_sys;
     vlc_meta_t  *p_meta;
     int64_t     i64, *pi64;
+    int         i;
     double      f, *pf;
 
     switch( i_query )
@@ -388,6 +444,31 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
         }
         return SeekPercent( p_demux, i_query, args );
 
+    case DEMUX_SET_ES:
+    {
+        i = (int)va_arg( args, int );
+        int i_ret;
+        if ( i >= 0 )
+        {
+            i++; /* video/audio-es variable starts 0 */
+            msg_Dbg( p_demux, "Requesting access to enable stream %d", i );
+            i_ret = stream_Control( p_demux->s, STREAM_SET_PRIVATE_ID_STATE, i, true );
+        }
+        else
+        {  /* i contains -1 * es_category */
+            msg_Dbg( p_demux, "Requesting access to disable stream %d", i );
+            i_ret = stream_Control( p_demux->s, STREAM_SET_PRIVATE_ID_STATE, i, false );
+        }
+
+        if ( i_ret == VLC_SUCCESS )
+        {
+            SeekPrepare( p_demux );
+            p_sys->i_seek_track = 0;
+            WaitKeyframe( p_demux );
+        }
+        return i_ret;
+    }
+
     case DEMUX_GET_POSITION:
         if( p_sys->i_time < 0 ) return VLC_EGENERIC;
         if( p_sys->i_length > 0 )
@@ -396,9 +477,11 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
             *pf = p_sys->i_time / (double)p_sys->i_length;
             return VLC_SUCCESS;
         }
-        return demux_vaControlHelper( p_demux->s, p_sys->i_data_begin,
-                                       p_sys->i_data_end, p_sys->i_bitrate,
-                                       p_sys->p_fp->i_min_data_packet_size,
+        return demux_vaControlHelper( p_demux->s,
+                                       __MIN( INT64_MAX, p_sys->i_data_begin ),
+                                       __MIN( INT64_MAX, p_sys->i_data_end ),
+                                       __MIN( INT64_MAX, p_sys->i_bitrate ),
+                                       __MIN( INT16_MAX, p_sys->p_fp->i_min_data_packet_size ),
                                        i_query, args );
 
     case DEMUX_SET_POSITION:
@@ -436,9 +519,11 @@ static int Control( demux_t *p_demux, int i_query, va_list args )
         // ft
 
     default:
-        return demux_vaControlHelper( p_demux->s, p_sys->i_data_begin,
-                    p_sys->i_data_end, p_sys->i_bitrate,
-                    ( p_sys->p_fp ) ? p_sys->p_fp->i_min_data_packet_size : 1,
+        return demux_vaControlHelper( p_demux->s,
+                                      __MIN( INT64_MAX, p_sys->i_data_begin ),
+                                      __MIN( INT64_MAX, p_sys->i_data_end),
+                                      __MIN( INT64_MAX, p_sys->i_bitrate ),
+                    ( p_sys->p_fp ) ? __MIN( INT_MAX, p_sys->p_fp->i_min_data_packet_size ) : 1,
                     i_query, args );
     }
 }
@@ -450,201 +535,85 @@ static mtime_t GetMoviePTS( demux_sys_t *p_sys )
 {
     mtime_t i_time = -1;
     int     i;
-
-    for( i = 0; i < 128 ; i++ )
+    /* As some tracks might have been deselected by access, the PCR might
+     * stop updating */
+    for( i = 0; i < MAX_ASF_TRACKS ; i++ )
     {
-        asf_track_t *tk = p_sys->track[i];
+        const asf_track_t *tk = p_sys->track[i];
 
-        if( tk && tk->p_es && tk->i_time > 0)
+        if( tk && tk->p_es && tk->b_selected )
         {
-            if( i_time < 0 ) i_time = tk->i_time;
-            else i_time = __MIN( i_time, tk->i_time );
+            /* Skip discrete tracks */
+            if ( tk->i_cat != VIDEO_ES && tk->i_cat != AUDIO_ES )
+                continue;
+
+            /* We need to have all ES seen once, as they might have lower DTS */
+            if ( tk->i_time + (int64_t)p_sys->p_fp->i_preroll * 1000 < 0 )
+            {
+                /* early fail */
+                return -1;
+            }
+            else if ( tk->i_time > -1 && ( i_time == -1 || i_time > tk->i_time ) )
+            {
+                i_time = tk->i_time;
+            }
         }
     }
 
     return i_time;
 }
 
-static inline int GetValue2b(uint32_t *var, const uint8_t *p, unsigned int *skip, int left, int bits)
+static void Packet_SetAR( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number,
+                          uint8_t i_ratio_x, uint8_t i_ratio_y )
 {
-    switch(bits&0x03)
+    demux_t *p_demux = p_packetsys->p_demux;
+    asf_track_t *tk = p_demux->p_sys->track[i_stream_number];
+    if ( tk->p_fmt->video.i_sar_num == i_ratio_x && tk->p_fmt->video.i_sar_den == i_ratio_y )
+        return;
+
+    /* Only apply if origin pixel size >= 1x1, due to broken yacast */
+    if ( tk->p_fmt->video.i_height * i_ratio_x > tk->p_fmt->video.i_width * i_ratio_y )
     {
-    case 1:
-        if (left < 1)
-            return -1;
-        *var = p[*skip]; *skip += 1;
-        return 0;
-    case 2:
-        if (left < 2)
-            return -1;
-        *var = GetWLE(&p[*skip]); *skip += 2;
-        return 0;
-    case 3:
-        if (left < 4)
-            return -1;
-        *var = GetDWLE(&p[*skip]); *skip += 4;
-        return 0;
-    case 0:
-    default:
-        return 0;
+        vout_thread_t *p_vout = input_GetVout( p_demux->p_input );
+        if ( p_vout )
+        {
+            msg_Info( p_demux, "Changing aspect ratio to %i/%i", i_ratio_x, i_ratio_y );
+            vout_ChangeAspectRatio( p_vout, i_ratio_x, i_ratio_y );
+            vlc_object_release( p_vout );
+        }
     }
+    tk->p_fmt->video.i_sar_num = i_ratio_x;
+    tk->p_fmt->video.i_sar_den = i_ratio_y;
 }
 
-struct asf_packet_t
+static void Packet_UpdateTime( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number,
+                               mtime_t i_time )
 {
-    uint32_t property;
-    uint32_t length;
-    uint32_t padding_length;
-    uint32_t send_time;
-    bool multiple;
-    int length_type;
-
-    /* buffer handling for this ASF packet */
-    uint32_t i_skip;
-    const uint8_t *p_peek;
-    uint32_t left;
-};
-
-static void SendPacket(demux_t *p_demux, asf_track_t *tk)
-{
-    demux_sys_t *p_sys = p_demux->p_sys;
-
-    block_t *p_gather = block_ChainGather( tk->p_frame );
-
-    if( p_gather->i_dts > VLC_TS_INVALID )
-        tk->i_time = p_gather->i_dts - VLC_TS_0;
-
-    if( p_sys->i_time < 0 )
-        es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_gather->i_dts );
-
-    es_out_Send( p_demux->out, tk->p_es, p_gather );
-
-    tk->p_frame = NULL;
-}
-
-static int DemuxSubPayload(demux_t *p_demux, asf_track_t *tk,
-        uint32_t i_sub_payload_data_length, mtime_t i_pts, uint32_t i_media_object_offset)
-{
-    /* FIXME I don't use i_media_object_number, sould I ? */
-    if( tk->p_frame && i_media_object_offset == 0 )
-        SendPacket(p_demux, tk);
-
-    block_t *p_frag = stream_Block( p_demux->s, i_sub_payload_data_length );
-    if( p_frag == NULL ) {
-        msg_Warn( p_demux, "cannot read data" );
-        return -1;
-    }
-
-    if( tk->p_frame == NULL ) {
-        p_frag->i_pts = VLC_TS_0 + i_pts;
-        p_frag->i_dts = VLC_TS_0 + p_frag->i_pts; //FIXME: VLC_TS_0 * 2 ?
-        if( tk->i_cat == VIDEO_ES )
-            p_frag->i_pts = VLC_TS_INVALID;
-    }
-
-    block_ChainAppend( &tk->p_frame, p_frag );
-
-    return 0;
+    asf_track_t *tk = p_packetsys->p_demux->p_sys->track[i_stream_number];
+    if ( tk )
+        tk->i_time = i_time;
 }
 
-static uint32_t SkipBytes( stream_t *s, uint32_t i_bytes )
+static asf_track_info_t * Packet_GetTrackInfo( asf_packet_sys_t *p_packetsys,
+                                               uint8_t i_stream_number )
 {
-    int i_read;
-    int i_to_read = __MIN(i_bytes, INT_MAX);
-    uint32_t i_bytes_read = 0;
-
-    while( i_bytes )
-    {
-        i_read = stream_Read( s, NULL, i_to_read );
-        i_bytes -= i_read;
-        i_bytes_read += i_read;
-        if ( i_read < i_to_read || i_bytes == 0 )
-        {
-            /* end of stream */
-            return i_bytes_read;
-        }
-        i_to_read = __MIN(i_bytes, INT_MAX);
-    }
-
-    return i_bytes_read;
+    asf_track_t *tk = p_packetsys->p_demux->p_sys->track[i_stream_number];
+    if (!tk)
+        return NULL;
+    else
+        return & tk->info;
 }
 
-static int DemuxPayload(demux_t *p_demux, struct asf_packet_t *pkt, int i_payload)
+static bool Packet_DoSkip( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, bool b_packet_keyframe )
 {
-#ifndef ASF_DEBUG
-    VLC_UNUSED( i_payload );
-#endif
+    demux_t *p_demux = p_packetsys->p_demux;
     demux_sys_t *p_sys = p_demux->p_sys;
+    const asf_track_t *tk = p_sys->track[i_stream_number];
 
-    if( ! pkt->left || pkt->i_skip >= pkt->left )
-        return -1;
-
-    bool b_packet_keyframe = pkt->p_peek[pkt->i_skip] >> 7;
-    uint8_t i_stream_number = pkt->p_peek[pkt->i_skip++] & 0x7f;
-
-    uint32_t i_media_object_number = 0;
-    if (GetValue2b(&i_media_object_number, pkt->p_peek, &pkt->i_skip, pkt->left - pkt->i_skip, pkt->property >> 4) < 0)
-        return -1;
-    uint32_t i_media_object_offset = 0;
-    if (GetValue2b(&i_media_object_offset, pkt->p_peek, &pkt->i_skip, pkt->left - pkt->i_skip, pkt->property >> 2) < 0)
-        return -1;
-    uint32_t i_replicated_data_length = 0;
-    if (GetValue2b(&i_replicated_data_length, pkt->p_peek, &pkt->i_skip, pkt->left - pkt->i_skip, pkt->property) < 0)
-        return -1;
-
-    mtime_t i_pts;
-    /* Non compressed */
-    if( i_replicated_data_length > 1 ) // should be at least 8 bytes
-    {
-        i_pts = (mtime_t)GetDWLE( pkt->p_peek + pkt->i_skip + 4 );
-        pkt->i_skip += i_replicated_data_length;
-
-        if( ! pkt->left || pkt->i_skip >= pkt->left )
-            return -1;
-    }
-    /* Compressed sub payload */
-    else if( i_replicated_data_length == 1 )
-    {
-        /* i_media_object_offset is presentation time */
-        /* Next byte is Presentation Time Delta */
-        i_pts = (mtime_t)i_media_object_offset + (mtime_t)pkt->p_peek[pkt->i_skip] * i_payload;
-        pkt->i_skip++;
-        i_media_object_offset = 0;
-    }
-    else
-    {
-        i_pts = (mtime_t)pkt->send_time * 1000;
-    }
-
-    i_pts -= p_sys->p_fp->i_preroll;
-    if (i_pts < 0) i_pts = 0; // FIXME?
-    i_pts *= 1000; // FIXME ?
-
-    uint32_t i_payload_data_length = 0;
-    uint32_t i_temp_payload_length = 0;
-    if( pkt->multiple ) {
-        if (GetValue2b(&i_temp_payload_length, pkt->p_peek, &pkt->i_skip, pkt->left - pkt->i_skip, pkt->length_type) < 0)
-            return -1;
-    } else
-        i_temp_payload_length = pkt->length - pkt->padding_length - pkt->i_skip;
-
-    if( ! i_temp_payload_length || i_temp_payload_length > pkt->left )
-        return -1;
-    else
-        i_payload_data_length = i_temp_payload_length;
-
-#ifdef ASF_DEBUG
-     msg_Dbg( p_demux,
-              "payload(%d) stream_number:%"PRIu8" media_object_number:%d media_object_offset:%"PRIu32" replicated_data_length:%"PRIu32" payload_data_length %"PRIu32,
-              i_payload + 1, i_stream_number, i_media_object_number,
-              i_media_object_offset, i_replicated_data_length, i_payload_data_length );
-#endif
-
-    asf_track_t *tk = p_sys->track[i_stream_number];
     if( tk == NULL )
     {
         msg_Warn( p_demux, "undeclared stream[Id 0x%x]", i_stream_number );
-        goto skip;
+        return true;
     }
 
     if( p_sys->i_wait_keyframe )
@@ -654,196 +623,45 @@ static int DemuxPayload(demux_t *p_demux, struct asf_packet_t *pkt, int i_payloa
             if ( !b_packet_keyframe )
             {
                 p_sys->i_wait_keyframe--;
-                goto skip;
+                return true;
             }
             else
                 p_sys->i_wait_keyframe = 0;
         }
         else
-            goto skip;
+            return true;
     }
 
     if( !tk->p_es )
-        goto skip;
-
-    while (i_payload_data_length)
-    {
-        uint32_t i_sub_payload_data_length = i_payload_data_length;
-        if( i_replicated_data_length == 1 )
-        {
-            i_sub_payload_data_length = pkt->p_peek[pkt->i_skip++];
-            i_payload_data_length--;
-        }
-
-        SkipBytes( p_demux->s, pkt->i_skip );
-
-        if ( i_sub_payload_data_length &&
-             DemuxSubPayload(p_demux, tk, i_sub_payload_data_length, i_pts,
-                            i_media_object_offset) < 0)
-            return -1;
+        return true;
 
-        if ( pkt->left > pkt->i_skip + i_sub_payload_data_length )
-            pkt->left -= pkt->i_skip + i_sub_payload_data_length;
-        else
-            pkt->left = 0;
-        pkt->i_skip = 0;
-        if( pkt->left > 0 )
-        {
-            int i_return = stream_Peek( p_demux->s, &pkt->p_peek, __MIN(pkt->left, INT_MAX) );
-            if ( i_return <= 0 || (unsigned int) i_return < __MIN(pkt->left, INT_MAX) )
-            {
-            msg_Warn( p_demux, "cannot peek, EOF ?" );
-            return -1;
-            }
-        }
-
-        if ( i_sub_payload_data_length <= i_payload_data_length )
-            i_payload_data_length -= i_sub_payload_data_length;
-        else
-            i_payload_data_length = 0;
-    }
-
-    return 0;
-
-skip:
-    pkt->i_skip += i_payload_data_length;
-    return 0;
+    return false;
 }
 
-static int DemuxPacket( demux_t *p_demux )
+static void Packet_Send(asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, block_t **pp_frame)
 {
+    demux_t *p_demux = p_packetsys->p_demux;
     demux_sys_t *p_sys = p_demux->p_sys;
+    const asf_track_t *tk = p_sys->track[i_stream_number];
+    if ( !tk )
+        return;
 
-    uint32_t i_data_packet_min = p_sys->p_fp->i_min_data_packet_size;
-
-    const uint8_t *p_peek;
-    int i_return = stream_Peek( p_demux->s, &p_peek,i_data_packet_min );
-    if( i_return <= 0 || ((unsigned int) i_return) < i_data_packet_min )
-    {
-        msg_Warn( p_demux, "cannot peek while getting new packet, EOF ?" );
-        return 0;
-    }
-    unsigned int i_skip = 0;
-
-    /* *** parse error correction if present *** */
-    if( p_peek[0]&0x80 )
-    {
-        unsigned int i_error_correction_data_length = p_peek[0] & 0x0f;
-        unsigned int i_opaque_data_present = ( p_peek[0] >> 4 )& 0x01;
-        unsigned int i_error_correction_length_type = ( p_peek[0] >> 5 ) & 0x03;
-        i_skip += 1; // skip error correction flags
-
-        if( i_error_correction_length_type != 0x00 ||
-            i_opaque_data_present != 0 ||
-            i_error_correction_data_length != 0x02 )
-        {
-            goto loop_error_recovery;
-        }
-
-        i_skip += i_error_correction_data_length;
-    }
-    else
-        msg_Warn( p_demux, "no error correction" );
-
-    /* sanity check */
-    if( i_skip + 2 >= i_data_packet_min )
-        goto loop_error_recovery;
-
-    struct asf_packet_t pkt;
-    int i_packet_flags = p_peek[i_skip]; i_skip++;
-    pkt.property = p_peek[i_skip]; i_skip++;
-    pkt.multiple = !!(i_packet_flags&0x01);
-
-    pkt.length = i_data_packet_min;
-    pkt.padding_length = 0;
-
-    if (GetValue2b(&pkt.length, p_peek, &i_skip, i_data_packet_min - i_skip, i_packet_flags >> 5) < 0)
-        goto loop_error_recovery;
-    uint32_t i_packet_sequence;
-    if (GetValue2b(&i_packet_sequence, p_peek, &i_skip, i_data_packet_min - i_skip, i_packet_flags >> 1) < 0)
-        goto loop_error_recovery;
-    if (GetValue2b(&pkt.padding_length, p_peek, &i_skip, i_data_packet_min - i_skip, i_packet_flags >> 3) < 0)
-        goto loop_error_recovery;
+    block_t *p_gather = block_ChainGather( *pp_frame );
 
-    if( pkt.padding_length > pkt.length )
+    if( p_sys->i_time < VLC_TS_0 && tk->i_time > VLC_TS_INVALID )
     {
-        msg_Warn( p_demux, "Too large padding: %d", pkt.padding_length );
-        goto loop_error_recovery;
-    }
-
-    if( pkt.length < i_data_packet_min )
-    {
-        /* if packet length too short, there is extra padding */
-        pkt.padding_length += i_data_packet_min - pkt.length;
-        pkt.length = i_data_packet_min;
-    }
-
-    pkt.send_time = GetDWLE( p_peek + i_skip ); i_skip += 4;
-    /* uint16_t i_packet_duration = GetWLE( p_peek + i_skip ); */ i_skip += 2;
-
-    i_return = stream_Peek( p_demux->s, &p_peek, pkt.length );
-    if( i_return <= 0 || pkt.length == 0 || (unsigned int)i_return < pkt.length )
-    {
-        msg_Warn( p_demux, "cannot peek, EOF ?" );
-        return 0;
-    }
-
-    int i_payload_count = 1;
-    pkt.length_type = 0x02; //unused
-    if( pkt.multiple )
-    {
-        i_payload_count = p_peek[i_skip] & 0x3f;
-        pkt.length_type = ( p_peek[i_skip] >> 6 )&0x03;
-        i_skip++;
-    }
-
+        p_sys->i_time = tk->i_time;
+        es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
 #ifdef ASF_DEBUG
-    msg_Dbg(p_demux, "%d payloads", i_payload_count);
+        msg_Dbg( p_demux, "    setting PCR to %"PRId64, VLC_TS_0 + p_sys->i_time );
 #endif
+    }
 
-    pkt.i_skip = i_skip;
-    pkt.p_peek = p_peek;
-    pkt.left = pkt.length;
-
-    for( int i_payload = 0; i_payload < i_payload_count ; i_payload++ )
-        if (DemuxPayload(p_demux, &pkt, i_payload) < 0)
-            return 0;
-
-    if( pkt.left > 0 )
-    {
 #ifdef ASF_DEBUG
-        if( pkt.left > pkt.padding_length )
-            msg_Warn( p_demux, "Didn't read %"PRIu32" bytes in the packet",
-                            pkt.left - pkt.padding_length );
-        else if( pkt.left < pkt.padding_length )
-            msg_Warn( p_demux, "Read %"PRIu32" too much bytes in the packet",
-                            pkt.padding_length - pkt.left );
+    msg_Dbg( p_demux, "    sending packet dts %"PRId64" pts %"PRId64" pcr %"PRId64, p_gather->i_dts, p_gather->i_pts, p_sys->i_time );
 #endif
-        int i_return = stream_Read( p_demux->s, NULL, pkt.left );
-        if( i_return < 0 || (unsigned int) i_return < pkt.left )
-        {
-            msg_Err( p_demux, "cannot skip data, EOF ?" );
-            return 0;
-        }
-    }
-
-    return 1;
-
-loop_error_recovery:
-    msg_Warn( p_demux, "unsupported packet header" );
-    if( p_sys->p_fp->i_min_data_packet_size != p_sys->p_fp->i_max_data_packet_size )
-    {
-        msg_Err( p_demux, "unsupported packet header, fatal error" );
-        return -1;
-    }
-    i_return = stream_Read( p_demux->s, NULL, i_data_packet_min );
-    if( i_return <= 0 || (unsigned int) i_return != i_data_packet_min )
-    {
-        msg_Warn( p_demux, "cannot skip data, EOF ?" );
-        return 0;
-    }
-
-    return 1;
+    es_out_Send( p_demux->out, tk->p_es, p_gather );
+    *pp_frame = NULL;
 }
 
 /*****************************************************************************
@@ -851,8 +669,8 @@ loop_error_recovery:
  *****************************************************************************/
 typedef struct asf_es_priorities_t
 {
-    int16_t *pi_stream_numbers;
-    int16_t i_count;
+    uint16_t *pi_stream_numbers;
+    uint16_t i_count;
 } asf_es_priorities_t;
 
 /* Fills up our exclusion list */
@@ -864,16 +682,19 @@ static void ASF_fillup_es_priorities_ex( demux_sys_t *p_sys, void *p_hdr,
             ASF_FindObject( p_hdr, &asf_object_advanced_mutual_exclusion, 0 );
     if (! p_mutex ) return;
 
-    p_prios->pi_stream_numbers = malloc( p_sys->i_track * sizeof( int16_t ) );
+#if ( UINT_MAX > SIZE_MAX / 2 )
+    if ( p_sys->i_track > (size_t)SIZE_MAX / sizeof(uint16_t) )
+        return;
+#endif
+    p_prios->pi_stream_numbers = malloc( (size_t)p_sys->i_track * sizeof(uint16_t) );
     if ( !p_prios->pi_stream_numbers ) return;
 
     if ( p_mutex->i_stream_number_count )
     {
         /* Just set highest prio on highest in the group */
-        for ( int16_t i = 1; i < p_mutex->i_stream_number_count; i++ )
+        for ( uint16_t i = 1; i < p_mutex->i_stream_number_count; i++ )
         {
-            if ( p_prios->i_count + 1 == INT_MAX ) break; /* FIXME: fix all types */
-            if ( (unsigned int) p_prios->i_count > p_sys->i_track ) break;
+            if ( p_prios->i_count > p_sys->i_track || i > p_sys->i_track ) break;
             p_prios->pi_stream_numbers[ p_prios->i_count++ ] = p_mutex->pi_stream_number[ i ];
         }
     }
@@ -888,22 +709,37 @@ static void ASF_fillup_es_bitrate_priorities_ex( demux_sys_t *p_sys, void *p_hdr
             ASF_FindObject( p_hdr, &asf_object_bitrate_mutual_exclusion_guid, 0 );
     if (! p_bitrate_mutex ) return;
 
-    p_prios->pi_stream_numbers = malloc( p_sys->i_track * sizeof( int16_t ) );
+#if ( UINT_MAX > SIZE_MAX / 2 )
+    if ( p_sys->i_track > (size_t)SIZE_MAX / sizeof(uint16_t) )
+        return;
+#endif
+    p_prios->pi_stream_numbers = malloc( (size_t)p_sys->i_track * sizeof( uint16_t ) );
     if ( !p_prios->pi_stream_numbers ) return;
 
     if ( p_bitrate_mutex->i_stream_number_count )
     {
         /* Just remove < highest */
-        for ( int16_t i = 1; i < p_bitrate_mutex->i_stream_number_count; i++ )
+        for ( uint16_t i = 1; i < p_bitrate_mutex->i_stream_number_count; i++ )
         {
-            if ( p_prios->i_count + 1 == INT_MAX ) break; /* FIXME: fix all types */
-            if ( (unsigned int) p_prios->i_count > p_sys->i_track ) break;
+            if ( p_prios->i_count > p_sys->i_track || i > p_sys->i_track ) break;
             p_prios->pi_stream_numbers[ p_prios->i_count++ ] = p_bitrate_mutex->pi_stream_numbers[ i ];
         }
     }
 
 }
 
+#define GET_CHECKED( target, getter, maxtarget, temp ) \
+{\
+    temp i_temp = getter;\
+    if ( i_temp > maxtarget ) {\
+        msg_Warn( p_demux, "rejecting stream %u : " #target " overflow", i_stream );\
+        es_format_Clean( &fmt );\
+        goto error;\
+    } else {\
+        target = i_temp;\
+    }\
+}
+
 static int DemuxInit( demux_t *p_demux )
 {
     demux_sys_t *p_sys = p_demux->p_sys;
@@ -918,12 +754,13 @@ static int DemuxInit( demux_t *p_demux )
     p_sys->i_track  = 0;
     p_sys->i_seek_track = 0;
     p_sys->i_wait_keyframe = 0;
-    for( int i = 0; i < 128; i++ )
+    for( int i = 0; i < MAX_ASF_TRACKS; i++ )
     {
         p_sys->track[i] = NULL;
     }
-    p_sys->i_data_begin = -1;
-    p_sys->i_data_end   = -1;
+    p_sys->i_data_begin = 0;
+    p_sys->i_data_end   = 0;
+    p_sys->i_preroll_start = 0;
     p_sys->meta         = NULL;
 
     /* Now load all object ( except raw data ) */
@@ -948,18 +785,19 @@ static int DemuxInit( demux_t *p_demux )
          || ASF_FindObject( p_sys->p_root->p_hdr,
                          &asf_object_advanced_content_encryption_guid, 0 ) != NULL )
     {
-        msg_Warn( p_demux, "ASF plugin discarded (DRM encumbered content)" );
+        dialog_Fatal( p_demux, _("Could not demux ASF stream"), "%s",
+                        _("DRM protected streams are not supported.") );
         goto error;
     }
 
     p_sys->i_track = ASF_CountObject( p_sys->p_root->p_hdr,
                                       &asf_object_stream_properties_guid );
-    if( p_sys->i_track <= 0 )
+    if( p_sys->i_track == 0 )
     {
         msg_Warn( p_demux, "ASF plugin discarded (cannot find any stream!)" );
         goto error;
     }
-    msg_Dbg( p_demux, "found %d streams", p_sys->i_track );
+    msg_Dbg( p_demux, "found %u streams", p_sys->i_track );
 
     /* check if index is available */
     asf_object_index_t *p_index = ASF_FindObject( p_sys->p_root,
@@ -998,20 +836,23 @@ static int DemuxInit( demux_t *p_demux )
         memset( tk, 0, sizeof( asf_track_t ) );
 
         tk->i_time = -1;
-        tk->p_sp = p_sp;
+        tk->info.p_sp = p_sp;
         tk->p_es = NULL;
-        tk->p_esp = NULL;
-        tk->p_frame = NULL;
+        tk->info.p_esp = NULL;
+        tk->info.p_frame = NULL;
 
-        /* Check (in case of mms) if this track is selected (ie will receive data) */
-        if( !stream_Control( p_demux->s, STREAM_GET_PRIVATE_ID_STATE,
-                             (int) p_sp->i_stream_number, &b_access_selected ) &&
-            !b_access_selected )
+        if ( strncmp( p_demux->psz_access, "mms", 3 ) )
         {
-            tk->i_cat = UNKNOWN_ES;
-            msg_Dbg( p_demux, "ignoring not selected stream(ID:%u) (by access)",
-                     p_sp->i_stream_number );
-            continue;
+            /* Check (not mms) if this track is selected (ie will receive data) */
+            if( !stream_Control( p_demux->s, STREAM_GET_PRIVATE_ID_STATE,
+                                 (int) p_sp->i_stream_number, &b_access_selected ) &&
+                !b_access_selected )
+            {
+                tk->i_cat = UNKNOWN_ES;
+                msg_Dbg( p_demux, "ignoring not selected stream(ID:%u) (by access)",
+                         p_sp->i_stream_number );
+                continue;
+            }
         }
 
         /* Find the associated extended_stream_properties if any */
@@ -1027,7 +868,7 @@ static int DemuxInit( demux_t *p_demux )
                 if( p_tmp->ext_stream.i_stream_number == p_sp->i_stream_number )
                 {
                     p_esp = &p_tmp->ext_stream;
-                    tk->p_esp = p_esp;
+                    tk->info.p_esp = p_esp;
                     break;
                 }
             }
@@ -1044,9 +885,13 @@ static int DemuxInit( demux_t *p_demux )
             es_format_Init( &fmt, AUDIO_ES, 0 );
             i_format = GetWLE( &p_data[0] );
             wf_tag_to_fourcc( i_format, &fmt.i_codec, NULL );
-            fmt.audio.i_channels        = GetWLE(  &p_data[2] );
-            fmt.audio.i_rate            = GetDWLE( &p_data[4] );
-            fmt.i_bitrate               = GetDWLE( &p_data[8] ) * 8;
+
+            GET_CHECKED( fmt.audio.i_channels,      GetWLE( &p_data[2] ),
+                                                        255, uint16_t );
+            GET_CHECKED( fmt.audio.i_rate,          GetDWLE( &p_data[4] ),
+                                                        UINT_MAX, uint32_t );
+            GET_CHECKED( fmt.i_bitrate,             GetDWLE( &p_data[8] ) * 8,
+                                                        UINT_MAX, uint32_t );
             fmt.audio.i_blockalign      = GetWLE(  &p_data[12] );
             fmt.audio.i_bitspersample   = GetWLE(  &p_data[14] );
 
@@ -1054,9 +899,10 @@ static int DemuxInit( demux_t *p_demux )
                 i_format != WAVE_FORMAT_MPEGLAYER3 &&
                 i_format != WAVE_FORMAT_MPEG )
             {
-                fmt.i_extra = __MIN( GetWLE( &p_data[16] ),
+                GET_CHECKED( fmt.i_extra, __MIN( GetWLE( &p_data[16] ),
                                      p_sp->i_type_specific_data_length -
-                                     sizeof( WAVEFORMATEX ) );
+                                     sizeof( WAVEFORMATEX ) ),
+                             INT_MAX, uint32_t );
                 fmt.p_extra = malloc( fmt.i_extra );
                 memcpy( fmt.p_extra, &p_data[sizeof( WAVEFORMATEX )],
                         fmt.i_extra );
@@ -1075,13 +921,18 @@ static int DemuxInit( demux_t *p_demux )
             es_format_Init( &fmt, VIDEO_ES,
                             VLC_FOURCC( p_data[16], p_data[17],
                                         p_data[18], p_data[19] ) );
-            fmt.video.i_width = GetDWLE( p_data + 4 );
-            fmt.video.i_height= GetDWLE( p_data + 8 );
+
+            GET_CHECKED( fmt.video.i_width,      GetDWLE( p_data + 4 ),
+                                                     UINT_MAX, uint32_t );
+            GET_CHECKED( fmt.video.i_height,     GetDWLE( p_data + 8 ),
+                                                     UINT_MAX, uint32_t );
 
             if( p_esp && p_esp->i_average_time_per_frame > 0 )
             {
                 fmt.video.i_frame_rate = 10000000;
-                fmt.video.i_frame_rate_base = p_esp->i_average_time_per_frame;
+                GET_CHECKED( fmt.video.i_frame_rate_base,
+                             p_esp->i_average_time_per_frame,
+                             UINT_MAX, uint64_t );
             }
 
             if( fmt.i_codec == VLC_FOURCC( 'D','V','R',' ') )
@@ -1094,9 +945,10 @@ static int DemuxInit( demux_t *p_demux )
             if( p_sp->i_type_specific_data_length > 11 +
                 sizeof( VLC_BITMAPINFOHEADER ) )
             {
-                fmt.i_extra = __MIN( GetDWLE( p_data ),
+                GET_CHECKED( fmt.i_extra, __MIN( GetDWLE( p_data ),
                                      p_sp->i_type_specific_data_length - 11 -
-                                     sizeof( VLC_BITMAPINFOHEADER ) );
+                                     sizeof( VLC_BITMAPINFOHEADER ) ),
+                             UINT_MAX, uint32_t );
                 fmt.p_extra = malloc( fmt.i_extra );
                 memcpy( fmt.p_extra, &p_data[sizeof( VLC_BITMAPINFOHEADER )],
                         fmt.i_extra );
@@ -1106,9 +958,8 @@ static int DemuxInit( demux_t *p_demux )
             if( p_sys->p_root->p_metadata )
             {
                 asf_object_metadata_t *p_meta = p_sys->p_root->p_metadata;
-                int i_aspect_x = 0, i_aspect_y = 0;
-                unsigned int i;
-
+                unsigned int i_aspect_x = 0, i_aspect_y = 0;
+                uint32_t i;
                 for( i = 0; i < p_meta->i_record_entries_count; i++ )
                 {
                     if( !strcmp( p_meta->record[i].psz_name, "AspectRatioX" ) )
@@ -1116,14 +967,16 @@ static int DemuxInit( demux_t *p_demux )
                         if( (!i_aspect_x && !p_meta->record[i].i_stream) ||
                             p_meta->record[i].i_stream ==
                             p_sp->i_stream_number )
-                            i_aspect_x = p_meta->record[i].i_val;
+                            GET_CHECKED( i_aspect_x, p_meta->record[i].i_val,
+                                         UINT_MAX, uint64_t );
                     }
                     if( !strcmp( p_meta->record[i].psz_name, "AspectRatioY" ) )
                     {
                         if( (!i_aspect_y && !p_meta->record[i].i_stream) ||
                             p_meta->record[i].i_stream ==
                             p_sp->i_stream_number )
-                            i_aspect_y = p_meta->record[i].i_val;
+                            GET_CHECKED( i_aspect_y, p_meta->record[i].i_val,
+                                         UINT_MAX, uint64_t );
                     }
                 }
 
@@ -1152,27 +1005,31 @@ static int DemuxInit( demux_t *p_demux )
             if( guidcmp( p_ref, &asf_object_extended_stream_type_audio ) &&
                 i_data >= sizeof( WAVEFORMATEX ) - 2)
             {
-                int      i_format;
+                uint16_t i_format;
                 es_format_Init( &fmt, AUDIO_ES, 0 );
                 i_format = GetWLE( &p_data[0] );
                 if( i_format == 0 )
                     fmt.i_codec = VLC_CODEC_A52;
                 else
                     wf_tag_to_fourcc( i_format, &fmt.i_codec, NULL );
-                fmt.audio.i_channels        = GetWLE(  &p_data[2] );
-                fmt.audio.i_rate            = GetDWLE( &p_data[4] );
-                fmt.i_bitrate               = GetDWLE( &p_data[8] ) * 8;
+                GET_CHECKED( fmt.audio.i_channels,      GetWLE( &p_data[2] ),
+                                                            255, uint16_t );
+                GET_CHECKED( fmt.audio.i_rate,          GetDWLE( &p_data[4] ),
+                                                            UINT_MAX, uint32_t );
+                GET_CHECKED( fmt.i_bitrate,             GetDWLE( &p_data[8] ) * 8,
+                                                            UINT_MAX, uint32_t );
                 fmt.audio.i_blockalign      = GetWLE(  &p_data[12] );
                 fmt.audio.i_bitspersample   = GetWLE(  &p_data[14] );
                 fmt.b_packetized = true;
 
                 if( p_sp->i_type_specific_data_length > sizeof( WAVEFORMATEX ) &&
                     i_format != WAVE_FORMAT_MPEGLAYER3 &&
-                    i_format != WAVE_FORMAT_MPEG )
+                    i_format != WAVE_FORMAT_MPEG && i_data >= 19 )
                 {
-                    fmt.i_extra = __MIN( GetWLE( &p_data[16] ),
+                    GET_CHECKED( fmt.i_extra, __MIN( GetWLE( &p_data[16] ),
                                          p_sp->i_type_specific_data_length -
-                                         sizeof( WAVEFORMATEX ) );
+                                         sizeof( WAVEFORMATEX ) ),
+                                 INT_MAX, uint32_t );
                     fmt.p_extra = malloc( fmt.i_extra );
                     memcpy( fmt.p_extra, &p_data[sizeof( WAVEFORMATEX )],
                         fmt.i_extra );
@@ -1195,7 +1052,6 @@ static int DemuxInit( demux_t *p_demux )
         if( fmt.i_cat != UNKNOWN_ES )
         {
             if( p_esp && p_languages &&
-                p_esp->i_language_index >= 0 &&
                 p_esp->i_language_index < p_languages->i_language )
             {
                 fmt.psz_language = strdup( p_languages->ppsz_language[p_esp->i_language_index] );
@@ -1206,7 +1062,7 @@ static int DemuxInit( demux_t *p_demux )
 
             /* Set our priority so we won't get multiple videos */
             int i_priority = ES_PRIORITY_SELECTABLE_MIN;
-            for( int16_t i = 0; i < fmt_priorities_ex.i_count; i++ )
+            for( uint16_t i = 0; i < fmt_priorities_ex.i_count; i++ )
             {
                 if ( fmt_priorities_ex.pi_stream_numbers[i] == p_sp->i_stream_number )
                 {
@@ -1214,7 +1070,7 @@ static int DemuxInit( demux_t *p_demux )
                     break;
                 }
             }
-            for( int16_t i = 0; i < fmt_priorities_bitrate_ex.i_count; i++ )
+            for( uint16_t i = 0; i < fmt_priorities_bitrate_ex.i_count; i++ )
             {
                 if ( fmt_priorities_bitrate_ex.pi_stream_numbers[i] == p_sp->i_stream_number )
                 {
@@ -1224,13 +1080,35 @@ static int DemuxInit( demux_t *p_demux )
             }
             fmt.i_priority = i_priority;
 
+            if ( i_stream <= INT_MAX )
+                fmt.i_id = i_stream;
+            else
+                msg_Warn( p_demux, "Can't set fmt.i_id to match stream id %u", i_stream );
+
+            if ( fmt.i_cat == VIDEO_ES )
+            {
+                /* Backup our video format */
+                tk->p_fmt = malloc( sizeof( es_format_t ) );
+                if ( tk->p_fmt )
+                    es_format_Copy( tk->p_fmt, &fmt );
+            }
+
             tk->p_es = es_out_Add( p_demux->out, &fmt );
+
+            if( !stream_Control( p_demux->s, STREAM_GET_PRIVATE_ID_STATE,
+                                 (int) p_sp->i_stream_number, &b_access_selected ) &&
+                b_access_selected )
+            {
+                p_sys->i_access_selected_track[fmt.i_cat] = p_sp->i_stream_number;
+            }
+
         }
         else
         {
             msg_Dbg( p_demux, "ignoring unknown stream(ID:%d)",
                      p_sp->i_stream_number );
         }
+
         es_format_Clean( &fmt );
     }
 
@@ -1242,11 +1120,11 @@ static int DemuxInit( demux_t *p_demux )
     { /* local file */
         p_sys->i_data_end = p_sys->p_root->p_data->i_object_pos +
                                     p_sys->p_root->p_data->i_object_size;
-        p_sys->i_data_end = __MIN( stream_Size( p_demux->s ), p_sys->i_data_end );
+        p_sys->i_data_end = __MIN( (uint64_t)stream_Size( p_demux->s ), p_sys->i_data_end );
     }
     else
     { /* live/broacast */
-        p_sys->i_data_end = -1;
+        p_sys->i_data_end = 0;
     }
 
     /* go to first packet */
@@ -1255,8 +1133,8 @@ static int DemuxInit( demux_t *p_demux )
     /* try to calculate movie time */
     if( p_sys->p_fp->i_data_packets_count > 0 )
     {
-        int64_t i_count;
-        int64_t i_size = stream_Size( p_demux->s );
+        uint64_t i_count;
+        uint64_t i_size = stream_Size( p_demux->s );
 
         if( p_sys->i_data_end > 0 && i_size > p_sys->i_data_end )
         {
@@ -1276,7 +1154,7 @@ static int DemuxInit( demux_t *p_demux )
 
         if( p_sys->i_length > 0 )
         {
-            p_sys->i_bitrate = 8 * i_size * (int64_t)1000000 / p_sys->i_length;
+            p_sys->i_bitrate = 8 * i_size * 1000000 / p_sys->i_length;
         }
     }
 
@@ -1310,7 +1188,7 @@ static int DemuxInit( demux_t *p_demux )
     }
     /// \tood Fix Child meta for ASF tracks
 #if 0
-    for( i_stream = 0, i = 0; i < 128; i++ )
+    for( i_stream = 0, i = 0; i < MAX_ASF_TRACKS; i++ )
     {
         asf_object_codec_list_t *p_cl = ASF_FindObject( p_sys->p_root->p_hdr,
                                                         &asf_object_codec_list_guid, 0 );
@@ -1339,12 +1217,32 @@ static int DemuxInit( demux_t *p_demux )
         }
     }
 #endif
+
+    p_sys->packet_sys.pi_preroll = &p_sys->p_fp->i_preroll;
+    p_sys->packet_sys.pi_preroll_start = &p_sys->i_preroll_start;
+
     return VLC_SUCCESS;
 
 error:
     ASF_FreeObjectRoot( p_demux->s, p_sys->p_root );
     return VLC_EGENERIC;
 }
+
+/*****************************************************************************
+ * FlushRemainingPackets: flushes tail packets
+ *****************************************************************************/
+
+static void FlushRemainingPackets( demux_t *p_demux )
+{
+    demux_sys_t *p_sys = p_demux->p_sys;
+    for ( unsigned int i = 0; i < MAX_ASF_TRACKS; i++ )
+    {
+        asf_track_t *tk = p_sys->track[i];
+        if( tk && tk->info.p_frame )
+            Packet_Send( &p_sys->packet_sys, i, &tk->info.p_frame );
+    }
+}
+
 /*****************************************************************************
  *
  *****************************************************************************/
@@ -1363,20 +1261,24 @@ static void DemuxEnd( demux_t *p_demux )
         p_sys->meta = NULL;
     }
 
-    for( int i = 0; i < 128; i++ )
+    for( int i = 0; i < MAX_ASF_TRACKS; i++ )
     {
         asf_track_t *tk = p_sys->track[i];
 
         if( tk )
         {
-            if( tk->p_frame )
-            {
-                block_ChainRelease( tk->p_frame );
-            }
+            if( tk->info.p_frame )
+                block_ChainRelease( tk->info.p_frame );
+
             if( tk->p_es )
             {
                 es_out_Del( p_demux->out, tk->p_es );
             }
+            if ( tk->p_fmt )
+            {
+                es_format_Clean( tk->p_fmt );
+                free( tk->p_fmt );
+            }
             free( tk );
         }
         p_sys->track[i] = 0;