Merge remote-tracking branch 'gfiber-internal/master' into moca27
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..7a7555d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,46 @@
+.config
+.version
+*.o
+*.so
+*.d
+*.exe
+*.ho
+*-example
+*-test
+*_g
+config.*
+doc/*.1
+doc/*.html
+doc/*.pod
+doxy
+ffmpeg
+ffplay
+ffprobe
+ffserver
+libavcodec/libavcodec*
+libavcore/libavcore*
+libavdevice/libavdevice*
+libavfilter/libavfilter*
+libavformat/libavformat*
+libavutil/avconfig.h
+libavutil/libavutil*
+libpostproc/libpostproc*
+libswscale/libswscale*
+tests/audiogen
+tests/base64
+tests/data
+tests/rotozoom
+tests/seek_test
+tests/tiny_psnr
+tests/videogen
+tests/vsynth1
+tests/vsynth2
+tools/cws2fws
+tools/graph2dot
+tools/lavfi-showfiltfmts
+tools/pktdumper
+tools/probetest
+tools/qt-faststart
+tools/trasher
+tools/trasher*.d
+version.h
diff --git a/cmdutils.c b/cmdutils.c
index 167d15a..9fc4fc6 100755
--- a/cmdutils.c
+++ b/cmdutils.c
@@ -46,11 +46,11 @@
 
 const char **opt_names;
 static int opt_name_count;
-AVCodecContext *avcodec_opts[CODEC_TYPE_NB];
+AVCodecContext *avctx_opts[CODEC_TYPE_NB];
 AVFormatContext *avformat_opts;
 struct SwsContext *sws_opts;
 
-const int this_year = 2009;
+const int this_year = 2012;
 
 double parse_number_or_die(const char *context, const char *numstr, int type, double min, double max)
 {
@@ -179,9 +179,9 @@
     int opt_types[]={AV_OPT_FLAG_VIDEO_PARAM, AV_OPT_FLAG_AUDIO_PARAM, 0, AV_OPT_FLAG_SUBTITLE_PARAM, 0};
 
     for(type=0; type<CODEC_TYPE_NB && ret>= 0; type++){
-        const AVOption *o2 = av_find_opt(avcodec_opts[0], opt, NULL, opt_types[type], opt_types[type]);
+        const AVOption *o2 = av_find_opt(avctx_opts[0], opt, NULL, opt_types[type], opt_types[type]);
         if(o2)
-            ret = av_set_string3(avcodec_opts[type], opt, arg, 1, &o);
+            ret = av_set_string3(avctx_opts[type], opt, arg, 1, &o);
     }
     if(!o)
         ret = av_set_string3(avformat_opts, opt, arg, 1, &o);
@@ -189,11 +189,11 @@
         ret = av_set_string3(sws_opts, opt, arg, 1, &o);
     if(!o){
         if(opt[0] == 'a')
-            ret = av_set_string3(avcodec_opts[CODEC_TYPE_AUDIO], opt+1, arg, 1, &o);
+            ret = av_set_string3(avctx_opts[CODEC_TYPE_AUDIO], opt+1, arg, 1, &o);
         else if(opt[0] == 'v')
-            ret = av_set_string3(avcodec_opts[CODEC_TYPE_VIDEO], opt+1, arg, 1, &o);
+            ret = av_set_string3(avctx_opts[CODEC_TYPE_VIDEO], opt+1, arg, 1, &o);
         else if(opt[0] == 's')
-            ret = av_set_string3(avcodec_opts[CODEC_TYPE_SUBTITLE], opt+1, arg, 1, &o);
+            ret = av_set_string3(avctx_opts[CODEC_TYPE_SUBTITLE], opt+1, arg, 1, &o);
     }
     if (o && ret < 0) {
         fprintf(stderr, "Invalid value '%s' for option '%s'\n", arg, opt);
@@ -202,13 +202,13 @@
     if(!o)
         return -1;
 
-//    av_log(NULL, AV_LOG_ERROR, "%s:%s: %f 0x%0X\n", opt, arg, av_get_double(avcodec_opts, opt, NULL), (int)av_get_int(avcodec_opts, opt, NULL));
+//    av_log(NULL, AV_LOG_ERROR, "%s:%s: %f 0x%0X\n", opt, arg, av_get_double(avctx_opts, opt, NULL), (int)av_get_int(avctx_opts, opt, NULL));
 
-    //FIXME we should always use avcodec_opts, ... for storing options so there will not be any need to keep track of what i set over this
+    //FIXME we should always use avctx_opts, ... for storing options so there will not be any need to keep track of what i set over this
     opt_names= av_realloc(opt_names, sizeof(void*)*(opt_name_count+1));
     opt_names[opt_name_count++]= o->name;
 
-    if(avcodec_opts[0]->debug || avformat_opts->debug)
+    if(avctx_opts[0]->debug || avformat_opts->debug)
         av_log_set_level(AV_LOG_DEBUG);
     return 0;
 }
@@ -288,7 +288,7 @@
 
 void show_banner(void)
 {
-    fprintf(stderr, "%s version " FFMPEG_VERSION ", Copyright (c) %d-%d Fabrice Bellard, et al.\n",
+    fprintf(stderr, "%s version: " FFMPEG_VERSION ", Copyright (c) %d-%d Fabrice Bellard, et al.\n",
             program_name, program_birth_year, this_year);
     fprintf(stderr, "  configuration: " FFMPEG_CONFIGURATION "\n");
     print_all_lib_versions(stderr, 1);
diff --git a/cmdutils.h b/cmdutils.h
index e30ea0f..607df6a 100755
--- a/cmdutils.h
+++ b/cmdutils.h
@@ -40,7 +40,7 @@
 extern const int this_year;
 
 extern const char **opt_names;
-extern AVCodecContext *avcodec_opts[CODEC_TYPE_NB];
+extern AVCodecContext *avctx_opts[CODEC_TYPE_NB];
 extern AVFormatContext *avformat_opts;
 extern struct SwsContext *sws_opts;
 
diff --git a/ffmpeg.c b/ffmpeg.c
index 02ff3fc..63813e4 100644
--- a/ffmpeg.c
+++ b/ffmpeg.c
@@ -1318,7 +1318,7 @@
             /* better than nothing: use input picture interlaced
                settings */
             big_picture.interlaced_frame = in_picture->interlaced_frame;
-            if(avcodec_opts[CODEC_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
+            if(avctx_opts[CODEC_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
                 if(top_field_first == -1)
                     big_picture.top_field_first = in_picture->top_field_first;
                 else
@@ -1616,6 +1616,7 @@
                     data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
                     /* XXX: allocate picture correctly */
                     avcodec_get_frame_defaults(&picture);
+
                     ret = avcodec_decode_video(ist->st->codec,
                                                &picture, &got_picture, ptr, len);
 //if (got_picture) fprintf(stderr, "   -- got picture, pts = %lld\n", picture.pts);
@@ -2725,7 +2726,7 @@
 
     opt_default(opt, arg);
 
-    if (av_get_int(avcodec_opts[codec_type], "b", NULL) < 1000)
+    if (av_get_int(avctx_opts[codec_type], "b", NULL) < 1000)
         fprintf(stderr, "WARNING: The bitrate parameter is set too low. It takes bits/s as argument, not kbits/s\n");
 
     return 0;
@@ -3289,7 +3290,7 @@
         enc->thread_count= thread_count;
         switch(enc->codec_type) {
         case CODEC_TYPE_AUDIO:
-            set_context_opts(enc, avcodec_opts[CODEC_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM);
+            set_context_opts(enc, avctx_opts[CODEC_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM);
             //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
             channel_layout = enc->channel_layout;
             audio_channels = enc->channels;
@@ -3300,7 +3301,7 @@
                 ic->streams[i]->discard= AVDISCARD_ALL;
             break;
         case CODEC_TYPE_VIDEO:
-            set_context_opts(enc, avcodec_opts[CODEC_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM);
+            set_context_opts(enc, avctx_opts[CODEC_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM);
             frame_height = enc->height;
             frame_width = enc->width;
             if(ic->streams[i]->sample_aspect_ratio.num)
@@ -3433,11 +3434,11 @@
     if(   (video_global_header&1)
        || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
         video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
-        avcodec_opts[CODEC_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
+        avctx_opts[CODEC_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
     }
     if(video_global_header&2){
         video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
-        avcodec_opts[CODEC_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;
+        avctx_opts[CODEC_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;
     }
 
     if (video_stream_copy) {
@@ -3462,7 +3463,7 @@
 
         video_enc->codec_id = codec_id;
 
-        set_context_opts(video_enc, avcodec_opts[CODEC_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
+        set_context_opts(video_enc, avctx_opts[CODEC_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
 
         if (codec && codec->supported_framerates && !force_fps)
             fps = codec->supported_framerates[av_find_nearest_q_idx(fps, codec->supported_framerates)];
@@ -3576,7 +3577,7 @@
 
     if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
         audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
-        avcodec_opts[CODEC_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
+        avctx_opts[CODEC_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
     }
     if (audio_stream_copy) {
         st->stream_copy = 1;
@@ -3584,7 +3585,7 @@
     } else {
         AVCodec *codec;
 
-        set_context_opts(audio_enc, avcodec_opts[CODEC_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
+        set_context_opts(audio_enc, avctx_opts[CODEC_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
 
         if (audio_codec_name) {
             codec_id = find_codec_or_die(audio_codec_name, CODEC_TYPE_AUDIO, 1);
@@ -3654,7 +3655,7 @@
     if (subtitle_stream_copy) {
         st->stream_copy = 1;
     } else {
-        set_context_opts(avcodec_opts[CODEC_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
+        set_context_opts(avctx_opts[CODEC_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
         subtitle_enc->codec_id = find_codec_or_die(subtitle_codec_name, CODEC_TYPE_SUBTITLE, 1);
         output_codecs[nb_ocodecs] = avcodec_find_encoder_by_name(subtitle_codec_name);
     }
@@ -3949,7 +3950,7 @@
                       OPT_GRAB,
                       OPT_GRAB);
     printf("\n");
-    av_opt_show(avcodec_opts[0], NULL);
+    av_opt_show(avctx_opts[0], NULL);
     printf("\n");
     av_opt_show(avformat_opts, NULL);
     printf("\n");
@@ -4386,7 +4387,7 @@
         url_set_interrupt_cb(decode_interrupt_cb);
 
     for(i=0; i<CODEC_TYPE_NB; i++){
-        avcodec_opts[i]= avcodec_alloc_context2(i);
+        avctx_opts[i]= avcodec_alloc_context2(i);
     }
     avformat_opts = avformat_alloc_context();
     sws_opts = sws_getContext(16,16,0, 16,16,0, sws_flags, NULL,NULL,NULL);
diff --git a/ffplay.c b/ffplay.c
index 18422e2..5383861 100755
--- a/ffplay.c
+++ b/ffplay.c
@@ -1755,7 +1755,7 @@
     enc->error_recognition= error_recognition;
     enc->error_concealment= error_concealment;
 
-    set_context_opts(enc, avcodec_opts[enc->codec_type], 0);
+    set_context_opts(enc, avctx_opts[enc->codec_type], 0);
 
     if (!codec ||
         avcodec_open(enc, codec) < 0)
@@ -2556,7 +2556,7 @@
     av_register_all();
 
     for(i=0; i<CODEC_TYPE_NB; i++){
-        avcodec_opts[i]= avcodec_alloc_context2(i);
+        avctx_opts[i]= avcodec_alloc_context2(i);
     }
     avformat_opts = avformat_alloc_context();
     sws_opts = sws_getContext(16,16,0, 16,16,0, sws_flags, NULL,NULL,NULL);
diff --git a/libavcodec/4xm.c b/libavcodec/4xm.c
index 5c96baa..e33001f 100755
--- a/libavcodec/4xm.c
+++ b/libavcodec/4xm.c
@@ -133,7 +133,9 @@
     GetBitContext pre_gb;          ///< ac/dc prefix
     GetBitContext gb;
     const uint8_t *bytestream;
+    const uint8_t *bytestream_end;
     const uint16_t *wordstream;
+    const uint16_t *wordstream_end;
     int mv[256];
     VLC pre_vlc;
     int last_dc;
@@ -308,6 +310,8 @@
     assert(code>=0 && code<=6);
 
     if(code == 0){
+        if (f->bytestream_end - f->bytestream < 1)
+            return;
         src += f->mv[ *f->bytestream++ ];
         if(start > src || src > end){
             av_log(f->avctx, AV_LOG_ERROR, "mv out of pic\n");
@@ -325,15 +329,23 @@
     }else if(code == 3 && f->version<2){
         mcdc(dst, src, log2w, h, stride, 1, 0);
     }else if(code == 4){
+        if (f->bytestream_end - f->bytestream < 1)
+            return;
         src += f->mv[ *f->bytestream++ ];
         if(start > src || src > end){
             av_log(f->avctx, AV_LOG_ERROR, "mv out of pic\n");
             return;
         }
+        if (f->wordstream_end - f->wordstream < 1)
+            return;
         mcdc(dst, src, log2w, h, stride, 1, le2me_16(*f->wordstream++));
     }else if(code == 5){
+        if (f->wordstream_end - f->wordstream < 1)
+            return;
         mcdc(dst, src, log2w, h, stride, 0, le2me_16(*f->wordstream++));
     }else if(code == 6){
+        if (f->wordstream_end - f->wordstream < 2)
+            return;
         if(log2w){
             dst[0] = le2me_16(*f->wordstream++);
             dst[1] = le2me_16(*f->wordstream++);
@@ -355,6 +367,8 @@
 
     if(f->version>1){
         extra=20;
+        if (length < extra)
+            return -1;
         bitstream_size= AV_RL32(buf+8);
         wordstream_size= AV_RL32(buf+12);
         bytestream_size= AV_RL32(buf+16);
@@ -365,11 +379,10 @@
         bytestream_size= FFMAX(length - bitstream_size - wordstream_size, 0);
     }
 
-    if(bitstream_size+ bytestream_size+ wordstream_size + extra != length
-       || bitstream_size  > (1<<26)
-       || bytestream_size > (1<<26)
-       || wordstream_size > (1<<26)
-       ){
+    if (bitstream_size > length ||
+        bytestream_size > length - bitstream_size ||
+        wordstream_size > length - bytestream_size - bitstream_size ||
+        extra > length - bytestream_size - bitstream_size - wordstream_size){
         av_log(f->avctx, AV_LOG_ERROR, "lengths %d %d %d %d\n", bitstream_size, bytestream_size, wordstream_size,
         bitstream_size+ bytestream_size+ wordstream_size - length);
         return -1;
@@ -380,7 +393,9 @@
     init_get_bits(&f->gb, f->bitstream_buffer, 8*bitstream_size);
 
     f->wordstream= (const uint16_t*)(buf + extra + bitstream_size);
+    f->wordstream_end= f->wordstream + wordstream_size/2;
     f->bytestream= buf + extra + bitstream_size + wordstream_size;
+    f->bytestream_end = f->bytestream + bytestream_size;
 
     init_mv(f);
 
@@ -509,7 +524,7 @@
     return 0;
 }
 
-static const uint8_t *read_huffman_tables(FourXContext *f, const uint8_t * const buf){
+static const uint8_t *read_huffman_tables(FourXContext *f, const uint8_t * const buf, int buf_size){
     int frequency[512];
     uint8_t flag[512];
     int up[512];
@@ -517,6 +532,7 @@
     int bits_tab[257];
     int start, end;
     const uint8_t *ptr= buf;
+    const uint8_t *ptr_end = buf + buf_size;
     int j;
 
     memset(frequency, 0, sizeof(frequency));
@@ -527,6 +543,8 @@
     for(;;){
         int i;
 
+        if (start <= end && ptr_end - ptr < end - start + 1 + 1)
+            return NULL;
         for(i=start; i<=end; i++){
             frequency[i]= *ptr++;
         }
@@ -599,10 +617,13 @@
     const int height= f->avctx->height;
     uint16_t *dst= (uint16_t*)f->current_picture.data[0];
     const int stride= f->current_picture.linesize[0]>>1;
+    const uint8_t *buf_end = buf + length;
 
     for(y=0; y<height; y+=16){
         for(x=0; x<width; x+=16){
             unsigned int color[4], bits;
+            if (buf_end - buf < 8)
+                return -1;
             memset(color, 0, sizeof(color));
 //warning following is purely guessed ...
             color[0]= bytestream_get_le16(&buf);
@@ -636,18 +657,23 @@
     uint16_t *dst= (uint16_t*)f->current_picture.data[0];
     const int stride= f->current_picture.linesize[0]>>1;
     const unsigned int bitstream_size= AV_RL32(buf);
-    const int token_count av_unused = AV_RL32(buf + bitstream_size + 8);
-    unsigned int prestream_size= 4*AV_RL32(buf + bitstream_size + 4);
-    const uint8_t *prestream= buf + bitstream_size + 12;
+    unsigned int prestream_size;
+    const uint8_t *prestream;
 
-    if(prestream_size + bitstream_size + 12 != length
-       || bitstream_size > (1<<26)
-       || prestream_size > (1<<26)){
+    if (bitstream_size > (1<<26) || length < bitstream_size + 12)
+        return -1;
+    prestream_size = 4*AV_RL32(buf + bitstream_size + 4);
+    prestream = buf + bitstream_size + 12;
+
+    if (prestream_size > (1<<26) ||
+        prestream_size != length - (bitstream_size + 12)){
         av_log(f->avctx, AV_LOG_ERROR, "size mismatch %d %d %d\n", prestream_size, bitstream_size, length);
         return -1;
     }
 
-    prestream= read_huffman_tables(f, prestream);
+    prestream= read_huffman_tables(f, prestream, buf + length - prestream);
+    if (!prestream)
+        return -1;
 
     init_get_bits(&f->gb, buf + 4, 8*bitstream_size);
 
@@ -684,6 +710,8 @@
     AVFrame *p, temp;
     int i, frame_4cc, frame_size;
 
+    if (buf_size < 12)
+        return AVERROR_INVALIDDATA;
     frame_4cc= AV_RL32(buf);
     if(buf_size != AV_RL32(buf+4)+8 || buf_size < 20){
         av_log(f->avctx, AV_LOG_ERROR, "size mismatch %d %d\n", buf_size, AV_RL32(buf+4));
@@ -696,6 +724,9 @@
         const int whole_size= AV_RL32(buf+16);
         CFrameBuffer *cfrm;
 
+        if (data_size < 0 || whole_size < 0)
+            return AVERROR_INVALIDDATA;
+
         for(i=0; i<CFRAME_BUFFER_COUNT; i++){
             if(f->cfrm[i].id && f->cfrm[i].id < avctx->frame_number)
                 av_log(f->avctx, AV_LOG_ERROR, "lost c frame %d\n", f->cfrm[i].id);
@@ -712,6 +743,8 @@
         }
         cfrm= &f->cfrm[i];
 
+        if (data_size > UINT_MAX -  cfrm->size - FF_INPUT_BUFFER_PADDING_SIZE)
+            return AVERROR_INVALIDDATA;
         cfrm->data= av_fast_realloc(cfrm->data, &cfrm->allocated_size, cfrm->size + data_size + FF_INPUT_BUFFER_PADDING_SIZE);
         if(!cfrm->data){ //explicit check needed as memcpy below might not catch a NULL
             av_log(f->avctx, AV_LOG_ERROR, "realloc falure");
diff --git a/libavcodec/aac.c b/libavcodec/aac.c
index dcd560d..b6759dd 100644
--- a/libavcodec/aac.c
+++ b/libavcodec/aac.c
@@ -93,8 +93,6 @@
 #include <math.h>
 #include <string.h>
 
-union float754 { float f; uint32_t i; };
-
 static VLC vlc_scalefactors;
 static VLC vlc_spectral[11];
 
@@ -932,24 +930,24 @@
 }
 
 static av_always_inline float flt16_round(float pf) {
-    union float754 tmp;
-    tmp.f = pf;
-    tmp.i = (tmp.i + 0x00008000U) & 0xFFFF0000U;
-    return tmp.f;
+    int exp;
+    pf = frexpf(pf, &exp);
+    pf = ldexpf(roundf(ldexpf(pf, 8)), exp-8);
+    return pf;
 }
 
 static av_always_inline float flt16_even(float pf) {
-    union float754 tmp;
-    tmp.f = pf;
-    tmp.i = (tmp.i + 0x00007FFFU + (tmp.i & 0x00010000U>>16)) & 0xFFFF0000U;
-    return tmp.f;
+    int exp;
+    pf = frexpf(pf, &exp);
+    pf = ldexpf(rintf(ldexpf(pf, 8)), exp-8);
+    return pf;
 }
 
 static av_always_inline float flt16_trunc(float pf) {
-    union float754 pun;
-    pun.f = pf;
-    pun.i &= 0xFFFF0000U;
-    return pun.f;
+    int exp;
+    pf = frexpf(pf, &exp);
+    pf = ldexpf(truncf(ldexpf(pf, 8)), exp-8);
+    return pf;
 }
 
 static void predict(AACContext * ac, PredictorState * ps, float* coef, int output_enable) {
@@ -1199,7 +1197,14 @@
         } else
             coup->ch_select[c] = 2;
     }
-    coup->coupling_point += get_bits1(gb) || (coup->coupling_point>>1);
+    coup->coupling_point += get_bits1(gb);
+
+    if (coup->coupling_point == 2) {
+        av_log(ac->avccontext, AV_LOG_ERROR,
+            "Independently switched CCE with 'invalid' domain signalled.\n");
+        memset(coup, 0, sizeof(ChannelCoupling));
+        return -1;
+    }
 
     sign = get_bits(gb, 1);
     scale = pow(2., pow(2., (int)get_bits(gb, 2) - 3));
@@ -1488,11 +1493,10 @@
     for (g = 0; g < ics->num_window_groups; g++) {
         for (i = 0; i < ics->max_sfb; i++, idx++) {
             if (cce->ch[0].band_type[idx] != ZERO_BT) {
-                const float gain = cce->coup.gain[index][idx];
                 for (group = 0; group < ics->group_len[g]; group++) {
                     for (k = offsets[i]; k < offsets[i+1]; k++) {
                         // XXX dsputil-ize
-                        dest[group*128+k] += gain * src[group*128+k];
+                        dest[group*128+k] += cce->coup.gain[index][idx] * src[group*128+k];
                     }
                 }
             }
diff --git a/libavcodec/ac3dec.c b/libavcodec/ac3dec.c
index 766b262..03f8f8c 100644
--- a/libavcodec/ac3dec.c
+++ b/libavcodec/ac3dec.c
@@ -7,24 +7,19 @@
  * Copyright (c) 2007-2008 Bartlomiej Wolowiec <bartek.wolowiec@gmail.com>
  * Copyright (c) 2007 Justin Ruggles <justin.ruggles@gmail.com>
  *
- * Portions of this code are derived from liba52
- * http://liba52.sourceforge.net
- * Copyright (C) 2000-2003 Michel Lespinasse <walken@zoy.org>
- * Copyright (C) 1999-2000 Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
- *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public
+ * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * General Public License for more details.
+ * Lesser General Public License for more details.
  *
- * You should have received a copy of the GNU General Public
+ * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
@@ -438,12 +433,12 @@
  * Grouped mantissas for 3-level 5-level and 11-level quantization
  */
 typedef struct {
-    int b1_mant[3];
-    int b2_mant[3];
-    int b4_mant[2];
-    int b1ptr;
-    int b2ptr;
-    int b4ptr;
+    int b1_mant[2];
+    int b2_mant[2];
+    int b4_mant;
+    int b1;
+    int b2;
+    int b4;
 } mant_groups;
 
 /**
@@ -452,73 +447,72 @@
  */
 static void ac3_decode_transform_coeffs_ch(AC3DecodeContext *s, int ch_index, mant_groups *m)
 {
+    int start_freq = s->start_freq[ch_index];
+    int end_freq = s->end_freq[ch_index];
+    uint8_t *baps = s->bap[ch_index];
+    int8_t *exps = s->dexps[ch_index];
+    int *coeffs = s->fixed_coeffs[ch_index];
     GetBitContext *gbc = &s->gbc;
-    int i, gcode, tbap, start, end;
-    uint8_t *exps;
-    uint8_t *bap;
-    int *coeffs;
+    int freq;
 
-    exps = s->dexps[ch_index];
-    bap = s->bap[ch_index];
-    coeffs = s->fixed_coeffs[ch_index];
-    start = s->start_freq[ch_index];
-    end = s->end_freq[ch_index];
-
-    for (i = start; i < end; i++) {
-        tbap = bap[i];
-        switch (tbap) {
+    for(freq = start_freq; freq < end_freq; freq++){
+        int bap = baps[freq];
+        int mantissa;
+        switch(bap){
             case 0:
-                coeffs[i] = (av_lfg_get(&s->dith_state) & 0x7FFFFF) - 0x400000;
+                mantissa = (av_lfg_get(&s->dith_state) & 0x7FFFFF) - 0x400000;
                 break;
-
             case 1:
-                if(m->b1ptr > 2) {
-                    gcode = get_bits(gbc, 5);
-                    m->b1_mant[0] = b1_mantissas[gcode][0];
-                    m->b1_mant[1] = b1_mantissas[gcode][1];
-                    m->b1_mant[2] = b1_mantissas[gcode][2];
-                    m->b1ptr = 0;
+                if(m->b1){
+                    m->b1--;
+                    mantissa = m->b1_mant[m->b1];
                 }
-                coeffs[i] = m->b1_mant[m->b1ptr++];
+                else{
+                    int bits      = get_bits(gbc, 5);
+                    mantissa      = b1_mantissas[bits][0];
+                    m->b1_mant[1] = b1_mantissas[bits][1];
+                    m->b1_mant[0] = b1_mantissas[bits][2];
+                    m->b1         = 2;
+                }
                 break;
-
             case 2:
-                if(m->b2ptr > 2) {
-                    gcode = get_bits(gbc, 7);
-                    m->b2_mant[0] = b2_mantissas[gcode][0];
-                    m->b2_mant[1] = b2_mantissas[gcode][1];
-                    m->b2_mant[2] = b2_mantissas[gcode][2];
-                    m->b2ptr = 0;
+                if(m->b2){
+                    m->b2--;
+                    mantissa = m->b2_mant[m->b2];
                 }
-                coeffs[i] = m->b2_mant[m->b2ptr++];
+                else{
+                    int bits      = get_bits(gbc, 7);
+                    mantissa      = b2_mantissas[bits][0];
+                    m->b2_mant[1] = b2_mantissas[bits][1];
+                    m->b2_mant[0] = b2_mantissas[bits][2];
+                    m->b2         = 2;
+                }
                 break;
-
             case 3:
-                coeffs[i] = b3_mantissas[get_bits(gbc, 3)];
+                mantissa = b3_mantissas[get_bits(gbc, 3)];
                 break;
-
             case 4:
-                if(m->b4ptr > 1) {
-                    gcode = get_bits(gbc, 7);
-                    m->b4_mant[0] = b4_mantissas[gcode][0];
-                    m->b4_mant[1] = b4_mantissas[gcode][1];
-                    m->b4ptr = 0;
+                if(m->b4){
+                    m->b4 = 0;
+                    mantissa = m->b4_mant;
                 }
-                coeffs[i] = m->b4_mant[m->b4ptr++];
+                else{
+                    int bits   = get_bits(gbc, 7);
+                    mantissa   = b4_mantissas[bits][0];
+                    m->b4_mant = b4_mantissas[bits][1];
+                    m->b4      = 1;
+                }
                 break;
-
             case 5:
-                coeffs[i] = b5_mantissas[get_bits(gbc, 4)];
+                mantissa = b5_mantissas[get_bits(gbc, 4)];
                 break;
-
-            default: {
-                /* asymmetric dequantization */
-                int qlevel = quantization_tab[tbap];
-                coeffs[i] = get_sbits(gbc, qlevel) << (24 - qlevel);
+            default: /* 6 to 15 */
+                mantissa = get_bits(gbc, quantization_tab[bap]);
+                /* Shift mantissa and sign-extend it. */
+                mantissa = (mantissa << (32-quantization_tab[bap]))>>8;
                 break;
             }
-        }
-        coeffs[i] >>= exps[i];
+        coeffs[freq] = mantissa >> exps[freq];
     }
 }
 
@@ -581,7 +575,7 @@
     int got_cplchan = 0;
     mant_groups m;
 
-    m.b1ptr = m.b2ptr = m.b4ptr = 3;
+    m.b1 = m.b2 = m.b4 = 0;
 
     for (ch = 1; ch <= s->channels; ch++) {
         /* transform coefficients for full-bandwidth channel */
diff --git a/libavcodec/ac3enc.c b/libavcodec/ac3enc.c
index d685801..2cd7cc6 100755
--- a/libavcodec/ac3enc.c
+++ b/libavcodec/ac3enc.c
@@ -116,6 +116,8 @@
   qim = (by - ay) >> 1;\
 }
 
+#define MUL16(a,b) ((a) * (b))
+
 #define CMUL(pre, pim, are, aim, bre, bim) \
 {\
    pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
diff --git a/libavcodec/adpcm.c b/libavcodec/adpcm.c
index 994c0c6..8eff05e 100755
--- a/libavcodec/adpcm.c
+++ b/libavcodec/adpcm.c
@@ -667,17 +667,23 @@
 static av_cold int adpcm_decode_init(AVCodecContext * avctx)
 {
     ADPCMContext *c = avctx->priv_data;
+    unsigned int min_channels = 1;
     unsigned int max_channels = 2;
 
     switch(avctx->codec->id) {
+    case CODEC_ID_ADPCM_EA:
+        min_channels = 2;
+        break;
     case CODEC_ID_ADPCM_EA_R1:
     case CODEC_ID_ADPCM_EA_R2:
     case CODEC_ID_ADPCM_EA_R3:
         max_channels = 6;
         break;
     }
-    if(avctx->channels > max_channels){
-        return -1;
+
+    if (avctx->channels < min_channels || avctx->channels > max_channels) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
+        return AVERROR(EINVAL);
     }
 
     switch(avctx->codec->id) {
diff --git a/libavcodec/alac.c b/libavcodec/alac.c
index 436329f..095876e 100755
--- a/libavcodec/alac.c
+++ b/libavcodec/alac.c
@@ -56,7 +56,6 @@
 #include "bitstream.h"
 #include "bytestream.h"
 #include "unary.h"
-#include "mathops.h"
 
 #define ALAC_EXTRADATA_SIZE 36
 #define MAX_CHANNELS 2
@@ -230,6 +229,11 @@
     }
 }
 
+static inline int32_t extend_sign32(int32_t val, int bits)
+{
+    return (val << (32 - bits)) >> (32 - bits);
+}
+
 static inline int sign_only(int v)
 {
     return v ? FFSIGN(v) : 0;
@@ -269,7 +273,7 @@
             prev_value = buffer_out[i];
             error_value = error_buffer[i+1];
             buffer_out[i+1] =
-                sign_extend((prev_value + error_value), readsamplesize);
+                extend_sign32((prev_value + error_value), readsamplesize);
         }
         return;
     }
@@ -280,7 +284,7 @@
             int32_t val;
 
             val = buffer_out[i] + error_buffer[i+1];
-            val = sign_extend(val, readsamplesize);
+            val = extend_sign32(val, readsamplesize);
             buffer_out[i+1] = val;
         }
 
@@ -315,7 +319,7 @@
             outval = (1 << (predictor_quantitization-1)) + sum;
             outval = outval >> predictor_quantitization;
             outval = outval + buffer_out[0] + error_val;
-            outval = sign_extend(outval, readsamplesize);
+            outval = extend_sign32(outval, readsamplesize);
 
             buffer_out[predictor_coef_num+1] = outval;
 
@@ -540,7 +544,8 @@
             for (chan = 0; chan < channels; chan++) {
                 int32_t audiobits;
 
-                audiobits = get_sbits_long(&alac->gb, alac->setinfo_sample_size);
+                audiobits = get_bits_long(&alac->gb, alac->setinfo_sample_size);
+                audiobits = extend_sign32(audiobits, alac->setinfo_sample_size);
 
                 alac->outputsamples_buffer[chan][i] = audiobits;
             }
diff --git a/libavcodec/alacenc.c b/libavcodec/alacenc.c
index 886b6c6..9fd5064 100644
--- a/libavcodec/alacenc.c
+++ b/libavcodec/alacenc.c
@@ -23,7 +23,6 @@
 #include "bitstream.h"
 #include "dsputil.h"
 #include "lpc.h"
-#include "mathops.h"
 
 #define DEFAULT_FRAME_SIZE        4096
 #define DEFAULT_SAMPLE_SIZE       16
@@ -254,8 +253,8 @@
 
             sum >>= lpc.lpc_quant;
             sum += samples[0];
-            residual[i] = sign_extend(samples[lpc.lpc_order+1] - sum,
-                                      s->write_sample_size);
+            residual[i] = (samples[lpc.lpc_order+1] - sum) << (32 - s->write_sample_size) >>
+                          (32 - s->write_sample_size);
             res_val = residual[i];
 
             if(res_val) {
diff --git a/libavcodec/apiexample.c b/libavcodec/apiexample.c
index 7f682cd..14fee3b 100755
--- a/libavcodec/apiexample.c
+++ b/libavcodec/apiexample.c
@@ -159,8 +159,7 @@
 
         inbuf_ptr = inbuf;
         while (size > 0) {
-            out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
-            len = avcodec_decode_audio2(c, (short *)outbuf, &out_size,
+            len = avcodec_decode_audio(c, (short *)outbuf, &out_size,
                                        inbuf_ptr, size);
             if (len < 0) {
                 fprintf(stderr, "Error while decoding\n");
diff --git a/libavcodec/atrac3.c b/libavcodec/atrac3.c
index bdb8a8a..22dfdfc 100644
--- a/libavcodec/atrac3.c
+++ b/libavcodec/atrac3.c
@@ -230,7 +230,7 @@
     const uint32_t* buf;
     uint32_t* obuf = (uint32_t*) out;
 
-    off = (intptr_t)inbuffer & 3;
+    off = (int)((long)inbuffer & 3);
     buf = (const uint32_t*) (inbuffer - off);
     c = be2me_32((0x537F6103 >> (off*8)) | (0x537F6103 << (32-(off*8))));
     bytes += 3 + off;
@@ -454,6 +454,8 @@
 
             for (k=0; k<coded_components; k++) {
                 sfIndx = get_bits(gb,6);
+                if(component_count>=64)
+                    return AVERROR_INVALIDDATA;
                 pComponent[component_count].pos = j * 64 + (get_bits(gb,6));
                 max_coded_values = 1024 - pComponent[component_count].pos;
                 coded_values = coded_values_per_component + 1;
diff --git a/libavcodec/avcodec.h b/libavcodec/avcodec.h
index 6d0e6d5..89a787d 100644
--- a/libavcodec/avcodec.h
+++ b/libavcodec/avcodec.h
@@ -512,6 +512,7 @@
 #define CODEC_FLAG2_CHUNKS        0x00008000 ///< Input bitstream might be truncated at a packet boundaries instead of only at frame boundaries.
 #define CODEC_FLAG2_NON_LINEAR_QUANT 0x00010000 ///< Use MPEG-2 nonlinear quantizer.
 #define CODEC_FLAG2_BIT_RESERVOIR 0x00020000 ///< Use a bit reservoir when encoding if possible
+#define CODEC_FLAG2_MBTREE        0x00040000 ///< Use macroblock tree ratecontrol (x264 only)
 
 /* Unsupported options :
  *              Syntax Arithmetic coding (SAC)
@@ -2369,6 +2370,16 @@
      * - decoding: Set by user
      */
     void *hwaccel_context;
+
+	/**
+     * explicit P-frame weighted prediction analysis method
+     * 0: off
+     * 1: fast blind weighting (one reference duplicate with -1 offset)
+     * 2: smart weighting (full fade detection analysis)
+     * - encoding: Set by user.
+     * - decoding: unused
+     */
+    int weighted_p_pred;
 } AVCodecContext;
 
 /**
diff --git a/libavcodec/bitstream.c b/libavcodec/bitstream.c
index 5d9bd32..d48a97a 100755
--- a/libavcodec/bitstream.c
+++ b/libavcodec/bitstream.c
@@ -85,7 +85,7 @@
     if(length==0) return;
 
     if(CONFIG_SMALL || words < 16 || put_bits_count(pb)&7){
-        for(i=0; i<words; i++) put_bits(pb, 16, AV_RB16(&srcw[i]));
+        for(i=0; i<words; i++) put_bits(pb, 16, be2me_16(srcw[i]));
     }else{
         for(i=0; put_bits_count(pb)&31; i++)
             put_bits(pb, 8, src[i]);
@@ -94,7 +94,7 @@
         skip_put_bytes(pb, 2*words-i);
     }
 
-    put_bits(pb, bits, AV_RB16(&srcw[words])>>(16-bits));
+    put_bits(pb, bits, be2me_16(srcw[words])>>(16-bits));
 }
 
 /* VLC decoding */
diff --git a/libavcodec/bitstream.h b/libavcodec/bitstream.h
index 3670285..0ba0bd3 100755
--- a/libavcodec/bitstream.h
+++ b/libavcodec/bitstream.h
@@ -721,7 +721,9 @@
     if(n<=17) return show_bits(s, n);
     else{
         GetBitContext gb= *s;
-        return get_bits_long(&gb, n);
+        int ret= get_bits_long(s, n);
+        *s= gb;
+        return ret;
     }
 }
 
@@ -952,4 +954,9 @@
         return 2 - get_bits1(gb);
 }
 
+static inline int get_bits_left(GetBitContext *gb)
+{
+    return gb->size_in_bits - get_bits_count(gb);
+}
+
 #endif /* AVCODEC_BITSTREAM_H */
diff --git a/libavcodec/cavsdec.c b/libavcodec/cavsdec.c
index a1895bc..25b97bf 100644
--- a/libavcodec/cavsdec.c
+++ b/libavcodec/cavsdec.c
@@ -130,12 +130,14 @@
                 r++;
             mask = -(level_code & 1);
             level = (level^mask) - mask;
-        } else {
+        } else if (level_code >= 0) {
             level = r->rltab[level_code][0];
             if(!level) //end of block signal
                 break;
             run   = r->rltab[level_code][1];
             r += r->rltab[level_code][2];
+        } else {
+            break;
         }
         level_buf[i] = level;
         run_buf[i] = run;
@@ -163,7 +165,7 @@
 
     /* get coded block pattern */
     int cbp= get_ue_golomb(&h->s.gb);
-    if(cbp > 63){
+    if(cbp > 63U){
         av_log(h->s.avctx, AV_LOG_ERROR, "illegal inter cbp\n");
         return -1;
     }
@@ -189,7 +191,8 @@
 
 static int decode_mb_i(AVSContext *h, int cbp_code) {
     GetBitContext *gb = &h->s.gb;
-    int block, pred_mode_uv;
+    unsigned pred_mode_uv;
+    int block;
     uint8_t top[18];
     uint8_t *left = NULL;
     uint8_t *d;
@@ -222,7 +225,7 @@
     /* get coded block pattern */
     if(h->pic_type == FF_I_TYPE)
         cbp_code = get_ue_golomb(gb);
-    if(cbp_code > 63){
+    if(cbp_code > 63U){
         av_log(h->s.avctx, AV_LOG_ERROR, "illegal intra cbp\n");
         return -1;
     }
@@ -445,6 +448,8 @@
     if((show_bits_long(gb,24+align) & 0xFFFFFF) == 0x000001) {
         skip_bits_long(gb,24+align);
         h->stc = get_bits(gb,8);
+        if (h->stc >= h->mb_height)
+            return 0;
         decode_slice_header(h,gb);
         return 1;
     }
@@ -648,7 +653,7 @@
     buf_end = buf + buf_size;
     for(;;) {
         buf_ptr = ff_find_start_code(buf_ptr,buf_end, &stc);
-        if(stc & 0xFFFFFE00)
+        if((stc & 0xFFFFFE00) || buf_ptr == buf_end)
             return FFMAX(0, buf_ptr - buf - s->parse_context.last_index);
         input_size = (buf_end - buf_ptr)*8;
         switch(stc) {
diff --git a/libavcodec/cinepak.c b/libavcodec/cinepak.c
index d0f5adb..f6d457d 100755
--- a/libavcodec/cinepak.c
+++ b/libavcodec/cinepak.c
@@ -336,7 +336,8 @@
              * If the frame header is followed by the bytes FE 00 00 06 00 00 then
              * this is probably one of the two known files that have 6 extra bytes
              * after the frame header. Else, assume 2 extra bytes. */
-            if ((s->data[10] == 0xFE) &&
+            if (s->size >= 16 &&
+                (s->data[10] == 0xFE) &&
                 (s->data[11] == 0x00) &&
                 (s->data[12] == 0x00) &&
                 (s->data[13] == 0x06) &&
@@ -365,6 +366,8 @@
         s->strips[i].x2 = s->avctx->width;
 
         strip_size = AV_RB24 (&s->data[1]) - 12;
+        if(strip_size < 0)
+            return -1;
         s->data   += 12;
         strip_size = ((s->data + strip_size) > eod) ? (eod - s->data) : strip_size;
 
diff --git a/libavcodec/cljr.c b/libavcodec/cljr.c
index 9f7ab61..39ac7d6 100755
--- a/libavcodec/cljr.c
+++ b/libavcodec/cljr.c
@@ -60,7 +60,7 @@
     p->pict_type= FF_I_TYPE;
     p->key_frame= 1;
 
-    init_get_bits(&a->gb, buf, buf_size);
+    init_get_bits(&a->gb, buf, buf_size * 8);
 
     for(y=0; y<avctx->height; y++){
         uint8_t *luma= &a->picture.data[0][ y*a->picture.linesize[0] ];
diff --git a/libavcodec/cook.c b/libavcodec/cook.c
index cee69fe..0c72b7d 100755
--- a/libavcodec/cook.c
+++ b/libavcodec/cook.c
@@ -303,7 +303,7 @@
      *     (int64_t)out[i] = 0x37c511f237c511f2^be2me_64(int64_t)in[i]);
      * Buffer alignment needs to be checked. */
 
-    off = (intptr_t)inbuffer & 3;
+    off = (int)((long)inbuffer & 3);
     buf = (const uint32_t*) (inbuffer - off);
     c = be2me_32((0x37c511f2 >> (off*8)) | (0x37c511f2 << (32-(off*8))));
     bytes += 3 + off;
@@ -620,7 +620,7 @@
                 for(j=0 ; j<q->total_subbands ; j++) category[band+j]=7;
             }
         }
-        if(index>=7) {
+        if(index==7) {
             memset(subband_coef_index, 0, sizeof(subband_coef_index));
             memset(subband_coef_sign, 0, sizeof(subband_coef_sign));
         }
diff --git a/libavcodec/dpcm.c b/libavcodec/dpcm.c
index daa21cd..a364864 100755
--- a/libavcodec/dpcm.c
+++ b/libavcodec/dpcm.c
@@ -167,6 +167,7 @@
     int in, out = 0;
     int predictor[2];
     int channel_number = 0;
+    int stereo = s->channels - 1;
     short *output_samples = data;
     int shift[2];
     unsigned char byte;
@@ -175,6 +176,9 @@
     if (!buf_size)
         return 0;
 
+    if (stereo && (buf_size & 1))
+        buf_size--;
+
     // almost every DPCM variant expands one byte of data into two
     if(*data_size/2 < buf_size)
         return -1;
diff --git a/libavcodec/dsicinav.c b/libavcodec/dsicinav.c
index f8093fc..0d9fe05 100755
--- a/libavcodec/dsicinav.c
+++ b/libavcodec/dsicinav.c
@@ -215,6 +215,8 @@
 
     /* handle palette */
     if (palette_type == 0) {
+        if (palette_colors_count > 256)
+            return AVERROR_INVALIDDATA;
         for (i = 0; i < palette_colors_count; ++i) {
             cin->palette[i] = bytestream_get_le24(&buf);
             bitmap_frame_size -= 3;
diff --git a/libavcodec/dsputil.c b/libavcodec/dsputil.c
index 05edf2b..da41bf8 100644
--- a/libavcodec/dsputil.c
+++ b/libavcodec/dsputil.c
@@ -4273,7 +4273,7 @@
     static int did_fail=0;
     DECLARE_ALIGNED_16(int, aligned);
 
-    if((intptr_t)&aligned & 15){
+    if((long)&aligned & 15){
         if(!did_fail){
 #if HAVE_MMX || HAVE_ALTIVEC
             av_log(NULL, AV_LOG_ERROR,
diff --git a/libavcodec/dv.c b/libavcodec/dv.c
index 59ebb08..be4a746 100755
--- a/libavcodec/dv.c
+++ b/libavcodec/dv.c
@@ -414,11 +414,6 @@
 /* see dv_88_areas and dv_248_areas for details */
 static const int mb_area_start[5] = { 1, 6, 21, 43, 64 };
 
-static inline int get_bits_left(GetBitContext *s)
-{
-    return s->size_in_bits - get_bits_count(s);
-}
-
 static inline int put_bits_left(PutBitContext* s)
 {
     return (s->buf_end - s->buf) * 8 - put_bits_count(s);
diff --git a/libavcodec/eatqi.c b/libavcodec/eatqi.c
index 66123a2..e3c06c0 100644
--- a/libavcodec/eatqi.c
+++ b/libavcodec/eatqi.c
@@ -40,6 +40,7 @@
     AVFrame frame;
     uint8_t *bitstream_buf;
     unsigned int bitstream_buf_size;
+    DECLARE_ALIGNED_16(DCTELEM, block[6][64]);
 } TqiContext;
 
 static av_cold int tqi_decode_init(AVCodecContext *avctx)
@@ -58,12 +59,15 @@
     return 0;
 }
 
-static void tqi_decode_mb(MpegEncContext *s, DCTELEM (*block)[64])
+static int tqi_decode_mb(MpegEncContext *s, DCTELEM (*block)[64])
 {
     int n;
     s->dsp.clear_blocks(block[0]);
     for (n=0; n<6; n++)
-        ff_mpeg1_decode_block_intra(s, block[n], n);
+        if (ff_mpeg1_decode_block_intra(s, block[n], n) < 0)
+            return -1;
+
+    return 0;
 }
 
 static inline void tqi_idct_put(TqiContext *t, DCTELEM (*block)[64])
@@ -106,7 +110,6 @@
     const uint8_t *buf_end = buf+buf_size;
     TqiContext *t = avctx->priv_data;
     MpegEncContext *s = &t->s;
-    DECLARE_ALIGNED_16(DCTELEM, block[6][64]);
 
     s->width  = AV_RL16(&buf[0]);
     s->height = AV_RL16(&buf[2]);
@@ -134,8 +137,9 @@
     for (s->mb_y=0; s->mb_y<(avctx->height+15)/16; s->mb_y++)
     for (s->mb_x=0; s->mb_x<(avctx->width+15)/16; s->mb_x++)
     {
-        tqi_decode_mb(s, block);
-        tqi_idct_put(t, block);
+        if (tqi_decode_mb(s, t->block) < 0)
+            break;
+        tqi_idct_put(t, t->block);
     }
 
     *data_size = sizeof(AVFrame);
diff --git a/libavcodec/elbg.c b/libavcodec/elbg.c
index 85319db..35f0688 100755
--- a/libavcodec/elbg.c
+++ b/libavcodec/elbg.c
@@ -105,7 +105,7 @@
 {
     int i=0;
     /* Using linear search, do binary if it ever turns to be speed critical */
-    int r = av_lfg_get(elbg->rand_state)%elbg->utility_inc[elbg->numCB-1] + 1;
+    int r = av_lfg_get(elbg->rand_state)%(elbg->utility_inc[elbg->numCB-1]-1) + 1;
     while (elbg->utility_inc[i] < r)
         i++;
 
diff --git a/libavcodec/ffv1.c b/libavcodec/ffv1.c
index 72c5fbd..ccfcb62 100755
--- a/libavcodec/ffv1.c
+++ b/libavcodec/ffv1.c
@@ -248,10 +248,9 @@
     else{
         int i, e, a;
         e= 0;
-        while(get_rac(c, state+1 + e)){ //1..10
+        while(get_rac(c, state+1 + e) && e<9){ //1..10
             e++;
         }
-        assert(e<=9);
 
         a= 1;
         for(i=e-1; i>=0; i--){
diff --git a/libavcodec/flicvideo.c b/libavcodec/flicvideo.c
index 2261c40..95255f9 100755
--- a/libavcodec/flicvideo.c
+++ b/libavcodec/flicvideo.c
@@ -160,7 +160,7 @@
     int pixel_skip;
     int pixel_countdown;
     unsigned char *pixels;
-    int pixel_limit;
+    unsigned int pixel_limit;
 
     s->frame.reference = 1;
     s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
@@ -254,10 +254,13 @@
                     av_log(avctx, AV_LOG_ERROR, "Undefined opcode (%x) in DELTA_FLI\n", line_packets);
                 } else if ((line_packets & 0xC000) == 0x8000) {
                     // "last byte" opcode
-                    pixels[y_ptr + s->frame.linesize[0] - 1] = line_packets & 0xff;
+                    pixel_ptr= y_ptr + s->frame.linesize[0] - 1;
+                    CHECK_PIXEL_PTR(0);
+                    pixels[pixel_ptr] = line_packets & 0xff;
                 } else {
                     compressed_lines--;
                     pixel_ptr = y_ptr;
+                    CHECK_PIXEL_PTR(0);
                     pixel_countdown = s->avctx->width;
                     for (i = 0; i < line_packets; i++) {
                         /* account for the skip bytes */
@@ -269,7 +272,7 @@
                             byte_run = -byte_run;
                             palette_idx1 = buf[stream_ptr++];
                             palette_idx2 = buf[stream_ptr++];
-                            CHECK_PIXEL_PTR(byte_run);
+                            CHECK_PIXEL_PTR(byte_run * 2);
                             for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {
                                 pixels[pixel_ptr++] = palette_idx1;
                                 pixels[pixel_ptr++] = palette_idx2;
@@ -299,6 +302,7 @@
             stream_ptr += 2;
             while (compressed_lines > 0) {
                 pixel_ptr = y_ptr;
+                CHECK_PIXEL_PTR(0);
                 pixel_countdown = s->avctx->width;
                 line_packets = buf[stream_ptr++];
                 if (line_packets > 0) {
@@ -454,7 +458,7 @@
     int pixel_countdown;
     unsigned char *pixels;
     int pixel;
-    int pixel_limit;
+    unsigned int pixel_limit;
 
     s->frame.reference = 1;
     s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
@@ -504,6 +508,7 @@
                 } else {
                     compressed_lines--;
                     pixel_ptr = y_ptr;
+                    CHECK_PIXEL_PTR(0);
                     pixel_countdown = s->avctx->width;
                     for (i = 0; i < line_packets; i++) {
                         /* account for the skip bytes */
@@ -515,13 +520,13 @@
                             byte_run = -byte_run;
                             pixel    = AV_RL16(&buf[stream_ptr]);
                             stream_ptr += 2;
-                            CHECK_PIXEL_PTR(byte_run);
+                            CHECK_PIXEL_PTR(2 * byte_run);
                             for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {
                                 *((signed short*)(&pixels[pixel_ptr])) = pixel;
                                 pixel_ptr += 2;
                             }
                         } else {
-                            CHECK_PIXEL_PTR(byte_run);
+                            CHECK_PIXEL_PTR(2 * byte_run);
                             for (j = 0; j < byte_run; j++, pixel_countdown--) {
                                 *((signed short*)(&pixels[pixel_ptr])) = AV_RL16(&buf[stream_ptr]);
                                 stream_ptr += 2;
@@ -612,7 +617,7 @@
                     if (byte_run > 0) {
                         pixel    = AV_RL16(&buf[stream_ptr]);
                         stream_ptr += 2;
-                        CHECK_PIXEL_PTR(byte_run);
+                        CHECK_PIXEL_PTR(2 * byte_run);
                         for (j = 0; j < byte_run; j++) {
                             *((signed short*)(&pixels[pixel_ptr])) = pixel;
                             pixel_ptr += 2;
@@ -623,7 +628,7 @@
                         }
                     } else {  /* copy pixels if byte_run < 0 */
                         byte_run = -byte_run;
-                        CHECK_PIXEL_PTR(byte_run);
+                        CHECK_PIXEL_PTR(2 * byte_run);
                         for (j = 0; j < byte_run; j++) {
                             *((signed short*)(&pixels[pixel_ptr])) = AV_RL16(&buf[stream_ptr]);
                             stream_ptr += 2;
diff --git a/libavcodec/h261dec.c b/libavcodec/h261dec.c
index 7054286..aa1be6f 100755
--- a/libavcodec/h261dec.c
+++ b/libavcodec/h261dec.c
@@ -285,6 +285,10 @@
 
     // Read mtype
     h->mtype = get_vlc2(&s->gb, h261_mtype_vlc.table, H261_MTYPE_VLC_BITS, 2);
+    if (h->mtype < 0) {
+        av_log(s->avctx, AV_LOG_ERROR, "illegal mtype %d\n", h->mtype);
+        return SLICE_ERROR;
+    }
     h->mtype = h261_mtype_map[h->mtype];
 
     // Read mquant
diff --git a/libavcodec/h264.c b/libavcodec/h264.c
index edc578d..a7ab3ae 100644
--- a/libavcodec/h264.c
+++ b/libavcodec/h264.c
@@ -3743,6 +3743,7 @@
         free_tables(h);
         flush_dpb(s->avctx);
         MPV_common_end(s);
+        h->list_count = 0;
     }
     if (!s->context_initialized) {
         if(h != h0)
@@ -3940,8 +3941,10 @@
         fill_default_ref_list(h);
     }
 
-    if(h->slice_type_nos!=FF_I_TYPE && decode_ref_pic_list_reordering(h) < 0)
+    if(h->slice_type_nos!=FF_I_TYPE && decode_ref_pic_list_reordering(h) < 0) {
+        h->ref_count[1]= h->ref_count[0]= 0;
         return -1;
+    }
 
     if(h->slice_type_nos!=FF_I_TYPE){
         s->last_picture_ptr= &h->ref_list[0][0];
@@ -7016,6 +7019,10 @@
     if(sps->timing_info_present_flag){
         sps->num_units_in_tick = get_bits_long(&s->gb, 32);
         sps->time_scale = get_bits_long(&s->gb, 32);
+        if(sps->num_units_in_tick-1 > 0x7FFFFFFEU || sps->time_scale-1 > 0x7FFFFFFEU){
+            av_log(h->s.avctx, AV_LOG_ERROR, "time_scale/num_units_in_tick inavlid or unsupported (%d/%d)\n", sps->time_scale, sps->num_units_in_tick);
+            return -1;
+        }
         sps->fixed_frame_rate_flag = get_bits1(&s->gb);
     }
 
@@ -7127,8 +7134,12 @@
 
     if(sps->profile_idc >= 100){ //high profile
         sps->chroma_format_idc= get_ue_golomb_31(&s->gb);
-        if(sps->chroma_format_idc == 3)
+        if(sps->chroma_format_idc > 3) {
+            av_log(h->s.avctx, AV_LOG_ERROR, "chroma_format_idc (%u) out of range\n", sps->chroma_format_idc);
+            return -1;
+        } else if(sps->chroma_format_idc == 3) {
             sps->residual_color_transform_flag = get_bits1(&s->gb);
+        }
         sps->bit_depth_luma   = get_ue_golomb(&s->gb) + 8;
         sps->bit_depth_chroma = get_ue_golomb(&s->gb) + 8;
         sps->transform_bypass = get_bits1(&s->gb);
diff --git a/libavcodec/huffyuv.c b/libavcodec/huffyuv.c
index 51acf05..242589f 100755
--- a/libavcodec/huffyuv.c
+++ b/libavcodec/huffyuv.c
@@ -728,20 +728,33 @@
 
     count/=2;
 
+    if(count >= (s->gb.size_in_bits - get_bits_count(&s->gb))/(31*4)){
+        for(i=0; i<count && get_bits_count(&s->gb) < s->gb.size_in_bits; i++){
+            READ_2PIX(s->temp[0][2*i  ], s->temp[1][i], 1);
+            READ_2PIX(s->temp[0][2*i+1], s->temp[2][i], 2);
+        }
+    }else{
     for(i=0; i<count; i++){
         READ_2PIX(s->temp[0][2*i  ], s->temp[1][i], 1);
         READ_2PIX(s->temp[0][2*i+1], s->temp[2][i], 2);
     }
 }
+}
 
 static void decode_gray_bitstream(HYuvContext *s, int count){
     int i;
 
     count/=2;
 
+    if(count >= (s->gb.size_in_bits - get_bits_count(&s->gb))/(31*2)){
+        for(i=0; i<count && get_bits_count(&s->gb) < s->gb.size_in_bits; i++){
+            READ_2PIX(s->temp[0][2*i  ], s->temp[0][2*i+1], 0);
+        }
+    }else{
     for(i=0; i<count; i++){
         READ_2PIX(s->temp[0][2*i  ], s->temp[0][2*i+1], 0);
     }
+    }
 }
 
 #if CONFIG_HUFFYUV_ENCODER || CONFIG_FFVHUFF_ENCODER
diff --git a/libavcodec/imgconvert.c b/libavcodec/imgconvert.c
index ffc0f08..c48e938 100755
--- a/libavcodec/imgconvert.c
+++ b/libavcodec/imgconvert.c
@@ -670,6 +670,7 @@
     case PIX_FMT_BGR4_BYTE:
     case PIX_FMT_GRAY8:
         picture->linesize[0] = width;
+        picture->linesize[1] = 4;
         break;
     default:
         return -1;
diff --git a/libavcodec/indeo2.c b/libavcodec/indeo2.c
index 40c561a..8ee6a86 100755
--- a/libavcodec/indeo2.c
+++ b/libavcodec/indeo2.c
@@ -153,6 +153,13 @@
         return -1;
     }
 
+    start = 48; /* hardcoded for now */
+
+    if (start >= buf_size) {
+        av_log(s->avctx, AV_LOG_ERROR, "input buffer size too small (%d)\n", buf_size);
+        return AVERROR_INVALIDDATA;
+    }
+
     s->decode_delta = buf[18];
 
     /* decide whether frame uses deltas or not */
@@ -160,9 +167,8 @@
     for (i = 0; i < buf_size; i++)
         buf[i] = ff_reverse[buf[i]];
 #endif
-    start = 48; /* hardcoded for now */
 
-    init_get_bits(&s->gb, buf + start, buf_size - start);
+    init_get_bits(&s->gb, buf + start, (buf_size - start) * 8);
 
     if (s->decode_delta) { /* intraframe */
         ir2_decode_plane(s, avctx->width, avctx->height,
diff --git a/libavcodec/interplayvideo.c b/libavcodec/interplayvideo.c
index 1ddbbee..2fbc6a1 100755
--- a/libavcodec/interplayvideo.c
+++ b/libavcodec/interplayvideo.c
@@ -94,7 +94,7 @@
             motion_offset, s->upper_motion_limit_offset); \
         return -1; \
     } \
-    s->dsp.put_pixels_tab[1][0](s->pixel_ptr, \
+    s->dsp.put_pixels_tab[0][0](s->pixel_ptr, \
         s->current_frame.data[0] + motion_offset, s->stride, 8);
 
 #define COPY_FROM_PREVIOUS() \
@@ -109,7 +109,7 @@
             motion_offset, s->upper_motion_limit_offset); \
         return -1; \
     } \
-    s->dsp.put_pixels_tab[1][0](s->pixel_ptr, \
+    s->dsp.put_pixels_tab[0][0](s->pixel_ptr, \
         s->last_frame.data[0] + motion_offset, s->stride, 8);
 
 #define COPY_FROM_SECOND_LAST() \
@@ -124,7 +124,7 @@
             motion_offset, s->upper_motion_limit_offset); \
         return -1; \
     } \
-    s->dsp.put_pixels_tab[1][0](s->pixel_ptr, \
+    s->dsp.put_pixels_tab[0][0](s->pixel_ptr, \
         s->second_last_frame.data[0] + motion_offset, s->stride, 8);
 
 static int ipvideo_decode_block_opcode_0x0(IpvideoContext *s)
diff --git a/libavcodec/kmvc.c b/libavcodec/kmvc.c
index 30939ab..69b5937 100755
--- a/libavcodec/kmvc.c
+++ b/libavcodec/kmvc.c
@@ -33,6 +33,7 @@
 #define KMVC_KEYFRAME 0x80
 #define KMVC_PALETTE  0x40
 #define KMVC_METHOD   0x0F
+#define MAX_PALSIZE   256
 
 /*
  * Decoder context
@@ -43,7 +44,7 @@
 
     int setpal;
     int palsize;
-    uint32_t pal[256];
+    uint32_t pal[MAX_PALSIZE];
     uint8_t *cur, *prev;
     uint8_t *frm0, *frm1;
 } KmvcContext;
@@ -366,6 +367,10 @@
         c->palsize = 127;
     } else {
         c->palsize = AV_RL16(avctx->extradata + 10);
+        if (c->palsize >= MAX_PALSIZE) {
+            av_log(avctx, AV_LOG_ERROR, "KMVC palette too large\n");
+            return AVERROR_INVALIDDATA;
+        }
     }
 
     if (avctx->extradata_size == 1036) {        // palette in extradata
diff --git a/libavcodec/libxvidff.c b/libavcodec/libxvidff.c
index bdf70a0..0bbb712 100755
--- a/libavcodec/libxvidff.c
+++ b/libavcodec/libxvidff.c
@@ -485,6 +485,7 @@
     if( x->twopassbuffer != NULL ) {
         av_free(x->twopassbuffer);
         av_free(x->old_twopassbuffer);
+        avctx->stats_out = NULL;
     }
     if( x->twopassfile != NULL )
         av_free(x->twopassfile);
diff --git a/libavcodec/lzwenc.c b/libavcodec/lzwenc.c
index 4565b22..d174acd 100755
--- a/libavcodec/lzwenc.c
+++ b/libavcodec/lzwenc.c
@@ -203,7 +203,7 @@
     s->maxbits = maxbits;
     init_put_bits(&s->pb, outbuf, outsize);
     s->bufsize = outsize;
-    assert(s->maxbits >= 9 && s->maxbits <= LZW_MAXBITS);
+    assert(9 <= s->maxbits && s->maxbits <= s->maxbits);
     s->maxcode = 1 << s->maxbits;
     s->output_bytes = 0;
     s->last_code = LZW_PREFIX_EMPTY;
diff --git a/libavcodec/mjpegbdec.c b/libavcodec/mjpegbdec.c
index 62b29e0..f19a87f 100755
--- a/libavcodec/mjpegbdec.c
+++ b/libavcodec/mjpegbdec.c
@@ -49,6 +49,9 @@
     s->restart_count = 0;
     s->mjpb_skiptosod = 0;
 
+    if (buf_end - buf_ptr >= 1 << 28)
+        return AVERROR_INVALIDDATA;
+
     init_get_bits(&hgb, buf_ptr, /*buf_size*/(buf_end - buf_ptr)*8);
 
     skip_bits(&hgb, 32); /* reserved zeros */
@@ -99,8 +102,8 @@
     av_log(avctx, AV_LOG_DEBUG, "sod offs: 0x%x\n", sod_offs);
     if (sos_offs)
     {
-//        init_get_bits(&s->gb, buf+sos_offs, (buf_end - (buf+sos_offs))*8);
-        init_get_bits(&s->gb, buf_ptr+sos_offs, field_size*8);
+        init_get_bits(&s->gb, buf_ptr + sos_offs,
+                      8 * FFMIN(field_size, buf_end - buf_ptr - sos_offs));
         s->mjpb_skiptosod = (sod_offs - sos_offs - show_bits(&s->gb, 16));
         s->start_code = SOS;
         ff_mjpeg_decode_sos(s);
diff --git a/libavcodec/mjpegdec.c b/libavcodec/mjpegdec.c
index 145719c..e5c9f38 100755
--- a/libavcodec/mjpegdec.c
+++ b/libavcodec/mjpegdec.c
@@ -784,6 +784,10 @@
             if (s->restart_interval && !s->restart_count)
                 s->restart_count = s->restart_interval;
 
+            if(get_bits_count(&s->gb)>s->gb.size_in_bits){
+                av_log(s->avctx, AV_LOG_ERROR, "overread %d\n", get_bits_count(&s->gb) - s->gb.size_in_bits);
+                return -1;
+            }
             for(i=0;i<nb_components;i++) {
                 uint8_t *ptr;
                 int n, h, v, x, y, c, j;
diff --git a/libavcodec/mlpdec.c b/libavcodec/mlpdec.c
index c5a97ac..9c1253f 100644
--- a/libavcodec/mlpdec.c
+++ b/libavcodec/mlpdec.c
@@ -891,7 +891,7 @@
 
     length = (AV_RB16(buf) & 0xfff) * 2;
 
-    if (length > buf_size)
+    if (length < 4 || length > buf_size)
         return -1;
 
     init_get_bits(&gb, (buf + 4), (length - 4) * 8);
diff --git a/libavcodec/motionpixels.c b/libavcodec/motionpixels.c
index f69dcf9..7971b09 100755
--- a/libavcodec/motionpixels.c
+++ b/libavcodec/motionpixels.c
@@ -239,10 +239,13 @@
             p = mp_get_yuv_from_rgb(mp, x - 1, y);
         } else {
             p.y += mp_gradient(mp, 0, mp_get_vlc(mp, gb));
+            p.y = av_clip(p.y, 0, 31);
             if ((x & 3) == 0) {
                 if ((y & 3) == 0) {
                     p.v += mp_gradient(mp, 1, mp_get_vlc(mp, gb));
+                    p.v = av_clip(p.v, -32, 31);
                     p.u += mp_gradient(mp, 2, mp_get_vlc(mp, gb));
+                    p.u = av_clip(p.u, -32, 31);
                     mp->hpt[((y / 4) * mp->avctx->width + x) / 4] = p;
                 } else {
                     p.v = mp->hpt[((y / 4) * mp->avctx->width + x) / 4].v;
@@ -266,9 +269,12 @@
             p = mp_get_yuv_from_rgb(mp, 0, y);
         } else {
             p.y += mp_gradient(mp, 0, mp_get_vlc(mp, gb));
+            p.y = av_clip(p.y, 0, 31);
             if ((y & 3) == 0) {
                 p.v += mp_gradient(mp, 1, mp_get_vlc(mp, gb));
+                p.v = av_clip(p.v, -32, 31);
                 p.u += mp_gradient(mp, 2, mp_get_vlc(mp, gb));
+                p.u = av_clip(p.u, -32, 31);
             }
             mp->vpt[y] = p;
             mp_set_rgb_from_yuv(mp, 0, y, &p);
@@ -325,7 +331,8 @@
     if (sz == 0)
         goto end;
 
-    init_vlc(&mp->vlc, mp->max_codes_bits, mp->codes_count, &mp->codes[0].size, sizeof(HuffCode), 1, &mp->codes[0].code, sizeof(HuffCode), 4, 0);
+    if (init_vlc(&mp->vlc, mp->max_codes_bits, mp->codes_count, &mp->codes[0].size, sizeof(HuffCode), 1, &mp->codes[0].code, sizeof(HuffCode), 4, 0))
+        goto end;
     mp_decode_frame_helper(mp, &gb);
     free_vlc(&mp->vlc);
 
diff --git a/libavcodec/mpc7.c b/libavcodec/mpc7.c
index 7362a19..b8735ac 100644
--- a/libavcodec/mpc7.c
+++ b/libavcodec/mpc7.c
@@ -164,12 +164,19 @@
     int i, ch, t;
     int mb = -1;
     Band *bands = c->bands;
-    int off;
+    int off, out_size;
     int bits_used, bits_avail;
 
     memset(bands, 0, sizeof(bands));
     if(buf_size <= 4){
         av_log(avctx, AV_LOG_ERROR, "Too small buffer passed (%i bytes)\n", buf_size);
+        return AVERROR(EINVAL);
+    }
+
+    out_size = (buf[1] ? c->lastframelen : MPC_FRAME_SIZE) * 4;
+    if (*data_size < out_size) {
+        av_log(avctx, AV_LOG_ERROR, "Output buffer is too small\n");
+        return AVERROR(EINVAL);
     }
 
     bits = av_malloc(((buf_size - 1) & ~3) + FF_INPUT_BUFFER_PADDING_SIZE);
@@ -248,7 +255,7 @@
         *data_size = 0;
         return buf_size;
     }
-    *data_size = (buf[1] ? c->lastframelen : MPC_FRAME_SIZE) * 4;
+    *data_size = out_size;
 
     return buf_size;
 }
diff --git a/libavcodec/mpegaudiodec.c b/libavcodec/mpegaudiodec.c
index 66bd006..822228e 100755
--- a/libavcodec/mpegaudiodec.c
+++ b/libavcodec/mpegaudiodec.c
@@ -2322,6 +2322,10 @@
     avctx->bit_rate = s->bit_rate;
     avctx->sub_id = s->layer;
 
+    if(*data_size < 1152*avctx->channels*sizeof(OUT_INT))
+        return -1;
+    *data_size = 0;
+
     if(s->frame_size<=0 || s->frame_size > buf_size){
         av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
         return -1;
@@ -2505,6 +2509,9 @@
     OUT_INT *outptr, *bp;
     int fr, j, n;
 
+    if(*data_size < MPA_FRAME_SIZE * MPA_MAX_CHANNELS * s->frames * sizeof(OUT_INT))
+        return -1;
+
     *data_size = 0;
     // Discard too short frames
     if (buf_size < HEADER_SIZE)
diff --git a/libavcodec/nellymoserdec.c b/libavcodec/nellymoserdec.c
index ff70854..d1f561e 100644
--- a/libavcodec/nellymoserdec.c
+++ b/libavcodec/nellymoserdec.c
@@ -155,6 +155,7 @@
                       void *data, int *data_size,
                       const uint8_t * buf, int buf_size) {
     NellyMoserDecodeContext *s = avctx->priv_data;
+    int data_max = *data_size;
     int blocks, i;
     int16_t* samples;
     *data_size = 0;
@@ -178,6 +179,8 @@
     }
 
     for (i=0 ; i<blocks ; i++) {
+        if ((i + 1) * NELLY_SAMPLES * sizeof(int16_t) > data_max)
+            return i > 0 ? i * NELLY_BLOCK_LEN : -1;
         nelly_decode_block(s, &buf[i*NELLY_BLOCK_LEN], s->float_buf);
         s->dsp.float_to_int16(&samples[i*NELLY_SAMPLES], s->float_buf, NELLY_SAMPLES);
         *data_size += NELLY_SAMPLES*sizeof(int16_t);
diff --git a/libavcodec/nuv.c b/libavcodec/nuv.c
index a89953c..109ef41 100755
--- a/libavcodec/nuv.c
+++ b/libavcodec/nuv.c
@@ -197,7 +197,7 @@
 
     if (keyframe && c->pic.data[0])
         avctx->release_buffer(avctx, &c->pic);
-    c->pic.reference = 3;
+    c->pic.reference = 1;
     c->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_READABLE |
                           FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
     result = keyframe ? avctx->get_buffer(avctx, &c->pic) : avctx->reget_buffer(avctx, &c->pic);
diff --git a/libavcodec/pngdec.c b/libavcodec/pngdec.c
index a343152..d583a52 100755
--- a/libavcodec/pngdec.c
+++ b/libavcodec/pngdec.c
@@ -473,7 +473,8 @@
                 } else if (s->bit_depth == 1 &&
                            s->color_type == PNG_COLOR_TYPE_GRAY) {
                     avctx->pix_fmt = PIX_FMT_MONOBLACK;
-                } else if (s->color_type == PNG_COLOR_TYPE_PALETTE) {
+                } else if (s->bit_depth == 8 &&
+                           s->color_type == PNG_COLOR_TYPE_PALETTE) {
                     avctx->pix_fmt = PIX_FMT_PAL8;
                 } else {
                     goto fail;
diff --git a/libavcodec/ppc/check_altivec.c b/libavcodec/ppc/check_altivec.c
index e034ceb..08cc0f4 100755
--- a/libavcodec/ppc/check_altivec.c
+++ b/libavcodec/ppc/check_altivec.c
@@ -63,7 +63,7 @@
 
     if (err == 0) return has_vu != 0;
     return 0;
-#elif defined(RUNTIME_CPUDETECT)
+#elif CONFIG_RUNTIME_CPUDETECT
     int proc_ver;
     // Support of mfspr PVR emulation added in Linux 2.6.17.
     __asm__ volatile("mfspr %0, 287" : "=r" (proc_ver));
diff --git a/libavcodec/ppc/fdct_altivec.c b/libavcodec/ppc/fdct_altivec.c
index 41bebd1..cb75774 100755
--- a/libavcodec/ppc/fdct_altivec.c
+++ b/libavcodec/ppc/fdct_altivec.c
@@ -1,4 +1,5 @@
-/*
+/* ffmpeg/libavcodec/ppc/fdct_altivec.c, this file is part of the
+ * AltiVec optimized library for the FFMPEG Multimedia System
  * Copyright (C) 2003  James Klicman <james@klicman.org>
  *
  * This file is part of FFmpeg.
diff --git a/libavcodec/ppc/h264_altivec.c b/libavcodec/ppc/h264_altivec.c
index 5248a2f..67d3367 100755
--- a/libavcodec/ppc/h264_altivec.c
+++ b/libavcodec/ppc/h264_altivec.c
@@ -201,7 +201,7 @@
     register int loadSecond     = (((unsigned long)src) % 16) <= 7 ? 0 : 1;
     register int reallyBadAlign = (((unsigned long)src) % 16) == 15 ? 1 : 0;
 
-    vec_u8 vsrcAuc, av_uninit(vsrcBuc), vsrcperm0, vsrcperm1;
+    vec_u8 vsrcAuc, vsrcBuc, vsrcperm0, vsrcperm1;
     vec_u8 vsrc0uc, vsrc1uc;
     vec_s16 vsrc0ssH, vsrc1ssH;
     vec_u8 vsrcCuc, vsrc2uc, vsrc3uc;
diff --git a/libavcodec/ppc/h264_template_altivec.c b/libavcodec/ppc/h264_template_altivec.c
index b41024a..698de08 100755
--- a/libavcodec/ppc/h264_template_altivec.c
+++ b/libavcodec/ppc/h264_template_altivec.c
@@ -92,7 +92,7 @@
     register int loadSecond = (((unsigned long)src) % 16) <= 7 ? 0 : 1;
     register int reallyBadAlign = (((unsigned long)src) % 16) == 15 ? 1 : 0;
 
-    vec_u8 vsrcAuc, av_uninit(vsrcBuc), vsrcperm0, vsrcperm1;
+    vec_u8 vsrcAuc, vsrcBuc, vsrcperm0, vsrcperm1;
     vec_u8 vsrc0uc, vsrc1uc;
     vec_s16 vsrc0ssH, vsrc1ssH;
     vec_u8 vsrcCuc, vsrc2uc, vsrc3uc;
diff --git a/libavcodec/ppc/imgresample_altivec.c b/libavcodec/ppc/imgresample_altivec.c
new file mode 100755
index 0000000..02d08ae
--- /dev/null
+++ b/libavcodec/ppc/imgresample_altivec.c
@@ -0,0 +1,142 @@
+/*
+ * High quality image resampling with polyphase filters
+ * Copyright (c) 2001 Fabrice Bellard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file libavcodec/ppc/imgresample_altivec.c
+ * High quality image resampling with polyphase filters - AltiVec bits
+ */
+
+#include "util_altivec.h"
+#define FILTER_BITS   8
+
+typedef         union {
+    vector signed short v;
+    signed short s[8];
+} vec_ss;
+
+void v_resample16_altivec(uint8_t *dst, int dst_width, const uint8_t *src,
+                          int wrap, int16_t *filter)
+{
+    int sum, i;
+    const uint8_t *s;
+    vector unsigned char *tv, tmp, dstv, zero;
+    vec_ss srchv[4], srclv[4], fv[4];
+    vector signed short zeros, sumhv, sumlv;
+    s = src;
+
+    for(i=0;i<4;i++) {
+        /*
+           The vec_madds later on does an implicit >>15 on the result.
+           Since FILTER_BITS is 8, and we have 15 bits of magnitude in
+           a signed short, we have just enough bits to pre-shift our
+           filter constants <<7 to compensate for vec_madds.
+        */
+        fv[i].s[0] = filter[i] << (15-FILTER_BITS);
+        fv[i].v = vec_splat(fv[i].v, 0);
+    }
+
+    zero = vec_splat_u8(0);
+    zeros = vec_splat_s16(0);
+
+
+    /*
+       When we're resampling, we'd ideally like both our input buffers,
+       and output buffers to be 16-byte aligned, so we can do both aligned
+       reads and writes. Sadly we can't always have this at the moment, so
+       we opt for aligned writes, as unaligned writes have a huge overhead.
+       To do this, do enough scalar resamples to get dst 16-byte aligned.
+    */
+    i = (-(int)dst) & 0xf;
+    while(i>0) {
+        sum = s[0 * wrap] * filter[0] +
+        s[1 * wrap] * filter[1] +
+        s[2 * wrap] * filter[2] +
+        s[3 * wrap] * filter[3];
+        sum = sum >> FILTER_BITS;
+        if (sum<0) sum = 0; else if (sum>255) sum=255;
+        dst[0] = sum;
+        dst++;
+        s++;
+        dst_width--;
+        i--;
+    }
+
+    /* Do our altivec resampling on 16 pixels at once. */
+    while(dst_width>=16) {
+        /* Read 16 (potentially unaligned) bytes from each of
+           4 lines into 4 vectors, and split them into shorts.
+           Interleave the multipy/accumulate for the resample
+           filter with the loads to hide the 3 cycle latency
+           the vec_madds have. */
+        tv = (vector unsigned char *) &s[0 * wrap];
+        tmp = vec_perm(tv[0], tv[1], vec_lvsl(0, &s[i * wrap]));
+        srchv[0].v = (vector signed short) vec_mergeh(zero, tmp);
+        srclv[0].v = (vector signed short) vec_mergel(zero, tmp);
+        sumhv = vec_madds(srchv[0].v, fv[0].v, zeros);
+        sumlv = vec_madds(srclv[0].v, fv[0].v, zeros);
+
+        tv = (vector unsigned char *) &s[1 * wrap];
+        tmp = vec_perm(tv[0], tv[1], vec_lvsl(0, &s[1 * wrap]));
+        srchv[1].v = (vector signed short) vec_mergeh(zero, tmp);
+        srclv[1].v = (vector signed short) vec_mergel(zero, tmp);
+        sumhv = vec_madds(srchv[1].v, fv[1].v, sumhv);
+        sumlv = vec_madds(srclv[1].v, fv[1].v, sumlv);
+
+        tv = (vector unsigned char *) &s[2 * wrap];
+        tmp = vec_perm(tv[0], tv[1], vec_lvsl(0, &s[2 * wrap]));
+        srchv[2].v = (vector signed short) vec_mergeh(zero, tmp);
+        srclv[2].v = (vector signed short) vec_mergel(zero, tmp);
+        sumhv = vec_madds(srchv[2].v, fv[2].v, sumhv);
+        sumlv = vec_madds(srclv[2].v, fv[2].v, sumlv);
+
+        tv = (vector unsigned char *) &s[3 * wrap];
+        tmp = vec_perm(tv[0], tv[1], vec_lvsl(0, &s[3 * wrap]));
+        srchv[3].v = (vector signed short) vec_mergeh(zero, tmp);
+        srclv[3].v = (vector signed short) vec_mergel(zero, tmp);
+        sumhv = vec_madds(srchv[3].v, fv[3].v, sumhv);
+        sumlv = vec_madds(srclv[3].v, fv[3].v, sumlv);
+
+        /* Pack the results into our destination vector,
+           and do an aligned write of that back to memory. */
+        dstv = vec_packsu(sumhv, sumlv) ;
+        vec_st(dstv, 0, (vector unsigned char *) dst);
+
+        dst+=16;
+        s+=16;
+        dst_width-=16;
+    }
+
+    /* If there are any leftover pixels, resample them
+       with the slow scalar method. */
+    while(dst_width>0) {
+        sum = s[0 * wrap] * filter[0] +
+        s[1 * wrap] * filter[1] +
+        s[2 * wrap] * filter[2] +
+        s[3 * wrap] * filter[3];
+        sum = sum >> FILTER_BITS;
+        if (sum<0) sum = 0; else if (sum>255) sum=255;
+        dst[0] = sum;
+        dst++;
+        s++;
+        dst_width--;
+    }
+}
+
diff --git a/libavcodec/ppc/imgresample_altivec.h b/libavcodec/ppc/imgresample_altivec.h
new file mode 100755
index 0000000..27b85f9
--- /dev/null
+++ b/libavcodec/ppc/imgresample_altivec.h
@@ -0,0 +1,26 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_PPC_IMGRESAMPLE_ALTIVEC_H
+#define AVCODEC_PPC_IMGRESAMPLE_ALTIVEC_H
+
+#include <stdint.h>
+
+void v_resample16_altivec(uint8_t *dst, int dst_width, const uint8_t *src,
+                          int wrap, int16_t *filter);
+#endif /* AVCODEC_PPC_IMGRESAMPLE_ALTIVEC_H */
diff --git a/libavcodec/qdm2.c b/libavcodec/qdm2.c
index a3373a1..6775abc 100755
--- a/libavcodec/qdm2.c
+++ b/libavcodec/qdm2.c
@@ -77,6 +77,7 @@
 #define SAMPLES_NEEDED_2(why) \
      av_log (NULL,AV_LOG_INFO,"This file triggers some missing code. Please contact the developers.\nPosition: %s\n",why);
 
+#define QDM2_MAX_FRAME_SIZE 512
 
 typedef int8_t sb_int8_array[2][30][64];
 
@@ -169,7 +170,7 @@
     /// I/O data
     const uint8_t *compressed_data;
     int compressed_size;
-    float output_buffer[1024];
+    float output_buffer[QDM2_MAX_FRAME_SIZE * MPA_MAX_CHANNELS * 2];
 
     /// Synthesis filter
     DECLARE_ALIGNED_16(MPA_INT, synth_buf[MPA_MAX_CHANNELS][512*2]);
@@ -904,9 +905,13 @@
                         break;
 
                     case 30:
-                        if (BITS_LEFT(length,gb) >= 4)
-                            samples[0] = type30_dequant[qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1)];
-                        else
+                        if (BITS_LEFT(length,gb) >= 4) {
+                            unsigned index = qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1);
+                            if (index < FF_ARRAY_ELEMS(type30_dequant)) {
+                                samples[0] = type30_dequant[index];
+                            } else
+                                samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
+                        } else
                             samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
 
                         run = 1;
@@ -920,8 +925,12 @@
                                 type34_predictor = samples[0];
                                 type34_first = 0;
                             } else {
-                                samples[0] = type34_delta[qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1)] / type34_div + type34_predictor;
+                                unsigned index = qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1);
+                                if (index < FF_ARRAY_ELEMS(type34_delta)) {
+                                    samples[0] = type34_delta[index] / type34_div + type34_predictor;
                                 type34_predictor = samples[0];
+                                } else
+                                    samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
                             }
                         } else {
                             samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
@@ -1351,7 +1360,7 @@
     local_int_10 = 1 << (q->group_order - duration - 1);
     offset = 1;
 
-    while (1) {
+    while (get_bits_left(gb)>0) {
         if (q->superblocktype_2_3) {
             while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {
                 offset = 1;
@@ -1377,6 +1386,8 @@
             return;
 
         local_int_14 = (offset >> local_int_8);
+        if (local_int_14 >= FF_ARRAY_ELEMS(fft_level_index_table))
+            return;
 
         if (q->nb_channels > 1) {
             channel = get_bits1(gb);
@@ -1821,6 +1832,8 @@
 
     avctx->channels = s->nb_channels = s->channels = AV_RB32(extradata);
     extradata += 4;
+    if (s->channels > MPA_MAX_CHANNELS)
+        return AVERROR_INVALIDDATA;
 
     avctx->sample_rate = AV_RB32(extradata);
     extradata += 4;
@@ -1844,6 +1857,9 @@
     s->group_order = av_log2(s->group_size) + 1;
     s->frame_size = s->group_size / 16; // 16 iterations per super block
 
+    if (s->frame_size > QDM2_MAX_FRAME_SIZE)
+        return AVERROR_INVALIDDATA;
+
     s->sub_sampling = s->fft_order - 7;
     s->frequency_range = 255 / (1 << (2 - s->sub_sampling));
 
@@ -1906,11 +1922,14 @@
 }
 
 
-static void qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
+static int qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
 {
     int ch, i;
     const int frame_size = (q->frame_size * q->channels);
 
+    if((unsigned)frame_size > FF_ARRAY_ELEMS(q->output_buffer)/2)
+        return -1;
+
     /* select input buffer */
     q->compressed_data = in;
     q->compressed_size = q->checksum_size;
@@ -1942,7 +1961,7 @@
 
         if (!q->has_errors && q->sub_packet_list_C[0].packet != NULL) {
             SAMPLES_NEEDED_2("has errors, and C list is not empty")
-            return;
+            return -1;
         }
     }
 
@@ -1963,6 +1982,8 @@
 
         out[i] = value;
     }
+
+    return 0;
 }
 
 
@@ -1971,25 +1992,33 @@
             const uint8_t *buf, int buf_size)
 {
     QDM2Context *s = avctx->priv_data;
+    int16_t *out = data;
+    int i, out_size;
 
     if(!buf)
         return 0;
     if(buf_size < s->checksum_size)
         return -1;
 
-    *data_size = s->channels * s->frame_size * sizeof(int16_t);
+    out_size = 16 * s->channels * s->frame_size *
+               av_get_bits_per_sample_format(avctx->sample_fmt)/8;
+    if (*data_size < out_size) {
+        av_log(avctx, AV_LOG_ERROR, "Output buffer is too small\n");
+        return AVERROR(EINVAL);
+    }
 
     av_log(avctx, AV_LOG_DEBUG, "decode(%d): %p[%d] -> %p[%d]\n",
        buf_size, buf, s->checksum_size, data, *data_size);
 
-    qdm2_decode(s, buf, data);
-
-    // reading only when next superblock found
-    if (s->sub_packet == 0) {
-        return s->checksum_size;
+    for (i = 0; i < 16; i++) {
+        if (qdm2_decode(s, buf, out) < 0)
+            return -1;
+        out += s->channels * s->frame_size;
     }
 
-    return 0;
+    *data_size = out_size;
+
+    return buf_size;
 }
 
 AVCodec qdm2_decoder =
diff --git a/libavcodec/qtrle.c b/libavcodec/qtrle.c
index d535c38..d68b44f 100755
--- a/libavcodec/qtrle.c
+++ b/libavcodec/qtrle.c
@@ -127,6 +127,7 @@
     while (lines_to_change--) {
         CHECK_STREAM_PTR(2);
         pixel_ptr = row_ptr + (num_pixels * (s->buf[stream_ptr++] - 1));
+        CHECK_PIXEL_PTR(0);  /* make sure pixel_ptr is positive */
 
         while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {
             if (rle_code == 0) {
@@ -183,6 +184,7 @@
     while (lines_to_change--) {
         CHECK_STREAM_PTR(2);
         pixel_ptr = row_ptr + (4 * (s->buf[stream_ptr++] - 1));
+        CHECK_PIXEL_PTR(0);  /* make sure pixel_ptr is positive */
 
         while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {
             if (rle_code == 0) {
@@ -236,6 +238,7 @@
     while (lines_to_change--) {
         CHECK_STREAM_PTR(2);
         pixel_ptr = row_ptr + (s->buf[stream_ptr++] - 1) * 2;
+        CHECK_PIXEL_PTR(0);  /* make sure pixel_ptr is positive */
 
         while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {
             if (rle_code == 0) {
@@ -285,6 +288,7 @@
     while (lines_to_change--) {
         CHECK_STREAM_PTR(2);
         pixel_ptr = row_ptr + (s->buf[stream_ptr++] - 1) * 3;
+        CHECK_PIXEL_PTR(0);  /* make sure pixel_ptr is positive */
 
         while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {
             if (rle_code == 0) {
@@ -336,6 +340,7 @@
     while (lines_to_change--) {
         CHECK_STREAM_PTR(2);
         pixel_ptr = row_ptr + (s->buf[stream_ptr++] - 1) * 4;
+        CHECK_PIXEL_PTR(0);  /* make sure pixel_ptr is positive */
 
         while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {
             if (rle_code == 0) {
@@ -461,6 +466,8 @@
         stream_ptr += 4;
         height = AV_RB16(&s->buf[stream_ptr]);
         stream_ptr += 4;
+        if (height > s->avctx->height - start_line)
+            goto done;
     } else {
         start_line = 0;
         height = s->avctx->height;
diff --git a/libavcodec/resample2.c b/libavcodec/resample2.c
index 31d2be7..6551b22 100755
--- a/libavcodec/resample2.c
+++ b/libavcodec/resample2.c
@@ -191,8 +191,10 @@
     memcpy(&c->filter_bank[c->filter_length*phase_count+1], c->filter_bank, (c->filter_length-1)*sizeof(FELEM));
     c->filter_bank[c->filter_length*phase_count]= c->filter_bank[c->filter_length - 1];
 
-    c->src_incr= out_rate;
-    c->ideal_dst_incr= c->dst_incr= in_rate * phase_count;
+    if(!av_reduce(&c->src_incr, &c->dst_incr, out_rate, in_rate * (int64_t)phase_count, INT32_MAX/2))
+        return NULL;
+    c->ideal_dst_incr= c->dst_incr;
+
     c->index= -phase_count*((c->filter_length-1)/2);
 
     return c;
@@ -226,10 +228,9 @@
             dst[dst_index] = src[index2>>32];
             index2 += incr;
         }
-        frac += dst_index * dst_incr_frac;
         index += dst_index * dst_incr;
-        index += frac / c->src_incr;
-        frac %= c->src_incr;
+        index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
+        frac   = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
   }else{
     for(dst_index=0; dst_index < dst_size; dst_index++){
         FELEM *filter= c->filter_bank + c->filter_length*(index & c->phase_mask);
diff --git a/libavcodec/rv10.c b/libavcodec/rv10.c
index 71a25d6..ddf0f1d 100755
--- a/libavcodec/rv10.c
+++ b/libavcodec/rv10.c
@@ -642,6 +642,11 @@
         if(MPV_frame_start(s, avctx) < 0)
             return -1;
         ff_er_frame_start(s);
+    } else {
+        if (s->current_picture_ptr->pict_type != s->pict_type) {
+            av_log(s->avctx, AV_LOG_ERROR, "Slice type mismatch\n");
+            return -1;
+        }
     }
 
 #ifdef DEBUG
diff --git a/libavcodec/rv30.c b/libavcodec/rv30.c
index e1b3ad1..0d25eac 100644
--- a/libavcodec/rv30.c
+++ b/libavcodec/rv30.c
@@ -51,6 +51,11 @@
     skip_bits1(gb);
     si->pts = get_bits(gb, 13);
     rpr = get_bits(gb, r->rpr);
+    if (r->s.avctx->extradata_size < 8 + rpr*2) {
+        av_log(r->s.avctx, AV_LOG_WARNING,
+               "Extradata does not contain selected resolution\n");
+        rpr = 0;
+    }
     if(rpr){
         w = r->s.avctx->extradata[6 + rpr*2] << 2;
         h = r->s.avctx->extradata[7 + rpr*2] << 2;
@@ -74,7 +79,7 @@
     for(i = 0; i < 4; i++, dst += r->s.b4_stride - 4){
         for(j = 0; j < 4; j+= 2){
             int code = svq3_get_ue_golomb(gb) << 1;
-            if(code >= 81*2){
+            if(code >= 81U*2U){
                 av_log(r->s.avctx, AV_LOG_ERROR, "Incorrect intra prediction code\n");
                 return -1;
             }
@@ -103,7 +108,7 @@
     GetBitContext *gb = &s->gb;
     int code = svq3_get_ue_golomb(gb);
 
-    if(code > 11){
+    if(code > 11U){
         av_log(s->avctx, AV_LOG_ERROR, "Incorrect MB type code\n");
         return -1;
     }
diff --git a/libavcodec/rv34.c b/libavcodec/rv34.c
index 6603641..48fe370 100644
--- a/libavcodec/rv34.c
+++ b/libavcodec/rv34.c
@@ -1250,6 +1250,7 @@
             MPV_common_end(s);
             s->width  = r->si.width;
             s->height = r->si.height;
+            avcodec_set_dimensions(s->avctx, s->width, s->height);
             if(MPV_common_init(s) < 0)
                 return -1;
             r->intra_types_hist = av_realloc(r->intra_types_hist, s->b4_stride * 4 * 2 * sizeof(*r->intra_types_hist));
@@ -1269,6 +1270,17 @@
             r->next_pts = r->cur_pts;
         }
         s->mb_x = s->mb_y = 0;
+    } else {
+        int slice_type = r->si.type ? r->si.type : FF_I_TYPE;
+
+        if (slice_type != s->pict_type) {
+            av_log(s->avctx, AV_LOG_ERROR, "Slice type mismatch\n");
+            return AVERROR_INVALIDDATA;
+        }
+        if (s->width != r->si.width || s->height != r->si.height) {
+            av_log(s->avctx, AV_LOG_ERROR, "Size mismatch\n");
+            return AVERROR_INVALIDDATA;
+        }
     }
 
     r->si.end = end;
@@ -1401,8 +1413,9 @@
         slice_count = avctx->slice_count;
 
     //parse first slice header to check whether this frame can be decoded
-    if(get_slice_offset(avctx, slices_hdr, 0) > buf_size){
-        av_log(avctx, AV_LOG_ERROR, "Slice offset is greater than frame size\n");
+    if(get_slice_offset(avctx, slices_hdr, 0) < 0 ||
+       get_slice_offset(avctx, slices_hdr, 0) > buf_size){
+        av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n");
         return -1;
     }
     init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, 0), buf_size-get_slice_offset(avctx, slices_hdr, 0));
@@ -1430,8 +1443,8 @@
         else
             size= get_slice_offset(avctx, slices_hdr, i+1) - offset;
 
-        if(offset > buf_size){
-            av_log(avctx, AV_LOG_ERROR, "Slice offset is greater than frame size\n");
+        if(offset < 0 || offset > buf_size || size < 0){
+            av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n");
             break;
         }
 
@@ -1452,7 +1465,7 @@
             break;
     }
 
-    if(last){
+    if(last && s->current_picture_ptr){
         if(r->loop_filter)
             r->loop_filter(r, s->mb_height - 1);
         ff_er_frame_end(s);
diff --git a/libavcodec/rv40.c b/libavcodec/rv40.c
index 8e1a470..31c9ca3 100644
--- a/libavcodec/rv40.c
+++ b/libavcodec/rv40.c
@@ -207,8 +207,11 @@
     int blocks[RV34_MB_TYPES] = {0};
     int count = 0;
 
-    if(!r->s.mb_skip_run)
+    if(!r->s.mb_skip_run) {
         r->s.mb_skip_run = svq3_get_ue_golomb(gb) + 1;
+        if(r->s.mb_skip_run > (unsigned)s->mb_num)
+            return -1;
+    }
 
     if(--r->s.mb_skip_run)
          return RV34_MB_SKIP;
diff --git a/libavcodec/shorten.c b/libavcodec/shorten.c
index 2da83cf..8f87a62 100755
--- a/libavcodec/shorten.c
+++ b/libavcodec/shorten.c
@@ -469,9 +469,15 @@
             case FN_BITSHIFT:
                 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
                 break;
-            case FN_BLOCKSIZE:
-                s->blocksize = get_uint(s, av_log2(s->blocksize));
+            case FN_BLOCKSIZE: {
+                int blocksize = get_uint(s, av_log2(s->blocksize));
+                if (blocksize > s->blocksize) {
+                    av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
+                    return AVERROR_PATCHWELCOME;
+                }
+                s->blocksize = blocksize;
                 break;
+            }
             case FN_QUIT:
                 *data_size = 0;
                 return buf_size;
diff --git a/libavcodec/smacker.c b/libavcodec/smacker.c
index ad5827e..95a9beb 100755
--- a/libavcodec/smacker.c
+++ b/libavcodec/smacker.c
@@ -133,11 +133,13 @@
             return -1;
         }
         b1 = get_bits_count(gb);
-        i1 = get_vlc2(gb, ctx->v1->table, SMKTREE_BITS, 3);
+        i1 = ctx->v1->table ? get_vlc2(gb, ctx->v1->table, SMKTREE_BITS, 3) : 0;
         b1 = get_bits_count(gb) - b1;
         b2 = get_bits_count(gb);
-        i2 = get_vlc2(gb, ctx->v2->table, SMKTREE_BITS, 3);
+        i2 = ctx->v2->table ? get_vlc2(gb, ctx->v2->table, SMKTREE_BITS, 3) : 0;
         b2 = get_bits_count(gb) - b2;
+        if (i1 < 0 || i2 < 0)
+            return -1;
         val = ctx->recode1[i1] | (ctx->recode2[i2] << 8);
         if(val == ctx->escapes[0]) {
             ctx->last[0] = hc->current;
@@ -289,7 +291,8 @@
         smk->mmap_tbl[0] = 0;
         smk->mmap_last[0] = smk->mmap_last[1] = smk->mmap_last[2] = 1;
     } else {
-        smacker_decode_header_tree(smk, &gb, &smk->mmap_tbl, smk->mmap_last, mmap_size);
+        if (smacker_decode_header_tree(smk, &gb, &smk->mmap_tbl, smk->mmap_last, mmap_size))
+            return -1;
     }
     if(!get_bits1(&gb)) {
         av_log(smk->avctx, AV_LOG_INFO, "Skipping MCLR tree\n");
@@ -297,7 +300,8 @@
         smk->mclr_tbl[0] = 0;
         smk->mclr_last[0] = smk->mclr_last[1] = smk->mclr_last[2] = 1;
     } else {
-        smacker_decode_header_tree(smk, &gb, &smk->mclr_tbl, smk->mclr_last, mclr_size);
+        if (smacker_decode_header_tree(smk, &gb, &smk->mclr_tbl, smk->mclr_last, mclr_size))
+            return -1;
     }
     if(!get_bits1(&gb)) {
         av_log(smk->avctx, AV_LOG_INFO, "Skipping FULL tree\n");
@@ -305,7 +309,8 @@
         smk->full_tbl[0] = 0;
         smk->full_last[0] = smk->full_last[1] = smk->full_last[2] = 1;
     } else {
-        smacker_decode_header_tree(smk, &gb, &smk->full_tbl, smk->full_last, full_size);
+        if (smacker_decode_header_tree(smk, &gb, &smk->full_tbl, smk->full_last, full_size))
+            return -1;
     }
     if(!get_bits1(&gb)) {
         av_log(smk->avctx, AV_LOG_INFO, "Skipping TYPE tree\n");
@@ -313,7 +318,8 @@
         smk->type_tbl[0] = 0;
         smk->type_last[0] = smk->type_last[1] = smk->type_last[2] = 1;
     } else {
-        smacker_decode_header_tree(smk, &gb, &smk->type_tbl, smk->type_last, type_size);
+        if (smacker_decode_header_tree(smk, &gb, &smk->type_tbl, smk->type_last, type_size))
+            return -1;
     }
 
     return 0;
@@ -527,8 +533,8 @@
         return -1;
     }
 
-    decode_header_trees(c);
-
+    if (decode_header_trees(c))
+        return -1;
 
     return 0;
 }
@@ -558,6 +564,7 @@
 
 static av_cold int smka_decode_init(AVCodecContext *avctx)
 {
+    avctx->sample_fmt = SAMPLE_FMT_S16;
     avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
     return 0;
 }
@@ -571,7 +578,6 @@
     HuffContext h[4];
     VLC vlc[4];
     int16_t *samples = data;
-    int8_t *samples8 = data;
     int val;
     int i, res;
     int unp_size;
@@ -589,7 +595,7 @@
     }
     stereo = get_bits1(&gb);
     bits = get_bits1(&gb);
-    if (unp_size & 0xC0000000 || unp_size > *data_size) {
+    if (unp_size & 0xC0000000 || (unp_size << !bits) > *data_size) {
         av_log(avctx, AV_LOG_ERROR, "Frame is too large to fit in buffer\n");
         return -1;
     }
@@ -654,8 +660,10 @@
     } else { //8-bit data
         for(i = stereo; i >= 0; i--)
             pred[i] = get_bits(&gb, 8);
+        if (stereo + unp_size > *data_size)
+            return -1;
         for(i = 0; i < stereo; i++)
-            *samples8++ = pred[i];
+            *samples++ = (pred[i] - 0x80) << 8;
         for(i = 0; i < unp_size; i++) {
             if(i & stereo){
                 if(vlc[1].table)
@@ -663,16 +671,17 @@
                 else
                     res = 0;
                 pred[1] += (int8_t)h[1].values[res];
-                *samples8++ = pred[1];
+                *samples++ = (pred[1] - 0x80) << 8;
             } else {
                 if(vlc[0].table)
                     res = get_vlc2(&gb, vlc[0].table, SMKTREE_BITS, 3);
                 else
                     res = 0;
                 pred[0] += (int8_t)h[0].values[res];
-                *samples8++ = pred[0];
+                *samples++ = (pred[0] - 0x80) << 8;
             }
         }
+        unp_size *= 2;
     }
 
     for(i = 0; i < 4; i++) {
diff --git a/libavcodec/snow.c b/libavcodec/snow.c
index 68c4745..58fcbff 100644
--- a/libavcodec/snow.c
+++ b/libavcodec/snow.c
@@ -1626,6 +1626,7 @@
     s->b_width = w;
     s->b_height= h;
 
+    av_free(s->block);
     s->block= av_mallocz(w * h * sizeof(BlockNode) << (s->block_max_depth*2));
     return 0;
 }
@@ -3554,7 +3555,7 @@
 }
 
 static int decode_header(SnowContext *s){
-    int plane_index;
+    int plane_index, tmp;
     uint8_t kstate[32];
 
     memset(kstate, MID_STATE, sizeof(kstate));
@@ -3583,7 +3584,12 @@
         s->chroma_v_shift= get_symbol(&s->c, s->header_state, 0);
         s->spatial_scalability= get_rac(&s->c, s->header_state);
 //        s->rate_scalability= get_rac(&s->c, s->header_state);
-        s->max_ref_frames= get_symbol(&s->c, s->header_state, 0)+1;
+        tmp= get_symbol(&s->c, s->header_state, 0)+1;
+        if(tmp < 1 || tmp > MAX_REF_FRAMES){
+            av_log(s->avctx, AV_LOG_ERROR, "reference frame count is %d\n", tmp);
+            return -1;
+        }
+        s->max_ref_frames= tmp;
 
         decode_qlogs(s);
     }
@@ -3649,6 +3655,7 @@
     int i, j;
 
     s->avctx= avctx;
+    s->max_ref_frames=1; //just make sure its not an invalid value in case of no initial keyframe
 
     dsputil_init(&s->dsp, avctx);
 
@@ -4509,7 +4516,7 @@
                                               && p->hcoeff[2]==2;
     }
 
-    if(!s->block) alloc_blocks(s);
+    alloc_blocks(s);
 
     frame_start(s);
     //keyframe flag duplication mess FIXME
diff --git a/libavcodec/svq1dec.c b/libavcodec/svq1dec.c
index 7fef10b..7c4e5c9 100755
--- a/libavcodec/svq1dec.c
+++ b/libavcodec/svq1dec.c
@@ -676,6 +676,7 @@
 #endif
     return result;
   }
+  avcodec_set_dimensions(avctx, s->width, s->height);
 
   //FIXME this avoids some confusion for "B frames" without 2 references
   //this should be removed after libavcodec can handle more flexible picture types & ordering
diff --git a/libavcodec/svq3.c b/libavcodec/svq3.c
index bef7075..5d4d411 100755
--- a/libavcodec/svq3.c
+++ b/libavcodec/svq3.c
@@ -202,7 +202,7 @@
     for (limit = (16 >> intra); index < 16; index = limit, limit += 8) {
         for (; (vlc = svq3_get_ue_golomb(gb)) != 0; index++) {
 
-          if (vlc == INVALID_VLC)
+          if (vlc < 0)
               return -1;
 
           sign = (vlc & 0x1) - 1;
@@ -220,7 +220,7 @@
                   level = ((vlc + 9) >> 2) - run;
               }
           } else {
-              if (vlc < 16) {
+              if (vlc < 16U) {
                   run   = svq3_dct_tables[intra][vlc].run;
                   level = svq3_dct_tables[intra][vlc].level;
               } else if (intra) {
@@ -549,7 +549,7 @@
             for (i = 0; i < 16; i+=2) {
                 vlc = svq3_get_ue_golomb(&s->gb);
 
-                if (vlc >= 25){
+                if (vlc >= 25U){
                     av_log(h->s.avctx, AV_LOG_ERROR, "luma prediction:%d\n", vlc);
                     return -1;
                 }
@@ -620,7 +620,7 @@
     }
 
     if (!IS_INTRA16x16(mb_type) && (!IS_SKIP(mb_type) || s->pict_type == FF_B_TYPE)) {
-        if ((vlc = svq3_get_ue_golomb(&s->gb)) >= 48){
+        if ((vlc = svq3_get_ue_golomb(&s->gb)) >= 48U){
             av_log(h->s.avctx, AV_LOG_ERROR, "cbp_vlc=%d\n", vlc);
             return -1;
         }
@@ -630,7 +630,7 @@
     if (IS_INTRA16x16(mb_type) || (s->pict_type != FF_I_TYPE && s->adaptive_quant && cbp)) {
         s->qscale += svq3_get_se_golomb(&s->gb);
 
-        if (s->qscale > 31){
+        if (s->qscale > 31U){
             av_log(h->s.avctx, AV_LOG_ERROR, "qscale:%d\n", s->qscale);
             return -1;
         }
@@ -727,7 +727,7 @@
         skip_bits_long(&s->gb, 0);
     }
 
-    if ((i = svq3_get_ue_golomb(&s->gb)) == INVALID_VLC || i >= 3){
+    if ((i = svq3_get_ue_golomb(&s->gb)) >= 3U){
         av_log(h->s.avctx, AV_LOG_ERROR, "illegal slice type %d \n", i);
         return -1;
     }
diff --git a/libavcodec/truemotion1.c b/libavcodec/truemotion1.c
index 1cf56ed..ada1270 100755
--- a/libavcodec/truemotion1.c
+++ b/libavcodec/truemotion1.c
@@ -519,6 +519,10 @@
 }
 
 #define APPLY_C_PREDICTOR() \
+    if(index > 1023){\
+        av_log(s->avctx, AV_LOG_ERROR, " index %d went out of bounds\n", index); \
+        return; \
+    }\
     predictor_pair = s->c_predictor_table[index]; \
     horiz_pred += (predictor_pair >> 1); \
     if (predictor_pair & 1) { \
@@ -536,6 +540,10 @@
         index++;
 
 #define APPLY_C_PREDICTOR_24() \
+    if(index > 1023){\
+        av_log(s->avctx, AV_LOG_ERROR, " index %d went out of bounds\n", index); \
+        return; \
+    }\
     predictor_pair = s->c_predictor_table[index]; \
     horiz_pred += (predictor_pair >> 1); \
     if (predictor_pair & 1) { \
@@ -554,6 +562,10 @@
 
 
 #define APPLY_Y_PREDICTOR() \
+    if(index > 1023){\
+        av_log(s->avctx, AV_LOG_ERROR, " index %d went out of bounds\n", index); \
+        return; \
+    }\
     predictor_pair = s->y_predictor_table[index]; \
     horiz_pred += (predictor_pair >> 1); \
     if (predictor_pair & 1) { \
@@ -571,6 +583,10 @@
         index++;
 
 #define APPLY_Y_PREDICTOR_24() \
+    if(index > 1023){\
+        av_log(s->avctx, AV_LOG_ERROR, " index %d went out of bounds\n", index); \
+        return; \
+    }\
     predictor_pair = s->y_predictor_table[index]; \
     horiz_pred += (predictor_pair >> 1); \
     if (predictor_pair & 1) { \
diff --git a/libavcodec/utils.c b/libavcodec/utils.c
index 2da9ca5..04ed39a 100644
--- a/libavcodec/utils.c
+++ b/libavcodec/utils.c
@@ -198,7 +198,7 @@
 }
 
 int avcodec_check_dimensions(void *av_log_ctx, unsigned int w, unsigned int h){
-    if((int)w>0 && (int)h>0 && (w+128)*(uint64_t)(h+128) < INT_MAX/4)
+    if((int)w>0 && (int)h>0 && (w+128)*(uint64_t)(h+128) < INT_MAX/8)
         return 0;
 
     av_log(av_log_ctx, AV_LOG_ERROR, "picture size invalid (%ux%u)\n", w, h);
diff --git a/libavcodec/vc1.c b/libavcodec/vc1.c
index 229c885..571d787 100755
--- a/libavcodec/vc1.c
+++ b/libavcodec/vc1.c
@@ -2366,7 +2366,7 @@
     if (index != vc1_ac_sizes[codingset] - 1) {
         run = vc1_index_decode_table[codingset][index][0];
         level = vc1_index_decode_table[codingset][index][1];
-        lst = index >= vc1_last_decode_table[codingset];
+        lst = index >= vc1_last_decode_table[codingset] || get_bits_left(gb) < 0;
         if(get_bits1(gb))
             level = -level;
     } else {
diff --git a/libavcodec/vmdav.c b/libavcodec/vmdav.c
index 1921c81..60dc7f9 100755
--- a/libavcodec/vmdav.c
+++ b/libavcodec/vmdav.c
@@ -73,9 +73,11 @@
 #define QUEUE_SIZE 0x1000
 #define QUEUE_MASK 0x0FFF
 
-static void lz_unpack(const unsigned char *src, unsigned char *dest, int dest_len)
+static void lz_unpack(const unsigned char *src, int src_len,
+                      unsigned char *dest, int dest_len)
 {
     const unsigned char *s;
+    unsigned int s_len;
     unsigned char *d;
     unsigned char *d_end;
     unsigned char queue[QUEUE_SIZE];
@@ -88,13 +90,16 @@
     unsigned int i, j;
 
     s = src;
+    s_len = src_len;
     d = dest;
     d_end = d + dest_len;
     dataleft = AV_RL32(s);
-    s += 4;
+    s += 4; s_len -= 4;
     memset(queue, 0x20, QUEUE_SIZE);
+    if (s_len < 4)
+        return;
     if (AV_RL32(s) == 0x56781234) {
-        s += 4;
+        s += 4; s_len -= 4;
         qpos = 0x111;
         speclen = 0xF + 3;
     } else {
@@ -102,32 +107,41 @@
         speclen = 100;  /* no speclen */
     }
 
-    while (dataleft > 0) {
-        tag = *s++;
+    while (dataleft > 0 && s_len > 0) {
+        tag = *s++; s_len--;
         if ((tag == 0xFF) && (dataleft > 8)) {
-            if (d + 8 > d_end)
+            if (d + 8 > d_end || s_len < 8)
                 return;
             for (i = 0; i < 8; i++) {
                 queue[qpos++] = *d++ = *s++;
                 qpos &= QUEUE_MASK;
             }
+            s_len -= 8;
             dataleft -= 8;
         } else {
             for (i = 0; i < 8; i++) {
                 if (dataleft == 0)
                     break;
                 if (tag & 0x01) {
-                    if (d + 1 > d_end)
+                    if (d + 1 > d_end || s_len < 1)
                         return;
                     queue[qpos++] = *d++ = *s++;
                     qpos &= QUEUE_MASK;
                     dataleft--;
+                    s_len--;
                 } else {
+                    if (s_len < 2)
+                        return;
                     chainofs = *s++;
                     chainofs |= ((*s & 0xF0) << 4);
                     chainlen = (*s++ & 0x0F) + 3;
-                    if (chainlen == speclen)
+                    s_len -= 2;
+                    if (chainlen == speclen) {
+                        if (s_len < 1)
+                            return;
                         chainlen = *s++ + 0xF + 3;
+                        s_len--;
+                    }
                     if (d + chainlen > d_end)
                         return;
                     for (j = 0; j < chainlen; j++) {
@@ -144,7 +158,7 @@
 }
 
 static int rle_unpack(const unsigned char *src, unsigned char *dest,
-    int src_len, int dest_len)
+    int src_count, int src_size, int dest_len)
 {
     const unsigned char *ps;
     unsigned char *pd;
@@ -153,31 +167,40 @@
 
     ps = src;
     pd = dest;
-    if (src_len & 1)
+    if (src_count & 1) {
+        if (src_size < 1)
+            return 0;
         *pd++ = *ps++;
+        src_size--;
+    }
 
-    src_len >>= 1;
+    src_count >>= 1;
     i = 0;
     do {
+        if (src_size < 1)
+            break;
         l = *ps++;
+        src_size--;
         if (l & 0x80) {
             l = (l & 0x7F) * 2;
-            if (pd + l > dest_end)
+            if (pd + l > dest_end || src_size < l)
                 return ps - src;
             memcpy(pd, ps, l);
             ps += l;
+            src_size -= l;
             pd += l;
         } else {
-            if (pd + i > dest_end)
+            if (pd + i > dest_end || src_size < 2)
                 return ps - src;
             for (i = 0; i < l; i++) {
                 *pd++ = ps[0];
                 *pd++ = ps[1];
             }
             ps += 2;
+            src_size -= 2;
         }
         i += l;
-    } while (i < src_len);
+    } while (i < src_count);
 
     return ps - src;
 }
@@ -192,6 +215,7 @@
     const unsigned char *p = s->buf + 16;
 
     const unsigned char *pb;
+    unsigned int pb_size;
     unsigned char meth;
     unsigned char *dp;   /* pointer to current frame */
     unsigned char *pp;   /* pointer to previous frame */
@@ -206,6 +230,16 @@
     frame_y = AV_RL16(&s->buf[8]);
     frame_width = AV_RL16(&s->buf[10]) - frame_x + 1;
     frame_height = AV_RL16(&s->buf[12]) - frame_y + 1;
+    if (frame_x < 0 || frame_width < 0 ||
+        frame_x >= s->avctx->width ||
+        frame_width > s->avctx->width ||
+        frame_x + frame_width > s->avctx->width)
+        return;
+    if (frame_y < 0 || frame_height < 0 ||
+        frame_y >= s->avctx->height ||
+        frame_height > s->avctx->height ||
+        frame_y + frame_height > s->avctx->height)
+        return;
 
     if ((frame_width == s->avctx->width && frame_height == s->avctx->height) &&
         (frame_x || frame_y)) {
@@ -218,8 +252,9 @@
 
     /* if only a certain region will be updated, copy the entire previous
      * frame before the decode */
-    if (frame_x || frame_y || (frame_width != s->avctx->width) ||
-        (frame_height != s->avctx->height)) {
+    if (s->prev_frame.data[0] &&
+        (frame_x || frame_y || (frame_width != s->avctx->width) ||
+        (frame_height != s->avctx->height))) {
 
         memcpy(s->frame.data[0], s->prev_frame.data[0],
             s->avctx->height * s->frame.linesize[0]);
@@ -237,14 +272,19 @@
         }
         s->size -= (256 * 3 + 2);
     }
-    if (s->size >= 0) {
+    if (s->size > 0) {
         /* originally UnpackFrame in VAG's code */
         pb = p;
-        meth = *pb++;
+        pb_size = s->buf + s->size - pb;
+        if (pb_size < 1)
+            return;
+        meth = *pb++; pb_size--;
         if (meth & 0x80) {
-            lz_unpack(pb, s->unpack_buffer, s->unpack_buffer_size);
+            lz_unpack(pb, pb_size,
+                      s->unpack_buffer, s->unpack_buffer_size);
             meth &= 0x7F;
             pb = s->unpack_buffer;
+            pb_size = s->unpack_buffer_size;
         }
 
         dp = &s->frame.data[0][frame_y * s->frame.linesize[0] + frame_x];
@@ -255,17 +295,21 @@
             for (i = 0; i < frame_height; i++) {
                 ofs = 0;
                 do {
+                    if (pb_size < 1)
+                        return;
                     len = *pb++;
+                    pb_size--;
                     if (len & 0x80) {
                         len = (len & 0x7F) + 1;
-                        if (ofs + len > frame_width)
+                        if (ofs + len > frame_width || pb_size < len)
                             return;
                         memcpy(&dp[ofs], pb, len);
                         pb += len;
+                        pb_size -= len;
                         ofs += len;
                     } else {
                         /* interframe pixel copy */
-                        if (ofs + len + 1 > frame_width)
+                        if (ofs + len + 1 > frame_width || !s->prev_frame.data[0])
                             return;
                         memcpy(&dp[ofs], &pp[ofs], len + 1);
                         ofs += len + 1;
@@ -283,8 +327,11 @@
 
         case 2:
             for (i = 0; i < frame_height; i++) {
+                if (pb_size < frame_width)
+                    return;
                 memcpy(dp, pb, frame_width);
                 pb += frame_width;
+                pb_size -= frame_width;
                 dp += s->frame.linesize[0];
                 pp += s->prev_frame.linesize[0];
             }
@@ -294,18 +341,27 @@
             for (i = 0; i < frame_height; i++) {
                 ofs = 0;
                 do {
+                    if (pb_size < 1)
+                        return;
                     len = *pb++;
+                    pb_size--;
                     if (len & 0x80) {
                         len = (len & 0x7F) + 1;
+                        if (pb_size < 1)
+                            return;
                         if (*pb++ == 0xFF)
-                            len = rle_unpack(pb, &dp[ofs], len, frame_width - ofs);
-                        else
+                            len = rle_unpack(pb, &dp[ofs], len, pb_size, frame_width - ofs);
+                        else {
+                            if (pb_size < len)
+                                return;
                             memcpy(&dp[ofs], pb, len);
+                        }
                         pb += len;
+                        pb_size -= 1 + len;
                         ofs += len;
                     } else {
                         /* interframe pixel copy */
-                        if (ofs + len + 1 > frame_width)
+                        if (ofs + len + 1 > frame_width || !s->prev_frame.data[0])
                             return;
                         memcpy(&dp[ofs], &pp[ofs], len + 1);
                         ofs += len + 1;
diff --git a/libavcodec/vorbis.c b/libavcodec/vorbis.c
index 45daa3c..13e7e65 100755
--- a/libavcodec/vorbis.c
+++ b/libavcodec/vorbis.c
@@ -45,6 +45,9 @@
 
 // Generate vlc codes from vorbis huffman code lengths
 
+// the two bits[p] > 32 checks should be redundant, all calling code should
+// already ensure that, but since it allows overwriting the stack it seems
+// reasonable to check redundantly.
 int ff_vorbis_len2vlc(uint8_t *bits, uint32_t *codes, uint_fast32_t num) {
     uint_fast32_t exit_at_level[33]={404,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
         0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
@@ -63,6 +66,7 @@
     }
 
     codes[p]=0;
+    if (bits[p] > 32) return 1;
     for(i=0;i<bits[p];++i) {
         exit_at_level[i+1]=1<<i;
     }
@@ -79,6 +83,7 @@
     ++p;
 
     for(;p<num;++p) {
+        if (bits[p] > 32) return 1;
         if (bits[p]==0) continue;
         // find corresponding exit(node which the tree can grow further from)
         for(i=bits[p];i>0;--i) {
@@ -141,13 +146,13 @@
     }
 }
 
-static void render_line(int x0, int y0, int x1, int y1, float * buf) {
+static void render_line(int x0, uint8_t y0, int x1, int y1, float * buf) {
     int dy = y1 - y0;
     int adx = x1 - x0;
     int base = dy / adx;
     int ady = FFABS(dy) - FFABS(base) * adx;
     int x = x0;
-    int y = y0;
+    uint8_t y = y0;
     int err = 0;
     int sy = dy<0 ? -1 : 1;
     buf[x] = ff_vorbis_floor1_inverse_db_table[y];
@@ -163,7 +168,8 @@
 }
 
 void ff_vorbis_floor1_render_list(vorbis_floor1_entry * list, int values, uint_fast16_t * y_list, int * flag, int multiplier, float * out, int samples) {
-    int lx, ly, i;
+    int lx, i;
+    uint8_t ly;
     lx = 0;
     ly = y_list[0] * multiplier;
     for (i = 1; i < values; i++) {
diff --git a/libavcodec/vorbis_dec.c b/libavcodec/vorbis_dec.c
index 6ca8763..7a1ea5d 100755
--- a/libavcodec/vorbis_dec.c
+++ b/libavcodec/vorbis_dec.c
@@ -37,6 +37,7 @@
 #define V_NB_BITS 8
 #define V_NB_BITS2 11
 #define V_MAX_VLCS (1<<16)
+#define V_MAX_PARTITIONS (1<<20)
 
 #ifndef V_DEBUG
 #define AV_DEBUG(...)
@@ -59,7 +60,7 @@
 typedef struct vorbis_floor1_s vorbis_floor1;
 struct vorbis_context_s;
 typedef
-uint_fast8_t (* vorbis_floor_decode_func)
+int (* vorbis_floor_decode_func)
              (struct vorbis_context_s *, vorbis_floor_data *, float *);
 typedef struct {
     uint_fast8_t floor_type;
@@ -249,8 +250,8 @@
         }
 
         codebook_setup->dimensions=get_bits(gb, 16);
-        if (codebook_setup->dimensions>16) {
-            av_log(vc->avccontext, AV_LOG_ERROR, " %"PRIdFAST16". Codebook's dimension is too large (%d). \n", cb, codebook_setup->dimensions);
+        if (codebook_setup->dimensions>16||codebook_setup->dimensions==0) {
+            av_log(vc->avccontext, AV_LOG_ERROR, " %"PRIdFAST16". Codebook's dimension is invalid (%d). \n", cb, codebook_setup->dimensions);
             goto error;
         }
         entries=get_bits(gb, 24);
@@ -442,14 +443,14 @@
 
 // Process floors part
 
-static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,
+static int vorbis_floor0_decode(vorbis_context *vc,
                                          vorbis_floor_data *vfu, float *vec);
 static void create_map( vorbis_context * vc, uint_fast8_t floor_number );
-static uint_fast8_t vorbis_floor1_decode(vorbis_context *vc,
+static int vorbis_floor1_decode(vorbis_context *vc,
                                          vorbis_floor_data *vfu, float *vec);
 static int vorbis_parse_setup_hdr_floors(vorbis_context *vc) {
     GetBitContext *gb=&vc->gb;
-    uint_fast16_t i,j,k;
+    int i,j,k;
 
     vc->floor_count=get_bits(gb, 6)+1;
 
@@ -465,6 +466,7 @@
         if (floor_setup->floor_type==1) {
             uint_fast8_t maximum_class=0;
             uint_fast8_t rangebits;
+            uint_fast32_t rangemax;
             uint_fast16_t floor1_values=2;
 
             floor_setup->decode=vorbis_floor1_decode;
@@ -492,13 +494,23 @@
                 AV_DEBUG(" %d floor %d class dim: %d subclasses %d \n", i, j, floor_setup->data.t1.class_dimensions[j], floor_setup->data.t1.class_subclasses[j]);
 
                 if (floor_setup->data.t1.class_subclasses[j]) {
-                    floor_setup->data.t1.class_masterbook[j]=get_bits(gb, 8);
+                    int bits=get_bits(gb, 8);
+                    if (bits>=vc->codebook_count) {
+                        av_log(vc->avccontext, AV_LOG_ERROR, "Masterbook index %d is out of range.\n", bits);
+                        return 1;
+                    }
+                    floor_setup->data.t1.class_masterbook[j]=bits;
 
                     AV_DEBUG("   masterbook: %d \n", floor_setup->data.t1.class_masterbook[j]);
                 }
 
                 for(k=0;k<(1<<floor_setup->data.t1.class_subclasses[j]);++k) {
-                    floor_setup->data.t1.subclass_books[j][k]=(int16_t)get_bits(gb, 8)-1;
+                    int16_t bits=get_bits(gb, 8)-1;
+                    if (bits!=-1 && bits>=vc->codebook_count) {
+                        av_log(vc->avccontext, AV_LOG_ERROR, "Subclass book index %d is out of range.\n", bits);
+                        return 1;
+                    }
+                    floor_setup->data.t1.subclass_books[j][k]=bits;
 
                     AV_DEBUG("    book %d. : %d \n", k, floor_setup->data.t1.subclass_books[j][k]);
                 }
@@ -515,8 +527,15 @@
 
 
             rangebits=get_bits(gb, 4);
+            rangemax = (1 << rangebits);
+            if (rangemax > vc->blocksize[1] / 2) {
+                av_log(vc->avccontext, AV_LOG_ERROR,
+                       "Floor value is too large for blocksize: %d (%d)\n",
+                       rangemax, vc->blocksize[1] / 2);
+                return -1;
+            }
             floor_setup->data.t1.list[0].x = 0;
-            floor_setup->data.t1.list[1].x = (1<<rangebits);
+            floor_setup->data.t1.list[1].x = rangemax;
 
             for(j=0;j<floor_setup->data.t1.partitions;++j) {
                 for(k=0;k<floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];++k,++floor1_values) {
@@ -558,12 +577,11 @@
                 uint_fast8_t book_idx;
                 for (idx=0;idx<floor_setup->data.t0.num_books;++idx) {
                     book_idx=get_bits(gb, 8);
+                    if (book_idx>=vc->codebook_count)
+                        return 1;
                     floor_setup->data.t0.book_list[idx]=book_idx;
                     if (vc->codebooks[book_idx].dimensions > max_codebook_dim)
                         max_codebook_dim=vc->codebooks[book_idx].dimensions;
-
-                    if (floor_setup->data.t0.book_list[idx]>vc->codebook_count)
-                        return 1;
                 }
             }
 
@@ -634,8 +652,20 @@
         res_setup->begin=get_bits(gb, 24);
         res_setup->end=get_bits(gb, 24);
         res_setup->partition_size=get_bits(gb, 24)+1;
+        /* Validations to prevent a buffer overflow later. */
+        if (res_setup->begin>res_setup->end
+        || res_setup->end > (res_setup->type == 2 ? vc->avccontext->channels : 1) * vc->blocksize[1] / 2
+        || (res_setup->end-res_setup->begin)/res_setup->partition_size>V_MAX_PARTITIONS) {
+            av_log(vc->avccontext, AV_LOG_ERROR, "partition out of bounds: type, begin, end, size, blocksize: %d, %d, %d, %d, %d\n", res_setup->type, res_setup->begin, res_setup->end, res_setup->partition_size, vc->blocksize[1]/2);
+            return 1;
+        }
+
         res_setup->classifications=get_bits(gb, 6)+1;
         res_setup->classbook=get_bits(gb, 8);
+        if (res_setup->classbook>=vc->codebook_count) {
+            av_log(vc->avccontext, AV_LOG_ERROR, "classbook value %d out of range. \n", res_setup->classbook);
+            return 1;
+        }
 
         AV_DEBUG("    begin %d end %d part.size %d classif.s %d classbook %d \n", res_setup->begin, res_setup->end, res_setup->partition_size,
           res_setup->classifications, res_setup->classbook);
@@ -655,7 +685,12 @@
         for(j=0;j<res_setup->classifications;++j) {
             for(k=0;k<8;++k) {
                 if (cascade[j]&(1<<k)) {
-                        res_setup->books[j][k]=get_bits(gb, 8);
+                    int bits=get_bits(gb, 8);
+                    if (bits>=vc->codebook_count) {
+                        av_log(vc->avccontext, AV_LOG_ERROR, "book value %d out of range. \n", bits);
+                        return 1;
+                    }
+                    res_setup->books[j][k]=bits;
 
                     AV_DEBUG("     %d class casscade depth %d book: %d \n", j, k, res_setup->books[j][k]);
 
@@ -702,7 +737,14 @@
             for(j=0;j<mapping_setup->coupling_steps;++j) {
                 mapping_setup->magnitude[j]=get_bits(gb, ilog(vc->audio_channels-1));
                 mapping_setup->angle[j]=get_bits(gb, ilog(vc->audio_channels-1));
-                // FIXME: sanity checks
+                if (mapping_setup->magnitude[j]>=vc->audio_channels) {
+                    av_log(vc->avccontext, AV_LOG_ERROR, "magnitude channel %d out of range. \n", mapping_setup->magnitude[j]);
+                    return 1;
+                }
+                if (mapping_setup->angle[j]>=vc->audio_channels) {
+                    av_log(vc->avccontext, AV_LOG_ERROR, "angle channel %d out of range. \n", mapping_setup->angle[j]);
+                    return 1;
+                }
             }
         } else {
             mapping_setup->coupling_steps=0;
@@ -723,9 +765,20 @@
         }
 
         for(j=0;j<mapping_setup->submaps;++j) {
+            int bits;
             skip_bits(gb, 8); // FIXME check?
-            mapping_setup->submap_floor[j]=get_bits(gb, 8);
-            mapping_setup->submap_residue[j]=get_bits(gb, 8);
+            bits=get_bits(gb, 8);
+            if (bits>=vc->floor_count) {
+                av_log(vc->avccontext, AV_LOG_ERROR, "submap floor value %d out of range. \n", bits);
+                return -1;
+            }
+            mapping_setup->submap_floor[j]=bits;
+            bits=get_bits(gb, 8);
+            if (bits>=vc->residue_count) {
+                av_log(vc->avccontext, AV_LOG_ERROR, "submap residue value %d out of range. \n", bits);
+                return -1;
+            }
+            mapping_setup->submap_residue[j]=bits;
 
             AV_DEBUG("   %d mapping %d submap : floor %d, residue %d \n", i, j, mapping_setup->submap_floor[j], mapping_setup->submap_residue[j]);
         }
@@ -788,7 +841,11 @@
         mode_setup->blockflag=get_bits1(gb);
         mode_setup->windowtype=get_bits(gb, 16); //FIXME check
         mode_setup->transformtype=get_bits(gb, 16); //FIXME check
-        mode_setup->mapping=get_bits(gb, 8); //FIXME check
+        mode_setup->mapping=get_bits(gb, 8);
+        if (mode_setup->mapping>=vc->mapping_count) {
+            av_log(vc->avccontext, AV_LOG_ERROR, "mode mapping value %d out of range. \n", mode_setup->mapping);
+            return 1;
+        }
 
         AV_DEBUG(" %d mode: blockflag %d, windowtype %d, transformtype %d, mapping %d \n", i, mode_setup->blockflag, mode_setup->windowtype, mode_setup->transformtype, mode_setup->mapping);
     }
@@ -853,8 +910,16 @@
     }
 
     vc->version=get_bits_long(gb, 32);    //FIXME check 0
-    vc->audio_channels=get_bits(gb, 8);   //FIXME check >0
-    vc->audio_samplerate=get_bits_long(gb, 32);   //FIXME check >0
+    vc->audio_channels=get_bits(gb, 8);
+    if(vc->audio_channels <= 0){
+        av_log(vc->avccontext, AV_LOG_ERROR, "Invalid number of channels\n");
+        return -1;
+    }
+    vc->audio_samplerate=get_bits_long(gb, 32);
+    if(vc->audio_samplerate <= 0){
+        av_log(vc->avccontext, AV_LOG_ERROR, "Invalid samplerate\n");
+        return -1;
+    }
     vc->bitrate_maximum=get_bits_long(gb, 32);
     vc->bitrate_nominal=get_bits_long(gb, 32);
     vc->bitrate_minimum=get_bits_long(gb, 32);
@@ -981,7 +1046,7 @@
 
 // Read and decode floor
 
-static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,
+static int vorbis_floor0_decode(vorbis_context *vc,
                                          vorbis_floor_data *vfu, float *vec) {
     vorbis_floor0 * vf=&vfu->t0;
     float * lsp=vf->lsp;
@@ -1005,6 +1070,9 @@
         }
         AV_DEBUG( "floor0 dec: booknumber: %u\n", book_idx );
         codebook=vc->codebooks[vf->book_list[book_idx]];
+        /* Invalid codebook! */
+        if (!codebook.codevectors)
+            return -1;
 
         while (lsp_len<vf->order) {
             int vec_off;
@@ -1094,7 +1162,7 @@
     return 0;
 }
 
-static uint_fast8_t vorbis_floor1_decode(vorbis_context *vc, vorbis_floor_data *vfu, float *vec) {
+static int vorbis_floor1_decode(vorbis_context *vc, vorbis_floor_data *vfu, float *vec) {
     vorbis_floor1 * vf=&vfu->t1;
     GetBitContext *gb=&vc->gb;
     uint_fast16_t range_v[4]={ 256, 128, 86, 64 };
@@ -1225,7 +1293,7 @@
 
 // Read and decode residue
 
-static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc, vorbis_residue *vr, uint_fast8_t ch, uint_fast8_t *do_not_decode, float *vec, uint_fast16_t vlen, int vr_type) {
+static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc, vorbis_residue *vr, uint_fast8_t ch, uint_fast8_t *do_not_decode, float *vec, uint_fast16_t vlen, unsigned ch_left, int vr_type) {
     GetBitContext *gb=&vc->gb;
     uint_fast8_t c_p_c=vc->codebooks[vr->classbook].dimensions;
     uint_fast16_t n_to_read=vr->end-vr->begin;
@@ -1235,6 +1303,7 @@
     uint_fast8_t ch_used;
     uint_fast8_t i,j,l;
     uint_fast16_t k;
+    unsigned max_output = (ch - 1) * vlen;
 
     if (vr_type==2) {
         for(j=1;j<ch;++j) {
@@ -1242,8 +1311,15 @@
         }
         if (do_not_decode[0]) return 0;
         ch_used=1;
+        max_output += vr->end / ch;
     } else {
         ch_used=ch;
+        max_output += vr->end;
+    }
+
+    if (max_output > ch_left * vlen) {
+        av_log(vc->avccontext, AV_LOG_ERROR, "Insufficient output buffer\n");
+        return -1;
     }
 
     AV_DEBUG(" residue type 0/1/2 decode begin, ch: %d  cpc %d  \n", ch, c_p_c);
@@ -1367,14 +1443,14 @@
     return 0;
 }
 
-static inline int vorbis_residue_decode(vorbis_context *vc, vorbis_residue *vr, uint_fast8_t ch, uint_fast8_t *do_not_decode, float *vec, uint_fast16_t vlen)
+static inline int vorbis_residue_decode(vorbis_context *vc, vorbis_residue *vr, uint_fast8_t ch, uint_fast8_t *do_not_decode, float *vec, uint_fast16_t vlen, unsigned ch_left)
 {
     if (vr->type==2)
-        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 2);
+        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, ch_left, 2);
     else if (vr->type==1)
-        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 1);
+        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, ch_left, 1);
     else if (vr->type==0)
-        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 0);
+        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, ch_left, 0);
     else {
         av_log(vc->avccontext, AV_LOG_ERROR, " Invalid residue type while residue decode?! \n");
         return 1;
@@ -1437,6 +1513,8 @@
     uint_fast8_t res_num=0;
     int_fast16_t retlen=0;
     float fadd_bias = vc->add_bias;
+    unsigned ch_left = vc->audio_channels;
+    unsigned vlen;
 
     if (get_bits1(gb)) {
         av_log(vc->avccontext, AV_LOG_ERROR, "Not a Vorbis I audio packet.\n");
@@ -1448,6 +1526,10 @@
     } else {
         mode_number=get_bits(gb, ilog(vc->mode_count-1));
     }
+    if (mode_number>=vc->mode_count) {
+        av_log(vc->avccontext, AV_LOG_ERROR, "mode number %d out of range.\n", mode_number);
+        return -1;
+    }
     vc->mode_number=mode_number;
     mapping=&vc->mappings[vc->modes[mode_number].mapping];
 
@@ -1455,25 +1537,33 @@
 
     blockflag=vc->modes[mode_number].blockflag;
     blocksize=vc->blocksize[blockflag];
+    vlen = blocksize / 2;
     if (blockflag) {
         skip_bits(gb, 2); // previous_window, next_window
     }
 
-    memset(ch_res_ptr, 0, sizeof(float)*vc->audio_channels*blocksize/2); //FIXME can this be removed ?
-    memset(ch_floor_ptr, 0, sizeof(float)*vc->audio_channels*blocksize/2); //FIXME can this be removed ?
+    memset(ch_res_ptr, 0, sizeof(float)*vc->audio_channels*vlen); //FIXME can this be removed ?
+    memset(ch_floor_ptr, 0, sizeof(float)*vc->audio_channels*vlen); //FIXME can this be removed ?
 
 // Decode floor
 
     for(i=0;i<vc->audio_channels;++i) {
         vorbis_floor *floor;
+        int ret;
         if (mapping->submaps>1) {
             floor=&vc->floors[mapping->submap_floor[mapping->mux[i]]];
         } else {
             floor=&vc->floors[mapping->submap_floor[0]];
         }
 
-        no_residue[i]=floor->decode(vc, &floor->data, ch_floor_ptr);
-        ch_floor_ptr+=blocksize/2;
+        ret = floor->decode(vc, &floor->data, ch_floor_ptr);
+
+        if (ret < 0) {
+            av_log(vc->avccontext, AV_LOG_ERROR, "Invalid codebook in vorbis_floor_decode.\n");
+            return -1;
+        }
+        no_residue[i] = ret;
+        ch_floor_ptr += vlen;
     }
 
 // Nonzero vector propagate
@@ -1490,9 +1580,10 @@
     for(i=0;i<mapping->submaps;++i) {
         vorbis_residue *residue;
         uint_fast8_t ch=0;
+        int ret;
 
         for(j=0;j<vc->audio_channels;++j) {
-            if ((mapping->submaps==1) || (i=mapping->mux[j])) {
+            if ((mapping->submaps==1) || (i==mapping->mux[j])) {
                 res_chan[j]=res_num;
                 if (no_residue[j]) {
                     do_not_decode[ch]=1;
@@ -1504,9 +1595,18 @@
             }
         }
         residue=&vc->residues[mapping->submap_residue[i]];
-        vorbis_residue_decode(vc, residue, ch, do_not_decode, ch_res_ptr, blocksize/2);
+        if (ch_left < ch) {
+            av_log(vc->avccontext, AV_LOG_ERROR, "Too many channels in vorbis_floor_decode.\n");
+            return -1;
+        }
+        if (ch) {
+            ret = vorbis_residue_decode(vc, residue, ch, do_not_decode, ch_res_ptr, vlen, ch_left);
+            if (ret < 0)
+                return ret;
+        }
 
-        ch_res_ptr+=ch*blocksize/2;
+        ch_res_ptr += ch * vlen;
+        ch_left -= ch;
     }
 
 // Inverse coupling
diff --git a/libavcodec/vp3.c b/libavcodec/vp3.c
index 6490161..69248d6 100755
--- a/libavcodec/vp3.c
+++ b/libavcodec/vp3.c
@@ -43,6 +43,8 @@
 
 #define FRAGMENT_PIXELS 8
 
+static av_cold int vp3_decode_end(AVCodecContext *avctx);
+
 typedef struct Coeff {
     struct Coeff *next;
     DCTELEM coeff;
@@ -1009,12 +1011,12 @@
             /* decode a VLC into a token */
             token = get_vlc2(gb, table->table, 5, 3);
             /* use the token to get a zero run, a coefficient, and an eob run */
-            if (token <= 6) {
+            if ((unsigned) token <= 6U) {
                 eob_run = eob_run_base[token];
                 if (eob_run_get_bits[token])
                     eob_run += get_bits(gb, eob_run_get_bits[token]);
                 coeff = zero_run = 0;
-            } else {
+            } else if (token >= 0) {
                 bits_to_get = coeff_get_bits[token];
                 if (!bits_to_get)
                     coeff = coeff_tables[token][0];
@@ -1024,6 +1026,10 @@
                 zero_run = zero_run_base[token];
                 if (zero_run_get_bits[token])
                     zero_run += get_bits(gb, zero_run_get_bits[token]);
+            } else {
+                av_log(s->avctx, AV_LOG_ERROR,
+                       "Invalid token %d\n", token);
+                return -1;
             }
         }
 
@@ -1069,6 +1075,8 @@
     /* unpack the C plane DC coefficients */
     residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
         s->first_coded_c_fragment, s->last_coded_c_fragment, residual_eob_run);
+    if (residual_eob_run < 0)
+        return residual_eob_run;
 
     /* fetch the AC table indexes */
     ac_y_table = get_bits(gb, 4);
@@ -1078,36 +1086,52 @@
     for (i = 1; i <= 5; i++) {
         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_1[ac_y_table], i,
             s->first_coded_y_fragment, s->last_coded_y_fragment, residual_eob_run);
+        if (residual_eob_run < 0)
+            return residual_eob_run;
 
         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_1[ac_c_table], i,
             s->first_coded_c_fragment, s->last_coded_c_fragment, residual_eob_run);
+        if (residual_eob_run < 0)
+            return residual_eob_run;
     }
 
     /* unpack the group 2 AC coefficients (coeffs 6-14) */
     for (i = 6; i <= 14; i++) {
         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_2[ac_y_table], i,
             s->first_coded_y_fragment, s->last_coded_y_fragment, residual_eob_run);
+        if (residual_eob_run < 0)
+            return residual_eob_run;
 
         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_2[ac_c_table], i,
             s->first_coded_c_fragment, s->last_coded_c_fragment, residual_eob_run);
+        if (residual_eob_run < 0)
+            return residual_eob_run;
     }
 
     /* unpack the group 3 AC coefficients (coeffs 15-27) */
     for (i = 15; i <= 27; i++) {
         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_3[ac_y_table], i,
             s->first_coded_y_fragment, s->last_coded_y_fragment, residual_eob_run);
+        if (residual_eob_run < 0)
+            return residual_eob_run;
 
         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_3[ac_c_table], i,
             s->first_coded_c_fragment, s->last_coded_c_fragment, residual_eob_run);
+        if (residual_eob_run < 0)
+            return residual_eob_run;
     }
 
     /* unpack the group 4 AC coefficients (coeffs 28-63) */
     for (i = 28; i <= 63; i++) {
         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_4[ac_y_table], i,
             s->first_coded_y_fragment, s->last_coded_y_fragment, residual_eob_run);
+        if (residual_eob_run < 0)
+            return residual_eob_run;
 
         residual_eob_run = unpack_vlcs(s, gb, &s->ac_vlc_4[ac_c_table], i,
             s->first_coded_c_fragment, s->last_coded_c_fragment, residual_eob_run);
+        if (residual_eob_run < 0)
+            return residual_eob_run;
     }
 
     return 0;
@@ -1684,6 +1708,11 @@
     s->coeffs = av_malloc(s->fragment_count * sizeof(Coeff) * 65);
     s->coded_fragment_list = av_malloc(s->fragment_count * sizeof(int));
     s->pixel_addresses_initialized = 0;
+    if (!s->superblock_coding || !s->all_fragments || !s->coeff_counts ||
+        !s->coeffs || !s->coded_fragment_list) {
+        vp3_decode_end(avctx);
+        return -1;
+    }
 
     if (!s->theora_tables)
     {
@@ -1737,29 +1766,34 @@
         for (i = 0; i < 16; i++) {
 
             /* DC histograms */
-            init_vlc(&s->dc_vlc[i], 5, 32,
+            if (init_vlc(&s->dc_vlc[i], 5, 32,
                 &s->huffman_table[i][0][1], 4, 2,
-                &s->huffman_table[i][0][0], 4, 2, 0);
+                &s->huffman_table[i][0][0], 4, 2, 0) < 0)
+                goto vlc_fail;
 
             /* group 1 AC histograms */
-            init_vlc(&s->ac_vlc_1[i], 5, 32,
+            if (init_vlc(&s->ac_vlc_1[i], 5, 32,
                 &s->huffman_table[i+16][0][1], 4, 2,
-                &s->huffman_table[i+16][0][0], 4, 2, 0);
+                &s->huffman_table[i+16][0][0], 4, 2, 0) < 0)
+                goto vlc_fail;
 
             /* group 2 AC histograms */
-            init_vlc(&s->ac_vlc_2[i], 5, 32,
+            if (init_vlc(&s->ac_vlc_2[i], 5, 32,
                 &s->huffman_table[i+16*2][0][1], 4, 2,
-                &s->huffman_table[i+16*2][0][0], 4, 2, 0);
+                &s->huffman_table[i+16*2][0][0], 4, 2, 0) < 0)
+                goto vlc_fail;
 
             /* group 3 AC histograms */
-            init_vlc(&s->ac_vlc_3[i], 5, 32,
+            if (init_vlc(&s->ac_vlc_3[i], 5, 32,
                 &s->huffman_table[i+16*3][0][1], 4, 2,
-                &s->huffman_table[i+16*3][0][0], 4, 2, 0);
+                &s->huffman_table[i+16*3][0][0], 4, 2, 0) < 0)
+                goto vlc_fail;
 
             /* group 4 AC histograms */
-            init_vlc(&s->ac_vlc_4[i], 5, 32,
+            if (init_vlc(&s->ac_vlc_4[i], 5, 32,
                 &s->huffman_table[i+16*4][0][1], 4, 2,
-                &s->huffman_table[i+16*4][0][0], 4, 2, 0);
+                &s->huffman_table[i+16*4][0][0], 4, 2, 0) < 0)
+                goto vlc_fail;
         }
     }
 
@@ -1784,6 +1818,11 @@
     s->superblock_macroblocks = av_malloc(s->superblock_count * 4 * sizeof(int));
     s->macroblock_fragments = av_malloc(s->macroblock_count * 6 * sizeof(int));
     s->macroblock_coding = av_malloc(s->macroblock_count + 1);
+    if (!s->superblock_fragments || !s->superblock_macroblocks ||
+        !s->macroblock_fragments || !s->macroblock_coding) {
+        vp3_decode_end(avctx);
+        return -1;
+    }
     init_block_mapping(s);
 
     for (i = 0; i < 3; i++) {
@@ -1793,6 +1832,10 @@
     }
 
     return 0;
+
+vlc_fail:
+    av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
+    return -1;
 }
 
 /*
@@ -2231,7 +2274,7 @@
     }
 
   for(i=0;i<3;i++) {
-    init_get_bits(&gb, header_start[i], header_len[i]);
+    init_get_bits(&gb, header_start[i], header_len[i] * 8);
 
     ptype = get_bits(&gb, 8);
 
diff --git a/libavcodec/vp5.c b/libavcodec/vp5.c
index dfa2a1b..c32f4f0 100644
--- a/libavcodec/vp5.c
+++ b/libavcodec/vp5.c
@@ -199,7 +199,8 @@
         model1 = model->coeff_dccv[pt];
         model2 = model->coeff_dcct[pt][ctx];
 
-        for (coeff_idx=0; coeff_idx<64; ) {
+        coeff_idx = 0;
+        for (;;) {
             if (vp56_rac_get_prob(c, model2[0])) {
                 if (vp56_rac_get_prob(c, model2[2])) {
                     if (vp56_rac_get_prob(c, model2[3])) {
@@ -236,8 +237,11 @@
                 ct = 0;
                 s->coeff_ctx[vp56_b6to4[b]][coeff_idx] = 0;
             }
+            coeff_idx++;
+            if (coeff_idx >= 64)
+                break;
 
-            cg = vp5_coeff_groups[++coeff_idx];
+            cg = vp5_coeff_groups[coeff_idx];
             ctx = s->coeff_ctx[vp56_b6to4[b]][coeff_idx];
             model1 = model->coeff_ract[pt][ct][cg];
             model2 = cg > 2 ? model1 : model->coeff_acct[pt][ct][cg][ctx];
diff --git a/libavcodec/vp56.c b/libavcodec/vp56.c
index ad11b52..1ca8a40 100644
--- a/libavcodec/vp56.c
+++ b/libavcodec/vp56.c
@@ -519,6 +519,16 @@
         if (!res)
             return -1;
 
+        if (res == 2) {
+            int i;
+            for (i = 0; i < 4; i++) {
+                if (s->frames[i].data[0])
+                    avctx->release_buffer(avctx, &s->frames[i]);
+            }
+            if (is_alpha)
+                return -1;
+        }
+
         if (!is_alpha) {
             p->reference = 1;
             if (avctx->get_buffer(avctx, p) < 0) {
@@ -685,6 +695,7 @@
 av_cold int vp56_free(AVCodecContext *avctx)
 {
     VP56Context *s = avctx->priv_data;
+    int pt;
 
     av_free(s->above_blocks);
     av_free(s->macroblocks);
@@ -695,5 +706,15 @@
         avctx->release_buffer(avctx, s->framep[VP56_FRAME_GOLDEN2]);
     if (s->framep[VP56_FRAME_PREVIOUS]->data[0])
         avctx->release_buffer(avctx, s->framep[VP56_FRAME_PREVIOUS]);
+
+    for (pt=0; pt < 2; pt++) {
+        int ct, cg;
+        free_vlc(&s->dccv_vlc[pt]);
+        free_vlc(&s->runv_vlc[pt]);
+        for (ct=0; ct<3; ct++)
+            for (cg = 0; cg < 6; cg++)
+                free_vlc(&s->ract_vlc[pt][ct][cg]);
+    }
+
     return 0;
 }
diff --git a/libavcodec/vp6.c b/libavcodec/vp6.c
index 5071903..fbfa385 100644
--- a/libavcodec/vp6.c
+++ b/libavcodec/vp6.c
@@ -136,8 +136,11 @@
     if (coeff_offset) {
         buf      += coeff_offset;
         buf_size -= coeff_offset;
-        if (buf_size < 0)
+        if (buf_size < 0) {
+            if (s->framep[VP56_FRAME_CURRENT]->key_frame)
+                avcodec_set_dimensions(s->avctx, 0, 0);
             return 0;
+        }
         if (s->use_huffman) {
             s->parse_coeff = vp6_parse_coeff_huffman;
             init_get_bits(&s->gb, buf, buf_size<<3);
@@ -212,7 +215,7 @@
     return (a->count - b->count)*16 + (b->sym - a->sym);
 }
 
-static void vp6_build_huff_tree(VP56Context *s, uint8_t coeff_model[],
+static int vp6_build_huff_tree(VP56Context *s, uint8_t coeff_model[],
                                 const uint8_t *map, unsigned size, VLC *vlc)
 {
     Node nodes[2*size], *tmp = &nodes[size];
@@ -227,8 +230,9 @@
         nodes[map[2*i+1]].count = b + !b;
     }
 
-    /* then build the huffman tree accodring to probabilities */
-    ff_huff_build_tree(s->avctx, vlc, size, nodes, vp6_huff_cmp,
+    free_vlc(vlc);
+    /* then build the huffman tree according to probabilities */
+    return ff_huff_build_tree(s->avctx, vlc, size, nodes, vp6_huff_cmp,
                        FF_HUFFMAN_FLAG_HNODE_FIRST);
 }
 
@@ -365,7 +369,7 @@
         if (b > 3) pt = 1;
         vlc_coeff = &s->dccv_vlc[pt];
 
-        for (coeff_idx=0; coeff_idx<64; ) {
+        for (coeff_idx = 0;;) {
             int run = 1;
             if (coeff_idx<2 && s->nb_null[coeff_idx][pt]) {
                 s->nb_null[coeff_idx][pt]--;
@@ -400,6 +404,8 @@
                 }
             }
             coeff_idx+=run;
+            if (coeff_idx >= 64)
+                break;
             cg = FFMIN(vp6_coeff_groups[coeff_idx], 3);
             vlc_coeff = &s->ract_vlc[pt][ct][cg];
         }
@@ -427,7 +433,8 @@
         model1 = model->coeff_dccv[pt];
         model2 = model->coeff_dcct[pt][ctx];
 
-        for (coeff_idx=0; coeff_idx<64; ) {
+        coeff_idx = 0;
+        for (;;) {
             if ((coeff_idx>1 && ct==0) || vp56_rac_get_prob(c, model2[0])) {
                 /* parse a coeff */
                 if (vp56_rac_get_prob(c, model2[2])) {
@@ -468,8 +475,10 @@
                             run += vp56_rac_get_prob(c, model3[i+8]) << i;
                 }
             }
-
-            cg = vp6_coeff_groups[coeff_idx+=run];
+            coeff_idx += run;
+            if (coeff_idx >= 64)
+                break;
+            cg = vp6_coeff_groups[coeff_idx];
             model1 = model2 = model->coeff_ract[pt][ct][cg];
         }
 
diff --git a/libavcodec/vqavideo.c b/libavcodec/vqavideo.c
index 00df736..f34a631 100755
--- a/libavcodec/vqavideo.c
+++ b/libavcodec/vqavideo.c
@@ -163,6 +163,12 @@
         return -1;
     }
 
+    if (s->width  & (s->vector_width  - 1) ||
+        s->height & (s->vector_height - 1)) {
+        av_log(avctx, AV_LOG_ERROR, "Image size not multiple of block size\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     /* allocate codebooks */
     s->codebook_size = MAX_CODEBOOK_SIZE;
     s->codebook = av_malloc(s->codebook_size);
diff --git a/libavcodec/wavpack.c b/libavcodec/wavpack.c
index 12eac33..19e5e05 100644
--- a/libavcodec/wavpack.c
+++ b/libavcodec/wavpack.c
@@ -536,12 +536,13 @@
         }
         switch(id & WP_IDF_MASK){
         case WP_ID_DECTERMS:
-            s->terms = size;
-            if(s->terms > MAX_TERMS){
+            if(size > MAX_TERMS){
                 av_log(avctx, AV_LOG_ERROR, "Too many decorrelation terms\n");
+                s->terms = 0;
                 buf += ssize;
                 continue;
             }
+            s->terms = size;
             for(i = 0; i < s->terms; i++) {
                 s->decorr[s->terms - i - 1].value = (*buf & 0x1F) - 5;
                 s->decorr[s->terms - i - 1].delta = *buf >> 5;
diff --git a/libavcodec/wmadec.c b/libavcodec/wmadec.c
index e7936ce..088d510 100755
--- a/libavcodec/wmadec.c
+++ b/libavcodec/wmadec.c
@@ -105,6 +105,11 @@
     s->use_bit_reservoir = flags2 & 0x0002;
     s->use_variable_block_len = flags2 & 0x0004;
 
+    if(avctx->channels > MAX_CHANNELS){
+        av_log(avctx, AV_LOG_ERROR, "Invalid number of channels (%d)\n", avctx->channels);
+        return -1;
+    }
+
     if(ff_wma_init(avctx, flags2)<0)
         return -1;
 
diff --git a/libavcodec/wnv1.c b/libavcodec/wnv1.c
index 7c0105f..aa284da 100755
--- a/libavcodec/wnv1.c
+++ b/libavcodec/wnv1.c
@@ -67,6 +67,11 @@
     int prev_y = 0, prev_u = 0, prev_v = 0;
     uint8_t *rbuf;
 
+    if(buf_size<=8) {
+        av_log(avctx, AV_LOG_ERROR, "buf_size %d is too small\n", buf_size);
+        return AVERROR_INVALIDDATA;
+    }
+
     rbuf = av_malloc(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
     if(!rbuf){
         av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");
diff --git a/libavcodec/x86/dsputilenc_mmx.c b/libavcodec/x86/dsputilenc_mmx.c
index 1717a01..c1a648b 100644
--- a/libavcodec/x86/dsputilenc_mmx.c
+++ b/libavcodec/x86/dsputilenc_mmx.c
@@ -882,6 +882,7 @@
 
 static void diff_bytes_mmx(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w){
     x86_reg i=0;
+    if(w>=16)
     __asm__ volatile(
         "1:                             \n\t"
         "movq  (%2, %0), %%mm0          \n\t"
diff --git a/libavcodec/x86/fft_sse.c b/libavcodec/x86/fft_sse.c
index 3d9f1c5..918fdf2 100644
--- a/libavcodec/x86/fft_sse.c
+++ b/libavcodec/x86/fft_sse.c
@@ -22,7 +22,7 @@
 #include "libavutil/x86_cpu.h"
 #include "libavcodec/dsputil.h"
 
-static const int m1m1m1m1[4] __attribute__((aligned(16))) =
+DECLARE_ASM_CONST(16, int, m1m1m1m1)[4] =
     { 1 << 31, 1 << 31, 1 << 31, 1 << 31 };
 
 void ff_fft_dispatch_sse(FFTComplex *z, int nbits);
@@ -182,7 +182,7 @@
     j = -n;
     k = n-16;
     __asm__ volatile(
-        "movaps %4, %%xmm7 \n"
+        "movaps "MANGLE(m1m1m1m1)", %%xmm7 \n"
         "1: \n"
         "movaps       (%2,%1), %%xmm0 \n"
         "movaps       (%3,%0), %%xmm1 \n"
@@ -195,8 +195,7 @@
         "add $16, %0 \n"
         "jl 1b \n"
         :"+r"(j), "+r"(k)
-        :"r"(output+n4), "r"(output+n4*3),
-         "m"(*m1m1m1m1)
+        :"r"(output+n4), "r"(output+n4*3)
     );
 }
 
diff --git a/libavcodec/x86/snowdsp_mmx.c b/libavcodec/x86/snowdsp_mmx.c
index e7868ea..8374a63 100644
--- a/libavcodec/x86/snowdsp_mmx.c
+++ b/libavcodec/x86/snowdsp_mmx.c
@@ -667,7 +667,7 @@
              "jnz 1b                         \n\t"\
              :"+m"(dst8),"+m"(dst_array),"=&r"(tmp)\
              :\
-             "rm"((x86_reg)(src_x<<1)),"m"(obmc),"a"(block),"m"(b_h),"m"(src_stride):\
+             "rm"((x86_reg)(src_x<<1)),"m"(obmc),"a"(block),"m"((x86_reg)b_h),"m"((x86_reg)src_stride):\
              "%"REG_c"","%"REG_S"","%"REG_D"","%"REG_d"");
 
 #define snow_inner_add_yblock_sse2_end_8\
@@ -815,7 +815,7 @@
              "jnz 1b                         \n\t"\
              :"+m"(dst8),"+m"(dst_array),"=&r"(tmp)\
              :\
-             "rm"((x86_reg)(src_x<<1)),"m"(obmc),"a"(block),"m"(b_h),"m"(src_stride):\
+             "rm"((x86_reg)(src_x<<1)),"m"(obmc),"a"(block),"m"((x86_reg)b_h),"m"((x86_reg)src_stride):\
              "%"REG_c"","%"REG_S"","%"REG_D"","%"REG_d"");
 
 static void inner_add_yblock_bw_8_obmc_16_mmx(const uint8_t *obmc, const x86_reg obmc_stride, uint8_t * * block, int b_w, x86_reg b_h,
diff --git a/libavcodec/x86/x86inc.asm b/libavcodec/x86/x86inc.asm
index 26ea929..fccabb8 100644
--- a/libavcodec/x86/x86inc.asm
+++ b/libavcodec/x86/x86inc.asm
@@ -29,10 +29,14 @@
 ; Kludge: Something on OS X fails to align .rodata even given an align attribute,
 ; so use a different read-only section.
 %macro SECTION_RODATA 0
-    %ifidn __OUTPUT_FORMAT__,macho
+    %ifidn __OUTPUT_FORMAT__,macho64
+        SECTION .text align=16
+    %elifidn __OUTPUT_FORMAT__,macho
+        SECTION .text align=16
         fakegot:
-    %endif
+    %else
     SECTION .rodata align=16
+    %endif
 %endmacro
 
 ; PIC support macros. All these macros are totally harmless when PIC is
diff --git a/libavcodec/xvmc.h b/libavcodec/xvmc.h
index 01f84b2..12da4bf 100644
--- a/libavcodec/xvmc.h
+++ b/libavcodec/xvmc.h
@@ -141,9 +141,9 @@
 
     /** Number of the the next free data block; one data block consists of
         64 short values in the data_blocks array.
-        All blocks before this one have already been claimed by placing their
-        position into the corresponding block description structure field,
-        that are part of the mv_blocks array.
+        All blocks before this one are already claimed by filling their number
+        into the corresponding blocks description structure field,
+        that are hold in mv_blocks array.
         - application - zeroes it on get_buffer().
                         A successful ff_draw_horiz_band() may zero it together
                         with start_mb_blocks_num.
diff --git a/libavdevice/alsa-audio-common.c b/libavdevice/alsa-audio-common.c
index 9812724..9616d8a 100644
--- a/libavdevice/alsa-audio-common.c
+++ b/libavdevice/alsa-audio-common.c
@@ -68,7 +68,7 @@
     s->frame_size = av_get_bits_per_sample(*codec_id) / 8 * channels;
 
     if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
-        flags = SND_PCM_NONBLOCK;
+        flags = O_NONBLOCK;
     }
     res = snd_pcm_open(&h, audio_device, mode, flags);
     if (res < 0) {
diff --git a/libavdevice/vfwcap.c b/libavdevice/vfwcap.c
index 4b6f73b..e415b74 100644
--- a/libavdevice/vfwcap.c
+++ b/libavdevice/vfwcap.c
@@ -20,8 +20,8 @@
  */
 
 #include "libavformat/avformat.h"
-#include <vfw.h>
 #include <windows.h>
+#include <vfw.h>
 
 //#define DEBUG_VFW
 
diff --git a/libavformat/4xm.c b/libavformat/4xm.c
index 631f821..d0fd312 100755
--- a/libavformat/4xm.c
+++ b/libavformat/4xm.c
@@ -127,6 +127,10 @@
     for (i = 0; i < header_size - 8; i++) {
         fourcc_tag = AV_RL32(&header[i]);
         size = AV_RL32(&header[i + 4]);
+        if (size > header_size - i - 8 && (fourcc_tag == vtrk_TAG || fourcc_tag == strk_TAG)) {
+            av_log(s, AV_LOG_ERROR, "chunk larger than array %d>%d\n", size, header_size - i - 8);
+            return AVERROR_INVALIDDATA;
+        }
 
         if (fourcc_tag == std__TAG) {
             fourxm->fps = av_int2flt(AV_RL32(&header[i + 12]));
diff --git a/libavformat/ape.c b/libavformat/ape.c
index fac9678..7511d93 100644
--- a/libavformat/ape.c
+++ b/libavformat/ape.c
@@ -335,6 +335,10 @@
             url_fskip(pb, ape->wavheaderlength);
     }
 
+    if(!ape->totalframes){
+        av_log(s, AV_LOG_ERROR, "No frames in the file!\n");
+        return AVERROR(EINVAL);
+    }
     if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
         av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes);
         return -1;
@@ -352,6 +356,8 @@
 
     if (ape->seektablelength > 0) {
         ape->seektable = av_malloc(ape->seektablelength);
+        if (!ape->seektable)
+            return AVERROR(ENOMEM);
         for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++)
             ape->seektable[i] = get_le32(pb);
     }
diff --git a/libavformat/asf.h b/libavformat/asf.h
index 18efb67..06f0f1b 100755
--- a/libavformat/asf.h
+++ b/libavformat/asf.h
@@ -80,7 +80,6 @@
 
 typedef struct {
     uint32_t seqno;
-    unsigned int packet_size;
     int is_streamed;
     int asfid2avid[128];                 ///< conversion table from asf ID 2 AVStream ID
     ASFStream streams[128];              ///< it's max number and it's not that big
diff --git a/libavformat/asfdec.c b/libavformat/asfdec.c
index bf92f7b..080b5ec 100644
--- a/libavformat/asfdec.c
+++ b/libavformat/asfdec.c
@@ -269,7 +269,7 @@
             asf->hdr.min_pktsize        = get_le32(pb);
             asf->hdr.max_pktsize        = get_le32(pb);
             asf->hdr.max_bitrate        = get_le32(pb);
-            asf->packet_size = asf->hdr.max_pktsize;
+            s->packet_size = asf->hdr.max_pktsize;
         } else if (!guidcmp(&g, &ff_asf_stream_header)) {
             enum CodecType type;
             int type_specific_size, sizeX;
@@ -621,7 +621,9 @@
     int rsize = 8;
     int c, d, e, off;
 
-    off= (url_ftell(pb) - s->data_offset) % asf->packet_size + 3;
+    off= 32768;
+    if (s->packet_size > 0)
+        off= (url_ftell(pb) - s->data_offset) % s->packet_size + 3;
 
     c=d=e=-1;
     while(off-- > 0){
@@ -651,12 +653,12 @@
     asf->packet_flags    = c;
     asf->packet_property = d;
 
-    DO_2BITS(asf->packet_flags >> 5, packet_length, asf->packet_size);
+    DO_2BITS(asf->packet_flags >> 5, packet_length, s->packet_size);
     DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
     DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
 
     //the following checks prevent overflows and infinite loops
-    if(packet_length >= (1U<<29)){
+    if(!packet_length || packet_length >= (1U<<29)){
         av_log(s, AV_LOG_ERROR, "invalid packet_length %d at:%"PRId64"\n", packet_length, url_ftell(pb));
         return -1;
     }
@@ -680,7 +682,7 @@
     if (packet_length < asf->hdr.min_pktsize)
         padsize += asf->hdr.min_pktsize - packet_length;
     asf->packet_padsize = padsize;
-    dprintf(s, "packet: size=%d padsize=%d  left=%d\n", asf->packet_size, asf->packet_padsize, asf->packet_size_left);
+    dprintf(s, "packet: size=%d padsize=%d  left=%d\n", s->packet_size, asf->packet_padsize, asf->packet_size_left);
     return 0;
 }
 
@@ -855,7 +857,7 @@
 
         /* read data */
         //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",
-        //       asf->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
+        //       s->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
         //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
         asf->packet_size_left -= asf->packet_frag_size;
         if (asf->packet_size_left < 0)
@@ -998,7 +1000,6 @@
 
 static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
 {
-    ASFContext *asf = s->priv_data;
     AVPacket pkt1, *pkt = &pkt1;
     ASFStream *asf_st;
     int64_t pts;
@@ -1010,7 +1011,8 @@
         start_pos[i]= pos;
     }
 
-    pos= (pos+asf->packet_size-1-s->data_offset)/asf->packet_size*asf->packet_size+ s->data_offset;
+    if (s->packet_size > 0)
+        pos= (pos+s->packet_size-1-s->data_offset)/s->packet_size*s->packet_size+ s->data_offset;
     *ppos= pos;
     url_fseek(s->pb, pos, SEEK_SET);
 
@@ -1030,7 +1032,7 @@
 
             asf_st= s->streams[i]->priv_data;
 
-//            assert((asf_st->packet_pos - s->data_offset) % asf->packet_size == 0);
+//            assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0);
             pos= asf_st->packet_pos;
 
             av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
@@ -1073,10 +1075,10 @@
             int pktct =get_le16(s->pb);
             av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d\n", pktnum, pktct);
 
-            pos=s->data_offset + asf->packet_size*(int64_t)pktnum;
+            pos=s->data_offset + s->packet_size*(int64_t)pktnum;
             index_pts=av_rescale(itime, i, 10000);
 
-            av_add_index_entry(s->streams[stream_index], pos, index_pts, asf->packet_size, 0, AVINDEX_KEYFRAME);
+            av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME);
         }
         asf->index_read= 1;
     }
@@ -1090,7 +1092,7 @@
     int64_t pos;
     int index;
 
-    if (asf->packet_size <= 0)
+    if (s->packet_size <= 0)
         return -1;
 
     /* Try using the protocol's read_seek if available */
diff --git a/libavformat/asfenc.c b/libavformat/asfenc.c
index 39b4842..168a221 100644
--- a/libavformat/asfenc.c
+++ b/libavformat/asfenc.c
@@ -321,8 +321,8 @@
     put_le64(pb, asf->duration); /* duration (in 100ns units) */
     put_le64(pb, PREROLL_TIME); /* start time stamp */
     put_le32(pb, (asf->is_streamed || url_is_streamed(pb)) ? 3 : 2); /* ??? */
-    put_le32(pb, asf->packet_size); /* packet size */
-    put_le32(pb, asf->packet_size); /* packet size */
+    put_le32(pb, s->packet_size); /* packet size */
+    put_le32(pb, s->packet_size); /* packet size */
     put_le32(pb, bit_rate); /* Nominal data rate in bps */
     end_header(pb, hpos);
 
@@ -514,7 +514,7 @@
 {
     ASFContext *asf = s->priv_data;
 
-    asf->packet_size = PACKET_SIZE;
+    s->packet_size  = PACKET_SIZE;
     asf->nb_packets = 0;
 
     asf->last_indexed_pts = 0;
@@ -536,7 +536,7 @@
     asf->packet_nb_payloads = 0;
     asf->packet_timestamp_start = -1;
     asf->packet_timestamp_end = -1;
-    init_put_byte(&asf->pb, asf->packet_buf, asf->packet_size, 1,
+    init_put_byte(&asf->pb, asf->packet_buf, s->packet_size, 1,
                   NULL, NULL, NULL, NULL);
 
     return 0;
@@ -612,7 +612,7 @@
     assert(asf->packet_timestamp_end >= asf->packet_timestamp_start);
 
     if (asf->is_streamed) {
-        put_chunk(s, 0x4424, asf->packet_size, 0);
+        put_chunk(s, 0x4424, s->packet_size, 0);
     }
 
     packet_hdr_size = put_payload_parsing_info(
@@ -627,14 +627,14 @@
     assert(packet_hdr_size <= asf->packet_size_left);
     memset(asf->packet_buf + packet_filled_size, 0, asf->packet_size_left);
 
-    put_buffer(s->pb, asf->packet_buf, asf->packet_size - packet_hdr_size);
+    put_buffer(s->pb, asf->packet_buf, s->packet_size - packet_hdr_size);
 
     put_flush_packet(s->pb);
     asf->nb_packets++;
     asf->packet_nb_payloads = 0;
     asf->packet_timestamp_start = -1;
     asf->packet_timestamp_end = -1;
-    init_put_byte(&asf->pb, asf->packet_buf, asf->packet_size, 1,
+    init_put_byte(&asf->pb, asf->packet_buf, s->packet_size, 1,
                   NULL, NULL, NULL, NULL);
 }
 
diff --git a/libavformat/avc.c b/libavformat/avc.c
index 578e7d0..6ecea38 100755
--- a/libavformat/avc.c
+++ b/libavformat/avc.c
@@ -25,7 +25,7 @@
 
 const uint8_t *ff_avc_find_startcode(const uint8_t *p, const uint8_t *end)
 {
-    const uint8_t *a = p + 4 - ((intptr_t)p & 3);
+    const uint8_t *a = p + 4 - ((long)p & 3);
 
     for( end -= 3; p < a && p < end; p++ ) {
         if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
diff --git a/libavformat/avformat.h b/libavformat/avformat.h
index 82f442c..ce8eb75 100755
--- a/libavformat/avformat.h
+++ b/libavformat/avformat.h
@@ -1052,7 +1052,7 @@
  * @param pts_den denominator to convert to seconds (MPEG: 90000)
  */
 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
-                     int pts_num, int pts_den);
+                     unsigned int pts_num, unsigned int pts_den);
 
 #define AVSEEK_FLAG_BACKWARD 1 ///< seek backward
 #define AVSEEK_FLAG_BYTE     2 ///< seeking based on position in bytes
diff --git a/libavformat/avs.c b/libavformat/avs.c
index 1fcb19f..eda7f9d 100755
--- a/libavformat/avs.c
+++ b/libavformat/avs.c
@@ -163,10 +163,14 @@
             sub_type = get_byte(s->pb);
             type = get_byte(s->pb);
             size = get_le16(s->pb);
+            if (size < 4)
+                return AVERROR_INVALIDDATA;
             avs->remaining_frame_size -= size;
 
             switch (type) {
             case AVS_PALETTE:
+                if (size - 4 > sizeof(palette))
+                    return AVERROR_INVALIDDATA;
                 ret = get_buffer(s->pb, palette, size - 4);
                 if (ret < size - 4)
                     return AVERROR(EIO);
diff --git a/libavformat/dv.c b/libavformat/dv.c
index 820c3b5..7a0f803 100755
--- a/libavformat/dv.c
+++ b/libavformat/dv.c
@@ -125,10 +125,14 @@
     /* We work with 720p frames split in half, thus even frames have
      * channels 0,1 and odd 2,3. */
     ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0;
-    pcm  = ppcm[ipcm++];
 
     /* for each DIF channel */
     for (chan = 0; chan < sys->n_difchan; chan++) {
+        /* next stereo channel (50Mbps and 100Mbps only) */
+        pcm = ppcm[ipcm++];
+        if (!pcm)
+            break;
+
         /* for each DIF segment */
         for (i = 0; i < sys->difseg_size; i++) {
             frame += 6 * 80; /* skip DIF segment header */
@@ -176,11 +180,6 @@
                 frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
             }
         }
-
-        /* next stereo channel (50Mbps and 100Mbps only) */
-        pcm = ppcm[ipcm++];
-        if (!pcm)
-            break;
     }
 
     return size;
@@ -202,6 +201,12 @@
     stype = (as_pack[3] & 0x1f);      /* 0 - 2CH, 2 - 4CH, 3 - 8CH */
     quant =  as_pack[4] & 0x07;       /* 0 - 16bit linear, 1 - 12bit nonlinear */
 
+    if (stype > 3) {
+        av_log(c->fctx, AV_LOG_ERROR, "stype %d is invalid\n", stype);
+        c->ach = 0;
+        return 0;
+    }
+
     /* note: ach counts PAIRS of channels (i.e. stereo channels) */
     ach = ((int[4]){  1,  0,  2,  4})[stype];
     if (ach == 1 && quant && freq == 2)
@@ -335,7 +340,8 @@
        c->audio_pkt[i].pts  = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate;
        ppcm[i] = c->audio_buf[i];
     }
-    dv_extract_audio(buf, ppcm, c->sys);
+    if (c->ach)
+    	dv_extract_audio(buf, ppcm, c->sys);
     c->abytes += size;
 
     /* We work with 720p frames split in half, thus even frames have
diff --git a/libavformat/electronicarts.c b/libavformat/electronicarts.c
index fe19e70..ad63c56 100755
--- a/libavformat/electronicarts.c
+++ b/libavformat/electronicarts.c
@@ -448,12 +448,17 @@
 
     while (!packet_read) {
         chunk_type = get_le32(pb);
-        chunk_size = (ea->big_endian ? get_be32(pb) : get_le32(pb)) - 8;
+        chunk_size = ea->big_endian ? get_be32(pb) : get_le32(pb);
+        if (chunk_size <= 8)
+            return AVERROR_INVALIDDATA;
+        chunk_size -= 8;
 
         switch (chunk_type) {
         /* audio data */
         case ISNh_TAG:
             /* header chunk also contains data; skip over the header portion*/
+            if (chunk_size < 32)
+                return AVERROR_INVALIDDATA;
             url_fskip(pb, 32);
             chunk_size -= 32;
         case ISNd_TAG:
diff --git a/libavformat/file.c b/libavformat/file.c
index 636992d..074f104 100755
--- a/libavformat/file.c
+++ b/libavformat/file.c
@@ -88,13 +88,13 @@
 #endif
     if (fd < 0)
         return AVERROR(ENOENT);
-    h->priv_data = (void *) (intptr_t) fd;
+    h->priv_data = (void *)(size_t)fd;
     return 0;
 }
 
 static int file_read(URLContext *h, unsigned char *buf, int size)
 {
-    int fd = (intptr_t) h->priv_data;
+    int fd = (size_t)h->priv_data;
     int rv;
 	do
 	{
@@ -113,20 +113,20 @@
 
 static int file_write(URLContext *h, unsigned char *buf, int size)
 {
-    int fd = (intptr_t) h->priv_data;
+    int fd = (size_t)h->priv_data;
     return write(fd, buf, size);
 }
 
 /* XXX: use llseek */
 static int64_t file_seek(URLContext *h, int64_t pos, int whence)
 {
-    int fd = (intptr_t) h->priv_data;
+    int fd = (size_t)h->priv_data;
     return lseek(fd, pos, whence);
 }
 
 static int file_close(URLContext *h)
 {
-    int fd = (intptr_t) h->priv_data;
+    int fd = (size_t)h->priv_data;
     return close(fd);
 }
 
@@ -164,7 +164,7 @@
 #if HAVE_SETMODE
     setmode(fd, O_BINARY);
 #endif
-    h->priv_data = (void *) (intptr_t) fd;
+    h->priv_data = (void *)(size_t)fd;
     h->is_streamed = 1;
     return 0;
 }
diff --git a/libavformat/http.c b/libavformat/http.c
index d904e7a..8f3f4ef 100755
--- a/libavformat/http.c
+++ b/libavformat/http.c
@@ -212,7 +212,7 @@
     int post, err, ch;
     char line[1024], *q;
     char *auth_b64;
-    int auth_b64_len = (strlen(auth) + 2) / 3 * 4 + 1;
+    int auth_b64_len = strlen(auth)* 4 / 3 + 12;
     int64_t off = s->off;
 
 
diff --git a/libavformat/idroq.c b/libavformat/idroq.c
index c570eec..7cf3808 100755
--- a/libavformat/idroq.c
+++ b/libavformat/idroq.c
@@ -46,6 +46,8 @@
     int width;
     int height;
     int audio_channels;
+    int framerate;
+    int frame_pts_inc;
 
     int video_stream_index;
     int audio_stream_index;
@@ -69,29 +71,102 @@
 {
     RoqDemuxContext *roq = s->priv_data;
     ByteIOContext *pb = s->pb;
-    int framerate;
     AVStream *st;
     unsigned char preamble[RoQ_CHUNK_PREAMBLE_SIZE];
+    int i;
+    unsigned int chunk_size;
+    unsigned int chunk_type;
 
     /* get the main header */
     if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
         RoQ_CHUNK_PREAMBLE_SIZE)
         return AVERROR(EIO);
-    framerate = AV_RL16(&preamble[6]);
+    roq->framerate = AV_RL16(&preamble[6]);
+    roq->frame_pts_inc = 90000 / roq->framerate;
 
     /* init private context parameters */
     roq->width = roq->height = roq->audio_channels = roq->video_pts =
     roq->audio_frame_count = 0;
-    roq->audio_stream_index = -1;
 
+    /* scan the first n chunks searching for A/V parameters */
+    for (i = 0; i < RoQ_CHUNKS_TO_SCAN; i++) {
+        if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
+            RoQ_CHUNK_PREAMBLE_SIZE)
+            return AVERROR(EIO);
+
+        chunk_type = AV_RL16(&preamble[0]);
+        chunk_size = AV_RL32(&preamble[2]);
+
+        switch (chunk_type) {
+
+        case RoQ_INFO:
+            /* fetch the width and height; reuse the preamble bytes */
+            if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) !=
+                RoQ_CHUNK_PREAMBLE_SIZE)
+                return AVERROR(EIO);
+            roq->width = AV_RL16(&preamble[0]);
+            roq->height = AV_RL16(&preamble[2]);
+            break;
+
+        case RoQ_QUAD_CODEBOOK:
+        case RoQ_QUAD_VQ:
+            /* ignore during this scan */
+            url_fseek(pb, chunk_size, SEEK_CUR);
+            break;
+
+        case RoQ_SOUND_MONO:
+            roq->audio_channels = 1;
+            url_fseek(pb, chunk_size, SEEK_CUR);
+            break;
+
+        case RoQ_SOUND_STEREO:
+            roq->audio_channels = 2;
+            url_fseek(pb, chunk_size, SEEK_CUR);
+            break;
+
+        default:
+            av_log(s, AV_LOG_ERROR, " unknown RoQ chunk type (%04X)\n", AV_RL16(&preamble[0]));
+            return AVERROR_INVALIDDATA;
+            break;
+        }
+
+        /* if all necessary parameters have been gathered, exit early */
+        if ((roq->width && roq->height) && roq->audio_channels)
+            break;
+    }
+
+    /* seek back to the first chunk */
+    url_fseek(pb, RoQ_CHUNK_PREAMBLE_SIZE, SEEK_SET);
+
+    /* initialize the decoders */
     st = av_new_stream(s, 0);
     if (!st)
         return AVERROR(ENOMEM);
-    av_set_pts_info(st, 63, 1, framerate);
+    /* set the pts reference (1 pts = 1/90000) */
+    av_set_pts_info(st, 33, 1, 90000);
     roq->video_stream_index = st->index;
     st->codec->codec_type = CODEC_TYPE_VIDEO;
     st->codec->codec_id = CODEC_ID_ROQ;
     st->codec->codec_tag = 0;  /* no fourcc */
+    st->codec->width = roq->width;
+    st->codec->height = roq->height;
+
+    if (roq->audio_channels) {
+        st = av_new_stream(s, 0);
+        if (!st)
+            return AVERROR(ENOMEM);
+        av_set_pts_info(st, 33, 1, 90000);
+        roq->audio_stream_index = st->index;
+        st->codec->codec_type = CODEC_TYPE_AUDIO;
+        st->codec->codec_id = CODEC_ID_ROQ_DPCM;
+        st->codec->codec_tag = 0;  /* no tag */
+        st->codec->channels = roq->audio_channels;
+        st->codec->sample_rate = RoQ_AUDIO_SAMPLE_RATE;
+        st->codec->bits_per_coded_sample = 16;
+        st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
+            st->codec->bits_per_coded_sample;
+        st->codec->block_align = st->codec->channels * st->codec->bits_per_coded_sample;
+    }
 
     return 0;
 }
@@ -127,14 +202,6 @@
         switch (chunk_type) {
 
         case RoQ_INFO:
-            if (!roq->width || !roq->height) {
-                AVStream *st = s->streams[roq->video_stream_index];
-                if (get_buffer(pb, preamble, RoQ_CHUNK_PREAMBLE_SIZE) != RoQ_CHUNK_PREAMBLE_SIZE)
-                    return AVERROR(EIO);
-                st->codec->width  = roq->width  = AV_RL16(preamble);
-                st->codec->height = roq->height = AV_RL16(preamble + 2);
-                break;
-            }
             /* don't care about this chunk anymore */
             url_fseek(pb, RoQ_CHUNK_PREAMBLE_SIZE, SEEK_CUR);
             break;
@@ -158,29 +225,14 @@
             if (ret != chunk_size)
                 return AVERROR(EIO);
             pkt->stream_index = roq->video_stream_index;
-            pkt->pts = roq->video_pts++;
+            pkt->pts = roq->video_pts;
 
+            roq->video_pts += roq->frame_pts_inc;
             packet_read = 1;
             break;
 
         case RoQ_SOUND_MONO:
         case RoQ_SOUND_STEREO:
-            if (roq->audio_stream_index == -1) {
-                AVStream *st = av_new_stream(s, 1);
-                if (!st)
-                    return AVERROR(ENOMEM);
-                av_set_pts_info(st, 32, 1, RoQ_AUDIO_SAMPLE_RATE);
-                roq->audio_stream_index = st->index;
-                st->codec->codec_type = CODEC_TYPE_AUDIO;
-                st->codec->codec_id = CODEC_ID_ROQ_DPCM;
-                st->codec->codec_tag = 0;  /* no tag */
-                st->codec->channels = roq->audio_channels = chunk_type == RoQ_SOUND_STEREO ? 2 : 1;
-                st->codec->sample_rate = RoQ_AUDIO_SAMPLE_RATE;
-                st->codec->bits_per_coded_sample = 16;
-                st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *
-                    st->codec->bits_per_coded_sample;
-                st->codec->block_align = st->codec->channels * st->codec->bits_per_coded_sample;
-            }
         case RoQ_QUAD_VQ:
             /* load up the packet */
             if (av_new_packet(pkt, chunk_size + RoQ_CHUNK_PREAMBLE_SIZE))
@@ -190,10 +242,13 @@
 
             if (chunk_type == RoQ_QUAD_VQ) {
                 pkt->stream_index = roq->video_stream_index;
-                pkt->pts = roq->video_pts++;
+                pkt->pts = roq->video_pts;
+                roq->video_pts += roq->frame_pts_inc;
             } else {
                 pkt->stream_index = roq->audio_stream_index;
                 pkt->pts = roq->audio_frame_count;
+                pkt->pts *= 90000;
+                pkt->pts /= RoQ_AUDIO_SAMPLE_RATE;
                 roq->audio_frame_count += (chunk_size / roq->audio_channels);
             }
 
diff --git a/libavformat/matroskadec.c b/libavformat/matroskadec.c
index 0d6260d..e026dc2 100755
--- a/libavformat/matroskadec.c
+++ b/libavformat/matroskadec.c
@@ -941,6 +941,7 @@
     uint8_t* data = *buf;
     int isize = *buf_size;
     uint8_t* pkt_data = NULL;
+    uint8_t* newpktdata;
     int pkt_size = isize;
     int result = 0;
     int olen;
@@ -967,7 +968,12 @@
         zstream.avail_in = isize;
         do {
             pkt_size *= 3;
-            pkt_data = av_realloc(pkt_data, pkt_size);
+            newpktdata = av_realloc(pkt_data, pkt_size);
+            if (!newpktdata) {
+                inflateEnd(&zstream);
+                goto failed;
+            }
+            pkt_data = newpktdata;
             zstream.avail_out = pkt_size - zstream.total_out;
             zstream.next_out = pkt_data + zstream.total_out;
             result = inflate(&zstream, Z_NO_FLUSH);
@@ -988,7 +994,12 @@
         bzstream.avail_in = isize;
         do {
             pkt_size *= 3;
-            pkt_data = av_realloc(pkt_data, pkt_size);
+            newpktdata = av_realloc(pkt_data, pkt_size);
+            if (!newpktdata) {
+                BZ2_bzDecompressEnd(&bzstream);
+                goto failed;
+            }
+            pkt_data = newpktdata;
             bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
             bzstream.next_out = pkt_data + bzstream.total_out_lo32;
             result = BZ2_bzDecompress(&bzstream);
@@ -1043,13 +1054,17 @@
     }
 }
 
-static void matroska_merge_packets(AVPacket *out, AVPacket *in)
+static int matroska_merge_packets(AVPacket *out, AVPacket *in)
 {
-    out->data = av_realloc(out->data, out->size+in->size);
+    void *newdata = av_realloc(out->data, out->size+in->size);
+    if (!newdata)
+        return AVERROR(ENOMEM);
+    out->data = newdata;
     memcpy(out->data+out->size, in->data, in->size);
     out->size += in->size;
     av_destruct_packet(in);
     av_free(in);
+    return 0;
 }
 
 static void matroska_convert_tag(AVFormatContext *s, EbmlList *list,
@@ -1112,13 +1127,13 @@
 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
 {
     EbmlList *seekhead_list = &matroska->seekhead;
-    MatroskaSeekhead *seekhead = seekhead_list->elem;
     uint32_t level_up = matroska->level_up;
     int64_t before_pos = url_ftell(matroska->ctx->pb);
     MatroskaLevel level;
     int i;
 
     for (i=0; i<seekhead_list->nb_elem; i++) {
+        MatroskaSeekhead *seekhead = seekhead_list->elem;
         int64_t offset = seekhead[i].pos + matroska->segment_start;
 
         if (seekhead[i].pos <= before_pos
@@ -1567,11 +1582,13 @@
         av_memcpy(pkt, matroska->packets[0], sizeof(AVPacket));
         av_free(matroska->packets[0]);
         if (matroska->num_packets > 1) {
+            void *newpackets;
             memmove(&matroska->packets[0], &matroska->packets[1],
                     (matroska->num_packets - 1) * sizeof(AVPacket *));
-            matroska->packets =
-                av_realloc(matroska->packets, (matroska->num_packets - 1) *
-                           sizeof(AVPacket *));
+            newpackets = av_realloc(matroska->packets,
+                            (matroska->num_packets - 1) * sizeof(AVPacket *));
+            if (newpackets)
+                matroska->packets = newpackets;
         } else {
             av_freep(&matroska->packets);
         }
@@ -1739,7 +1756,7 @@
                         lace_size[n] = lace_size[n - 1] + snum;
                         total += lace_size[n];
                     }
-                    lace_size[n] = size - total;
+                    lace_size[laces - 1] = size - total;
                     break;
                 }
             }
diff --git a/libavformat/mov.c b/libavformat/mov.c
index 89b4e9c..c8ffbd6 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -85,7 +85,7 @@
 {
     char buf[16];
 	int data1, data2;
-	
+
     get_be16(pb); // unknown
 	data1 = get_be16(pb); // Track
 	data2 = get_be16(pb); // TotalTracks
@@ -251,10 +251,15 @@
 
 static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    MOVStreamContext *sc = st->priv_data;
+    AVStream *st;
+    MOVStreamContext *sc;
     int entries, i, j;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
     get_be32(pb); // version + flags
     entries = get_be32(pb);
     if (entries >= UINT_MAX / sizeof(*sc->drefs))
@@ -396,9 +401,13 @@
 
 static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
+    AVStream *st;
     int tag, len;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+
     get_be32(pb); /* version + flags */
     len = mp4_read_descr(c, pb, &tag);
     if (tag == MP4ESDescrTag) {
@@ -455,7 +464,12 @@
 {
     const int num = get_be32(pb);
     const int den = get_be32(pb);
-    AVStream * const st = c->fc->streams[c->fc->nb_streams-1];
+    AVStream *st;
+
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+
     if (den != 0) {
         if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
             (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
@@ -509,12 +523,18 @@
 
 static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    MOVStreamContext *sc = st->priv_data;
-    int version = get_byte(pb);
+    AVStream *st;
+    MOVStreamContext *sc;
+    int version;
     char language[4] = {0};
     unsigned lang;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
+    version = get_byte(pb);
     if (version > 1)
         return -1; /* unsupported */
 
@@ -576,7 +596,11 @@
 
 static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
+    AVStream *st;
+
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
 
     if((uint64_t)atom.size > (1<<30))
         return -1;
@@ -596,9 +620,14 @@
 
 static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    int little_endian = get_be16(pb);
+    AVStream *st;
+    int little_endian;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+
+    little_endian = get_be16(pb);
     dprintf(c->fc, "enda %d\n", little_endian);
     if (little_endian == 1) {
         switch (st->codec->codec_id) {
@@ -648,7 +677,11 @@
 
 static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
+    AVStream *st;
+
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
 
     if((uint64_t)atom.size > (1<<30))
         return -1;
@@ -675,7 +708,11 @@
  */
 static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
+    AVStream *st;
+
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
 
     if((uint64_t)atom.size > (1<<30))
         return -1;
@@ -691,10 +728,15 @@
 
 static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    MOVStreamContext *sc = st->priv_data;
+    AVStream *st;
+    MOVStreamContext *sc;
     unsigned int i, entries;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
 
@@ -757,10 +799,15 @@
 
 static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    MOVStreamContext *sc = st->priv_data;
+    AVStream *st;
+    MOVStreamContext *sc;
     int j, entries, pseudo_stream_id;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
 
@@ -888,9 +935,9 @@
                         color_table = ff_qt_default_palette_256;
 
                     for (j = 0; j < color_count; j++) {
-                        r = color_table[j * 3 + 0];
-                        g = color_table[j * 3 + 1];
-                        b = color_table[j * 3 + 2];
+                        r = color_table[j * 4 + 0];
+                        g = color_table[j * 4 + 1];
+                        b = color_table[j * 4 + 2];
                         st->codec->palctrl->palette[j] =
                             (r << 16) | (g << 8) | (b);
                     }
@@ -919,7 +966,8 @@
                     }
                 }
                 st->codec->palctrl->palette_changed = 1;
-            }
+            } else
+                st->codec->palctrl = NULL;
         } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
             int bits_per_sample, flags;
             uint16_t version = get_be16(pb);
@@ -1078,10 +1126,15 @@
 
 static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    MOVStreamContext *sc = st->priv_data;
+    AVStream *st;
+    MOVStreamContext *sc;
     unsigned int i, entries;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
 
@@ -1106,10 +1159,15 @@
 
 static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    MOVStreamContext *sc = st->priv_data;
+    AVStream *st;
+    MOVStreamContext *sc;
     unsigned int i, entries;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
 
@@ -1133,12 +1191,17 @@
 
 static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    MOVStreamContext *sc = st->priv_data;
+    AVStream *st;
+    MOVStreamContext *sc;
     unsigned int i, entries, sample_size, field_size, num_bytes;
     GetBitContext gb;
     unsigned char* buf;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
 
@@ -1196,12 +1259,17 @@
 
 static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    MOVStreamContext *sc = st->priv_data;
+    AVStream *st;
+    MOVStreamContext *sc;
     unsigned int i, entries;
     int64_t duration=0;
     int64_t total_sample_count=0;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
     entries = get_be32(pb);
@@ -1240,10 +1308,15 @@
 
 static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    MOVStreamContext *sc = st->priv_data;
+    AVStream *st;
+    MOVStreamContext *sc;
     unsigned int i, entries;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
     entries = get_be32(pb);
@@ -1421,12 +1494,10 @@
                st->index);
         return 0;
     }
-
     if (!sc->time_rate)
         sc->time_rate = 1;
     if (!sc->time_scale)
         sc->time_scale = c->time_scale;
-
     av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
 
     if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
@@ -1548,10 +1619,16 @@
     int height;
     int64_t disp_transform[2];
     int display_matrix[3][2];
-    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
-    MOVStreamContext *sc = st->priv_data;
-    int version = get_byte(pb);
+    AVStream *st;
+    MOVStreamContext *sc;
+    int version;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    st = c->fc->streams[c->fc->nb_streams-1];
+    sc = st->priv_data;
+
+    version = get_byte(pb);
     get_be24(pb); /* flags */
     /*
     MOV_TRACK_ENABLED 0x0001
@@ -1625,7 +1702,7 @@
     flags = get_be24(pb);
 
     track_id = get_be32(pb);
-    if (!track_id)
+    if (!track_id || track_id > c->fc->nb_streams)
         return -1;
     frag->track_id = track_id;
     for (i = 0; i < c->trex_count; i++)
@@ -1826,9 +1903,13 @@
 /* edit list atom */
 static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
 {
-    MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
+    MOVStreamContext *sc;
     int i, edit_count;
 
+    if (c->fc->nb_streams < 1)
+        return 0;
+    sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
+
     get_byte(pb); /* version */
     get_be24(pb); /* flags */
     edit_count = get_be32(pb); /* entries */
diff --git a/libavformat/nsvdec.c b/libavformat/nsvdec.c
index 719337c..25b3d6c 100755
--- a/libavformat/nsvdec.c
+++ b/libavformat/nsvdec.c
@@ -317,7 +317,9 @@
         char *token, *value;
         char quote;
 
-        p = strings = av_mallocz(strings_size + 1);
+        p = strings = av_mallocz((size_t)strings_size + 1);
+        if (!p)
+            return AVERROR(ENOMEM);
         endp = strings + strings_size;
         get_buffer(pb, strings, strings_size);
         while (p < endp) {
@@ -351,6 +353,8 @@
         if((unsigned)table_entries >= UINT_MAX / sizeof(uint32_t))
             return -1;
         nsv->nsvf_index_data = av_malloc(table_entries * sizeof(uint32_t));
+        if (!nsv->nsvf_index_data)
+            return AVERROR(ENOMEM);
 #warning "FIXME: Byteswap buffer as needed"
         get_buffer(pb, (unsigned char *)nsv->nsvf_index_data, table_entries * sizeof(uint32_t));
     }
@@ -507,11 +511,16 @@
     for (i = 0; i < NSV_MAX_RESYNC_TRIES; i++) {
         if (nsv_resync(s) < 0)
             return -1;
-        if (nsv->state == NSV_FOUND_NSVF)
+        if (nsv->state == NSV_FOUND_NSVF) {
             err = nsv_parse_NSVf_header(s, ap);
+            if (err < 0)
+                return err;
+        }
             /* we need the first NSVs also... */
         if (nsv->state == NSV_FOUND_NSVS) {
             err = nsv_parse_NSVs_header(s, ap);
+            if (err < 0)
+                return err;
             break; /* we just want the first one */
         }
     }
@@ -586,12 +595,12 @@
     }
 
     /* map back streams to v,a */
-    if (s->streams[0])
+    if (s->nb_streams > 0)
         st[s->streams[0]->id] = s->streams[0];
-    if (s->streams[1])
+    if (s->nb_streams > 1)
         st[s->streams[1]->id] = s->streams[1];
 
-    if (vsize/* && st[NSV_ST_VIDEO]*/) {
+    if (vsize && st[NSV_ST_VIDEO]) {
         nst = st[NSV_ST_VIDEO]->priv_data;
         pkt = &nsv->ahead[NSV_ST_VIDEO];
         av_get_packet(pb, pkt, vsize);
@@ -606,7 +615,7 @@
     if(st[NSV_ST_VIDEO])
         ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;
 
-    if (asize/*st[NSV_ST_AUDIO]*/) {
+    if (asize && st[NSV_ST_AUDIO]) {
         nst = st[NSV_ST_AUDIO]->priv_data;
         pkt = &nsv->ahead[NSV_ST_AUDIO];
         /* read raw audio specific header on the first audio chunk... */
diff --git a/libavformat/nuv.c b/libavformat/nuv.c
index 9c139e8..fed0d69 100755
--- a/libavformat/nuv.c
+++ b/libavformat/nuv.c
@@ -197,7 +197,6 @@
     int ret, size;
     while (!url_feof(pb)) {
         int copyhdrsize = ctx->rtjpg_video ? HDRSIZE : 0;
-        uint64_t pos = url_ftell(pb);
         ret = get_buffer(pb, hdr, HDRSIZE);
         if (ret <= 0)
             return ret ? ret : -1;
@@ -218,10 +217,7 @@
                 ret = av_new_packet(pkt, copyhdrsize + size);
                 if (ret < 0)
                     return ret;
-                // HACK: we have no idea if it is a keyframe,
-                // but if we mark none seeking will not work at all.
-                pkt->flags |= PKT_FLAG_KEY;
-                pkt->pos = pos;
+                pkt->pos = url_ftell(pb) - copyhdrsize;
                 pkt->pts = AV_RL32(&hdr[4]);
                 pkt->stream_index = ctx->v_id;
                 memcpy(pkt->data, hdr, copyhdrsize);
@@ -234,8 +230,6 @@
                     break;
                 }
                 ret = av_get_packet(pb, pkt, size);
-                pkt->flags |= PKT_FLAG_KEY;
-                pkt->pos = pos;
                 pkt->pts = AV_RL32(&hdr[4]);
                 pkt->stream_index = ctx->a_id;
                 return ret;
@@ -259,5 +253,4 @@
     nuv_packet,
     NULL,
     NULL,
-    .flags = AVFMT_GENERIC_INDEX,
 };
diff --git a/libavformat/oggdec.c b/libavformat/oggdec.c
index 9565bf9..24a0c46 100755
--- a/libavformat/oggdec.c
+++ b/libavformat/oggdec.c
@@ -90,14 +90,24 @@
     ogg->state = ost->next;
 
     if (!discard){
+        struct ogg_stream *old_streams = ogg->streams;
+
         for (i = 0; i < ogg->nstreams; i++)
             av_free (ogg->streams[i].buf);
 
         url_fseek (bc, ost->pos, SEEK_SET);
         ogg->curidx = ost->curidx;
         ogg->nstreams = ost->nstreams;
+        ogg->streams = av_realloc (ogg->streams,
+                                   ogg->nstreams * sizeof (*ogg->streams));
+
+        if (ogg->streams) {
         memcpy(ogg->streams, ost->streams,
                ost->nstreams * sizeof(*ogg->streams));
+        } else {
+            av_free(old_streams);
+            ogg->nstreams = 0;
+        }
     }
 
     av_free (ost);
diff --git a/libavformat/oggparsevorbis.c b/libavformat/oggparsevorbis.c
index 6549161..7a4f562 100755
--- a/libavformat/oggparsevorbis.c
+++ b/libavformat/oggparsevorbis.c
@@ -35,27 +35,28 @@
 {
     const uint8_t *p = buf;
     const uint8_t *end = buf + size;
-    unsigned s, n, j;
+    unsigned n, j;
+    int s;
 
     if (size < 8) /* must have vendor_length and user_comment_list_length */
         return -1;
 
     s = bytestream_get_le32(&p);
 
-    if (end - p < s)
+    if (end - p - 4 < s || s < 0)
         return -1;
 
     p += s;
 
     n = bytestream_get_le32(&p);
 
-    while (p < end && n > 0) {
+    while (end - p >= 4 && n > 0) {
         const char *t, *v;
         int tl, vl;
 
         s = bytestream_get_le32(&p);
 
-        if (end - p < s)
+        if (end - p < s || s < 0)
             break;
 
         t = p;
diff --git a/libavformat/qtpalette.h b/libavformat/qtpalette.h
index 7d6802f..52c1907 100755
--- a/libavformat/qtpalette.h
+++ b/libavformat/qtpalette.h
@@ -25,289 +25,289 @@
 
 #include <inttypes.h>
 
-static const uint8_t ff_qt_default_palette_4[4 * 3] = {
-  0x93, 0x65, 0x5E,
-  0xFF, 0xFF, 0xFF,
-  0xDF, 0xD0, 0xAB,
-  0x00, 0x00, 0x00
+static const uint8_t ff_qt_default_palette_4[4 * 4] = {
+  0x93, 0x65, 0x5E, 0x00,
+  0xFF, 0xFF, 0xFF, 0x00,
+  0xDF, 0xD0, 0xAB, 0x00,
+  0x00, 0x00, 0x00, 0x00
 };
 
-static const uint8_t ff_qt_default_palette_16[16 * 3] = {
-  0xFF, 0xFB, 0xFF,
-  0xEF, 0xD9, 0xBB,
-  0xE8, 0xC9, 0xB1,
-  0x93, 0x65, 0x5E,
-  0xFC, 0xDE, 0xE8,
-  0x9D, 0x88, 0x91,
-  0xFF, 0xFF, 0xFF,
-  0xFF, 0xFF, 0xFF,
-  0xFF, 0xFF, 0xFF,
-  0x47, 0x48, 0x37,
-  0x7A, 0x5E, 0x55,
-  0xDF, 0xD0, 0xAB,
-  0xFF, 0xFB, 0xF9,
-  0xE8, 0xCA, 0xC5,
-  0x8A, 0x7C, 0x77,
-  0x00, 0x00, 0x00
+static const uint8_t ff_qt_default_palette_16[16 * 4] = {
+  0xFF, 0xFB, 0xFF, 0x00,
+  0xEF, 0xD9, 0xBB, 0x00,
+  0xE8, 0xC9, 0xB1, 0x00,
+  0x93, 0x65, 0x5E, 0x00,
+  0xFC, 0xDE, 0xE8, 0x00,
+  0x9D, 0x88, 0x91, 0x00,
+  0xFF, 0xFF, 0xFF, 0x00,
+  0xFF, 0xFF, 0xFF, 0x00,
+  0xFF, 0xFF, 0xFF, 0x00,
+  0x47, 0x48, 0x37, 0x00,
+  0x7A, 0x5E, 0x55, 0x00,
+  0xDF, 0xD0, 0xAB, 0x00,
+  0xFF, 0xFB, 0xF9, 0x00,
+  0xE8, 0xCA, 0xC5, 0x00,
+  0x8A, 0x7C, 0x77, 0x00,
+  0x00, 0x00, 0x00, 0x00
 };
 
-static const uint8_t ff_qt_default_palette_256[256 * 3] = {
-  /*   0, 0x00 */  0xFF, 0xFF, 0xFF,
-  /*   1, 0x01 */  0xFF, 0xFF, 0xCC,
-  /*   2, 0x02 */  0xFF, 0xFF, 0x99,
-  /*   3, 0x03 */  0xFF, 0xFF, 0x66,
-  /*   4, 0x04 */  0xFF, 0xFF, 0x33,
-  /*   5, 0x05 */  0xFF, 0xFF, 0x00,
-  /*   6, 0x06 */  0xFF, 0xCC, 0xFF,
-  /*   7, 0x07 */  0xFF, 0xCC, 0xCC,
-  /*   8, 0x08 */  0xFF, 0xCC, 0x99,
-  /*   9, 0x09 */  0xFF, 0xCC, 0x66,
-  /*  10, 0x0A */  0xFF, 0xCC, 0x33,
-  /*  11, 0x0B */  0xFF, 0xCC, 0x00,
-  /*  12, 0x0C */  0xFF, 0x99, 0xFF,
-  /*  13, 0x0D */  0xFF, 0x99, 0xCC,
-  /*  14, 0x0E */  0xFF, 0x99, 0x99,
-  /*  15, 0x0F */  0xFF, 0x99, 0x66,
-  /*  16, 0x10 */  0xFF, 0x99, 0x33,
-  /*  17, 0x11 */  0xFF, 0x99, 0x00,
-  /*  18, 0x12 */  0xFF, 0x66, 0xFF,
-  /*  19, 0x13 */  0xFF, 0x66, 0xCC,
-  /*  20, 0x14 */  0xFF, 0x66, 0x99,
-  /*  21, 0x15 */  0xFF, 0x66, 0x66,
-  /*  22, 0x16 */  0xFF, 0x66, 0x33,
-  /*  23, 0x17 */  0xFF, 0x66, 0x00,
-  /*  24, 0x18 */  0xFF, 0x33, 0xFF,
-  /*  25, 0x19 */  0xFF, 0x33, 0xCC,
-  /*  26, 0x1A */  0xFF, 0x33, 0x99,
-  /*  27, 0x1B */  0xFF, 0x33, 0x66,
-  /*  28, 0x1C */  0xFF, 0x33, 0x33,
-  /*  29, 0x1D */  0xFF, 0x33, 0x00,
-  /*  30, 0x1E */  0xFF, 0x00, 0xFF,
-  /*  31, 0x1F */  0xFF, 0x00, 0xCC,
-  /*  32, 0x20 */  0xFF, 0x00, 0x99,
-  /*  33, 0x21 */  0xFF, 0x00, 0x66,
-  /*  34, 0x22 */  0xFF, 0x00, 0x33,
-  /*  35, 0x23 */  0xFF, 0x00, 0x00,
-  /*  36, 0x24 */  0xCC, 0xFF, 0xFF,
-  /*  37, 0x25 */  0xCC, 0xFF, 0xCC,
-  /*  38, 0x26 */  0xCC, 0xFF, 0x99,
-  /*  39, 0x27 */  0xCC, 0xFF, 0x66,
-  /*  40, 0x28 */  0xCC, 0xFF, 0x33,
-  /*  41, 0x29 */  0xCC, 0xFF, 0x00,
-  /*  42, 0x2A */  0xCC, 0xCC, 0xFF,
-  /*  43, 0x2B */  0xCC, 0xCC, 0xCC,
-  /*  44, 0x2C */  0xCC, 0xCC, 0x99,
-  /*  45, 0x2D */  0xCC, 0xCC, 0x66,
-  /*  46, 0x2E */  0xCC, 0xCC, 0x33,
-  /*  47, 0x2F */  0xCC, 0xCC, 0x00,
-  /*  48, 0x30 */  0xCC, 0x99, 0xFF,
-  /*  49, 0x31 */  0xCC, 0x99, 0xCC,
-  /*  50, 0x32 */  0xCC, 0x99, 0x99,
-  /*  51, 0x33 */  0xCC, 0x99, 0x66,
-  /*  52, 0x34 */  0xCC, 0x99, 0x33,
-  /*  53, 0x35 */  0xCC, 0x99, 0x00,
-  /*  54, 0x36 */  0xCC, 0x66, 0xFF,
-  /*  55, 0x37 */  0xCC, 0x66, 0xCC,
-  /*  56, 0x38 */  0xCC, 0x66, 0x99,
-  /*  57, 0x39 */  0xCC, 0x66, 0x66,
-  /*  58, 0x3A */  0xCC, 0x66, 0x33,
-  /*  59, 0x3B */  0xCC, 0x66, 0x00,
-  /*  60, 0x3C */  0xCC, 0x33, 0xFF,
-  /*  61, 0x3D */  0xCC, 0x33, 0xCC,
-  /*  62, 0x3E */  0xCC, 0x33, 0x99,
-  /*  63, 0x3F */  0xCC, 0x33, 0x66,
-  /*  64, 0x40 */  0xCC, 0x33, 0x33,
-  /*  65, 0x41 */  0xCC, 0x33, 0x00,
-  /*  66, 0x42 */  0xCC, 0x00, 0xFF,
-  /*  67, 0x43 */  0xCC, 0x00, 0xCC,
-  /*  68, 0x44 */  0xCC, 0x00, 0x99,
-  /*  69, 0x45 */  0xCC, 0x00, 0x66,
-  /*  70, 0x46 */  0xCC, 0x00, 0x33,
-  /*  71, 0x47 */  0xCC, 0x00, 0x00,
-  /*  72, 0x48 */  0x99, 0xFF, 0xFF,
-  /*  73, 0x49 */  0x99, 0xFF, 0xCC,
-  /*  74, 0x4A */  0x99, 0xFF, 0x99,
-  /*  75, 0x4B */  0x99, 0xFF, 0x66,
-  /*  76, 0x4C */  0x99, 0xFF, 0x33,
-  /*  77, 0x4D */  0x99, 0xFF, 0x00,
-  /*  78, 0x4E */  0x99, 0xCC, 0xFF,
-  /*  79, 0x4F */  0x99, 0xCC, 0xCC,
-  /*  80, 0x50 */  0x99, 0xCC, 0x99,
-  /*  81, 0x51 */  0x99, 0xCC, 0x66,
-  /*  82, 0x52 */  0x99, 0xCC, 0x33,
-  /*  83, 0x53 */  0x99, 0xCC, 0x00,
-  /*  84, 0x54 */  0x99, 0x99, 0xFF,
-  /*  85, 0x55 */  0x99, 0x99, 0xCC,
-  /*  86, 0x56 */  0x99, 0x99, 0x99,
-  /*  87, 0x57 */  0x99, 0x99, 0x66,
-  /*  88, 0x58 */  0x99, 0x99, 0x33,
-  /*  89, 0x59 */  0x99, 0x99, 0x00,
-  /*  90, 0x5A */  0x99, 0x66, 0xFF,
-  /*  91, 0x5B */  0x99, 0x66, 0xCC,
-  /*  92, 0x5C */  0x99, 0x66, 0x99,
-  /*  93, 0x5D */  0x99, 0x66, 0x66,
-  /*  94, 0x5E */  0x99, 0x66, 0x33,
-  /*  95, 0x5F */  0x99, 0x66, 0x00,
-  /*  96, 0x60 */  0x99, 0x33, 0xFF,
-  /*  97, 0x61 */  0x99, 0x33, 0xCC,
-  /*  98, 0x62 */  0x99, 0x33, 0x99,
-  /*  99, 0x63 */  0x99, 0x33, 0x66,
-  /* 100, 0x64 */  0x99, 0x33, 0x33,
-  /* 101, 0x65 */  0x99, 0x33, 0x00,
-  /* 102, 0x66 */  0x99, 0x00, 0xFF,
-  /* 103, 0x67 */  0x99, 0x00, 0xCC,
-  /* 104, 0x68 */  0x99, 0x00, 0x99,
-  /* 105, 0x69 */  0x99, 0x00, 0x66,
-  /* 106, 0x6A */  0x99, 0x00, 0x33,
-  /* 107, 0x6B */  0x99, 0x00, 0x00,
-  /* 108, 0x6C */  0x66, 0xFF, 0xFF,
-  /* 109, 0x6D */  0x66, 0xFF, 0xCC,
-  /* 110, 0x6E */  0x66, 0xFF, 0x99,
-  /* 111, 0x6F */  0x66, 0xFF, 0x66,
-  /* 112, 0x70 */  0x66, 0xFF, 0x33,
-  /* 113, 0x71 */  0x66, 0xFF, 0x00,
-  /* 114, 0x72 */  0x66, 0xCC, 0xFF,
-  /* 115, 0x73 */  0x66, 0xCC, 0xCC,
-  /* 116, 0x74 */  0x66, 0xCC, 0x99,
-  /* 117, 0x75 */  0x66, 0xCC, 0x66,
-  /* 118, 0x76 */  0x66, 0xCC, 0x33,
-  /* 119, 0x77 */  0x66, 0xCC, 0x00,
-  /* 120, 0x78 */  0x66, 0x99, 0xFF,
-  /* 121, 0x79 */  0x66, 0x99, 0xCC,
-  /* 122, 0x7A */  0x66, 0x99, 0x99,
-  /* 123, 0x7B */  0x66, 0x99, 0x66,
-  /* 124, 0x7C */  0x66, 0x99, 0x33,
-  /* 125, 0x7D */  0x66, 0x99, 0x00,
-  /* 126, 0x7E */  0x66, 0x66, 0xFF,
-  /* 127, 0x7F */  0x66, 0x66, 0xCC,
-  /* 128, 0x80 */  0x66, 0x66, 0x99,
-  /* 129, 0x81 */  0x66, 0x66, 0x66,
-  /* 130, 0x82 */  0x66, 0x66, 0x33,
-  /* 131, 0x83 */  0x66, 0x66, 0x00,
-  /* 132, 0x84 */  0x66, 0x33, 0xFF,
-  /* 133, 0x85 */  0x66, 0x33, 0xCC,
-  /* 134, 0x86 */  0x66, 0x33, 0x99,
-  /* 135, 0x87 */  0x66, 0x33, 0x66,
-  /* 136, 0x88 */  0x66, 0x33, 0x33,
-  /* 137, 0x89 */  0x66, 0x33, 0x00,
-  /* 138, 0x8A */  0x66, 0x00, 0xFF,
-  /* 139, 0x8B */  0x66, 0x00, 0xCC,
-  /* 140, 0x8C */  0x66, 0x00, 0x99,
-  /* 141, 0x8D */  0x66, 0x00, 0x66,
-  /* 142, 0x8E */  0x66, 0x00, 0x33,
-  /* 143, 0x8F */  0x66, 0x00, 0x00,
-  /* 144, 0x90 */  0x33, 0xFF, 0xFF,
-  /* 145, 0x91 */  0x33, 0xFF, 0xCC,
-  /* 146, 0x92 */  0x33, 0xFF, 0x99,
-  /* 147, 0x93 */  0x33, 0xFF, 0x66,
-  /* 148, 0x94 */  0x33, 0xFF, 0x33,
-  /* 149, 0x95 */  0x33, 0xFF, 0x00,
-  /* 150, 0x96 */  0x33, 0xCC, 0xFF,
-  /* 151, 0x97 */  0x33, 0xCC, 0xCC,
-  /* 152, 0x98 */  0x33, 0xCC, 0x99,
-  /* 153, 0x99 */  0x33, 0xCC, 0x66,
-  /* 154, 0x9A */  0x33, 0xCC, 0x33,
-  /* 155, 0x9B */  0x33, 0xCC, 0x00,
-  /* 156, 0x9C */  0x33, 0x99, 0xFF,
-  /* 157, 0x9D */  0x33, 0x99, 0xCC,
-  /* 158, 0x9E */  0x33, 0x99, 0x99,
-  /* 159, 0x9F */  0x33, 0x99, 0x66,
-  /* 160, 0xA0 */  0x33, 0x99, 0x33,
-  /* 161, 0xA1 */  0x33, 0x99, 0x00,
-  /* 162, 0xA2 */  0x33, 0x66, 0xFF,
-  /* 163, 0xA3 */  0x33, 0x66, 0xCC,
-  /* 164, 0xA4 */  0x33, 0x66, 0x99,
-  /* 165, 0xA5 */  0x33, 0x66, 0x66,
-  /* 166, 0xA6 */  0x33, 0x66, 0x33,
-  /* 167, 0xA7 */  0x33, 0x66, 0x00,
-  /* 168, 0xA8 */  0x33, 0x33, 0xFF,
-  /* 169, 0xA9 */  0x33, 0x33, 0xCC,
-  /* 170, 0xAA */  0x33, 0x33, 0x99,
-  /* 171, 0xAB */  0x33, 0x33, 0x66,
-  /* 172, 0xAC */  0x33, 0x33, 0x33,
-  /* 173, 0xAD */  0x33, 0x33, 0x00,
-  /* 174, 0xAE */  0x33, 0x00, 0xFF,
-  /* 175, 0xAF */  0x33, 0x00, 0xCC,
-  /* 176, 0xB0 */  0x33, 0x00, 0x99,
-  /* 177, 0xB1 */  0x33, 0x00, 0x66,
-  /* 178, 0xB2 */  0x33, 0x00, 0x33,
-  /* 179, 0xB3 */  0x33, 0x00, 0x00,
-  /* 180, 0xB4 */  0x00, 0xFF, 0xFF,
-  /* 181, 0xB5 */  0x00, 0xFF, 0xCC,
-  /* 182, 0xB6 */  0x00, 0xFF, 0x99,
-  /* 183, 0xB7 */  0x00, 0xFF, 0x66,
-  /* 184, 0xB8 */  0x00, 0xFF, 0x33,
-  /* 185, 0xB9 */  0x00, 0xFF, 0x00,
-  /* 186, 0xBA */  0x00, 0xCC, 0xFF,
-  /* 187, 0xBB */  0x00, 0xCC, 0xCC,
-  /* 188, 0xBC */  0x00, 0xCC, 0x99,
-  /* 189, 0xBD */  0x00, 0xCC, 0x66,
-  /* 190, 0xBE */  0x00, 0xCC, 0x33,
-  /* 191, 0xBF */  0x00, 0xCC, 0x00,
-  /* 192, 0xC0 */  0x00, 0x99, 0xFF,
-  /* 193, 0xC1 */  0x00, 0x99, 0xCC,
-  /* 194, 0xC2 */  0x00, 0x99, 0x99,
-  /* 195, 0xC3 */  0x00, 0x99, 0x66,
-  /* 196, 0xC4 */  0x00, 0x99, 0x33,
-  /* 197, 0xC5 */  0x00, 0x99, 0x00,
-  /* 198, 0xC6 */  0x00, 0x66, 0xFF,
-  /* 199, 0xC7 */  0x00, 0x66, 0xCC,
-  /* 200, 0xC8 */  0x00, 0x66, 0x99,
-  /* 201, 0xC9 */  0x00, 0x66, 0x66,
-  /* 202, 0xCA */  0x00, 0x66, 0x33,
-  /* 203, 0xCB */  0x00, 0x66, 0x00,
-  /* 204, 0xCC */  0x00, 0x33, 0xFF,
-  /* 205, 0xCD */  0x00, 0x33, 0xCC,
-  /* 206, 0xCE */  0x00, 0x33, 0x99,
-  /* 207, 0xCF */  0x00, 0x33, 0x66,
-  /* 208, 0xD0 */  0x00, 0x33, 0x33,
-  /* 209, 0xD1 */  0x00, 0x33, 0x00,
-  /* 210, 0xD2 */  0x00, 0x00, 0xFF,
-  /* 211, 0xD3 */  0x00, 0x00, 0xCC,
-  /* 212, 0xD4 */  0x00, 0x00, 0x99,
-  /* 213, 0xD5 */  0x00, 0x00, 0x66,
-  /* 214, 0xD6 */  0x00, 0x00, 0x33,
-  /* 215, 0xD7 */  0xEE, 0x00, 0x00,
-  /* 216, 0xD8 */  0xDD, 0x00, 0x00,
-  /* 217, 0xD9 */  0xBB, 0x00, 0x00,
-  /* 218, 0xDA */  0xAA, 0x00, 0x00,
-  /* 219, 0xDB */  0x88, 0x00, 0x00,
-  /* 220, 0xDC */  0x77, 0x00, 0x00,
-  /* 221, 0xDD */  0x55, 0x00, 0x00,
-  /* 222, 0xDE */  0x44, 0x00, 0x00,
-  /* 223, 0xDF */  0x22, 0x00, 0x00,
-  /* 224, 0xE0 */  0x11, 0x00, 0x00,
-  /* 225, 0xE1 */  0x00, 0xEE, 0x00,
-  /* 226, 0xE2 */  0x00, 0xDD, 0x00,
-  /* 227, 0xE3 */  0x00, 0xBB, 0x00,
-  /* 228, 0xE4 */  0x00, 0xAA, 0x00,
-  /* 229, 0xE5 */  0x00, 0x88, 0x00,
-  /* 230, 0xE6 */  0x00, 0x77, 0x00,
-  /* 231, 0xE7 */  0x00, 0x55, 0x00,
-  /* 232, 0xE8 */  0x00, 0x44, 0x00,
-  /* 233, 0xE9 */  0x00, 0x22, 0x00,
-  /* 234, 0xEA */  0x00, 0x11, 0x00,
-  /* 235, 0xEB */  0x00, 0x00, 0xEE,
-  /* 236, 0xEC */  0x00, 0x00, 0xDD,
-  /* 237, 0xED */  0x00, 0x00, 0xBB,
-  /* 238, 0xEE */  0x00, 0x00, 0xAA,
-  /* 239, 0xEF */  0x00, 0x00, 0x88,
-  /* 240, 0xF0 */  0x00, 0x00, 0x77,
-  /* 241, 0xF1 */  0x00, 0x00, 0x55,
-  /* 242, 0xF2 */  0x00, 0x00, 0x44,
-  /* 243, 0xF3 */  0x00, 0x00, 0x22,
-  /* 244, 0xF4 */  0x00, 0x00, 0x11,
-  /* 245, 0xF5 */  0xEE, 0xEE, 0xEE,
-  /* 246, 0xF6 */  0xDD, 0xDD, 0xDD,
-  /* 247, 0xF7 */  0xBB, 0xBB, 0xBB,
-  /* 248, 0xF8 */  0xAA, 0xAA, 0xAA,
-  /* 249, 0xF9 */  0x88, 0x88, 0x88,
-  /* 250, 0xFA */  0x77, 0x77, 0x77,
-  /* 251, 0xFB */  0x55, 0x55, 0x55,
-  /* 252, 0xFC */  0x44, 0x44, 0x44,
-  /* 253, 0xFD */  0x22, 0x22, 0x22,
-  /* 254, 0xFE */  0x11, 0x11, 0x11,
-  /* 255, 0xFF */  0x00, 0x00, 0x00
+static const uint8_t ff_qt_default_palette_256[256 * 4] = {
+  /*   0, 0x00 */  0xFF, 0xFF, 0xFF, 0x00,
+  /*   1, 0x01 */  0xFF, 0xFF, 0xCC, 0x00,
+  /*   2, 0x02 */  0xFF, 0xFF, 0x99, 0x00,
+  /*   3, 0x03 */  0xFF, 0xFF, 0x66, 0x00,
+  /*   4, 0x04 */  0xFF, 0xFF, 0x33, 0x00,
+  /*   5, 0x05 */  0xFF, 0xFF, 0x00, 0x00,
+  /*   6, 0x06 */  0xFF, 0xCC, 0xFF, 0x00,
+  /*   7, 0x07 */  0xFF, 0xCC, 0xCC, 0x00,
+  /*   8, 0x08 */  0xFF, 0xCC, 0x99, 0x00,
+  /*   9, 0x09 */  0xFF, 0xCC, 0x66, 0x00,
+  /*  10, 0x0A */  0xFF, 0xCC, 0x33, 0x00,
+  /*  11, 0x0B */  0xFF, 0xCC, 0x00, 0x00,
+  /*  12, 0x0C */  0xFF, 0x99, 0xFF, 0x00,
+  /*  13, 0x0D */  0xFF, 0x99, 0xCC, 0x00,
+  /*  14, 0x0E */  0xFF, 0x99, 0x99, 0x00,
+  /*  15, 0x0F */  0xFF, 0x99, 0x66, 0x00,
+  /*  16, 0x10 */  0xFF, 0x99, 0x33, 0x00,
+  /*  17, 0x11 */  0xFF, 0x99, 0x00, 0x00,
+  /*  18, 0x12 */  0xFF, 0x66, 0xFF, 0x00,
+  /*  19, 0x13 */  0xFF, 0x66, 0xCC, 0x00,
+  /*  20, 0x14 */  0xFF, 0x66, 0x99, 0x00,
+  /*  21, 0x15 */  0xFF, 0x66, 0x66, 0x00,
+  /*  22, 0x16 */  0xFF, 0x66, 0x33, 0x00,
+  /*  23, 0x17 */  0xFF, 0x66, 0x00, 0x00,
+  /*  24, 0x18 */  0xFF, 0x33, 0xFF, 0x00,
+  /*  25, 0x19 */  0xFF, 0x33, 0xCC, 0x00,
+  /*  26, 0x1A */  0xFF, 0x33, 0x99, 0x00,
+  /*  27, 0x1B */  0xFF, 0x33, 0x66, 0x00,
+  /*  28, 0x1C */  0xFF, 0x33, 0x33, 0x00,
+  /*  29, 0x1D */  0xFF, 0x33, 0x00, 0x00,
+  /*  30, 0x1E */  0xFF, 0x00, 0xFF, 0x00,
+  /*  31, 0x1F */  0xFF, 0x00, 0xCC, 0x00,
+  /*  32, 0x20 */  0xFF, 0x00, 0x99, 0x00,
+  /*  33, 0x21 */  0xFF, 0x00, 0x66, 0x00,
+  /*  34, 0x22 */  0xFF, 0x00, 0x33, 0x00,
+  /*  35, 0x23 */  0xFF, 0x00, 0x00, 0x00,
+  /*  36, 0x24 */  0xCC, 0xFF, 0xFF, 0x00,
+  /*  37, 0x25 */  0xCC, 0xFF, 0xCC, 0x00,
+  /*  38, 0x26 */  0xCC, 0xFF, 0x99, 0x00,
+  /*  39, 0x27 */  0xCC, 0xFF, 0x66, 0x00,
+  /*  40, 0x28 */  0xCC, 0xFF, 0x33, 0x00,
+  /*  41, 0x29 */  0xCC, 0xFF, 0x00, 0x00,
+  /*  42, 0x2A */  0xCC, 0xCC, 0xFF, 0x00,
+  /*  43, 0x2B */  0xCC, 0xCC, 0xCC, 0x00,
+  /*  44, 0x2C */  0xCC, 0xCC, 0x99, 0x00,
+  /*  45, 0x2D */  0xCC, 0xCC, 0x66, 0x00,
+  /*  46, 0x2E */  0xCC, 0xCC, 0x33, 0x00,
+  /*  47, 0x2F */  0xCC, 0xCC, 0x00, 0x00,
+  /*  48, 0x30 */  0xCC, 0x99, 0xFF, 0x00,
+  /*  49, 0x31 */  0xCC, 0x99, 0xCC, 0x00,
+  /*  50, 0x32 */  0xCC, 0x99, 0x99, 0x00,
+  /*  51, 0x33 */  0xCC, 0x99, 0x66, 0x00,
+  /*  52, 0x34 */  0xCC, 0x99, 0x33, 0x00,
+  /*  53, 0x35 */  0xCC, 0x99, 0x00, 0x00,
+  /*  54, 0x36 */  0xCC, 0x66, 0xFF, 0x00,
+  /*  55, 0x37 */  0xCC, 0x66, 0xCC, 0x00,
+  /*  56, 0x38 */  0xCC, 0x66, 0x99, 0x00,
+  /*  57, 0x39 */  0xCC, 0x66, 0x66, 0x00,
+  /*  58, 0x3A */  0xCC, 0x66, 0x33, 0x00,
+  /*  59, 0x3B */  0xCC, 0x66, 0x00, 0x00,
+  /*  60, 0x3C */  0xCC, 0x33, 0xFF, 0x00,
+  /*  61, 0x3D */  0xCC, 0x33, 0xCC, 0x00,
+  /*  62, 0x3E */  0xCC, 0x33, 0x99, 0x00,
+  /*  63, 0x3F */  0xCC, 0x33, 0x66, 0x00,
+  /*  64, 0x40 */  0xCC, 0x33, 0x33, 0x00,
+  /*  65, 0x41 */  0xCC, 0x33, 0x00, 0x00,
+  /*  66, 0x42 */  0xCC, 0x00, 0xFF, 0x00,
+  /*  67, 0x43 */  0xCC, 0x00, 0xCC, 0x00,
+  /*  68, 0x44 */  0xCC, 0x00, 0x99, 0x00,
+  /*  69, 0x45 */  0xCC, 0x00, 0x66, 0x00,
+  /*  70, 0x46 */  0xCC, 0x00, 0x33, 0x00,
+  /*  71, 0x47 */  0xCC, 0x00, 0x00, 0x00,
+  /*  72, 0x48 */  0x99, 0xFF, 0xFF, 0x00,
+  /*  73, 0x49 */  0x99, 0xFF, 0xCC, 0x00,
+  /*  74, 0x4A */  0x99, 0xFF, 0x99, 0x00,
+  /*  75, 0x4B */  0x99, 0xFF, 0x66, 0x00,
+  /*  76, 0x4C */  0x99, 0xFF, 0x33, 0x00,
+  /*  77, 0x4D */  0x99, 0xFF, 0x00, 0x00,
+  /*  78, 0x4E */  0x99, 0xCC, 0xFF, 0x00,
+  /*  79, 0x4F */  0x99, 0xCC, 0xCC, 0x00,
+  /*  80, 0x50 */  0x99, 0xCC, 0x99, 0x00,
+  /*  81, 0x51 */  0x99, 0xCC, 0x66, 0x00,
+  /*  82, 0x52 */  0x99, 0xCC, 0x33, 0x00,
+  /*  83, 0x53 */  0x99, 0xCC, 0x00, 0x00,
+  /*  84, 0x54 */  0x99, 0x99, 0xFF, 0x00,
+  /*  85, 0x55 */  0x99, 0x99, 0xCC, 0x00,
+  /*  86, 0x56 */  0x99, 0x99, 0x99, 0x00,
+  /*  87, 0x57 */  0x99, 0x99, 0x66, 0x00,
+  /*  88, 0x58 */  0x99, 0x99, 0x33, 0x00,
+  /*  89, 0x59 */  0x99, 0x99, 0x00, 0x00,
+  /*  90, 0x5A */  0x99, 0x66, 0xFF, 0x00,
+  /*  91, 0x5B */  0x99, 0x66, 0xCC, 0x00,
+  /*  92, 0x5C */  0x99, 0x66, 0x99, 0x00,
+  /*  93, 0x5D */  0x99, 0x66, 0x66, 0x00,
+  /*  94, 0x5E */  0x99, 0x66, 0x33, 0x00,
+  /*  95, 0x5F */  0x99, 0x66, 0x00, 0x00,
+  /*  96, 0x60 */  0x99, 0x33, 0xFF, 0x00,
+  /*  97, 0x61 */  0x99, 0x33, 0xCC, 0x00,
+  /*  98, 0x62 */  0x99, 0x33, 0x99, 0x00,
+  /*  99, 0x63 */  0x99, 0x33, 0x66, 0x00,
+  /* 100, 0x64 */  0x99, 0x33, 0x33, 0x00,
+  /* 101, 0x65 */  0x99, 0x33, 0x00, 0x00,
+  /* 102, 0x66 */  0x99, 0x00, 0xFF, 0x00,
+  /* 103, 0x67 */  0x99, 0x00, 0xCC, 0x00,
+  /* 104, 0x68 */  0x99, 0x00, 0x99, 0x00,
+  /* 105, 0x69 */  0x99, 0x00, 0x66, 0x00,
+  /* 106, 0x6A */  0x99, 0x00, 0x33, 0x00,
+  /* 107, 0x6B */  0x99, 0x00, 0x00, 0x00,
+  /* 108, 0x6C */  0x66, 0xFF, 0xFF, 0x00,
+  /* 109, 0x6D */  0x66, 0xFF, 0xCC, 0x00,
+  /* 110, 0x6E */  0x66, 0xFF, 0x99, 0x00,
+  /* 111, 0x6F */  0x66, 0xFF, 0x66, 0x00,
+  /* 112, 0x70 */  0x66, 0xFF, 0x33, 0x00,
+  /* 113, 0x71 */  0x66, 0xFF, 0x00, 0x00,
+  /* 114, 0x72 */  0x66, 0xCC, 0xFF, 0x00,
+  /* 115, 0x73 */  0x66, 0xCC, 0xCC, 0x00,
+  /* 116, 0x74 */  0x66, 0xCC, 0x99, 0x00,
+  /* 117, 0x75 */  0x66, 0xCC, 0x66, 0x00,
+  /* 118, 0x76 */  0x66, 0xCC, 0x33, 0x00,
+  /* 119, 0x77 */  0x66, 0xCC, 0x00, 0x00,
+  /* 120, 0x78 */  0x66, 0x99, 0xFF, 0x00,
+  /* 121, 0x79 */  0x66, 0x99, 0xCC, 0x00,
+  /* 122, 0x7A */  0x66, 0x99, 0x99, 0x00,
+  /* 123, 0x7B */  0x66, 0x99, 0x66, 0x00,
+  /* 124, 0x7C */  0x66, 0x99, 0x33, 0x00,
+  /* 125, 0x7D */  0x66, 0x99, 0x00, 0x00,
+  /* 126, 0x7E */  0x66, 0x66, 0xFF, 0x00,
+  /* 127, 0x7F */  0x66, 0x66, 0xCC, 0x00,
+  /* 128, 0x80 */  0x66, 0x66, 0x99, 0x00,
+  /* 129, 0x81 */  0x66, 0x66, 0x66, 0x00,
+  /* 130, 0x82 */  0x66, 0x66, 0x33, 0x00,
+  /* 131, 0x83 */  0x66, 0x66, 0x00, 0x00,
+  /* 132, 0x84 */  0x66, 0x33, 0xFF, 0x00,
+  /* 133, 0x85 */  0x66, 0x33, 0xCC, 0x00,
+  /* 134, 0x86 */  0x66, 0x33, 0x99, 0x00,
+  /* 135, 0x87 */  0x66, 0x33, 0x66, 0x00,
+  /* 136, 0x88 */  0x66, 0x33, 0x33, 0x00,
+  /* 137, 0x89 */  0x66, 0x33, 0x00, 0x00,
+  /* 138, 0x8A */  0x66, 0x00, 0xFF, 0x00,
+  /* 139, 0x8B */  0x66, 0x00, 0xCC, 0x00,
+  /* 140, 0x8C */  0x66, 0x00, 0x99, 0x00,
+  /* 141, 0x8D */  0x66, 0x00, 0x66, 0x00,
+  /* 142, 0x8E */  0x66, 0x00, 0x33, 0x00,
+  /* 143, 0x8F */  0x66, 0x00, 0x00, 0x00,
+  /* 144, 0x90 */  0x33, 0xFF, 0xFF, 0x00,
+  /* 145, 0x91 */  0x33, 0xFF, 0xCC, 0x00,
+  /* 146, 0x92 */  0x33, 0xFF, 0x99, 0x00,
+  /* 147, 0x93 */  0x33, 0xFF, 0x66, 0x00,
+  /* 148, 0x94 */  0x33, 0xFF, 0x33, 0x00,
+  /* 149, 0x95 */  0x33, 0xFF, 0x00, 0x00,
+  /* 150, 0x96 */  0x33, 0xCC, 0xFF, 0x00,
+  /* 151, 0x97 */  0x33, 0xCC, 0xCC, 0x00,
+  /* 152, 0x98 */  0x33, 0xCC, 0x99, 0x00,
+  /* 153, 0x99 */  0x33, 0xCC, 0x66, 0x00,
+  /* 154, 0x9A */  0x33, 0xCC, 0x33, 0x00,
+  /* 155, 0x9B */  0x33, 0xCC, 0x00, 0x00,
+  /* 156, 0x9C */  0x33, 0x99, 0xFF, 0x00,
+  /* 157, 0x9D */  0x33, 0x99, 0xCC, 0x00,
+  /* 158, 0x9E */  0x33, 0x99, 0x99, 0x00,
+  /* 159, 0x9F */  0x33, 0x99, 0x66, 0x00,
+  /* 160, 0xA0 */  0x33, 0x99, 0x33, 0x00,
+  /* 161, 0xA1 */  0x33, 0x99, 0x00, 0x00,
+  /* 162, 0xA2 */  0x33, 0x66, 0xFF, 0x00,
+  /* 163, 0xA3 */  0x33, 0x66, 0xCC, 0x00,
+  /* 164, 0xA4 */  0x33, 0x66, 0x99, 0x00,
+  /* 165, 0xA5 */  0x33, 0x66, 0x66, 0x00,
+  /* 166, 0xA6 */  0x33, 0x66, 0x33, 0x00,
+  /* 167, 0xA7 */  0x33, 0x66, 0x00, 0x00,
+  /* 168, 0xA8 */  0x33, 0x33, 0xFF, 0x00,
+  /* 169, 0xA9 */  0x33, 0x33, 0xCC, 0x00,
+  /* 170, 0xAA */  0x33, 0x33, 0x99, 0x00,
+  /* 171, 0xAB */  0x33, 0x33, 0x66, 0x00,
+  /* 172, 0xAC */  0x33, 0x33, 0x33, 0x00,
+  /* 173, 0xAD */  0x33, 0x33, 0x00, 0x00,
+  /* 174, 0xAE */  0x33, 0x00, 0xFF, 0x00,
+  /* 175, 0xAF */  0x33, 0x00, 0xCC, 0x00,
+  /* 176, 0xB0 */  0x33, 0x00, 0x99, 0x00,
+  /* 177, 0xB1 */  0x33, 0x00, 0x66, 0x00,
+  /* 178, 0xB2 */  0x33, 0x00, 0x33, 0x00,
+  /* 179, 0xB3 */  0x33, 0x00, 0x00, 0x00,
+  /* 180, 0xB4 */  0x00, 0xFF, 0xFF, 0x00,
+  /* 181, 0xB5 */  0x00, 0xFF, 0xCC, 0x00,
+  /* 182, 0xB6 */  0x00, 0xFF, 0x99, 0x00,
+  /* 183, 0xB7 */  0x00, 0xFF, 0x66, 0x00,
+  /* 184, 0xB8 */  0x00, 0xFF, 0x33, 0x00,
+  /* 185, 0xB9 */  0x00, 0xFF, 0x00, 0x00,
+  /* 186, 0xBA */  0x00, 0xCC, 0xFF, 0x00,
+  /* 187, 0xBB */  0x00, 0xCC, 0xCC, 0x00,
+  /* 188, 0xBC */  0x00, 0xCC, 0x99, 0x00,
+  /* 189, 0xBD */  0x00, 0xCC, 0x66, 0x00,
+  /* 190, 0xBE */  0x00, 0xCC, 0x33, 0x00,
+  /* 191, 0xBF */  0x00, 0xCC, 0x00, 0x00,
+  /* 192, 0xC0 */  0x00, 0x99, 0xFF, 0x00,
+  /* 193, 0xC1 */  0x00, 0x99, 0xCC, 0x00,
+  /* 194, 0xC2 */  0x00, 0x99, 0x99, 0x00,
+  /* 195, 0xC3 */  0x00, 0x99, 0x66, 0x00,
+  /* 196, 0xC4 */  0x00, 0x99, 0x33, 0x00,
+  /* 197, 0xC5 */  0x00, 0x99, 0x00, 0x00,
+  /* 198, 0xC6 */  0x00, 0x66, 0xFF, 0x00,
+  /* 199, 0xC7 */  0x00, 0x66, 0xCC, 0x00,
+  /* 200, 0xC8 */  0x00, 0x66, 0x99, 0x00,
+  /* 201, 0xC9 */  0x00, 0x66, 0x66, 0x00,
+  /* 202, 0xCA */  0x00, 0x66, 0x33, 0x00,
+  /* 203, 0xCB */  0x00, 0x66, 0x00, 0x00,
+  /* 204, 0xCC */  0x00, 0x33, 0xFF, 0x00,
+  /* 205, 0xCD */  0x00, 0x33, 0xCC, 0x00,
+  /* 206, 0xCE */  0x00, 0x33, 0x99, 0x00,
+  /* 207, 0xCF */  0x00, 0x33, 0x66, 0x00,
+  /* 208, 0xD0 */  0x00, 0x33, 0x33, 0x00,
+  /* 209, 0xD1 */  0x00, 0x33, 0x00, 0x00,
+  /* 210, 0xD2 */  0x00, 0x00, 0xFF, 0x00,
+  /* 211, 0xD3 */  0x00, 0x00, 0xCC, 0x00,
+  /* 212, 0xD4 */  0x00, 0x00, 0x99, 0x00,
+  /* 213, 0xD5 */  0x00, 0x00, 0x66, 0x00,
+  /* 214, 0xD6 */  0x00, 0x00, 0x33, 0x00,
+  /* 215, 0xD7 */  0xEE, 0x00, 0x00, 0x00,
+  /* 216, 0xD8 */  0xDD, 0x00, 0x00, 0x00,
+  /* 217, 0xD9 */  0xBB, 0x00, 0x00, 0x00,
+  /* 218, 0xDA */  0xAA, 0x00, 0x00, 0x00,
+  /* 219, 0xDB */  0x88, 0x00, 0x00, 0x00,
+  /* 220, 0xDC */  0x77, 0x00, 0x00, 0x00,
+  /* 221, 0xDD */  0x55, 0x00, 0x00, 0x00,
+  /* 222, 0xDE */  0x44, 0x00, 0x00, 0x00,
+  /* 223, 0xDF */  0x22, 0x00, 0x00, 0x00,
+  /* 224, 0xE0 */  0x11, 0x00, 0x00, 0x00,
+  /* 225, 0xE1 */  0x00, 0xEE, 0x00, 0x00,
+  /* 226, 0xE2 */  0x00, 0xDD, 0x00, 0x00,
+  /* 227, 0xE3 */  0x00, 0xBB, 0x00, 0x00,
+  /* 228, 0xE4 */  0x00, 0xAA, 0x00, 0x00,
+  /* 229, 0xE5 */  0x00, 0x88, 0x00, 0x00,
+  /* 230, 0xE6 */  0x00, 0x77, 0x00, 0x00,
+  /* 231, 0xE7 */  0x00, 0x55, 0x00, 0x00,
+  /* 232, 0xE8 */  0x00, 0x44, 0x00, 0x00,
+  /* 233, 0xE9 */  0x00, 0x22, 0x00, 0x00,
+  /* 234, 0xEA */  0x00, 0x11, 0x00, 0x00,
+  /* 235, 0xEB */  0x00, 0x00, 0xEE, 0x00,
+  /* 236, 0xEC */  0x00, 0x00, 0xDD, 0x00,
+  /* 237, 0xED */  0x00, 0x00, 0xBB, 0x00,
+  /* 238, 0xEE */  0x00, 0x00, 0xAA, 0x00,
+  /* 239, 0xEF */  0x00, 0x00, 0x88, 0x00,
+  /* 240, 0xF0 */  0x00, 0x00, 0x77, 0x00,
+  /* 241, 0xF1 */  0x00, 0x00, 0x55, 0x00,
+  /* 242, 0xF2 */  0x00, 0x00, 0x44, 0x00,
+  /* 243, 0xF3 */  0x00, 0x00, 0x22, 0x00,
+  /* 244, 0xF4 */  0x00, 0x00, 0x11, 0x00,
+  /* 245, 0xF5 */  0xEE, 0xEE, 0xEE, 0x00,
+  /* 246, 0xF6 */  0xDD, 0xDD, 0xDD, 0x00,
+  /* 247, 0xF7 */  0xBB, 0xBB, 0xBB, 0x00,
+  /* 248, 0xF8 */  0xAA, 0xAA, 0xAA, 0x00,
+  /* 249, 0xF9 */  0x88, 0x88, 0x88, 0x00,
+  /* 250, 0xFA */  0x77, 0x77, 0x77, 0x00,
+  /* 251, 0xFB */  0x55, 0x55, 0x55, 0x00,
+  /* 252, 0xFC */  0x44, 0x44, 0x44, 0x00,
+  /* 253, 0xFD */  0x22, 0x22, 0x22, 0x00,
+  /* 254, 0xFE */  0x11, 0x11, 0x11, 0x00,
+  /* 255, 0xFF */  0x00, 0x00, 0x00, 0x00
 };
 
 #endif /* AVFORMAT_QTPALETTE_H */
diff --git a/libavformat/rdt.c b/libavformat/rdt.c
index 9b5f1e6..7400a6d 100644
--- a/libavformat/rdt.c
+++ b/libavformat/rdt.c
@@ -312,16 +312,14 @@
         pos = url_ftell(&pb);
         if (res < 0)
             return res;
-        if (res > 0) {
-            if (st->codec->codec_id == CODEC_ID_AAC) {
+        rdt->audio_pkt_cnt = res;
+        if (rdt->audio_pkt_cnt > 0 &&
+            st->codec->codec_id == CODEC_ID_AAC) {
                 memcpy (rdt->buffer, buf + pos, len - pos);
                 rdt->rmctx->pb = av_alloc_put_byte (rdt->buffer, len - pos, 0,
                                                     NULL, NULL, NULL, NULL);
             }
-            goto get_cache;
-        }
     } else {
-get_cache:
         rdt->audio_pkt_cnt =
             ff_rm_retrieve_cache (rdt->rmctx, rdt->rmctx->pb,
                                   st, rdt->rmst[st->index], pkt);
diff --git a/libavformat/rmdec.c b/libavformat/rmdec.c
index 2dbe7bc..eb75eb7 100755
--- a/libavformat/rmdec.c
+++ b/libavformat/rmdec.c
@@ -48,21 +48,6 @@
     int audio_pkt_cnt; ///< Output packet counter
 } RMDemuxContext;
 
-static const unsigned char sipr_swaps[38][2] = {
-    {  0, 63 }, {  1, 22 }, {  2, 44 }, {  3, 90 },
-    {  5, 81 }, {  7, 31 }, {  8, 86 }, {  9, 58 },
-    { 10, 36 }, { 12, 68 }, { 13, 39 }, { 14, 73 },
-    { 15, 53 }, { 16, 69 }, { 17, 57 }, { 19, 88 },
-    { 20, 34 }, { 21, 71 }, { 24, 46 }, { 25, 94 },
-    { 26, 54 }, { 28, 75 }, { 29, 50 }, { 32, 70 },
-    { 33, 92 }, { 35, 74 }, { 38, 85 }, { 40, 56 },
-    { 42, 87 }, { 43, 65 }, { 45, 59 }, { 48, 79 },
-    { 49, 93 }, { 51, 89 }, { 55, 95 }, { 61, 76 },
-    { 67, 83 }, { 77, 80 }
-};
-
-static const unsigned char sipr_subpk_size[4] = { 29, 19, 37, 20 };
-
 static inline void get_strl(ByteIOContext *pb, char *buf, int buf_size, int len)
 {
     int i;
@@ -169,8 +154,9 @@
             ast->audio_framesize = st->codec->block_align;
             st->codec->block_align = coded_framesize;
 
-            if(ast->audio_framesize >= UINT_MAX / sub_packet_h){
-                av_log(s, AV_LOG_ERROR, "ast->audio_framesize * sub_packet_h too large\n");
+            if (ast->audio_framesize <= 0 || sub_packet_h <= 0 ||
+                ast->audio_framesize >= UINT_MAX / sub_packet_h){
+                av_log(s, AV_LOG_ERROR, "ast->audio_framesize * sub_packet_h is invalid\n");
                 return -1;
             }
 
@@ -186,31 +172,23 @@
                 return -1;
             }
 
-            if (!strcmp(buf, "cook")) st->codec->codec_id = CODEC_ID_COOK;
-            else if (!strcmp(buf, "sipr")) st->codec->codec_id = CODEC_ID_SIPR;
-            else st->codec->codec_id = CODEC_ID_ATRAC3;
-
-            ast->audio_framesize = st->codec->block_align;
-            if (st->codec->codec_id == CODEC_ID_SIPR) {
-                if (flavor > 3) {
-                    av_log(s, AV_LOG_ERROR, "bad SIPR file flavor %d\n",
-                           flavor);
-                    return -1;
-                }
-                st->codec->block_align = sipr_subpk_size[flavor];
-            } else {
                 if(sub_packet_size <= 0){
                     av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n");
                     return -1;
                 }
-                st->codec->block_align = ast->sub_packet_size;
-            }
+
+            if (!strcmp(buf, "cook")) st->codec->codec_id = CODEC_ID_COOK;
+            else if (!strcmp(buf, "sipr")) st->codec->codec_id = CODEC_ID_SIPR;
+            else st->codec->codec_id = CODEC_ID_ATRAC3;
             st->codec->extradata_size= codecdata_length;
             st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
             get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
+            ast->audio_framesize = st->codec->block_align;
+            st->codec->block_align = ast->sub_packet_size;
 
-            if(ast->audio_framesize >= UINT_MAX / sub_packet_h){
-                av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");
+            if (ast->audio_framesize <= 0 || sub_packet_h <= 0 ||
+                ast->audio_framesize >= UINT_MAX / sub_packet_h){
+                av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h is invalid\n");
                 return -1;
             }
 
@@ -316,49 +294,6 @@
     return 0;
 }
 
-/** this function assumes that the demuxer has already seeked to the start
- * of the INDX chunk, and will bail out if not. */
-static int rm_read_index(AVFormatContext *s)
-{
-    ByteIOContext *pb = s->pb;
-    unsigned int size, n_pkts, str_id, next_off, n, pos, pts;
-    AVStream *st;
-
-    do {
-        if (get_le32(pb) != MKTAG('I','N','D','X'))
-            return -1;
-        size     = get_be32(pb);
-        if (size < 20)
-            return -1;
-        url_fskip(pb, 2);
-        n_pkts   = get_be32(pb);
-        str_id   = get_be16(pb);
-        next_off = get_be32(pb);
-        for (n = 0; n < s->nb_streams; n++)
-            if (s->streams[n]->id == str_id) {
-                st = s->streams[n];
-                break;
-            }
-        if (n == s->nb_streams)
-            goto skip;
-
-        for (n = 0; n < n_pkts; n++) {
-            url_fskip(pb, 2);
-            pts = get_be32(pb);
-            pos = get_be32(pb);
-            url_fskip(pb, 4); /* packet no. */
-
-            av_add_index_entry(st, pos, pts, 0, 0, AVINDEX_KEYFRAME);
-        }
-
-skip:
-        if (next_off && url_ftell(pb) != next_off &&
-            url_fseek(pb, next_off, SEEK_SET) < 0)
-            return -1;
-    } while (next_off);
-
-    return 0;
-}
 
 static int rm_read_header_old(AVFormatContext *s, AVFormatParameters *ap)
 {
@@ -381,7 +316,6 @@
     unsigned int tag;
     int tag_size;
     unsigned int start_time, duration;
-    unsigned int data_off = 0, indx_off = 0;
     char buf[128];
     int flags = 0;
 
@@ -425,8 +359,8 @@
             get_be32(pb); /* nb packets */
             get_be32(pb); /* duration */
             get_be32(pb); /* preroll */
-            indx_off = get_be32(pb); /* index offset */
-            data_off = get_be32(pb); /* data offset */
+            get_be32(pb); /* index offset */
+            get_be32(pb); /* data offset */
             get_be16(pb); /* nb streams */
             flags = get_be16(pb); /* flags */
             break;
@@ -468,14 +402,6 @@
     if (!rm->nb_packets && (flags & 4))
         rm->nb_packets = 3600 * 25;
     get_be32(pb); /* next data header */
-
-    if (!data_off)
-        data_off = url_ftell(pb) - 18;
-    if (indx_off && url_fseek(pb, indx_off, SEEK_SET) >= 0) {
-        rm_read_index(s);
-        url_fseek(pb, data_off + 18, SEEK_SET);
-    }
-
     return 0;
 }
 
@@ -516,33 +442,24 @@
             state= (state<<8) + get_byte(pb);
 
             if(state == MKBETAG('I', 'N', 'D', 'X')){
-                int n_pkts, expected_len;
-                len = get_be32(pb);
-                url_fskip(pb, 2);
-                n_pkts = get_be32(pb);
-                expected_len = 20 + n_pkts * 14;
-                if (len == 20)
-                    /* some files don't add index entries to chunk size... */
-                    len = expected_len;
-                else if (len != expected_len)
-                    av_log(s, AV_LOG_WARNING,
-                           "Index size %d (%d pkts) is wrong, should be %d.\n",
-                           len, n_pkts, expected_len);
-                len -= 14; // we already read part of the index header
+                len = get_be16(pb) - 6;
                 if(len<0)
                     continue;
                 goto skip;
             }
 
-            if(state > (unsigned)0xFFFF || state <= 12)
+            if(state > (unsigned)0xFFFF || state < 12)
                 continue;
-            len=state - 12;
+            len=state;
             state= 0xFFFFFFFF;
 
             num = get_be16(pb);
             *timestamp = get_be32(pb);
             res= get_byte(pb); /* reserved */
             *flags = get_byte(pb); /* flags */
+
+
+            len -= 12;
         }
         for(i=0;i<s->nb_streams;i++) {
             st = s->streams[i];
@@ -553,7 +470,7 @@
 skip:
             /* skip packet if unknown number */
             url_fskip(pb, len);
-            rm->remaining_len = 0;
+            rm->remaining_len -= len;
             continue;
         }
         *stream_index= i;
@@ -565,7 +482,7 @@
 
 static int rm_assemble_video_frame(AVFormatContext *s, ByteIOContext *pb,
                                    RMDemuxContext *rm, RMStream *vst,
-                                   AVPacket *pkt, int len, int *pseq)
+                                   AVPacket *pkt, int len)
 {
     int hdr, seq, pic_num, len2, pos;
     int type;
@@ -600,7 +517,6 @@
     }
     //now we have to deal with single slice
 
-    *pseq = seq;
     if((seq & 0x7F) == 1 || vst->curpic_num != pic_num){
         vst->slices = ((hdr & 0x3F) << 1) + 1;
         vst->videobufsize = len2 + 8*vst->slices + 1;
@@ -658,34 +574,6 @@
     }
 }
 
-/**
- * Perform 4-bit block reordering for SIPR data.
- * @todo This can be optimized, e.g. use memcpy() if data blocks are aligned
- */
-static void
-rm_reorder_sipr_data (RMStream *ast)
-{
-    int n, bs = ast->sub_packet_h * ast->audio_framesize * 2 / 96; // nibbles per subpacket
-
-    for (n = 0; n < 38; n++) {
-        int j;
-        int i = bs * sipr_swaps[n][0];
-        int o = bs * sipr_swaps[n][1];
-        uint8_t *buf = ast->pkt.data;
-
-        /* swap 4bit-nibbles of block 'i' with 'o' */
-        for (j = 0; j < bs; j++, i++, o++) {
-            int x = (buf[i >> 1] >> (4 * (i & 1))) & 0xF,
-                y = (buf[o >> 1] >> (4 * (o & 1))) & 0xF;
-
-            buf[o >> 1] = (x << (4 * (o & 1))) |
-                (buf[o >> 1] & (0xF << (4 * !(o & 1))));
-            buf[i >> 1] = (y << (4 * (i & 1))) |
-                (buf[i >> 1] & (0xF << (4 * !(i & 1))));
-        }
-    }
-}
-
 int
 ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
                     AVStream *st, RMStream *ast, int len, AVPacket *pkt,
@@ -695,7 +583,7 @@
 
     if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
         rm->current_stream= st->id;
-        if(rm_assemble_video_frame(s, pb, rm, ast, pkt, len, seq))
+        if(rm_assemble_video_frame(s, pb, rm, ast, pkt, len))
             return -1; //got partial frame
     } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
         if ((st->codec->codec_id == CODEC_ID_RA_288) ||
@@ -724,19 +612,20 @@
                     for (x = 0; x < w/sps; x++)
                         get_buffer(pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
                     break;
-                case CODEC_ID_SIPR:
-                    get_buffer(pb, ast->pkt.data + y * w, w);
-                    break;
             }
 
             if (++(ast->sub_packet_cnt) < h)
                 return -1;
-            if (st->codec->codec_id == CODEC_ID_SIPR)
-                rm_reorder_sipr_data(ast);
-
+            else {
              ast->sub_packet_cnt = 0;
              rm->audio_stream_num = st->index;
-             rm->audio_pkt_cnt = h * w / st->codec->block_align;
+                rm->audio_pkt_cnt = h * w / st->codec->block_align - 1;
+                // Release first audio packet
+                av_new_packet(pkt, st->codec->block_align);
+                memcpy(pkt->data, ast->pkt.data, st->codec->block_align); //FIXME avoid this
+                *timestamp = ast->audiotimestamp;
+                *flags = 2; // Mark first packet as keyframe
+            }
         } else if (st->codec->codec_id == CODEC_ID_AAC) {
             int x;
             rm->audio_stream_num = st->index;
@@ -744,10 +633,11 @@
             if (ast->sub_packet_cnt) {
                 for (x = 0; x < ast->sub_packet_cnt; x++)
                     ast->sub_packet_lengths[x] = get_be16(pb);
-                rm->audio_pkt_cnt = ast->sub_packet_cnt;
-                ast->audiotimestamp = *timestamp;
-            } else
-                return -1;
+                // Release first audio packet
+                rm->audio_pkt_cnt = ast->sub_packet_cnt - 1;
+                av_get_packet(pb, pkt, ast->sub_packet_lengths[0]);
+                *flags = 2; // Mark first packet as keyframe
+            }
         } else {
             av_get_packet(pb, pkt, len);
             rm_ac3_swap_bytes(st, pkt);
@@ -755,6 +645,12 @@
     } else
         av_get_packet(pb, pkt, len);
 
+    if(  (st->discard >= AVDISCARD_NONKEY && !(*flags&2))
+       || st->discard >= AVDISCARD_ALL){
+        av_free_packet(pkt);
+        return -1;
+    }
+
     pkt->stream_index = st->index;
 
 #if 0
@@ -794,10 +690,6 @@
                st->codec->block_align);
     }
     rm->audio_pkt_cnt--;
-    if ((pkt->pts = ast->audiotimestamp) != AV_NOPTS_VALUE) {
-        ast->audiotimestamp = AV_NOPTS_VALUE;
-        pkt->flags = PKT_FLAG_KEY;
-    } else
         pkt->flags = 0;
     pkt->stream_index = st->index;
 
@@ -807,49 +699,60 @@
 static int rm_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     RMDemuxContext *rm = s->priv_data;
+    ByteIOContext *pb = s->pb;
     AVStream *st;
-    int i, len, res, seq = 1;
+    int i, len;
     int64_t timestamp, pos;
-    int old_flags, flags;
+    int flags;
 
-    for (;;) {
         if (rm->audio_pkt_cnt) {
             // If there are queued audio packet return them first
             st = s->streams[rm->audio_stream_num];
             ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt);
-        } else {
-            if (rm->old_format) {
+    } else if (rm->old_format) {
                 RMStream *ast;
 
                 st = s->streams[0];
                 ast = st->priv_data;
-                timestamp = AV_NOPTS_VALUE;
-                len = !ast->audio_framesize ? RAW_PACKET_SIZE :
-                    ast->coded_framesize * ast->sub_packet_h / 2;
-                flags = (seq++ == 1) ? 2 : 0;
-            } else {
-                len=sync(s, &timestamp, &flags, &i, &pos);
-                if (len > 0)
-                    st = s->streams[i];
-            }
+        if (st->codec->codec_id == CODEC_ID_RA_288) {
+            int x, y;
 
-            if(len<0 || url_feof(s->pb))
+            for (y = 0; y < ast->sub_packet_h; y++)
+                for (x = 0; x < ast->sub_packet_h/2; x++)
+                    if (get_buffer(pb, ast->pkt.data+x*2*ast->audio_framesize+y*ast->coded_framesize, ast->coded_framesize) <= 0)
                 return AVERROR(EIO);
-
-            old_flags = flags;
-            res = ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt,
-                                      &seq, &flags, &timestamp);
-            if((old_flags&2) && (seq&0x7F) == 1)
-                av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
-            if (res)
-                continue;
+            rm->audio_stream_num = 0;
+            rm->audio_pkt_cnt = ast->sub_packet_h * ast->audio_framesize / st->codec->block_align - 1;
+            // Release first audio packet
+            av_new_packet(pkt, st->codec->block_align);
+            memcpy(pkt->data, ast->pkt.data, st->codec->block_align); //FIXME avoid this
+            pkt->flags |= PKT_FLAG_KEY; // Mark first packet as keyframe
+            pkt->stream_index = 0;
+            } else {
+            /* just read raw bytes */
+            len = RAW_PACKET_SIZE;
+            len= av_get_packet(pb, pkt, len);
+            pkt->stream_index = 0;
+            if (len <= 0) {
+                return AVERROR(EIO);
+            }
+            pkt->size = len;
         }
+        rm_ac3_swap_bytes(st, pkt);
+    } else {
+        int seq=1;
+resync:
+                len=sync(s, &timestamp, &flags, &i, &pos);
+        if(len<0)
+            return AVERROR(EIO);
+                    st = s->streams[i];
 
-        if(  (st->discard >= AVDISCARD_NONKEY && !(flags&2))
-           || st->discard >= AVDISCARD_ALL){
-            av_free_packet(pkt);
-        } else
-            break;
+        if (ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt,
+                                &seq, &flags, &timestamp) < 0)
+            goto resync;
+
+        if((flags&2) && (seq&0x7F) == 1)
+                av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
     }
 
     return 0;
diff --git a/libavformat/rmenc.c b/libavformat/rmenc.c
index 21748d5..78b180f 100755
--- a/libavformat/rmenc.c
+++ b/libavformat/rmenc.c
@@ -425,8 +425,16 @@
         index_pos = url_fseek(pb, 0, SEEK_CUR);
         data_size = index_pos - rm->data_pos;
 
-        /* FIXME: write index */
+        /* index */
+        put_tag(pb, "INDX");
+        put_be32(pb, 10 + 10 * s->nb_streams);
+        put_be16(pb, 0);
 
+        for(i=0;i<s->nb_streams;i++) {
+            put_be32(pb, 0); /* zero indexes */
+            put_be16(pb, i); /* stream number */
+            put_be32(pb, 0); /* next index */
+        }
         /* undocumented end header */
         put_be32(pb, 0);
         put_be32(pb, 0);
@@ -434,7 +442,7 @@
         url_fseek(pb, 0, SEEK_SET);
         for(i=0;i<s->nb_streams;i++)
             rm->streams[i].total_frames = rm->streams[i].nb_frames;
-        rv10_write_header(s, data_size, 0);
+        rv10_write_header(s, data_size, index_pos);
     } else {
         /* undocumented end header */
         put_be32(pb, 0);
diff --git a/libavformat/rtpdec.c b/libavformat/rtpdec.c
index 9076f3f..2107c5e 100755
--- a/libavformat/rtpdec.c
+++ b/libavformat/rtpdec.c
@@ -30,7 +30,6 @@
 #include "network.h"
 
 #include "rtpdec.h"
-#include "rtp_asf.h"
 #include "rtp_h264.h"
 
 //#define DEBUG
@@ -61,9 +60,6 @@
     ff_register_dynamic_payload_handler(&mp4v_es_handler);
     ff_register_dynamic_payload_handler(&mpeg4_generic_handler);
     ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
-
-    ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
-    ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
 }
 
 static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
@@ -386,6 +382,7 @@
         addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);
         pkt->pts = addend + delta_timestamp;
     }
+    pkt->stream_index = s->st->index;
 }
 
 /**
@@ -476,7 +473,6 @@
             s->read_buf_index = 0;
             return 1;
         }
-        return 0;
     } else if (s->parse_packet) {
         rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
                              s->st, pkt, &timestamp, buf, len, flags);
@@ -540,12 +536,9 @@
             break;
         }
 
-        pkt->stream_index = st->index;
-    }
-
     // now perform timestamp things....
     finalize_packet(s, pkt, timestamp);
-
+    }
     return rv;
 }
 
diff --git a/libavformat/rtsp.c b/libavformat/rtsp.c
index 758314f..da7701c 100644
--- a/libavformat/rtsp.c
+++ b/libavformat/rtsp.c
@@ -36,13 +36,15 @@
 
 #include "rtpdec.h"
 #include "rdt.h"
-#include "rtp_asf.h"
 
 //#define DEBUG
 //#define DEBUG_RTP_TCP
 
 static int rtsp_read_play(AVFormatContext *s);
 
+/* XXX: currently, the only way to change the protocols consists in
+   changing this variable */
+
 #if LIBAVFORMAT_VERSION_INT < (53 << 16)
 int rtsp_default_protocols = (1 << RTSP_LOWER_TRANSPORT_UDP);
 #endif
@@ -54,10 +56,11 @@
     return 0;
 }
 
-#define SPACE_CHARS " \t\r\n"
-/* we use memchr() instead of strchr() here because strchr() will return
- * the terminating '\0' of SPACE_CHARS instead of NULL if c is '\0'. */
-#define redir_isspace(c) memchr(SPACE_CHARS, c, 4)
+static int redir_isspace(int c)
+{
+    return c == ' ' || c == '\t' || c == '\n' || c == '\r';
+}
+
 static void skip_spaces(const char **pp)
 {
     const char *p;
@@ -67,13 +70,15 @@
     *pp = p;
 }
 
-static void get_word_until_chars(char *buf, int buf_size,
-                                 const char *sep, const char **pp)
+static void get_word_sep(char *buf, int buf_size, const char *sep,
+                         const char **pp)
 {
     const char *p;
     char *q;
 
     p = *pp;
+    if (*p == '/')
+        p++;
     skip_spaces(&p);
     q = buf;
     while (!strchr(sep, *p) && *p != '\0') {
@@ -86,16 +91,22 @@
     *pp = p;
 }
 
-static void get_word_sep(char *buf, int buf_size, const char *sep,
-                         const char **pp)
-{
-    if (**pp == '/') (*pp)++;
-    get_word_until_chars(buf, buf_size, sep, pp);
-}
-
 static void get_word(char *buf, int buf_size, const char **pp)
 {
-    get_word_until_chars(buf, buf_size, SPACE_CHARS, pp);
+    const char *p;
+    char *q;
+
+    p = *pp;
+    skip_spaces(&p);
+    q = buf;
+    while (!redir_isspace(*p) && *p != '\0') {
+        if ((q - buf) < buf_size - 1)
+            *q++ = *p;
+        p++;
+    }
+    if (buf_size > 0)
+        *q = '\0';
+    *pp = p;
 }
 
 /* parse the rtpmap description: <codec_name>/<clock_rate>[/<other
@@ -113,7 +124,7 @@
     if (payload_type >= RTP_PT_PRIVATE) {
         RTPDynamicProtocolHandler *handler= RTPFirstDynamicPayloadHandler;
         while(handler) {
-            if (!strcasecmp(buf, handler->enc_name) && (codec->codec_type == handler->codec_type)) {
+            if (!strcmp(buf, handler->enc_name) && (codec->codec_type == handler->codec_type)) {
                 codec->codec_id = handler->codec_id;
                 rtsp_st->dynamic_handler= handler;
                 if(handler->open) {
@@ -176,7 +187,7 @@
     v = 1;
     for(;;) {
         skip_spaces(&p);
-        if (*p == '\0')
+        if (p == '\0')
             break;
         c = toupper((unsigned char)*p++);
         if (c >= '0' && c <= '9')
@@ -204,8 +215,6 @@
             if (!strcmp(attr, "config")) {
                 /* decode the hexa encoded parameter */
                 int len = hex_to_data(NULL, value);
-                if (codec->extradata)
-                    av_free(codec->extradata);
                 codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
                 if (!codec->extradata)
                     return;
@@ -245,7 +254,8 @@
 int rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size)
 {
     skip_spaces(p);
-    if(**p) {
+    if(**p)
+    {
         get_word_sep(attr, attr_size, "=", p);
         if (**p == '=')
             (*p)++;
@@ -382,8 +392,6 @@
             codec_type = CODEC_TYPE_AUDIO;
         } else if (!strcmp(st_type, "video")) {
             codec_type = CODEC_TYPE_VIDEO;
-        } else if (!strcmp(st_type, "application")) {
-            codec_type = CODEC_TYPE_DATA;
         } else {
             s1->skip_media = 1;
             return;
@@ -486,10 +494,7 @@
         } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {
             if (atoi(p) == 1)
                 rt->transport = RTSP_TRANSPORT_RDT;
-        } else {
-            if (rt->server_type == RTSP_SERVER_WMS)
-                ff_wms_parse_sdp_a_line(s, p);
-            if (s->nb_streams > 0) {
+        } else if (s->nb_streams > 0) {
                 if (rt->server_type == RTSP_SERVER_REAL)
                     ff_real_parse_sdp_a_line(s, s->nb_streams - 1, p);
 
@@ -498,7 +503,6 @@
                     rtsp_st->dynamic_handler->parse_sdp_a_line)
                     rtsp_st->dynamic_handler->parse_sdp_a_line(s, s->nb_streams - 1,
                         rtsp_st->dynamic_protocol_context, buf);
-            }
         }
         break;
     }
@@ -586,11 +590,14 @@
 
         get_word_sep(transport_protocol, sizeof(transport_protocol),
                      "/", &p);
+        if (*p == '/')
+            p++;
         if (!strcasecmp (transport_protocol, "rtp")) {
             get_word_sep(profile, sizeof(profile), "/;,", &p);
             lower_transport[0] = '\0';
             /* rtp/avp/<protocol> */
             if (*p == '/') {
+                p++;
                 get_word_sep(lower_transport, sizeof(lower_transport),
                              ";,", &p);
             }
@@ -730,58 +737,45 @@
     }
 }
 
-/**
- * Read a RTSP message from the server, or prepare to read data
- * packets if we're reading data interleaved over the TCP/RTSP
- * connection as well.
- *
- * @param s RTSP demuxer context
- * @param reply pointer where the RTSP message header will be stored
- * @param content_ptr pointer where the RTSP message body, if any, will
- *                    be stored (length is in \p reply)
- * @param return_on_interleaved_data whether the function may return if we
- *                   encounter a data marker ('$'), which precedes data
- *                   packets over interleaved TCP/RTSP connections. If this
- *                   is set, this function will return 1 after encountering
- *                   a '$'. If it is not set, the function will skip any
- *                   data packets (if they are encountered), until a reply
- *                   has been fully parsed. If no more data is available
- *                   without parsing a reply, it will return an error.
- *
- * @returns 1 if a data packets is ready to be received, -1 on error,
- *          and 0 on success.
- */
-static int
-rtsp_read_reply (AVFormatContext *s, RTSPMessageHeader *reply,
-                 unsigned char **content_ptr, int return_on_interleaved_data)
+static void rtsp_send_cmd(AVFormatContext *s,
+                          const char *cmd, RTSPMessageHeader *reply,
+                          unsigned char **content_ptr)
 {
     RTSPState *rt = s->priv_data;
     char buf[4096], buf1[1024], *q;
     unsigned char ch;
     const char *p;
-    int ret, content_length, line_count = 0;
+    int content_length, line_count;
     unsigned char *content = NULL;
 
     memset(reply, 0, sizeof(*reply));
 
+    rt->seq++;
+    av_strlcpy(buf, cmd, sizeof(buf));
+    snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
+    av_strlcat(buf, buf1, sizeof(buf));
+    if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
+        snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
+        av_strlcat(buf, buf1, sizeof(buf));
+    }
+    av_strlcat(buf, "\r\n", sizeof(buf));
+#ifdef DEBUG
+    printf("Sending:\n%s--\n", buf);
+#endif
+    url_write(rt->rtsp_hd, buf, strlen(buf));
+
     /* parse reply (XXX: use buffers) */
+    line_count = 0;
     rt->last_reply[0] = '\0';
     for(;;) {
         q = buf;
         for(;;) {
-            ret = url_readbuf(rt->rtsp_hd, &ch, 1);
-#ifdef DEBUG_RTP_TCP
-            printf("ret=%d c=%02x [%c]\n", ret, ch, ch);
-#endif
-            if (ret != 1)
-                return -1;
+            if (url_readbuf(rt->rtsp_hd, &ch, 1) != 1)
+                break;
             if (ch == '\n')
                 break;
             if (ch == '$') {
                 /* XXX: only parse it if first char on line ? */
-                if (return_on_interleaved_data) {
-                    return 1;
-                } else
                 rtsp_skip_packet(s);
             } else if (ch != '\r') {
                 if ((q - buf) < sizeof(buf) - 1)
@@ -823,32 +817,6 @@
         *content_ptr = content;
     else
         av_free(content);
-
-    return 0;
-}
-
-static void rtsp_send_cmd(AVFormatContext *s,
-                          const char *cmd, RTSPMessageHeader *reply,
-                          unsigned char **content_ptr)
-{
-    RTSPState *rt = s->priv_data;
-    char buf[4096], buf1[1024];
-
-    rt->seq++;
-    av_strlcpy(buf, cmd, sizeof(buf));
-    snprintf(buf1, sizeof(buf1), "CSeq: %d\r\n", rt->seq);
-    av_strlcat(buf, buf1, sizeof(buf));
-    if (rt->session_id[0] != '\0' && !strstr(cmd, "\nIf-Match:")) {
-        snprintf(buf1, sizeof(buf1), "Session: %s\r\n", rt->session_id);
-        av_strlcat(buf, buf1, sizeof(buf));
-    }
-    av_strlcat(buf, "\r\n", sizeof(buf));
-#ifdef DEBUG
-    printf("Sending:\n%s--\n", buf);
-#endif
-    url_write(rt->rtsp_hd, buf, strlen(buf));
-
-    rtsp_read_reply(s, reply, content_ptr, 0);
 }
 
 
@@ -874,10 +842,6 @@
         }
     }
     av_free(rt->rtsp_streams);
-    if (rt->asf_ctx) {
-        av_close_input_stream (rt->asf_ctx);
-        rt->asf_ctx = NULL;
-    }
 }
 
 static int
@@ -922,7 +886,7 @@
                     int lower_transport, const char *real_challenge)
 {
     RTSPState *rt = s->priv_data;
-    int rtx, j, i, err, interleave = 0;
+    int j, i, err, interleave = 0;
     RTSPStream *rtsp_st;
     RTSPMessageHeader reply1, *reply = &reply1;
     char cmd[2048];
@@ -940,38 +904,12 @@
     for(j = RTSP_RTP_PORT_MIN, i = 0; i < rt->nb_rtsp_streams; ++i) {
         char transport[2048];
 
-        /**
-         * WMS serves all UDP data over a single connection, the RTX, which
-         * isn't necessarily the first in the SDP but has to be the first
-         * to be set up, else the second/third SETUP will fail with a 461.
-         */
-        if (lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
-             rt->server_type == RTSP_SERVER_WMS) {
-            if (i == 0) {
-                /* rtx first */
-                for (rtx = 0; rtx < rt->nb_rtsp_streams; rtx++) {
-                    int len = strlen(rt->rtsp_streams[rtx]->control_url);
-                    if (len >= 4 &&
-                        !strcmp(rt->rtsp_streams[rtx]->control_url + len - 4, "/rtx"))
-                        break;
-                }
-                if (rtx == rt->nb_rtsp_streams)
-                    return -1; /* no RTX found */
-                rtsp_st = rt->rtsp_streams[rtx];
-            } else
-                rtsp_st = rt->rtsp_streams[i > rtx ? i : i - 1];
-        } else
             rtsp_st = rt->rtsp_streams[i];
 
         /* RTP/UDP */
         if (lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
             char buf[256];
 
-            if (rt->server_type == RTSP_SERVER_WMS && i > 1) {
-                port = reply->transports[0].client_port_min;
-                goto have_port;
-            }
-
             /* first try in specified port range */
             if (RTSP_RTP_PORT_MIN != 0) {
                 while(j <= RTSP_RTP_PORT_MAX) {
@@ -992,26 +930,18 @@
 
         rtp_opened:
             port = rtp_get_local_port(rtsp_st->rtp_handle);
-        have_port:
             snprintf(transport, sizeof(transport) - 1,
                      "%s/UDP;", trans_pref);
             if (rt->server_type != RTSP_SERVER_REAL)
                 av_strlcat(transport, "unicast;", sizeof(transport));
             av_strlcatf(transport, sizeof(transport),
                      "client_port=%d", port);
-            if (rt->transport == RTSP_TRANSPORT_RTP &&
-                !(rt->server_type == RTSP_SERVER_WMS && i > 0))
+            if (rt->transport == RTSP_TRANSPORT_RTP)
                 av_strlcatf(transport, sizeof(transport), "-%d", port + 1);
         }
 
         /* RTP/TCP */
         else if (lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
-            /** For WMS streams, the application streams are only used for
-             * UDP. When trying to set it up for TCP streams, the server
-             * will return an error. Therefore, we skip those streams. */
-            if (rt->server_type == RTSP_SERVER_WMS &&
-                s->streams[rtsp_st->stream_index]->codec->codec_type == CODEC_TYPE_DATA)
-                continue;
             snprintf(transport, sizeof(transport) - 1,
                      "%s/TCP;", trans_pref);
             if (rt->server_type == RTSP_SERVER_WMS)
@@ -1084,8 +1014,7 @@
                 /* XXX: also use address if specified */
                 snprintf(url, sizeof(url), "rtp://%s:%d",
                          host, reply->transports[0].server_port_min);
-                if (!(rt->server_type == RTSP_SERVER_WMS && i > 1) &&
-                    rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
+                if (rtp_set_remote_url(rtsp_st->rtp_handle, url) < 0) {
                     err = AVERROR_INVALIDDATA;
                     goto fail;
                 }
@@ -1293,14 +1222,14 @@
 #endif
  redo:
     for(;;) {
-        RTSPMessageHeader reply;
-
-        ret = rtsp_read_reply(s, &reply, NULL, 1);
-        if (ret == -1)
+        ret = url_readbuf(rt->rtsp_hd, buf, 1);
+#ifdef DEBUG_RTP_TCP
+        printf("ret=%d c=%02x [%c]\n", ret, buf[0], buf[0]);
+#endif
+        if (ret != 1)
             return -1;
-        if (ret == 1) /* received '$' */
+        if (buf[0] == '$')
             break;
-        /* XXX: parse message */
     }
     ret = url_readbuf(rt->rtsp_hd, buf, 3);
     if (ret != 3)
@@ -1339,25 +1268,21 @@
     RTSPState *rt = s->priv_data;
     RTSPStream *rtsp_st;
     fd_set rfds;
-    int fd, fd_max, n, i, ret, tcp_fd;
+    int fd1, fd2, fd_max, n, i, ret;
     struct timeval tv;
 
     for(;;) {
         if (url_interrupt_cb())
             return AVERROR(EINTR);
         FD_ZERO(&rfds);
-        tcp_fd = fd_max = url_get_file_handle(rt->rtsp_hd);
-        FD_SET(tcp_fd, &rfds);
+        fd_max = -1;
         for(i = 0; i < rt->nb_rtsp_streams; i++) {
             rtsp_st = rt->rtsp_streams[i];
-            if (rtsp_st->rtp_handle) {
-                /* currently, we cannot probe RTCP handle because of
-                 * blocking restrictions */
-                fd = url_get_file_handle(rtsp_st->rtp_handle);
-                if (fd > fd_max)
-                    fd_max = fd;
-                FD_SET(fd, &rfds);
-            }
+            /* currently, we cannot probe RTCP handle because of blocking restrictions */
+            rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
+            if (fd1 > fd_max)
+                fd_max = fd1;
+            FD_SET(fd1, &rfds);
         }
         tv.tv_sec = 0;
         tv.tv_usec = 100 * 1000;
@@ -1365,22 +1290,14 @@
         if (n > 0) {
             for(i = 0; i < rt->nb_rtsp_streams; i++) {
                 rtsp_st = rt->rtsp_streams[i];
-                if (rtsp_st->rtp_handle) {
-                    fd = url_get_file_handle(rtsp_st->rtp_handle);
-                    if (FD_ISSET(fd, &rfds)) {
+                rtp_get_file_handles(rtsp_st->rtp_handle, &fd1, &fd2);
+                if (FD_ISSET(fd1, &rfds)) {
                         ret = url_read(rtsp_st->rtp_handle, buf, buf_size);
                         if (ret > 0) {
                             *prtsp_st = rtsp_st;
                             return ret;
                         }
                     }
-                }
-            }
-            if (FD_ISSET(tcp_fd, &rfds)) {
-                RTSPMessageHeader reply;
-
-                rtsp_read_reply(s, &reply, NULL, 0);
-                /* XXX: parse message */
             }
         }
     }
@@ -1708,7 +1625,8 @@
 {
     const char *p;
     p = pd->buf;
-    skip_spaces(&p);
+    while (redir_isspace(*p))
+        p++;
     if (av_strstart(p, "http://", NULL) ||
         av_strstart(p, "rtsp://", NULL))
         return AVPROBE_SCORE_MAX;
diff --git a/libavformat/segafilm.c b/libavformat/segafilm.c
index ae1263c..72fc25b 100755
--- a/libavformat/segafilm.c
+++ b/libavformat/segafilm.c
@@ -111,11 +111,16 @@
         film->audio_samplerate = AV_RB16(&scratch[24]);
         film->audio_channels = scratch[21];
         film->audio_bits = scratch[22];
+        if (scratch[23] == 2)
+            film->audio_type = CODEC_ID_ADPCM_ADX;
+        else if (film->audio_channels > 0) {
         if (film->audio_bits == 8)
             film->audio_type = CODEC_ID_PCM_S8;
         else if (film->audio_bits == 16)
             film->audio_type = CODEC_ID_PCM_S16BE;
         else
+                film->audio_type = CODEC_ID_NONE;
+        } else
             film->audio_type = CODEC_ID_NONE;
     }
 
@@ -167,6 +172,8 @@
     if(film->sample_count >= UINT_MAX / sizeof(film_sample))
         return -1;
     film->sample_table = av_malloc(film->sample_count * sizeof(film_sample));
+    if (!film->sample_table)
+        return AVERROR(ENOMEM);
 
     for(i=0; i<s->nb_streams; i++)
         av_set_pts_info(s->streams[i], 33, 1, film->base_clock);
@@ -187,6 +194,10 @@
             film->sample_table[i].pts *= film->base_clock;
             film->sample_table[i].pts /= film->audio_samplerate;
 
+            if (film->audio_type == CODEC_ID_ADPCM_ADX)
+                audio_frame_counter += (film->sample_table[i].sample_size * 32 /
+                    (18 * film->audio_channels));
+            else if (film->audio_type != CODEC_ID_NONE)
             audio_frame_counter += (film->sample_table[i].sample_size /
                 (film->audio_channels * film->audio_bits / 8));
         } else {
@@ -238,6 +249,10 @@
             av_free(film->stereo_buffer);
             film->stereo_buffer_size = sample->sample_size;
             film->stereo_buffer = av_malloc(film->stereo_buffer_size);
+            if (!film->stereo_buffer) {
+                film->stereo_buffer_size = 0;
+                return AVERROR(ENOMEM);
+            }
         }
 
         pkt->pos= url_ftell(pb);
diff --git a/libavformat/smacker.c b/libavformat/smacker.c
index 7d0a8d5..04dfe8d 100755
--- a/libavformat/smacker.c
+++ b/libavformat/smacker.c
@@ -285,6 +285,10 @@
                 frame_size -= 4;
                 smk->curstream++;
                 smk->bufs[smk->curstream] = av_realloc(smk->bufs[smk->curstream], size);
+                if (!smk->bufs[smk->curstream]) {
+                    smk->buf_sizes[smk->curstream] = 0;
+                    return AVERROR(ENOMEM);
+                }
                 smk->buf_sizes[smk->curstream] = size;
                 ret = get_buffer(s->pb, smk->bufs[smk->curstream], size);
                 if(ret != size)
@@ -293,7 +297,9 @@
             }
             flags >>= 1;
         }
-        if (av_new_packet(pkt, frame_size + 768))
+        if (frame_size < 0)
+            return AVERROR_INVALIDDATA;
+        if (av_new_packet(pkt, frame_size + 769))
             return AVERROR(ENOMEM);
         if(smk->frm_size[smk->cur_frame] & 1)
             palchange |= 2;
diff --git a/libavformat/stv.c b/libavformat/stv.c
index 771ba78..9a9dd4d 100755
--- a/libavformat/stv.c
+++ b/libavformat/stv.c
@@ -109,6 +109,8 @@
 	int i = 0;
 	while (!endFound)
 	{
+		if (bufLen <= 0)
+			return SOCKET_ERROR;
 		currRecv = recv(sd, buffer + offset, bufLen, MSG_PEEK);
 		if (currRecv == SOCKET_ERROR)
 		{
@@ -145,6 +147,7 @@
 				return endFound ? 0 : SOCKET_ERROR;
 			}
 			offset += currRecv;
+			bufLen -= currRecv;
 		}
 	}
 
@@ -759,8 +762,10 @@
 	pathSlash = strchr(fullURL, '/');
 	if (!pathSlash)
 		goto fail;
+	if (pathSlash - fullURL > 255)
+		goto fail;
 	strncpy(p->host, fullURL, pathSlash - fullURL);
-	strcpy(p->url, pathSlash + 1);
+	av_strlcpy(p->url, pathSlash + 1, 1024);
 
 	if (!OpenConnection(p))
 		goto fail;
diff --git a/libavformat/swf.h b/libavformat/swf.h
index 69064a2..a4638bb 100755
--- a/libavformat/swf.h
+++ b/libavformat/swf.h
@@ -65,6 +65,7 @@
 #include <assert.h>
 
 typedef struct {
+    int audio_stream_index;
     int64_t duration_pos;
     int64_t tag_pos;
     int64_t vframes_pos;
diff --git a/libavformat/swfdec.c b/libavformat/swfdec.c
index 6f70926..468611c 100755
--- a/libavformat/swfdec.c
+++ b/libavformat/swfdec.c
@@ -87,20 +87,11 @@
     int tag, len, i, frame, v;
 
     for(;;) {
-        uint64_t pos = url_ftell(pb);
         tag = get_swf_tag(pb, &len);
         if (tag < 0)
             return AVERROR(EIO);
-        if (tag == TAG_VIDEOSTREAM) {
+        if (tag == TAG_VIDEOSTREAM && !vst) {
             int ch_id = get_le16(pb);
-            len -= 2;
-
-            for (i=0; i<s->nb_streams; i++) {
-                st = s->streams[i];
-                if (st->codec->codec_type == CODEC_TYPE_VIDEO && st->id == ch_id)
-                    goto skip;
-            }
-
             get_le16(pb);
             get_le16(pb);
             get_le16(pb);
@@ -111,25 +102,19 @@
                 return -1;
             vst->codec->codec_type = CODEC_TYPE_VIDEO;
             vst->codec->codec_id = codec_get_id(swf_codec_tags, get_byte(pb));
-            av_set_pts_info(vst, 16, 256, swf->frame_rate);
+            av_set_pts_info(vst, 64, 256, swf->frame_rate);
             vst->codec->time_base = (AVRational){ 256, swf->frame_rate };
-            len -= 8;
-        } else if (tag == TAG_STREAMHEAD || tag == TAG_STREAMHEAD2) {
+            len -= 10;
+        } else if ((tag == TAG_STREAMHEAD || tag == TAG_STREAMHEAD2) && !ast) {
             /* streaming found */
             int sample_rate_code;
-
-            for (i=0; i<s->nb_streams; i++) {
-                st = s->streams[i];
-                if (st->codec->codec_type == CODEC_TYPE_AUDIO && st->id == -1)
-                    goto skip;
-            }
-
             get_byte(pb);
             v = get_byte(pb);
             swf->samples_per_frame = get_le16(pb);
             ast = av_new_stream(s, -1); /* -1 to avoid clash with video stream ch_id */
             if (!ast)
                 return -1;
+            swf->audio_stream_index = ast->index;
             ast->codec->channels = 1 + (v&1);
             ast->codec->codec_type = CODEC_TYPE_AUDIO;
             ast->codec->codec_id = codec_get_id(swf_audio_codec_tags, (v>>4) & 15);
@@ -148,31 +133,25 @@
                 if (st->codec->codec_type == CODEC_TYPE_VIDEO && st->id == ch_id) {
                     frame = get_le16(pb);
                     av_get_packet(pb, pkt, len-2);
-                    pkt->pos = pos;
                     pkt->pts = frame;
                     pkt->stream_index = st->index;
                     return pkt->size;
                 }
             }
         } else if (tag == TAG_STREAMBLOCK) {
-            for (i = 0; i < s->nb_streams; i++) {
-                st = s->streams[i];
-                if (st->codec->codec_type == CODEC_TYPE_AUDIO && st->id == -1) {
+            st = s->streams[swf->audio_stream_index];
             if (st->codec->codec_id == CODEC_ID_MP3) {
                 url_fskip(pb, 4);
                 av_get_packet(pb, pkt, len-4);
             } else { // ADPCM, PCM
                 av_get_packet(pb, pkt, len);
             }
-            pkt->pos = pos;
             pkt->stream_index = st->index;
             return pkt->size;
-                }
-            }
         } else if (tag == TAG_JPEG2) {
             for (i=0; i<s->nb_streams; i++) {
                 st = s->streams[i];
-                if (st->codec->codec_id == CODEC_ID_MJPEG && st->id == -2)
+                if (st->id == -2)
                     break;
             }
             if (i == s->nb_streams) {
@@ -197,11 +176,9 @@
             } else {
                 get_buffer(pb, pkt->data + 4, pkt->size - 4);
             }
-            pkt->pos = pos;
             pkt->stream_index = st->index;
             return pkt->size;
         }
-    skip:
         url_fskip(pb, len);
     }
     return 0;
diff --git a/libavformat/utils.c b/libavformat/utils.c
index b6f445a..3d2c6a3 100755
--- a/libavformat/utils.c
+++ b/libavformat/utils.c
@@ -3433,7 +3433,7 @@
 }
 
 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
-                     int pts_num, int pts_den)
+                     unsigned int pts_num, unsigned int pts_den)
 {
     unsigned int gcd= av_gcd(pts_num, pts_den);
     s->pts_wrap_bits = pts_wrap_bits;
diff --git a/libavutil/adler32.c b/libavutil/adler32.c
index de79316..a4c3810 100644
--- a/libavutil/adler32.c
+++ b/libavutil/adler32.c
@@ -58,7 +58,7 @@
 int main(void){
     int i;
     char data[LEN];
-    av_log_set_level(AV_LOG_DEBUG);
+    av_log_level = AV_LOG_DEBUG;
     for(i=0; i<LEN; i++)
         data[i]= ((i*i)>>3) + 123*i;
     for(i=0; i<1000; i++){
diff --git a/libavutil/lls.c b/libavutil/lls.c
index 792ffa7..ad54aba 100755
--- a/libavutil/lls.c
+++ b/libavutil/lls.c
@@ -136,7 +136,7 @@
         av_solve_lls(&m, 0.001, 0);
         for(order=0; order<3; order++){
             eval= av_evaluate_lls(&m, var+1, order);
-            printf("real:%9f order:%d pred:%9f var:%f coeffs:%f %9f %9f\n",
+            printf("real:%f order:%d pred:%f var:%f coeffs:%f %f %f\n",
                 var[0], order, eval, sqrt(m.variance[order] / (i+1)),
                 m.coeff[order][0], m.coeff[order][1], m.coeff[order][2]);
         }
diff --git a/libavutil/log.c b/libavutil/log.c
index 4bb9652..fb773d0 100755
--- a/libavutil/log.c
+++ b/libavutil/log.c
@@ -33,7 +33,8 @@
 {
     static int print_prefix=1;
     static int count;
-    static char line[1024], prev[1024];
+    static char prev[1024];
+    char line[1024];
     AVClass* avc= ptr ? *(AVClass**)ptr : NULL;
     if(level>av_log_level)
         return;
diff --git a/libavutil/log.h b/libavutil/log.h
index 1206a2f..a886844 100644
--- a/libavutil/log.h
+++ b/libavutil/log.h
@@ -53,6 +53,15 @@
 
 /* av_log API */
 
+#if LIBAVUTIL_VERSION_INT < (50<<16)
+#define AV_LOG_QUIET -1
+#define AV_LOG_FATAL 0
+#define AV_LOG_ERROR 0
+#define AV_LOG_WARNING 1
+#define AV_LOG_INFO 1
+#define AV_LOG_VERBOSE 1
+#define AV_LOG_DEBUG 2
+#else
 #define AV_LOG_QUIET    -8
 
 /**
@@ -86,6 +95,11 @@
  * Stuff which is only useful for libav* developers.
  */
 #define AV_LOG_DEBUG    48
+#endif
+
+#if LIBAVUTIL_VERSION_INT < (50<<16)
+extern int av_log_level;
+#endif
 
 /**
  * Sends the specified message to the log if the level is less than or equal
diff --git a/libavutil/lzo.c b/libavutil/lzo.c
index 686983a..83fa9bf 100755
--- a/libavutil/lzo.c
+++ b/libavutil/lzo.c
@@ -234,6 +234,12 @@
     return c.error;
 }
 
+#if LIBAVUTIL_VERSION_MAJOR < 50
+int lzo1x_decode(void *out, int *outlen, const void *in, int *inlen) {
+    return av_lzo1x_decode(out, outlen, in, inlen);
+}
+#endif
+
 #ifdef TEST
 #include <stdio.h>
 #include <lzo/lzo1x.h>
diff --git a/libavutil/mem.c b/libavutil/mem.c
index 8d9a675..b74b3a6 100755
--- a/libavutil/mem.c
+++ b/libavutil/mem.c
@@ -159,7 +159,9 @@
     //FIXME this isn't aligned correctly, though it probably isn't needed
     if(!ptr) return av_malloc(size);
     diff= ((char*)ptr)[-1];
-    return (char*)realloc((char*)ptr - diff, size + diff) + diff;
+    ptr= realloc((char*)ptr - diff, size + diff);
+    if(ptr) ptr = (char*)ptr + diff;
+    return ptr;
 #else
     return realloc(ptr, size);
 #endif
diff --git a/libpostproc/postprocess_altivec_template.c b/libpostproc/postprocess_altivec_template.c
index c3c7461..159f990 100755
--- a/libpostproc/postprocess_altivec_template.c
+++ b/libpostproc/postprocess_altivec_template.c
@@ -225,8 +225,8 @@
     DECLARE_ALIGNED(16, short, qp[8]) = {c->QP};
     vector signed short vqp = vec_ld(0, qp);
     vector signed short vb0, vb1, vb2, vb3, vb4, vb5, vb6, vb7, vb8, vb9;
-    vector unsigned char vbA0, av_uninit(vbA1), av_uninit(vbA2), av_uninit(vbA3), av_uninit(vbA4), av_uninit(vbA5), av_uninit(vbA6), av_uninit(vbA7), av_uninit(vbA8), vbA9;
-    vector unsigned char vbB0, av_uninit(vbB1), av_uninit(vbB2), av_uninit(vbB3), av_uninit(vbB4), av_uninit(vbB5), av_uninit(vbB6), av_uninit(vbB7), av_uninit(vbB8), vbB9;
+    vector unsigned char vbA0, vbA1, vbA2, vbA3, vbA4, vbA5, vbA6, vbA7, vbA8, vbA9;
+    vector unsigned char vbB0, vbB1, vbB2, vbB3, vbB4, vbB5, vbB6, vbB7, vbB8, vbB9;
     vector unsigned char vbT0, vbT1, vbT2, vbT3, vbT4, vbT5, vbT6, vbT7, vbT8, vbT9;
     vector unsigned char perml0, perml1, perml2, perml3, perml4,
                          perml5, perml6, perml7, perml8, perml9;