[SCM] libav/master: Imported Upstream version 0.8.4

siretart at users.alioth.debian.org siretart at users.alioth.debian.org
Mon Oct 22 20:00:24 UTC 2012


The following commit has been merged in the master branch:
commit 4fee3b65f226eaf61eb1a4cf27417507fd567647
Author: Reinhard Tartler <siretart at tauware.de>
Date:   Mon Oct 22 20:53:48 2012 +0200

    Imported Upstream version 0.8.4

diff --git a/Changelog b/Changelog
index fb9a7a6..d3c743d 100644
--- a/Changelog
+++ b/Changelog
@@ -1,6 +1,35 @@
 Entries are sorted chronologically from oldest to youngest within each release,
 releases are sorted from youngest to oldest.
 
+version 0.8.4:
+
+- Several bugs and crashes have been fixed in the following codecs:
+  h264 (Bug 118), vc1dec (CVE-2012-2796), sipr, bmpdec (bug 367), alsdec
+  (CVE-2012-2775), rv34/rv40 (CVE-2012-2772), indeo3/indeo4
+  (CVE-2012-2776, CVE-2012-2779, CVE-2012-2787, CVE-2012-2794,
+  CVE-2012-2800), vorbisenc, vorbisdec (Bug 277), snow, ac3dec
+  (CVE-2012-2802), avsdec (CVE-2012-2801), dfa (CVE-2012-2786,
+  CVE-2012-2798), lagrith (CVE-2012-2793), wmaprodec (CVE-2012-2789 &
+  Bug 327), avidec (CVE-2012-2788, CVE-2012-2790), cavsdec
+  (CVE-2012-2777, CVE-2012-2784), wav (Bug 379), yuff4mpeg (Bug 373),
+  mpegaudio, tiffenc, smacker (Bug 265).
+
+- smaller bug fixes in avconv (Bug 352)
+
+- fix lt() and lte() in function evaluator
+
+- fix segfault in avformat_open_input()
+
+- fix segfault in golomb decoder (bug 310)
+
+- fix segfault (double free) in libavfilter
+
+- convert dfa decoder to bytestream2 API to protect from overreads
+
+- bugfix in vf_pad/scale filter (Bug 203 & 245)
+
+- lavc: remove stats_out and stats_in from the options table. (Bug 380)
+
 
 version 0.8.3:
 
diff --git a/RELEASE b/RELEASE
index ee94dd8..b60d719 100644
--- a/RELEASE
+++ b/RELEASE
@@ -1 +1 @@
-0.8.3
+0.8.4
diff --git a/VERSION b/VERSION
index ee94dd8..b60d719 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.8.3
+0.8.4
diff --git a/avconv.c b/avconv.c
index dcc0935..34507d4 100644
--- a/avconv.c
+++ b/avconv.c
@@ -226,6 +226,7 @@ typedef struct OutputStream {
     int64_t *forced_kf_pts;
     int forced_kf_count;
     int forced_kf_index;
+    char *forced_keyframes;
 
     /* audio only */
     int audio_resample;
@@ -454,7 +455,7 @@ static int alloc_buffer(InputStream *ist, FrameBuffer **pbuf)
         const int v_shift = i==0 ? 0 : v_chroma_shift;
         if (s->flags & CODEC_FLAG_EMU_EDGE)
             buf->data[i] = buf->base[i];
-        else
+        else if (buf->base[i])
             buf->data[i] = buf->base[i] +
                            FFALIGN((buf->linesize[i]*edge >> v_shift) +
                                    (pixel_size*edge >> h_shift), 32);
@@ -687,6 +688,7 @@ void exit_program(int ret)
             av_freep(&frame);
         }
 
+        av_freep(&output_streams[i].forced_keyframes);
 #if CONFIG_AVFILTER
         av_freep(&output_streams[i].avfilter);
 #endif
@@ -2229,6 +2231,37 @@ static int init_input_stream(int ist_index, OutputStream *output_streams, int nb
     return 0;
 }
 
+static void parse_forced_key_frames(char *kf, OutputStream *ost,
+                                    AVCodecContext *avctx)
+{
+    char *p;
+    int n = 1, i;
+    int64_t t;
+
+    for (p = kf; *p; p++)
+        if (*p == ',')
+            n++;
+    ost->forced_kf_count = n;
+    ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
+    if (!ost->forced_kf_pts) {
+        av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
+        exit_program(1);
+    }
+
+    p = kf;
+    for (i = 0; i < n; i++) {
+        char *next = strchr(p, ',');
+
+        if (next)
+            *next++ = 0;
+
+        t = parse_time_or_die("force_key_frames", p, 1);
+        ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
+
+        p = next;
+    }
+}
+
 static int transcode_init(OutputFile *output_files,
                           int nb_output_files,
                           InputFile *input_files,
@@ -2444,6 +2477,9 @@ static int transcode_init(OutputFile *output_files,
                     exit(1);
                 }
 #endif
+                if (ost->forced_keyframes)
+                    parse_forced_key_frames(ost->forced_keyframes, ost,
+                                            ost->st->codec);
                 break;
             case AVMEDIA_TYPE_SUBTITLE:
                 break;
@@ -3362,29 +3398,6 @@ static int opt_input_file(OptionsContext *o, const char *opt, const char *filena
     return 0;
 }
 
-static void parse_forced_key_frames(char *kf, OutputStream *ost,
-                                    AVCodecContext *avctx)
-{
-    char *p;
-    int n = 1, i;
-    int64_t t;
-
-    for (p = kf; *p; p++)
-        if (*p == ',')
-            n++;
-    ost->forced_kf_count = n;
-    ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
-    if (!ost->forced_kf_pts) {
-        av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
-        exit_program(1);
-    }
-    for (i = 0; i < n; i++) {
-        p = i ? strchr(p, ',') + 1 : kf;
-        t = parse_time_or_die("force_key_frames", p, 1);
-        ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
-    }
-}
-
 static uint8_t *get_line(AVIOContext *s)
 {
     AVIOContext *line;
@@ -3576,7 +3589,7 @@ static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
 
     if (!ost->stream_copy) {
         const char *p = NULL;
-        char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
+        char *frame_rate = NULL, *frame_size = NULL;
         char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
         char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
         int i;
@@ -3659,9 +3672,9 @@ static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
             }
         }
 
-        MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
-        if (forced_key_frames)
-            parse_forced_key_frames(forced_key_frames, ost, video_enc);
+        MATCH_PER_STREAM_OPT(forced_key_frames, str, ost->forced_keyframes, oc, st);
+        if (ost->forced_keyframes)
+            ost->forced_keyframes = av_strdup(ost->forced_keyframes);
 
         MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
 
diff --git a/libavcodec/4xm.c b/libavcodec/4xm.c
index 52edc99..0d4f036 100644
--- a/libavcodec/4xm.c
+++ b/libavcodec/4xm.c
@@ -866,7 +866,7 @@ static av_cold int decode_end(AVCodecContext *avctx){
         av_freep(&f->cfrm[i].data);
         f->cfrm[i].allocated_size= 0;
     }
-    free_vlc(&f->pre_vlc);
+    ff_free_vlc(&f->pre_vlc);
     if(f->current_picture.data[0])
         avctx->release_buffer(avctx, &f->current_picture);
     if(f->last_picture.data[0])
diff --git a/libavcodec/ac3dec.c b/libavcodec/ac3dec.c
index fdc1d68..28a783a 100644
--- a/libavcodec/ac3dec.c
+++ b/libavcodec/ac3dec.c
@@ -1404,6 +1404,7 @@ static int ac3_decode_frame(AVCodecContext * avctx, void *data,
         avctx->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
 
     /* get output buffer */
+    avctx->channels = s->out_channels;
     s->frame.nb_samples = s->num_blocks * 256;
     if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
diff --git a/libavcodec/alsdec.c b/libavcodec/alsdec.c
index 26496bf..459e2af 100644
--- a/libavcodec/alsdec.c
+++ b/libavcodec/alsdec.c
@@ -651,6 +651,11 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
         for (k = 1; k < sub_blocks; k++)
             s[k] = s[k - 1] + decode_rice(gb, 0);
     }
+    for (k = 1; k < sub_blocks; k++)
+        if (s[k] > 32) {
+            av_log(avctx, AV_LOG_ERROR, "k invalid for rice code.\n");
+            return AVERROR_INVALIDDATA;
+        }
 
     if (get_bits1(gb))
         *bd->shift_lsbs = get_bits(gb, 4) + 1;
@@ -663,6 +668,11 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
             int opt_order_length = av_ceil_log2(av_clip((bd->block_length >> 3) - 1,
                                                 2, sconf->max_order + 1));
             *bd->opt_order       = get_bits(gb, opt_order_length);
+            if (*bd->opt_order > sconf->max_order) {
+                *bd->opt_order = sconf->max_order;
+                av_log(avctx, AV_LOG_ERROR, "Predictor order too large!\n");
+                return AVERROR_INVALIDDATA;
+            }
         } else {
             *bd->opt_order = sconf->max_order;
         }
@@ -695,6 +705,10 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
                     int rice_param = parcor_rice_table[sconf->coef_table][k][1];
                     int offset     = parcor_rice_table[sconf->coef_table][k][0];
                     quant_cof[k] = decode_rice(gb, rice_param) + offset;
+                    if (quant_cof[k] < -64 || quant_cof[k] > 63) {
+                        av_log(avctx, AV_LOG_ERROR, "quant_cof %d is out of range\n", quant_cof[k]);
+                        return AVERROR_INVALIDDATA;
+                    }
                 }
 
                 // read coefficients 20 to 126
@@ -727,7 +741,7 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
             bd->ltp_gain[0]   = decode_rice(gb, 1) << 3;
             bd->ltp_gain[1]   = decode_rice(gb, 2) << 3;
 
-            r                 = get_unary(gb, 0, 4);
+            r                 = get_unary(gb, 0, 3);
             c                 = get_bits(gb, 2);
             bd->ltp_gain[2]   = ltp_gain_values[r][c];
 
@@ -756,7 +770,6 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
         int          delta[8];
         unsigned int k    [8];
         unsigned int b = av_clip((av_ceil_log2(bd->block_length) - 3) >> 1, 0, 5);
-        unsigned int i = start;
 
         // read most significant bits
         unsigned int high;
@@ -767,29 +780,30 @@ static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
 
         current_res = bd->raw_samples + start;
 
-        for (sb = 0; sb < sub_blocks; sb++, i = 0) {
+        for (sb = 0; sb < sub_blocks; sb++) {
+            unsigned int sb_len  = sb_length - (sb ? 0 : start);
+
             k    [sb] = s[sb] > b ? s[sb] - b : 0;
             delta[sb] = 5 - s[sb] + k[sb];
 
-            ff_bgmc_decode(gb, sb_length, current_res,
+            ff_bgmc_decode(gb, sb_len, current_res,
                         delta[sb], sx[sb], &high, &low, &value, ctx->bgmc_lut, ctx->bgmc_lut_status);
 
-            current_res += sb_length;
+            current_res += sb_len;
         }
 
         ff_bgmc_decode_end(gb);
 
 
         // read least significant bits and tails
-        i = start;
         current_res = bd->raw_samples + start;
 
-        for (sb = 0; sb < sub_blocks; sb++, i = 0) {
+        for (sb = 0; sb < sub_blocks; sb++, start = 0) {
             unsigned int cur_tail_code = tail_code[sx[sb]][delta[sb]];
             unsigned int cur_k         = k[sb];
             unsigned int cur_s         = s[sb];
 
-            for (; i < sb_length; i++) {
+            for (; start < sb_length; start++) {
                 int32_t res = *current_res;
 
                 if (res == cur_tail_code) {
diff --git a/libavcodec/avs.c b/libavcodec/avs.c
index b3cd5b1..0ce190a 100644
--- a/libavcodec/avs.c
+++ b/libavcodec/avs.c
@@ -158,6 +158,7 @@ avs_decode_frame(AVCodecContext * avctx,
 static av_cold int avs_decode_init(AVCodecContext * avctx)
 {
     avctx->pix_fmt = PIX_FMT_PAL8;
+    avcodec_set_dimensions(avctx, 318, 198);
     return 0;
 }
 
diff --git a/libavcodec/bitstream.c b/libavcodec/bitstream.c
index 14e392f..7fe38be 100644
--- a/libavcodec/bitstream.c
+++ b/libavcodec/bitstream.c
@@ -253,9 +253,9 @@ static int build_table(VLC *vlc, int table_nb_bits, int nb_codes,
    (byte/word/long) to store the 'bits', 'codes', and 'symbols' tables.
 
    'use_static' should be set to 1 for tables, which should be freed
-   with av_free_static(), 0 if free_vlc() will be used.
+   with av_free_static(), 0 if ff_free_vlc() will be used.
 */
-int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
+int ff_init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
              const void *bits, int bits_wrap, int bits_size,
              const void *codes, int codes_wrap, int codes_size,
              const void *symbols, int symbols_wrap, int symbols_size,
@@ -318,7 +318,7 @@ int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
 }
 
 
-void free_vlc(VLC *vlc)
+void ff_free_vlc(VLC *vlc)
 {
     av_freep(&vlc->table);
 }
diff --git a/libavcodec/bmp.c b/libavcodec/bmp.c
index 1f725f5..974db49 100644
--- a/libavcodec/bmp.c
+++ b/libavcodec/bmp.c
@@ -227,9 +227,6 @@ static int bmp_decode_frame(AVCodecContext *avctx,
     if(comp == BMP_RLE4 || comp == BMP_RLE8)
         memset(p->data[0], 0, avctx->height * p->linesize[0]);
 
-    if(depth == 4 || depth == 8)
-        memset(p->data[1], 0, 1024);
-
     if(height > 0){
         ptr = p->data[0] + (avctx->height - 1) * p->linesize[0];
         linesize = -p->linesize[0];
@@ -240,6 +237,9 @@ static int bmp_decode_frame(AVCodecContext *avctx,
 
     if(avctx->pix_fmt == PIX_FMT_PAL8){
         int colors = 1 << depth;
+
+        memset(p->data[1], 0, 1024);
+
         if(ihsize >= 36){
             int t;
             buf = buf0 + 46;
diff --git a/libavcodec/cavsdec.c b/libavcodec/cavsdec.c
index b0e517b..1dd237a 100644
--- a/libavcodec/cavsdec.c
+++ b/libavcodec/cavsdec.c
@@ -608,12 +608,21 @@ static int decode_pic(AVSContext *h) {
 static int decode_seq_header(AVSContext *h) {
     MpegEncContext *s = &h->s;
     int frame_rate_code;
+    int width, height;
 
     h->profile =         get_bits(&s->gb,8);
     h->level =           get_bits(&s->gb,8);
     skip_bits1(&s->gb); //progressive sequence
-    s->width =           get_bits(&s->gb,14);
-    s->height =          get_bits(&s->gb,14);
+
+    width  = get_bits(&s->gb, 14);
+    height = get_bits(&s->gb, 14);
+    if ((s->width || s->height) && (s->width != width || s->height != height)) {
+        av_log_missing_feature(s, "Width/height changing in CAVS is", 0);
+        return AVERROR_PATCHWELCOME;
+    }
+    s->width  = width;
+    s->height = height;
+
     skip_bits(&s->gb,2); //chroma format
     skip_bits(&s->gb,3); //sample_precision
     h->aspect_ratio =    get_bits(&s->gb,4);
diff --git a/libavcodec/cook.c b/libavcodec/cook.c
index a835442..7437852 100644
--- a/libavcodec/cook.c
+++ b/libavcodec/cook.c
@@ -321,11 +321,11 @@ static av_cold int cook_decode_close(AVCodecContext *avctx)
 
     /* Free the VLC tables. */
     for (i = 0; i < 13; i++)
-        free_vlc(&q->envelope_quant_index[i]);
+        ff_free_vlc(&q->envelope_quant_index[i]);
     for (i = 0; i < 7; i++)
-        free_vlc(&q->sqvh[i]);
+        ff_free_vlc(&q->sqvh[i]);
     for (i = 0; i < q->num_subpackets; i++)
-        free_vlc(&q->subpacket[i].ccpl);
+        ff_free_vlc(&q->subpacket[i].ccpl);
 
     av_log(avctx, AV_LOG_DEBUG, "Memory deallocated.\n");
 
diff --git a/libavcodec/dfa.c b/libavcodec/dfa.c
index 08bb2a4..c2f8002 100644
--- a/libavcodec/dfa.c
+++ b/libavcodec/dfa.c
@@ -21,8 +21,9 @@
  */
 
 #include "avcodec.h"
-#include "libavutil/intreadwrite.h"
 #include "bytestream.h"
+
+#include "libavutil/imgutils.h"
 #include "libavutil/lzo.h" // for av_memcpy_backptr
 
 typedef struct DfaContext {
@@ -35,9 +36,13 @@ typedef struct DfaContext {
 static av_cold int dfa_decode_init(AVCodecContext *avctx)
 {
     DfaContext *s = avctx->priv_data;
+    int ret;
 
     avctx->pix_fmt = PIX_FMT_PAL8;
 
+    if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)
+        return ret;
+
     s->frame_buf = av_mallocz(avctx->width * avctx->height + AV_LZO_OUTPUT_PADDING);
     if (!s->frame_buf)
         return AVERROR(ENOMEM);
@@ -45,19 +50,16 @@ static av_cold int dfa_decode_init(AVCodecContext *avctx)
     return 0;
 }
 
-static int decode_copy(uint8_t *frame, int width, int height,
-                       const uint8_t *src, const uint8_t *src_end)
+static int decode_copy(GetByteContext *gb, uint8_t *frame, int width, int height)
 {
     const int size = width * height;
 
-    if (src_end - src < size)
-        return -1;
-    bytestream_get_buffer(&src, frame, size);
+    if (bytestream2_get_buffer(gb, frame, size) != size)
+        return AVERROR_INVALIDDATA;
     return 0;
 }
 
-static int decode_tsw1(uint8_t *frame, int width, int height,
-                       const uint8_t *src, const uint8_t *src_end)
+static int decode_tsw1(GetByteContext *gb, uint8_t *frame, int width, int height)
 {
     const uint8_t *frame_start = frame;
     const uint8_t *frame_end   = frame + width * height;
@@ -65,31 +67,31 @@ static int decode_tsw1(uint8_t *frame, int width, int height,
     int v, count, segments;
     unsigned offset;
 
-    segments = bytestream_get_le32(&src);
-    offset   = bytestream_get_le32(&src);
+    segments = bytestream2_get_le32(gb);
+    offset   = bytestream2_get_le32(gb);
     if (frame_end - frame <= offset)
-        return -1;
+        return AVERROR_INVALIDDATA;
     frame += offset;
     while (segments--) {
+        if (bytestream2_get_bytes_left(gb) < 2)
+            return AVERROR_INVALIDDATA;
         if (mask == 0x10000) {
-            if (src >= src_end)
-                return -1;
-            bitbuf = bytestream_get_le16(&src);
+            bitbuf = bytestream2_get_le16u(gb);
             mask = 1;
         }
-        if (src_end - src < 2 || frame_end - frame < 2)
-            return -1;
+        if (frame_end - frame < 2)
+            return AVERROR_INVALIDDATA;
         if (bitbuf & mask) {
-            v = bytestream_get_le16(&src);
+            v = bytestream2_get_le16(gb);
             offset = (v & 0x1FFF) << 1;
             count = ((v >> 13) + 2) << 1;
             if (frame - frame_start < offset || frame_end - frame < count)
-                return -1;
+                return AVERROR_INVALIDDATA;
             av_memcpy_backptr(frame, offset, count);
             frame += count;
         } else {
-            *frame++ = *src++;
-            *frame++ = *src++;
+            *frame++ = bytestream2_get_byte(gb);
+            *frame++ = bytestream2_get_byte(gb);
         }
         mask <<= 1;
     }
@@ -97,39 +99,38 @@ static int decode_tsw1(uint8_t *frame, int width, int height,
     return 0;
 }
 
-static int decode_dsw1(uint8_t *frame, int width, int height,
-                       const uint8_t *src, const uint8_t *src_end)
+static int decode_dsw1(GetByteContext *gb, uint8_t *frame, int width, int height)
 {
     const uint8_t *frame_start = frame;
     const uint8_t *frame_end   = frame + width * height;
     int mask = 0x10000, bitbuf = 0;
     int v, offset, count, segments;
 
-    segments = bytestream_get_le16(&src);
+    segments = bytestream2_get_le16(gb);
     while (segments--) {
+        if (bytestream2_get_bytes_left(gb) < 2)
+            return AVERROR_INVALIDDATA;
         if (mask == 0x10000) {
-            if (src >= src_end)
-                return -1;
-            bitbuf = bytestream_get_le16(&src);
+            bitbuf = bytestream2_get_le16u(gb);
             mask = 1;
         }
-        if (src_end - src < 2 || frame_end - frame < 2)
-            return -1;
+        if (frame_end - frame < 2)
+            return AVERROR_INVALIDDATA;
         if (bitbuf & mask) {
-            v = bytestream_get_le16(&src);
+            v = bytestream2_get_le16(gb);
             offset = (v & 0x1FFF) << 1;
             count = ((v >> 13) + 2) << 1;
             if (frame - frame_start < offset || frame_end - frame < count)
-                return -1;
+                return AVERROR_INVALIDDATA;
             // can't use av_memcpy_backptr() since it can overwrite following pixels
             for (v = 0; v < count; v++)
                 frame[v] = frame[v - offset];
             frame += count;
         } else if (bitbuf & (mask << 1)) {
-            frame += bytestream_get_le16(&src);
+            frame += bytestream2_get_le16(gb);
         } else {
-            *frame++ = *src++;
-            *frame++ = *src++;
+            *frame++ = bytestream2_get_byte(gb);
+            *frame++ = bytestream2_get_byte(gb);
         }
         mask <<= 2;
     }
@@ -137,30 +138,28 @@ static int decode_dsw1(uint8_t *frame, int width, int height,
     return 0;
 }
 
-static int decode_dds1(uint8_t *frame, int width, int height,
-                       const uint8_t *src, const uint8_t *src_end)
+static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height)
 {
     const uint8_t *frame_start = frame;
     const uint8_t *frame_end   = frame + width * height;
     int mask = 0x10000, bitbuf = 0;
     int i, v, offset, count, segments;
 
-    segments = bytestream_get_le16(&src);
+    segments = bytestream2_get_le16(gb);
     while (segments--) {
+        if (bytestream2_get_bytes_left(gb) < 2)
+            return AVERROR_INVALIDDATA;
         if (mask == 0x10000) {
-            if (src >= src_end)
-                return -1;
-            bitbuf = bytestream_get_le16(&src);
+            bitbuf = bytestream2_get_le16u(gb);
             mask = 1;
         }
-        if (src_end - src < 2 || frame_end - frame < 2)
-            return -1;
+
         if (bitbuf & mask) {
-            v = bytestream_get_le16(&src);
+            v = bytestream2_get_le16(gb);
             offset = (v & 0x1FFF) << 2;
             count = ((v >> 13) + 2) << 1;
             if (frame - frame_start < offset || frame_end - frame < count*2 + width)
-                return -1;
+                return AVERROR_INVALIDDATA;
             for (i = 0; i < count; i++) {
                 frame[0] = frame[1] =
                 frame[width] = frame[width + 1] = frame[-offset];
@@ -168,13 +167,18 @@ static int decode_dds1(uint8_t *frame, int width, int height,
                 frame += 2;
             }
         } else if (bitbuf & (mask << 1)) {
-            frame += bytestream_get_le16(&src) * 2;
+            v = bytestream2_get_le16(gb)*2;
+            if (frame - frame_end < v)
+                return AVERROR_INVALIDDATA;
+            frame += v;
         } else {
+            if (frame_end - frame < width + 3)
+                return AVERROR_INVALIDDATA;
             frame[0] = frame[1] =
-            frame[width] = frame[width + 1] =  *src++;
+            frame[width] = frame[width + 1] =  bytestream2_get_byte(gb);
             frame += 2;
             frame[0] = frame[1] =
-            frame[width] = frame[width + 1] =  *src++;
+            frame[width] = frame[width + 1] =  bytestream2_get_byte(gb);
             frame += 2;
         }
         mask <<= 2;
@@ -183,40 +187,40 @@ static int decode_dds1(uint8_t *frame, int width, int height,
     return 0;
 }
 
-static int decode_bdlt(uint8_t *frame, int width, int height,
-                       const uint8_t *src, const uint8_t *src_end)
+static int decode_bdlt(GetByteContext *gb, uint8_t *frame, int width, int height)
 {
     uint8_t *line_ptr;
     int count, lines, segments;
 
-    count = bytestream_get_le16(&src);
+    count = bytestream2_get_le16(gb);
     if (count >= height)
-        return -1;
+        return AVERROR_INVALIDDATA;
     frame += width * count;
-    lines = bytestream_get_le16(&src);
-    if (count + lines > height || src >= src_end)
-        return -1;
+    lines = bytestream2_get_le16(gb);
+    if (count + lines > height)
+        return AVERROR_INVALIDDATA;
 
     while (lines--) {
+        if (bytestream2_get_bytes_left(gb) < 1)
+            return AVERROR_INVALIDDATA;
         line_ptr = frame;
         frame += width;
-        segments = *src++;
+        segments = bytestream2_get_byteu(gb);
         while (segments--) {
-            if (src_end - src < 3)
-                return -1;
-            if (frame - line_ptr <= *src)
-                return -1;
-            line_ptr += *src++;
-            count = (int8_t)*src++;
+            if (frame - line_ptr <= bytestream2_peek_byte(gb))
+                return AVERROR_INVALIDDATA;
+            line_ptr += bytestream2_get_byte(gb);
+            count = (int8_t)bytestream2_get_byte(gb);
             if (count >= 0) {
-                if (frame - line_ptr < count || src_end - src < count)
-                    return -1;
-                bytestream_get_buffer(&src, line_ptr, count);
+                if (frame - line_ptr < count)
+                    return AVERROR_INVALIDDATA;
+                if (bytestream2_get_buffer(gb, line_ptr, count) != count)
+                    return AVERROR_INVALIDDATA;
             } else {
                 count = -count;
-                if (frame - line_ptr < count || src >= src_end)
-                    return -1;
-                memset(line_ptr, *src++, count);
+                if (frame - line_ptr < count)
+                    return AVERROR_INVALIDDATA;
+                memset(line_ptr, bytestream2_get_byte(gb), count);
             }
             line_ptr += count;
         }
@@ -225,49 +229,53 @@ static int decode_bdlt(uint8_t *frame, int width, int height,
     return 0;
 }
 
-static int decode_wdlt(uint8_t *frame, int width, int height,
-                       const uint8_t *src, const uint8_t *src_end)
+static int decode_wdlt(GetByteContext *gb, uint8_t *frame, int width, int height)
 {
     const uint8_t *frame_end   = frame + width * height;
     uint8_t *line_ptr;
     int count, i, v, lines, segments;
+    int y = 0;
 
-    lines = bytestream_get_le16(&src);
-    if (lines > height || src >= src_end)
-        return -1;
+    lines = bytestream2_get_le16(gb);
+    if (lines > height)
+        return AVERROR_INVALIDDATA;
 
     while (lines--) {
-        segments = bytestream_get_le16(&src);
+        if (bytestream2_get_bytes_left(gb) < 2)
+            return AVERROR_INVALIDDATA;
+        segments = bytestream2_get_le16u(gb);
         while ((segments & 0xC000) == 0xC000) {
+            unsigned skip_lines = -(int16_t)segments;
             unsigned delta = -((int16_t)segments * width);
-            if (frame_end - frame <= delta)
-                return -1;
+            if (frame_end - frame <= delta || y + lines + skip_lines > height)
+                return AVERROR_INVALIDDATA;
             frame    += delta;
-            segments = bytestream_get_le16(&src);
+            y        += skip_lines;
+            segments = bytestream2_get_le16(gb);
         }
         if (segments & 0x8000) {
             frame[width - 1] = segments & 0xFF;
-            segments = bytestream_get_le16(&src);
+            segments = bytestream2_get_le16(gb);
         }
         line_ptr = frame;
         frame += width;
+        y++;
         while (segments--) {
-            if (src_end - src < 2)
-                return -1;
-            if (frame - line_ptr <= *src)
-                return -1;
-            line_ptr += *src++;
-            count = (int8_t)*src++;
+            if (frame - line_ptr <= bytestream2_peek_byte(gb))
+                return AVERROR_INVALIDDATA;
+            line_ptr += bytestream2_get_byte(gb);
+            count = (int8_t)bytestream2_get_byte(gb);
             if (count >= 0) {
-                if (frame - line_ptr < count*2 || src_end - src < count*2)
-                    return -1;
-                bytestream_get_buffer(&src, line_ptr, count*2);
+                if (frame - line_ptr < count * 2)
+                    return AVERROR_INVALIDDATA;
+                if (bytestream2_get_buffer(gb, line_ptr, count * 2) != count * 2)
+                    return AVERROR_INVALIDDATA;
                 line_ptr += count * 2;
             } else {
                 count = -count;
-                if (frame - line_ptr < count*2 || src_end - src < 2)
-                    return -1;
-                v = bytestream_get_le16(&src);
+                if (frame - line_ptr < count * 2)
+                    return AVERROR_INVALIDDATA;
+                v = bytestream2_get_le16(gb);
                 for (i = 0; i < count; i++)
                     bytestream_put_le16(&line_ptr, v);
             }
@@ -277,22 +285,19 @@ static int decode_wdlt(uint8_t *frame, int width, int height,
     return 0;
 }
 
-static int decode_unk6(uint8_t *frame, int width, int height,
-                       const uint8_t *src, const uint8_t *src_end)
+static int decode_unk6(GetByteContext *gb, uint8_t *frame, int width, int height)
 {
-    return -1;
+    return AVERROR_PATCHWELCOME;
 }
 
-static int decode_blck(uint8_t *frame, int width, int height,
-                       const uint8_t *src, const uint8_t *src_end)
+static int decode_blck(GetByteContext *gb, uint8_t *frame, int width, int height)
 {
     memset(frame, 0, width * height);
     return 0;
 }
 
 
-typedef int (*chunk_decoder)(uint8_t *frame, int width, int height,
-                             const uint8_t *src, const uint8_t *src_end);
+typedef int (*chunk_decoder)(GetByteContext *gb, uint8_t *frame, int width, int height);
 
 static const chunk_decoder decoder[8] = {
     decode_copy, decode_tsw1, decode_bdlt, decode_wdlt,
@@ -308,9 +313,8 @@ static int dfa_decode_frame(AVCodecContext *avctx,
                             AVPacket *avpkt)
 {
     DfaContext *s = avctx->priv_data;
+    GetByteContext gb;
     const uint8_t *buf = avpkt->data;
-    const uint8_t *buf_end = avpkt->data + avpkt->size;
-    const uint8_t *tmp_buf;
     uint32_t chunk_type, chunk_size;
     uint8_t *dst;
     int ret;
@@ -324,30 +328,25 @@ static int dfa_decode_frame(AVCodecContext *avctx,
         return ret;
     }
 
-    while (buf < buf_end) {
-        chunk_size = AV_RL32(buf + 4);
-        chunk_type = AV_RL32(buf + 8);
-        buf += 12;
-        if (buf_end - buf < chunk_size) {
-            av_log(avctx, AV_LOG_ERROR, "Chunk size is too big (%d bytes)\n", chunk_size);
-            return -1;
-        }
+    bytestream2_init(&gb, avpkt->data, avpkt->size);
+    while (bytestream2_get_bytes_left(&gb) > 0) {
+        bytestream2_skip(&gb, 4);
+        chunk_size = bytestream2_get_le32(&gb);
+        chunk_type = bytestream2_get_le32(&gb);
         if (!chunk_type)
             break;
         if (chunk_type == 1) {
             pal_elems = FFMIN(chunk_size / 3, 256);
-            tmp_buf = buf;
             for (i = 0; i < pal_elems; i++) {
-                s->pal[i] = bytestream_get_be24(&tmp_buf) << 2;
+                s->pal[i] = bytestream2_get_be24(&gb) << 2;
                 s->pal[i] |= (s->pal[i] >> 6) & 0x333;
             }
             s->pic.palette_has_changed = 1;
         } else if (chunk_type <= 9) {
-            if (decoder[chunk_type - 2](s->frame_buf, avctx->width, avctx->height,
-                                        buf, buf + chunk_size)) {
+            if (decoder[chunk_type - 2](&gb, s->frame_buf, avctx->width, avctx->height)) {
                 av_log(avctx, AV_LOG_ERROR, "Error decoding %s chunk\n",
                        chunk_name[chunk_type - 2]);
-                return -1;
+                return AVERROR_INVALIDDATA;
             }
         } else {
             av_log(avctx, AV_LOG_WARNING, "Ignoring unknown chunk type %d\n",
diff --git a/libavcodec/dnxhddec.c b/libavcodec/dnxhddec.c
index 956196c..bf5acf3 100644
--- a/libavcodec/dnxhddec.c
+++ b/libavcodec/dnxhddec.c
@@ -79,9 +79,9 @@ static int dnxhd_init_vlc(DNXHDContext *ctx, int cid)
         }
         ctx->cid_table = &ff_dnxhd_cid_table[index];
 
-        free_vlc(&ctx->ac_vlc);
-        free_vlc(&ctx->dc_vlc);
-        free_vlc(&ctx->run_vlc);
+        ff_free_vlc(&ctx->ac_vlc);
+        ff_free_vlc(&ctx->dc_vlc);
+        ff_free_vlc(&ctx->run_vlc);
 
         init_vlc(&ctx->ac_vlc, DNXHD_VLC_BITS, 257,
                  ctx->cid_table->ac_bits, 1, 1,
@@ -391,9 +391,9 @@ static av_cold int dnxhd_decode_close(AVCodecContext *avctx)
 
     if (ctx->picture.data[0])
         avctx->release_buffer(avctx, &ctx->picture);
-    free_vlc(&ctx->ac_vlc);
-    free_vlc(&ctx->dc_vlc);
-    free_vlc(&ctx->run_vlc);
+    ff_free_vlc(&ctx->ac_vlc);
+    ff_free_vlc(&ctx->dc_vlc);
+    ff_free_vlc(&ctx->run_vlc);
     return 0;
 }
 
diff --git a/libavcodec/dv.c b/libavcodec/dv.c
index 74cbffb..03a05b3 100644
--- a/libavcodec/dv.c
+++ b/libavcodec/dv.c
@@ -312,7 +312,7 @@ static av_cold int dvvideo_init(AVCodecContext *avctx)
             dv_rl_vlc[i].level = level;
             dv_rl_vlc[i].run   = run;
         }
-        free_vlc(&dv_vlc);
+        ff_free_vlc(&dv_vlc);
 
         dv_vlc_map_tableinit();
     }
diff --git a/libavcodec/faxcompr.c b/libavcodec/faxcompr.c
index e59dad6..a0fa825 100644
--- a/libavcodec/faxcompr.c
+++ b/libavcodec/faxcompr.c
@@ -110,11 +110,11 @@ av_cold void ff_ccitt_unpack_init(void)
     ccitt_vlc[1].table = code_table2;
     ccitt_vlc[1].table_allocated = 648;
     for(i = 0; i < 2; i++){
-        init_vlc_sparse(&ccitt_vlc[i], 9, CCITT_SYMS,
-                        ccitt_codes_lens[i], 1, 1,
-                        ccitt_codes_bits[i], 1, 1,
-                        ccitt_syms, 2, 2,
-                        INIT_VLC_USE_NEW_STATIC);
+        ff_init_vlc_sparse(&ccitt_vlc[i], 9, CCITT_SYMS,
+                           ccitt_codes_lens[i], 1, 1,
+                           ccitt_codes_bits[i], 1, 1,
+                           ccitt_syms, 2, 2,
+                           INIT_VLC_USE_NEW_STATIC);
     }
     INIT_VLC_STATIC(&ccitt_group3_2d_vlc, 9, 11,
                     ccitt_group3_2d_lens, 1, 1,
diff --git a/libavcodec/fraps.c b/libavcodec/fraps.c
index d887cde..4d03057 100644
--- a/libavcodec/fraps.c
+++ b/libavcodec/fraps.c
@@ -112,13 +112,13 @@ static int fraps2_decode_plane(FrapsContext *s, uint8_t *dst, int stride, int w,
             if(j) dst[i] += dst[i - stride];
             else if(Uoff) dst[i] += 0x80;
             if (get_bits_left(&gb) < 0) {
-                free_vlc(&vlc);
+                ff_free_vlc(&vlc);
                 return AVERROR_INVALIDDATA;
             }
         }
         dst += stride;
     }
-    free_vlc(&vlc);
+    ff_free_vlc(&vlc);
     return 0;
 }
 
diff --git a/libavcodec/get_bits.h b/libavcodec/get_bits.h
index ee47441..64393bc 100644
--- a/libavcodec/get_bits.h
+++ b/libavcodec/get_bits.h
@@ -377,19 +377,19 @@ static inline void align_get_bits(GetBitContext *s)
                  bits, bits_wrap, bits_size,            \
                  codes, codes_wrap, codes_size,         \
                  flags)                                 \
-        init_vlc_sparse(vlc, nb_bits, nb_codes,         \
-                        bits, bits_wrap, bits_size,     \
-                        codes, codes_wrap, codes_size,  \
-                        NULL, 0, 0, flags)
+        ff_init_vlc_sparse(vlc, nb_bits, nb_codes,         \
+                           bits, bits_wrap, bits_size,     \
+                           codes, codes_wrap, codes_size,  \
+                           NULL, 0, 0, flags)
 
-int init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
+int ff_init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,
              const void *bits, int bits_wrap, int bits_size,
              const void *codes, int codes_wrap, int codes_size,
              const void *symbols, int symbols_wrap, int symbols_size,
              int flags);
 #define INIT_VLC_LE         2
 #define INIT_VLC_USE_NEW_STATIC 4
-void free_vlc(VLC *vlc);
+void ff_free_vlc(VLC *vlc);
 
 #define INIT_VLC_STATIC(vlc, bits, a,b,c,d,e,f,g, static_size) do {     \
         static VLC_TYPE table[static_size][2];                          \
diff --git a/libavcodec/golomb.h b/libavcodec/golomb.h
index 1712540..b6b8cc8 100644
--- a/libavcodec/golomb.h
+++ b/libavcodec/golomb.h
@@ -301,7 +301,7 @@ static inline int get_ur_golomb_jpegls(GetBitContext *gb, int k, int limit, int
         return buf;
     }else{
         int i;
-        for (i = 0; i < limit && SHOW_UBITS(re, gb, 1) == 0; i++) {
+        for (i = 0; i < limit && SHOW_UBITS(re, gb, 1) == 0 && HAVE_BITS_REMAINING(re, gb); i++) {
             LAST_SKIP_BITS(re, gb, 1);
             UPDATE_CACHE(re, gb);
         }
diff --git a/libavcodec/h261dec.c b/libavcodec/h261dec.c
index 0be0134..665cc0d 100644
--- a/libavcodec/h261dec.c
+++ b/libavcodec/h261dec.c
@@ -66,7 +66,7 @@ static av_cold void h261_decode_init_vlc(H261Context *h){
         INIT_VLC_STATIC(&h261_cbp_vlc, H261_CBP_VLC_BITS, 63,
                  &h261_cbp_tab[0][1], 2, 1,
                  &h261_cbp_tab[0][0], 2, 1, 512);
-        init_rl(&h261_rl_tcoeff, ff_h261_rl_table_store);
+        ff_init_rl(&h261_rl_tcoeff, ff_h261_rl_table_store);
         INIT_VLC_RL(h261_rl_tcoeff, 552);
     }
 }
diff --git a/libavcodec/h261enc.c b/libavcodec/h261enc.c
index c758ec0..ee37fe3 100644
--- a/libavcodec/h261enc.c
+++ b/libavcodec/h261enc.c
@@ -240,7 +240,7 @@ void ff_h261_encode_init(MpegEncContext *s){
 
     if (!done) {
         done = 1;
-        init_rl(&h261_rl_tcoeff, ff_h261_rl_table_store);
+        ff_init_rl(&h261_rl_tcoeff, ff_h261_rl_table_store);
     }
 
     s->min_qcoeff= -127;
diff --git a/libavcodec/h263.c b/libavcodec/h263.c
index 77a1bb8..7f1966f 100644
--- a/libavcodec/h263.c
+++ b/libavcodec/h263.c
@@ -98,7 +98,7 @@ void ff_h263_update_motion_val(MpegEncContext * s){
     }
 }
 
-int h263_pred_dc(MpegEncContext * s, int n, int16_t **dc_val_ptr)
+int ff_h263_pred_dc(MpegEncContext * s, int n, int16_t **dc_val_ptr)
 {
     int x, y, wrap, a, c, pred_dc;
     int16_t *dc_val;
@@ -226,7 +226,7 @@ void ff_h263_loop_filter(MpegEncContext * s){
     }
 }
 
-void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
+void ff_h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
 {
     int x, y, wrap, a, c, pred_dc, scale, i;
     int16_t *dc_val, *ac_val, *ac_val1;
@@ -313,8 +313,8 @@ void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n)
         ac_val1[8 + i] = block[s->dsp.idct_permutation[i   ]];
 }
 
-int16_t *h263_pred_motion(MpegEncContext * s, int block, int dir,
-                        int *px, int *py)
+int16_t *ff_h263_pred_motion(MpegEncContext * s, int block, int dir,
+                             int *px, int *py)
 {
     int wrap;
     int16_t *A, *B, *C, (*mot_val)[2];
diff --git a/libavcodec/h263.h b/libavcodec/h263.h
index 73c5966..d26cf63 100644
--- a/libavcodec/h263.h
+++ b/libavcodec/h263.h
@@ -38,16 +38,16 @@
 extern const AVRational ff_h263_pixel_aspect[16];
 extern const uint8_t ff_h263_cbpy_tab[16][2];
 
-extern const uint8_t cbpc_b_tab[4][2];
+extern const uint8_t ff_cbpc_b_tab[4][2];
 
-extern const uint8_t mvtab[33][2];
+extern const uint8_t ff_mvtab[33][2];
 
 extern const uint8_t ff_h263_intra_MCBPC_code[9];
 extern const uint8_t ff_h263_intra_MCBPC_bits[9];
 
 extern const uint8_t ff_h263_inter_MCBPC_code[28];
 extern const uint8_t ff_h263_inter_MCBPC_bits[28];
-extern const uint8_t h263_mbtype_b_tab[15][2];
+extern const uint8_t ff_h263_mbtype_b_tab[15][2];
 
 extern VLC ff_h263_intra_MCBPC_vlc;
 extern VLC ff_h263_inter_MCBPC_vlc;
@@ -55,41 +55,41 @@ extern VLC ff_h263_cbpy_vlc;
 
 extern RLTable ff_h263_rl_inter;
 
-extern RLTable rl_intra_aic;
+extern RLTable ff_rl_intra_aic;
 
-extern const uint16_t h263_format[8][2];
-extern const uint8_t modified_quant_tab[2][32];
+extern const uint16_t ff_h263_format[8][2];
+extern const uint8_t ff_modified_quant_tab[2][32];
 extern uint16_t ff_mba_max[6];
 extern uint8_t ff_mba_length[7];
 
 extern uint8_t ff_h263_static_rl_table_store[2][2][2*MAX_RUN + MAX_LEVEL + 3];
 
 
-int h263_decode_motion(MpegEncContext * s, int pred, int f_code);
+int ff_h263_decode_motion(MpegEncContext * s, int pred, int f_code);
 av_const int ff_h263_aspect_to_info(AVRational aspect);
 int ff_h263_decode_init(AVCodecContext *avctx);
 int ff_h263_decode_frame(AVCodecContext *avctx,
                              void *data, int *data_size,
                              AVPacket *avpkt);
 int ff_h263_decode_end(AVCodecContext *avctx);
-void h263_encode_mb(MpegEncContext *s,
-                    DCTELEM block[6][64],
-                    int motion_x, int motion_y);
-void h263_encode_picture_header(MpegEncContext *s, int picture_number);
-void h263_encode_gob_header(MpegEncContext * s, int mb_line);
-int16_t *h263_pred_motion(MpegEncContext * s, int block, int dir,
-                        int *px, int *py);
-void h263_encode_init(MpegEncContext *s);
-void h263_decode_init_vlc(MpegEncContext *s);
-int h263_decode_picture_header(MpegEncContext *s);
+void ff_h263_encode_mb(MpegEncContext *s,
+                       DCTELEM block[6][64],
+                       int motion_x, int motion_y);
+void ff_h263_encode_picture_header(MpegEncContext *s, int picture_number);
+void ff_h263_encode_gob_header(MpegEncContext * s, int mb_line);
+int16_t *ff_h263_pred_motion(MpegEncContext * s, int block, int dir,
+                             int *px, int *py);
+void ff_h263_encode_init(MpegEncContext *s);
+void ff_h263_decode_init_vlc(MpegEncContext *s);
+int ff_h263_decode_picture_header(MpegEncContext *s);
 int ff_h263_decode_gob_header(MpegEncContext *s);
 void ff_h263_update_motion_val(MpegEncContext * s);
 void ff_h263_loop_filter(MpegEncContext * s);
 int ff_h263_decode_mba(MpegEncContext *s);
 void ff_h263_encode_mba(MpegEncContext *s);
 void ff_init_qscale_tab(MpegEncContext *s);
-int h263_pred_dc(MpegEncContext * s, int n, int16_t **dc_val_ptr);
-void h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n);
+int ff_h263_pred_dc(MpegEncContext * s, int n, int16_t **dc_val_ptr);
+void ff_h263_pred_acdc(MpegEncContext * s, DCTELEM *block, int n);
 
 
 /**
@@ -119,7 +119,7 @@ static inline int h263_get_motion_length(MpegEncContext * s, int val, int f_code
     int l, bit_size, code;
 
     if (val == 0) {
-        return mvtab[0][1];
+        return ff_mvtab[0][1];
     } else {
         bit_size = f_code - 1;
         /* modulo encoding */
@@ -128,7 +128,7 @@ static inline int h263_get_motion_length(MpegEncContext * s, int val, int f_code
         val--;
         code = (val >> bit_size) + 1;
 
-        return mvtab[code][1] + 1 + bit_size;
+        return ff_mvtab[code][1] + 1 + bit_size;
     }
 }
 
diff --git a/libavcodec/h263data.h b/libavcodec/h263data.h
index 966da56..e3b83ad 100644
--- a/libavcodec/h263data.h
+++ b/libavcodec/h263data.h
@@ -57,7 +57,7 @@ const uint8_t ff_h263_inter_MCBPC_bits[28] = {
     11, 13, 13, 13,/* inter4Q*/
 };
 
-const uint8_t h263_mbtype_b_tab[15][2] = {
+const uint8_t ff_h263_mbtype_b_tab[15][2] = {
  {1, 1},
  {3, 3},
  {1, 5},
@@ -75,7 +75,7 @@ const uint8_t h263_mbtype_b_tab[15][2] = {
  {1, 8},
 };
 
-const uint8_t cbpc_b_tab[4][2] = {
+const uint8_t ff_cbpc_b_tab[4][2] = {
 {0, 1},
 {2, 2},
 {7, 3},
@@ -88,7 +88,7 @@ const uint8_t ff_h263_cbpy_tab[16][2] =
   {2,5}, {3,6}, {5,4}, {10,4}, {4,4}, {8,4}, {6,4}, {3,2}
 };
 
-const uint8_t mvtab[33][2] =
+const uint8_t ff_mvtab[33][2] =
 {
   {1,1}, {1,2}, {1,3}, {1,4}, {3,6}, {5,7}, {4,7}, {3,7},
   {11,9}, {10,9}, {9,9}, {17,10}, {16,10}, {15,10}, {14,10}, {13,10},
@@ -98,7 +98,7 @@ const uint8_t mvtab[33][2] =
 };
 
 /* third non intra table */
-const uint16_t inter_vlc[103][2] = {
+const uint16_t ff_inter_vlc[103][2] = {
 { 0x2, 2 },{ 0xf, 4 },{ 0x15, 6 },{ 0x17, 7 },
 { 0x1f, 8 },{ 0x25, 9 },{ 0x24, 9 },{ 0x21, 10 },
 { 0x20, 10 },{ 0x7, 11 },{ 0x6, 11 },{ 0x20, 11 },
@@ -127,7 +127,7 @@ const uint16_t inter_vlc[103][2] = {
 { 0x5e, 12 },{ 0x5f, 12 },{ 0x3, 7 },
 };
 
-const int8_t inter_level[102] = {
+const int8_t ff_inter_level[102] = {
   1,  2,  3,  4,  5,  6,  7,  8,
   9, 10, 11, 12,  1,  2,  3,  4,
   5,  6,  1,  2,  3,  4,  1,  2,
@@ -143,7 +143,7 @@ const int8_t inter_level[102] = {
   1,  1,  1,  1,  1,  1,
 };
 
-const int8_t inter_run[102] = {
+const int8_t ff_inter_run[102] = {
   0,  0,  0,  0,  0,  0,  0,  0,
   0,  0,  0,  0,  1,  1,  1,  1,
   1,  1,  2,  2,  2,  2,  3,  3,
@@ -162,9 +162,9 @@ const int8_t inter_run[102] = {
 RLTable ff_h263_rl_inter = {
     102,
     58,
-    inter_vlc,
-    inter_run,
-    inter_level,
+    ff_inter_vlc,
+    ff_inter_run,
+    ff_inter_level,
 };
 
 static const uint16_t intra_vlc_aic[103][2] = {
@@ -228,7 +228,7 @@ static const int8_t intra_level_aic[102] = {
  1,  1,  1,  1,  1,  1,
 };
 
-RLTable rl_intra_aic = {
+RLTable ff_rl_intra_aic = {
     102,
     58,
     intra_vlc_aic,
@@ -236,7 +236,7 @@ RLTable rl_intra_aic = {
     intra_level_aic,
 };
 
-const uint16_t h263_format[8][2] = {
+const uint16_t ff_h263_format[8][2] = {
     { 0, 0 },
     { 128, 96 },
     { 176, 144 },
@@ -250,7 +250,7 @@ const uint8_t ff_aic_dc_scale_table[32]={
     0, 2, 4, 6, 8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62
 };
 
-const uint8_t modified_quant_tab[2][32]={
+const uint8_t ff_modified_quant_tab[2][32]={
 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 {
     0, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9,10,11,12,13,14,15,16,17,18,18,19,20,21,22,23,24,25,26,27,28
diff --git a/libavcodec/h263dec.c b/libavcodec/h263dec.c
index 1ddca19..a675e6e 100644
--- a/libavcodec/h263dec.c
+++ b/libavcodec/h263dec.c
@@ -113,7 +113,7 @@ av_cold int ff_h263_decode_init(AVCodecContext *avctx)
         if (MPV_common_init(s) < 0)
             return -1;
 
-        h263_decode_init_vlc(s);
+        ff_h263_decode_init_vlc(s);
 
     return 0;
 }
@@ -421,7 +421,7 @@ retry:
     } else if (CONFIG_FLV_DECODER && s->h263_flv) {
         ret = ff_flv_decode_picture_header(s);
     } else {
-        ret = h263_decode_picture_header(s);
+        ret = ff_h263_decode_picture_header(s);
     }
 
     if(ret==FRAME_SKIPPED) return get_consumed_bytes(s, buf_size);
diff --git a/libavcodec/h264.c b/libavcodec/h264.c
index b229510..d8d0a7d 100644
--- a/libavcodec/h264.c
+++ b/libavcodec/h264.c
@@ -2522,8 +2522,8 @@ static int field_end(H264Context *h, int in_setup){
     s->mb_y= 0;
 
     if (!in_setup && !s->dropable)
-        ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
-                                 s->picture_structure==PICT_BOTTOM_FIELD);
+        ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
+                                  s->picture_structure == PICT_BOTTOM_FIELD);
 
     if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
         ff_vdpau_h264_set_reference_frames(s);
@@ -2640,9 +2640,7 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
     int num_ref_idx_active_override_flag;
     unsigned int slice_type, tmp, i, j;
     int default_ref_list_done = 0;
-    int last_pic_structure;
-
-    s->dropable= h->nal_ref_idc == 0;
+    int last_pic_structure, last_pic_dropable;
 
     /* FIXME: 2tap qpel isn't implemented for high bit depth. */
     if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc && !h->pixel_shift){
@@ -2661,8 +2659,14 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
         }
 
         h0->current_slice = 0;
-        if (!s0->first_field)
-            s->current_picture_ptr= NULL;
+        if (!s0->first_field) {
+            if (s->current_picture_ptr && !s->dropable &&
+                s->current_picture_ptr->owner2 == s) {
+                ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
+                                          s->picture_structure == PICT_BOTTOM_FIELD);
+            }
+            s->current_picture_ptr = NULL;
+        }
     }
 
     slice_type= get_ue_golomb_31(&s->gb);
@@ -2720,6 +2724,12 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
     else
         s->height= 16*s->mb_height - (2<<s->chroma_y_shift)*FFMIN(h->sps.crop_bottom, (16>>s->chroma_y_shift)-1);
 
+    if (FFALIGN(s->avctx->width,  16) == s->width &&
+        FFALIGN(s->avctx->height, 16) == s->height) {
+        s->width  = s->avctx->width;
+        s->height = s->avctx->height;
+    }
+
     if (s->context_initialized
         && (   s->width != s->avctx->width || s->height != s->avctx->height
             || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
@@ -2856,6 +2866,8 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
     h->mb_mbaff = 0;
     h->mb_aff_frame = 0;
     last_pic_structure = s0->picture_structure;
+    last_pic_dropable  = s->dropable;
+    s->dropable        = h->nal_ref_idc == 0;
     if(h->sps.frame_mbs_only_flag){
         s->picture_structure= PICT_FRAME;
     }else{
@@ -2868,10 +2880,22 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
     }
     h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
 
-    if(h0->current_slice == 0){
-        // Shorten frame num gaps so we don't have to allocate reference frames just to throw them away
-        if(h->frame_num != h->prev_frame_num) {
-            int unwrap_prev_frame_num = h->prev_frame_num, max_frame_num = 1<<h->sps.log2_max_frame_num;
+    if (h0->current_slice != 0) {
+        if (last_pic_structure != s->picture_structure ||
+            last_pic_dropable  != s->dropable) {
+            av_log(h->s.avctx, AV_LOG_ERROR,
+                   "Changing field mode (%d -> %d) between slices is not allowed\n",
+                   last_pic_structure, s->picture_structure);
+            s->picture_structure = last_pic_structure;
+            s->dropable          = last_pic_dropable;
+            return AVERROR_INVALIDDATA;
+        }
+    } else {
+        /* Shorten frame num gaps so we don't have to allocate reference
+         * frames just to throw them away */
+        if (h->frame_num != h->prev_frame_num) {
+            int unwrap_prev_frame_num = h->prev_frame_num;
+            int max_frame_num         = 1 << h->sps.log2_max_frame_num;
 
             if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num;
 
@@ -2884,8 +2908,74 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
             }
         }
 
-        while(h->frame_num !=  h->prev_frame_num &&
-              h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
+        /* See if we have a decoded first field looking for a pair...
+         * Here, we're using that to see if we should mark previously
+         * decode frames as "finished".
+         * We have to do that before the "dummy" in-between frame allocation,
+         * since that can modify s->current_picture_ptr. */
+        if (s0->first_field) {
+            assert(s0->current_picture_ptr);
+            assert(s0->current_picture_ptr->f.data[0]);
+            assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
+
+            /* Mark old field/frame as completed */
+            if (!last_pic_dropable && s0->current_picture_ptr->owner2 == s0) {
+                ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
+                                          last_pic_structure == PICT_BOTTOM_FIELD);
+            }
+
+            /* figure out if we have a complementary field pair */
+            if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
+                /* Previous field is unmatched. Don't display it, but let it
+                 * remain for reference if marked as such. */
+                if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
+                    ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
+                                              last_pic_structure == PICT_TOP_FIELD);
+                }
+            } else {
+                if (s0->current_picture_ptr->frame_num != h->frame_num) {
+                    /* This and previous field were reference, but had
+                     * different frame_nums. Consider this field first in
+                     * pair. Throw away previous field except for reference
+                     * purposes. */
+                    if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
+                        ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
+                                                  last_pic_structure == PICT_TOP_FIELD);
+                    }
+                } else {
+                    /* Second field in complementary pair */
+                    if (!((last_pic_structure   == PICT_TOP_FIELD &&
+                           s->picture_structure == PICT_BOTTOM_FIELD) ||
+                          (last_pic_structure   == PICT_BOTTOM_FIELD &&
+                           s->picture_structure == PICT_TOP_FIELD))) {
+                        av_log(s->avctx, AV_LOG_ERROR,
+                               "Invalid field mode combination %d/%d\n",
+                               last_pic_structure, s->picture_structure);
+                        s->picture_structure = last_pic_structure;
+                        s->dropable          = last_pic_dropable;
+                        return AVERROR_INVALIDDATA;
+                    } else if (last_pic_dropable != s->dropable) {
+                        av_log(s->avctx, AV_LOG_ERROR,
+                               "Cannot combine reference and non-reference fields in the same frame\n");
+                        av_log_ask_for_sample(s->avctx, NULL);
+                        s->picture_structure = last_pic_structure;
+                        s->dropable          = last_pic_dropable;
+                        return AVERROR_INVALIDDATA;
+                    }
+
+                    /* Take ownership of this buffer. Note that if another thread owned
+                     * the first field of this buffer, we're not operating on that pointer,
+                     * so the original thread is still responsible for reporting progress
+                     * on that first field (or if that was us, we just did that above).
+                     * By taking ownership, we assign responsibility to ourselves to
+                     * report progress on the second field. */
+                    s0->current_picture_ptr->owner2 = s0;
+                }
+            }
+        }
+
+        while (h->frame_num != h->prev_frame_num &&
+               h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
             Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
             av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
             if (ff_h264_frame_start(h) < 0)
@@ -2916,7 +3006,9 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
             }
         }
 
-        /* See if we have a decoded first field looking for a pair... */
+        /* See if we have a decoded first field looking for a pair...
+         * We're using that to see whether to continue decoding in that
+         * frame, or to allocate a new one. */
         if (s0->first_field) {
             assert(s0->current_picture_ptr);
             assert(s0->current_picture_ptr->f.data[0]);
@@ -2932,16 +3024,11 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
                 s0->first_field = FIELD_PICTURE;
 
             } else {
-                if (h->nal_ref_idc &&
-                        s0->current_picture_ptr->f.reference &&
-                        s0->current_picture_ptr->frame_num != h->frame_num) {
-                    /*
-                     * This and previous field were reference, but had
-                     * different frame_nums. Consider this field first in
-                     * pair. Throw away previous field except for reference
-                     * purposes.
-                     */
-                    s0->first_field = 1;
+                if (s0->current_picture_ptr->frame_num != h->frame_num) {
+                    /* This and the previous field had different frame_nums.
+                     * Consider this field first in pair. Throw away previous
+                     * one except for reference purposes. */
+                    s0->first_field         = 1;
                     s0->current_picture_ptr = NULL;
 
                 } else {
@@ -3788,7 +3875,11 @@ static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
                     break;
             }
 
-            if(buf_index+3 >= buf_size) break;
+
+            if (buf_index + 3 >= buf_size) {
+                buf_index = buf_size;
+                break;
+            }
 
             buf_index+=3;
             if(buf_index >= next_avc) continue;
@@ -3797,8 +3888,9 @@ static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
         hx = h->thread_context[context_count];
 
         ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
-        if (ptr==NULL || dst_length < 0){
-            return -1;
+        if (ptr == NULL || dst_length < 0) {
+            buf_index = -1;
+            goto end;
         }
         i= buf_index + consumed;
         if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
@@ -3850,7 +3942,8 @@ static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
         case NAL_IDR_SLICE:
             if (h->nal_unit_type != NAL_IDR_SLICE) {
                 av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
-                return -1;
+                buf_index = -1;
+                goto end;
             }
             idr(h); // FIXME ensure we don't lose some frames if there is reordering
         case NAL_SLICE:
@@ -3956,7 +4049,8 @@ static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
                     dsputil_init(&s->dsp, s->avctx);
                 } else {
                     av_log(avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
-                    return -1;
+                    buf_index = -1;
+                    goto end;
                 }
             }
             break;
@@ -3998,6 +4092,15 @@ static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
     }
     if(context_count)
         execute_decode_slices(h, context_count);
+
+end:
+    /* clean up */
+    if (s->current_picture_ptr && s->current_picture_ptr->owner2 == s &&
+        !s->dropable) {
+        ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
+                                  s->picture_structure == PICT_BOTTOM_FIELD);
+    }
+
     return buf_index;
 }
 
diff --git a/libavcodec/huffman.c b/libavcodec/huffman.c
index 4fb6530..9446332 100644
--- a/libavcodec/huffman.c
+++ b/libavcodec/huffman.c
@@ -61,7 +61,7 @@ static int build_huff_tree(VLC *vlc, Node *nodes, int head, int flags)
     int pos = 0;
 
     get_tree_codes(bits, lens, xlat, nodes, head, 0, 0, &pos, no_zero_count);
-    return init_vlc_sparse(vlc, 9, pos, lens, 2, 2, bits, 4, 4, xlat, 1, 1, 0);
+    return ff_init_vlc_sparse(vlc, 9, pos, lens, 2, 2, bits, 4, 4, xlat, 1, 1, 0);
 }
 
 
diff --git a/libavcodec/huffyuv.c b/libavcodec/huffyuv.c
index a173a13..f9e101d 100644
--- a/libavcodec/huffyuv.c
+++ b/libavcodec/huffyuv.c
@@ -296,8 +296,8 @@ static void generate_joint_tables(HYuvContext *s){
                         i++;
                 }
             }
-            free_vlc(&s->vlc[3+p]);
-            init_vlc_sparse(&s->vlc[3+p], VLC_BITS, i, len, 1, 1, bits, 2, 2, symbols, 2, 2, 0);
+            ff_free_vlc(&s->vlc[3+p]);
+            ff_init_vlc_sparse(&s->vlc[3+p], VLC_BITS, i, len, 1, 1, bits, 2, 2, symbols, 2, 2, 0);
         }
     }else{
         uint8_t (*map)[4] = (uint8_t(*)[4])s->pix_bgr_map;
@@ -337,7 +337,7 @@ static void generate_joint_tables(HYuvContext *s){
                 }
             }
         }
-        free_vlc(&s->vlc[3]);
+        ff_free_vlc(&s->vlc[3]);
         init_vlc(&s->vlc[3], VLC_BITS, i, len, 1, 1, bits, 2, 2, 0);
     }
 }
@@ -354,7 +354,7 @@ static int read_huffman_tables(HYuvContext *s, const uint8_t *src, int length){
         if(generate_bits_table(s->bits[i], s->len[i])<0){
             return -1;
         }
-        free_vlc(&s->vlc[i]);
+        ff_free_vlc(&s->vlc[i]);
         init_vlc(&s->vlc[i], VLC_BITS, 256, s->len[i], 1, 1, s->bits[i], 4, 4, 0);
     }
 
@@ -386,7 +386,7 @@ static int read_old_huffman_tables(HYuvContext *s){
     memcpy(s->len[2] , s->len [1], 256*sizeof(uint8_t));
 
     for(i=0; i<3; i++){
-        free_vlc(&s->vlc[i]);
+        ff_free_vlc(&s->vlc[i]);
         init_vlc(&s->vlc[i], VLC_BITS, 256, s->len[i], 1, 1, s->bits[i], 4, 4, 0);
     }
 
@@ -1220,7 +1220,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     av_freep(&s->bitstream_buffer);
 
     for(i=0; i<6; i++){
-        free_vlc(&s->vlc[i]);
+        ff_free_vlc(&s->vlc[i]);
     }
 
     return 0;
diff --git a/libavcodec/imgconvert.c b/libavcodec/imgconvert.c
index eab051b..1dfe3b7 100644
--- a/libavcodec/imgconvert.c
+++ b/libavcodec/imgconvert.c
@@ -612,7 +612,8 @@ static enum PixelFormat avcodec_find_best_pix_fmt1(int64_t pix_fmt_mask,
     /* find exact color match with smallest size */
     dst_pix_fmt = PIX_FMT_NONE;
     min_dist = 0x7fffffff;
-    for(i = 0;i < PIX_FMT_NB; i++) {
+    /* test only the first 64 pixel formats to avoid undefined behaviour */
+    for (i = 0; i < 64; i++) {
         if (pix_fmt_mask & (1ULL << i)) {
             loss = avcodec_get_pix_fmt_loss(i, src_pix_fmt, has_alpha) & loss_mask;
             if (loss == 0) {
diff --git a/libavcodec/indeo3.c b/libavcodec/indeo3.c
index 55b4ec7..294527e 100644
--- a/libavcodec/indeo3.c
+++ b/libavcodec/indeo3.c
@@ -416,6 +416,9 @@ static int decode_cell_data(Cell *cell, uint8_t *block, uint8_t *ref_block,
     blk_row_offset = (row_offset << (2 + v_zoom)) - (cell->width << 2);
     line_offset    = v_zoom ? row_offset : 0;
 
+    if (cell->height & v_zoom || cell->width & h_zoom)
+        return IV3_BAD_DATA;
+
     for (y = 0; y < cell->height; is_first_row = 0, y += 1 + v_zoom) {
         for (x = 0; x < cell->width; x += 1 + h_zoom) {
             ref = ref_block;
@@ -895,6 +898,14 @@ static int decode_frame_headers(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
 
         av_dlog(avctx, "Frame dimensions changed!\n");
 
+        if (width  < 16 || width  > 640 ||
+            height < 16 || height > 480 ||
+            width  &  3 || height &   3) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "Invalid picture dimensions: %d x %d!\n", width, height);
+            return AVERROR_INVALIDDATA;
+        }
+
         ctx->width  = width;
         ctx->height = height;
 
diff --git a/libavcodec/indeo4.c b/libavcodec/indeo4.c
index 3e8a398..c8ee0be 100644
--- a/libavcodec/indeo4.c
+++ b/libavcodec/indeo4.c
@@ -35,9 +35,6 @@
 #include "ivi_common.h"
 #include "indeo4data.h"
 
-#define IVI4_STREAM_ANALYSER    0
-#define IVI4_DEBUG_CHECKSUM     0
-
 /**
  *  Indeo 4 frame types.
  */
@@ -54,46 +51,6 @@ enum {
 #define IVI4_PIC_SIZE_ESC   7
 
 
-typedef struct {
-    GetBitContext   gb;
-    AVFrame         frame;
-    RVMapDesc       rvmap_tabs[9];   ///< local corrected copy of the static rvmap tables
-
-    uint32_t        frame_num;
-    int             frame_type;
-    int             prev_frame_type; ///< frame type of the previous frame
-    uint32_t        data_size;       ///< size of the frame data in bytes from picture header
-    int             is_scalable;
-    int             transp_status;   ///< transparency mode status: 1 - enabled
-
-    IVIPicConfig    pic_conf;
-    IVIPlaneDesc    planes[3];       ///< color planes
-
-    int             buf_switch;      ///< used to switch between three buffers
-    int             dst_buf;         ///< buffer index for the currently decoded frame
-    int             ref_buf;         ///< inter frame reference buffer index
-
-    IVIHuffTab      mb_vlc;          ///< current macroblock table descriptor
-    IVIHuffTab      blk_vlc;         ///< current block table descriptor
-
-    uint16_t        checksum;        ///< frame checksum
-
-    uint8_t         rvmap_sel;
-    uint8_t         in_imf;
-    uint8_t         in_q;            ///< flag for explicitly stored quantiser delta
-    uint8_t         pic_glob_quant;
-    uint8_t         unknown1;
-
-#if IVI4_STREAM_ANALYSER
-    uint8_t         has_b_frames;
-    uint8_t         has_transp;
-    uint8_t         uses_tiling;
-    uint8_t         uses_haar;
-    uint8_t         uses_fullpel;
-#endif
-} IVI4DecContext;
-
-
 static const struct {
     InvTransformPtr *inv_trans;
     DCTransformPtr  *dc_trans;
@@ -158,7 +115,7 @@ static inline int scale_tile_size(int def_size, int size_factor)
  *  @param[in]     avctx     pointer to the AVCodecContext
  *  @return        result code: 0 = OK, negative number = error
  */
-static int decode_pic_hdr(IVI4DecContext *ctx, AVCodecContext *avctx)
+static int decode_pic_hdr(IVI45DecContext *ctx, AVCodecContext *avctx)
 {
     int             pic_size_indx, i, p;
     IVIPicConfig    pic_conf;
@@ -322,7 +279,7 @@ static int decode_pic_hdr(IVI4DecContext *ctx, AVCodecContext *avctx)
  *  @param[in]     avctx     pointer to the AVCodecContext
  *  @return        result code: 0 = OK, negative number = error
  */
-static int decode_band_hdr(IVI4DecContext *ctx, IVIBandDesc *band,
+static int decode_band_hdr(IVI45DecContext *ctx, IVIBandDesc *band,
                            AVCodecContext *avctx)
 {
     int plane, band_num, indx, transform_id, scan_indx;
@@ -458,7 +415,7 @@ static int decode_band_hdr(IVI4DecContext *ctx, IVIBandDesc *band,
  *  @param[in]     avctx     pointer to the AVCodecContext
  *  @return        result code: 0 = OK, negative number = error
  */
-static int decode_mb_info(IVI4DecContext *ctx, IVIBandDesc *band,
+static int decode_mb_info(IVI45DecContext *ctx, IVIBandDesc *band,
                           IVITile *tile, AVCodecContext *avctx)
 {
     int         x, y, mv_x, mv_y, mv_delta, offs, mb_offset, blks_per_mb,
@@ -574,125 +531,11 @@ static int decode_mb_info(IVI4DecContext *ctx, IVIBandDesc *band,
 
 
 /**
- *  Decode an Indeo 4 band.
- *
- *  @param[in,out] ctx       pointer to the decoder context
- *  @param[in,out] band      pointer to the band descriptor
- *  @param[in]     avctx     pointer to the AVCodecContext
- *  @return        result code: 0 = OK, negative number = error
- */
-static int decode_band(IVI4DecContext *ctx, int plane_num,
-                       IVIBandDesc *band, AVCodecContext *avctx)
-{
-    int         result, i, t, pos, idx1, idx2;
-    IVITile     *tile;
-
-    band->buf     = band->bufs[ctx->dst_buf];
-    band->ref_buf = band->bufs[ctx->ref_buf];
-
-    result = decode_band_hdr(ctx, band, avctx);
-    if (result) {
-        av_log(avctx, AV_LOG_ERROR, "Error decoding band header\n");
-        return result;
-    }
-
-    if (band->is_empty) {
-        av_log(avctx, AV_LOG_ERROR, "Empty band encountered!\n");
-        return AVERROR_INVALIDDATA;
-    }
-
-    band->rv_map = &ctx->rvmap_tabs[band->rvmap_sel];
-
-    /* apply corrections to the selected rvmap table if present */
-    for (i = 0; i < band->num_corr; i++) {
-        idx1 = band->corr[i * 2];
-        idx2 = band->corr[i * 2 + 1];
-        FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);
-        FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);
-    }
-
-    pos = get_bits_count(&ctx->gb);
-
-    for (t = 0; t < band->num_tiles; t++) {
-        tile = &band->tiles[t];
-
-        tile->is_empty = get_bits1(&ctx->gb);
-        if (tile->is_empty) {
-            ff_ivi_process_empty_tile(avctx, band, tile,
-                                      (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3));
-            av_dlog(avctx, "Empty tile encountered!\n");
-        } else {
-            tile->data_size = ff_ivi_dec_tile_data_size(&ctx->gb);
-            if (!tile->data_size) {
-                av_log(avctx, AV_LOG_ERROR, "Tile data size is zero!\n");
-                return AVERROR_INVALIDDATA;
-            }
-
-            result = decode_mb_info(ctx, band, tile, avctx);
-            if (result < 0)
-                break;
-
-            result = ff_ivi_decode_blocks(&ctx->gb, band, tile);
-            if (result < 0 || ((get_bits_count(&ctx->gb) - pos) >> 3) != tile->data_size) {
-                av_log(avctx, AV_LOG_ERROR, "Corrupted tile data encountered!\n");
-                break;
-            }
-
-            pos += tile->data_size << 3; // skip to next tile
-        }
-    }
-
-    /* restore the selected rvmap table by applying its corrections in reverse order */
-    for (i = band->num_corr - 1; i >= 0; i--) {
-        idx1 = band->corr[i * 2];
-        idx2 = band->corr[i * 2 + 1];
-        FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);
-        FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);
-    }
-
-#if defined(DEBUG) && IVI4_DEBUG_CHECKSUM
-    if (band->checksum_present) {
-        uint16_t chksum = ivi_calc_band_checksum(band);
-        if (chksum != band->checksum) {
-            av_log(avctx, AV_LOG_ERROR,
-                   "Band checksum mismatch! Plane %d, band %d, received: %x, calculated: %x\n",
-                   band->plane, band->band_num, band->checksum, chksum);
-        }
-    }
-#endif
-
-    align_get_bits(&ctx->gb);
-
-    return 0;
-}
-
-
-static av_cold int decode_init(AVCodecContext *avctx)
-{
-    IVI4DecContext *ctx = avctx->priv_data;
-
-    ff_ivi_init_static_vlc();
-
-    /* copy rvmap tables in our context so we can apply changes to them */
-    memcpy(ctx->rvmap_tabs, ff_ivi_rvmap_tabs, sizeof(ff_ivi_rvmap_tabs));
-
-    /* Force allocation of the internal buffers */
-    /* during picture header decoding.          */
-    ctx->pic_conf.pic_width  = 0;
-    ctx->pic_conf.pic_height = 0;
-
-    avctx->pix_fmt = PIX_FMT_YUV410P;
-
-    return 0;
-}
-
-
-/**
  *  Rearrange decoding and reference buffers.
  *
  *  @param[in,out] ctx       pointer to the decoder context
  */
-static void switch_buffers(IVI4DecContext *ctx)
+static void switch_buffers(IVI45DecContext *ctx)
 {
     switch (ctx->prev_frame_type) {
     case FRAMETYPE_INTRA:
@@ -721,95 +564,33 @@ static void switch_buffers(IVI4DecContext *ctx)
 }
 
 
-static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
-                        AVPacket *avpkt)
+static int is_nonnull_frame(IVI45DecContext *ctx)
 {
-    IVI4DecContext  *ctx = avctx->priv_data;
-    const uint8_t   *buf = avpkt->data;
-    int             buf_size = avpkt->size;
-    int             result, p, b;
-
-    init_get_bits(&ctx->gb, buf, buf_size * 8);
-
-    result = decode_pic_hdr(ctx, avctx);
-    if (result) {
-        av_log(avctx, AV_LOG_ERROR, "Error decoding picture header\n");
-        return result;
-    }
-
-    switch_buffers(ctx);
-
-    if (ctx->frame_type < FRAMETYPE_NULL_FIRST) {
-        for (p = 0; p < 3; p++) {
-            for (b = 0; b < ctx->planes[p].num_bands; b++) {
-                result = decode_band(ctx, p, &ctx->planes[p].bands[b], avctx);
-                if (result) {
-                    av_log(avctx, AV_LOG_ERROR,
-                           "Error decoding band: %d, plane: %d\n", b, p);
-                    return result;
-                }
-            }
-        }
-    }
-
-    /* If the bidirectional mode is enabled, next I and the following P frame will */
-    /* be sent together. Unfortunately the approach below seems to be the only way */
-    /* to handle the B-frames mode. That's exactly the same Intel decoders do.     */
-    if (ctx->frame_type == FRAMETYPE_INTRA) {
-        while (get_bits(&ctx->gb, 8)); // skip version string
-        skip_bits_long(&ctx->gb, 64);  // skip padding, TODO: implement correct 8-bytes alignment
-        if (get_bits_left(&ctx->gb) > 18 && show_bits(&ctx->gb, 18) == 0x3FFF8)
-            av_log(avctx, AV_LOG_ERROR, "Buffer contains IP frames!\n");
-    }
-
-    if (ctx->frame.data[0])
-        avctx->release_buffer(avctx, &ctx->frame);
-
-    ctx->frame.reference = 0;
-    if ((result = avctx->get_buffer(avctx, &ctx->frame)) < 0) {
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return result;
-    }
-
-    if (ctx->is_scalable) {
-        ff_ivi_recompose_haar(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0], 4);
-    } else {
-        ff_ivi_output_plane(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0]);
-    }
-
-    ff_ivi_output_plane(&ctx->planes[2], ctx->frame.data[1], ctx->frame.linesize[1]);
-    ff_ivi_output_plane(&ctx->planes[1], ctx->frame.data[2], ctx->frame.linesize[2]);
-
-    *data_size = sizeof(AVFrame);
-    *(AVFrame*)data = ctx->frame;
-
-    return buf_size;
+    return ctx->frame_type < FRAMETYPE_NULL_FIRST;
 }
 
 
-static av_cold int decode_close(AVCodecContext *avctx)
+static av_cold int decode_init(AVCodecContext *avctx)
 {
-    IVI4DecContext *ctx = avctx->priv_data;
+    IVI45DecContext *ctx = avctx->priv_data;
 
-    ff_ivi_free_buffers(&ctx->planes[0]);
+    ff_ivi_init_static_vlc();
 
-    if (ctx->frame.data[0])
-        avctx->release_buffer(avctx, &ctx->frame);
+    /* copy rvmap tables in our context so we can apply changes to them */
+    memcpy(ctx->rvmap_tabs, ff_ivi_rvmap_tabs, sizeof(ff_ivi_rvmap_tabs));
 
-#if IVI4_STREAM_ANALYSER
-    if (ctx->is_scalable)
-        av_log(avctx, AV_LOG_ERROR, "This video uses scalability mode!\n");
-    if (ctx->uses_tiling)
-        av_log(avctx, AV_LOG_ERROR, "This video uses local decoding!\n");
-    if (ctx->has_b_frames)
-        av_log(avctx, AV_LOG_ERROR, "This video contains B-frames!\n");
-    if (ctx->has_transp)
-        av_log(avctx, AV_LOG_ERROR, "Transparency mode is enabled!\n");
-    if (ctx->uses_haar)
-        av_log(avctx, AV_LOG_ERROR, "This video uses Haar transform!\n");
-    if (ctx->uses_fullpel)
-        av_log(avctx, AV_LOG_ERROR, "This video uses fullpel motion vectors!\n");
-#endif
+    /* Force allocation of the internal buffers */
+    /* during picture header decoding.          */
+    ctx->pic_conf.pic_width  = 0;
+    ctx->pic_conf.pic_height = 0;
+
+    avctx->pix_fmt = PIX_FMT_YUV410P;
+
+    ctx->decode_pic_hdr   = decode_pic_hdr;
+    ctx->decode_band_hdr  = decode_band_hdr;
+    ctx->decode_mb_info   = decode_mb_info;
+    ctx->switch_buffers   = switch_buffers;
+    ctx->is_nonnull_frame = is_nonnull_frame;
 
     return 0;
 }
@@ -819,9 +600,9 @@ AVCodec ff_indeo4_decoder = {
     .name           = "indeo4",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_INDEO4,
-    .priv_data_size = sizeof(IVI4DecContext),
+    .priv_data_size = sizeof(IVI45DecContext),
     .init           = decode_init,
-    .close          = decode_close,
-    .decode         = decode_frame,
+    .close          = ff_ivi_decode_close,
+    .decode         = ff_ivi_decode_frame,
     .long_name      = NULL_IF_CONFIG_SMALL("Intel Indeo Video Interactive 4"),
 };
diff --git a/libavcodec/indeo5.c b/libavcodec/indeo5.c
index 019fa2b..987b1a3 100644
--- a/libavcodec/indeo5.c
+++ b/libavcodec/indeo5.c
@@ -48,37 +48,6 @@ enum {
 
 #define IVI5_PIC_SIZE_ESC       15
 
-#define IVI5_IS_PROTECTED       0x20
-
-typedef struct {
-    GetBitContext   gb;
-    AVFrame         frame;
-    RVMapDesc       rvmap_tabs[9];   ///< local corrected copy of the static rvmap tables
-    IVIPlaneDesc    planes[3];       ///< color planes
-    const uint8_t   *frame_data;     ///< input frame data pointer
-    int             buf_switch;      ///< used to switch between three buffers
-    int             inter_scal;      ///< signals a sequence of scalable inter frames
-    int             dst_buf;         ///< buffer index for the currently decoded frame
-    int             ref_buf;         ///< inter frame reference buffer index
-    int             ref2_buf;        ///< temporal storage for switching buffers
-    uint32_t        frame_size;      ///< frame size in bytes
-    int             frame_type;
-    int             prev_frame_type; ///< frame type of the previous frame
-    int             frame_num;
-    uint32_t        pic_hdr_size;    ///< picture header size in bytes
-    uint8_t         frame_flags;
-    uint16_t        checksum;        ///< frame checksum
-
-    IVIHuffTab      mb_vlc;          ///< vlc table for decoding macroblock data
-
-    uint16_t        gop_hdr_size;
-    uint8_t         gop_flags;
-    int             is_scalable;
-    uint32_t        lock_word;
-    IVIPicConfig    pic_conf;
-} IVI5DecContext;
-
-
 /**
  *  Decode Indeo5 GOP (Group of pictures) header.
  *  This header is present in key frames only.
@@ -88,7 +57,7 @@ typedef struct {
  *  @param[in]     avctx  ptr to the AVCodecContext
  *  @return         result code: 0 = OK, -1 = error
  */
-static int decode_gop_header(IVI5DecContext *ctx, AVCodecContext *avctx)
+static int decode_gop_header(IVI45DecContext *ctx, AVCodecContext *avctx)
 {
     int             result, i, p, tile_size, pic_size_indx, mb_size, blk_size;
     int             quant_mat, blk_size_changed = 0;
@@ -318,7 +287,7 @@ static inline void skip_hdr_extension(GetBitContext *gb)
  *  @param[in]      avctx  ptr to the AVCodecContext
  *  @return         result code: 0 = OK, -1 = error
  */
-static int decode_pic_hdr(IVI5DecContext *ctx, AVCodecContext *avctx)
+static int decode_pic_hdr(IVI45DecContext *ctx, AVCodecContext *avctx)
 {
     if (get_bits(&ctx->gb, 5) != 0x1F) {
         av_log(avctx, AV_LOG_ERROR, "Invalid picture start code!\n");
@@ -335,8 +304,12 @@ static int decode_pic_hdr(IVI5DecContext *ctx, AVCodecContext *avctx)
     ctx->frame_num = get_bits(&ctx->gb, 8);
 
     if (ctx->frame_type == FRAMETYPE_INTRA) {
-        if (decode_gop_header(ctx, avctx))
-            return -1;
+        ctx->gop_invalid = 1;
+        if (decode_gop_header(ctx, avctx)) {
+            av_log(avctx, AV_LOG_ERROR, "Invalid GOP header, skipping frames.\n");
+            return AVERROR_INVALIDDATA;
+        }
+        ctx->gop_invalid = 0;
     }
 
     if (ctx->frame_type != FRAMETYPE_NULL) {
@@ -371,7 +344,7 @@ static int decode_pic_hdr(IVI5DecContext *ctx, AVCodecContext *avctx)
  *  @param[in]      avctx  ptr to the AVCodecContext
  *  @return         result code: 0 = OK, -1 = error
  */
-static int decode_band_hdr(IVI5DecContext *ctx, IVIBandDesc *band,
+static int decode_band_hdr(IVI45DecContext *ctx, IVIBandDesc *band,
                            AVCodecContext *avctx)
 {
     int         i;
@@ -441,7 +414,7 @@ static int decode_band_hdr(IVI5DecContext *ctx, IVIBandDesc *band,
  *  @param[in]      avctx  ptr to the AVCodecContext
  *  @return         result code: 0 = OK, -1 = error
  */
-static int decode_mb_info(IVI5DecContext *ctx, IVIBandDesc *band,
+static int decode_mb_info(IVI45DecContext *ctx, IVIBandDesc *band,
                           IVITile *tile, AVCodecContext *avctx)
 {
     int         x, y, mv_x, mv_y, mv_delta, offs, mb_offset,
@@ -453,6 +426,16 @@ static int decode_mb_info(IVI5DecContext *ctx, IVIBandDesc *band,
     ref_mb = tile->ref_mbs;
     offs   = tile->ypos * band->pitch + tile->xpos;
 
+    if (!ref_mb &&
+        ((band->qdelta_present && band->inherit_qdelta) || band->inherit_mv))
+        return AVERROR_INVALIDDATA;
+
+    if (tile->num_MBs != IVI_MBs_PER_TILE(tile->width, tile->height, band->mb_size)) {
+        av_log(avctx, AV_LOG_ERROR, "Allocated tile size %d mismatches parameters %d\n",
+               tile->num_MBs, IVI_MBs_PER_TILE(tile->width, tile->height, band->mb_size));
+        return AVERROR_INVALIDDATA;
+    }
+
     /* scale factor for motion vectors */
     mv_scale = (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3);
     mv_x = mv_y = 0;
@@ -557,101 +540,11 @@ static int decode_mb_info(IVI5DecContext *ctx, IVIBandDesc *band,
 
 
 /**
- *  Decode an Indeo5 band.
- *
- *  @param[in,out]  ctx    ptr to the decoder context
- *  @param[in,out]  band   ptr to the band descriptor
- *  @param[in]      avctx  ptr to the AVCodecContext
- *  @return         result code: 0 = OK, -1 = error
- */
-static int decode_band(IVI5DecContext *ctx, int plane_num,
-                       IVIBandDesc *band, AVCodecContext *avctx)
-{
-    int         result, i, t, idx1, idx2, pos;
-    IVITile     *tile;
-
-    band->buf     = band->bufs[ctx->dst_buf];
-    band->ref_buf = band->bufs[ctx->ref_buf];
-    band->data_ptr = ctx->frame_data + (get_bits_count(&ctx->gb) >> 3);
-
-    result = decode_band_hdr(ctx, band, avctx);
-    if (result) {
-        av_log(avctx, AV_LOG_ERROR, "Error while decoding band header: %d\n",
-               result);
-        return -1;
-    }
-
-    if (band->is_empty) {
-        av_log(avctx, AV_LOG_ERROR, "Empty band encountered!\n");
-        return -1;
-    }
-
-    band->rv_map = &ctx->rvmap_tabs[band->rvmap_sel];
-
-    /* apply corrections to the selected rvmap table if present */
-    for (i = 0; i < band->num_corr; i++) {
-        idx1 = band->corr[i*2];
-        idx2 = band->corr[i*2+1];
-        FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);
-        FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);
-    }
-
-    pos = get_bits_count(&ctx->gb);
-
-    for (t = 0; t < band->num_tiles; t++) {
-        tile = &band->tiles[t];
-
-        tile->is_empty = get_bits1(&ctx->gb);
-        if (tile->is_empty) {
-            ff_ivi_process_empty_tile(avctx, band, tile,
-                                      (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3));
-        } else {
-            tile->data_size = ff_ivi_dec_tile_data_size(&ctx->gb);
-
-            result = decode_mb_info(ctx, band, tile, avctx);
-            if (result < 0)
-                break;
-
-            result = ff_ivi_decode_blocks(&ctx->gb, band, tile);
-            if (result < 0 || (get_bits_count(&ctx->gb) - pos) >> 3 != tile->data_size) {
-                av_log(avctx, AV_LOG_ERROR, "Corrupted tile data encountered!\n");
-                break;
-            }
-            pos += tile->data_size << 3; // skip to next tile
-        }
-    }
-
-    /* restore the selected rvmap table by applying its corrections in reverse order */
-    for (i = band->num_corr-1; i >= 0; i--) {
-        idx1 = band->corr[i*2];
-        idx2 = band->corr[i*2+1];
-        FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);
-        FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);
-    }
-
-#ifdef DEBUG
-    if (band->checksum_present) {
-        uint16_t chksum = ivi_calc_band_checksum(band);
-        if (chksum != band->checksum) {
-            av_log(avctx, AV_LOG_ERROR,
-                   "Band checksum mismatch! Plane %d, band %d, received: %x, calculated: %x\n",
-                   band->plane, band->band_num, band->checksum, chksum);
-        }
-    }
-#endif
-
-    align_get_bits(&ctx->gb);
-
-    return result;
-}
-
-
-/**
  *  Switch buffers.
  *
  *  @param[in,out] ctx  ptr to the decoder context
  */
-static void switch_buffers(IVI5DecContext *ctx)
+static void switch_buffers(IVI45DecContext *ctx)
 {
     switch (ctx->prev_frame_type) {
     case FRAMETYPE_INTRA:
@@ -689,12 +582,18 @@ static void switch_buffers(IVI5DecContext *ctx)
 }
 
 
+static int is_nonnull_frame(IVI45DecContext *ctx)
+{
+    return ctx->frame_type != FRAMETYPE_NULL;
+}
+
+
 /**
  *  Initialize Indeo5 decoder.
  */
 static av_cold int decode_init(AVCodecContext *avctx)
 {
-    IVI5DecContext  *ctx = avctx->priv_data;
+    IVI45DecContext  *ctx = avctx->priv_data;
     int             result;
 
     ff_ivi_init_static_vlc();
@@ -722,97 +621,13 @@ static av_cold int decode_init(AVCodecContext *avctx)
     ctx->buf_switch = 0;
     ctx->inter_scal = 0;
 
-    avctx->pix_fmt = PIX_FMT_YUV410P;
-
-    return 0;
-}
-
-
-/**
- *  main decoder function
- */
-static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
-                        AVPacket *avpkt)
-{
-    IVI5DecContext  *ctx = avctx->priv_data;
-    const uint8_t   *buf = avpkt->data;
-    int             buf_size = avpkt->size;
-    int             result, p, b;
-
-    init_get_bits(&ctx->gb, buf, buf_size * 8);
-    ctx->frame_data = buf;
-    ctx->frame_size = buf_size;
+    ctx->decode_pic_hdr   = decode_pic_hdr;
+    ctx->decode_band_hdr  = decode_band_hdr;
+    ctx->decode_mb_info   = decode_mb_info;
+    ctx->switch_buffers   = switch_buffers;
+    ctx->is_nonnull_frame = is_nonnull_frame;
 
-    result = decode_pic_hdr(ctx, avctx);
-    if (result) {
-        av_log(avctx, AV_LOG_ERROR,
-               "Error while decoding picture header: %d\n", result);
-        return -1;
-    }
-
-    if (ctx->gop_flags & IVI5_IS_PROTECTED) {
-        av_log(avctx, AV_LOG_ERROR, "Password-protected clip!\n");
-        return -1;
-    }
-
-    switch_buffers(ctx);
-
-    //{ START_TIMER;
-
-    if (ctx->frame_type != FRAMETYPE_NULL) {
-        for (p = 0; p < 3; p++) {
-            for (b = 0; b < ctx->planes[p].num_bands; b++) {
-                result = decode_band(ctx, p, &ctx->planes[p].bands[b], avctx);
-                if (result) {
-                    av_log(avctx, AV_LOG_ERROR,
-                           "Error while decoding band: %d, plane: %d\n", b, p);
-                    return -1;
-                }
-            }
-        }
-    }
-
-    //STOP_TIMER("decode_planes"); }
-
-    if (ctx->frame.data[0])
-        avctx->release_buffer(avctx, &ctx->frame);
-
-    ctx->frame.reference = 0;
-    if (avctx->get_buffer(avctx, &ctx->frame) < 0) {
-        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
-        return -1;
-    }
-
-    if (ctx->is_scalable) {
-        ff_ivi_recompose53 (&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0], 4);
-    } else {
-        ff_ivi_output_plane(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0]);
-    }
-
-    ff_ivi_output_plane(&ctx->planes[2], ctx->frame.data[1], ctx->frame.linesize[1]);
-    ff_ivi_output_plane(&ctx->planes[1], ctx->frame.data[2], ctx->frame.linesize[2]);
-
-    *data_size = sizeof(AVFrame);
-    *(AVFrame*)data = ctx->frame;
-
-    return buf_size;
-}
-
-
-/**
- *  Close Indeo5 decoder and clean up its context.
- */
-static av_cold int decode_close(AVCodecContext *avctx)
-{
-    IVI5DecContext *ctx = avctx->priv_data;
-
-    ff_ivi_free_buffers(&ctx->planes[0]);
-
-    if (ctx->mb_vlc.cust_tab.table)
-        free_vlc(&ctx->mb_vlc.cust_tab);
-
-    if (ctx->frame.data[0])
-        avctx->release_buffer(avctx, &ctx->frame);
+    avctx->pix_fmt = PIX_FMT_YUV410P;
 
     return 0;
 }
@@ -822,9 +637,9 @@ AVCodec ff_indeo5_decoder = {
     .name           = "indeo5",
     .type           = AVMEDIA_TYPE_VIDEO,
     .id             = CODEC_ID_INDEO5,
-    .priv_data_size = sizeof(IVI5DecContext),
+    .priv_data_size = sizeof(IVI45DecContext),
     .init           = decode_init,
-    .close          = decode_close,
-    .decode         = decode_frame,
+    .close          = ff_ivi_decode_close,
+    .decode         = ff_ivi_decode_frame,
     .long_name      = NULL_IF_CONFIG_SMALL("Intel Indeo Video Interactive 5"),
 };
diff --git a/libavcodec/intelh263dec.c b/libavcodec/intelh263dec.c
index 8347c79..8556128 100644
--- a/libavcodec/intelh263dec.c
+++ b/libavcodec/intelh263dec.c
@@ -65,8 +65,8 @@ int ff_intel_h263_decode_picture_header(MpegEncContext *s)
     s->pb_frame = get_bits1(&s->gb);
 
     if (format < 6) {
-        s->width = h263_format[format][0];
-        s->height = h263_format[format][1];
+        s->width = ff_h263_format[format][0];
+        s->height = ff_h263_format[format][1];
         s->avctx->sample_aspect_ratio.num = 12;
         s->avctx->sample_aspect_ratio.den = 11;
     } else {
diff --git a/libavcodec/ituh263dec.c b/libavcodec/ituh263dec.c
index 3d82e5c..028d2a1 100644
--- a/libavcodec/ituh263dec.c
+++ b/libavcodec/ituh263dec.c
@@ -101,7 +101,7 @@ static VLC cbpc_b_vlc;
 /* init vlcs */
 
 /* XXX: find a better solution to handle static init */
-void h263_decode_init_vlc(MpegEncContext *s)
+void ff_h263_decode_init_vlc(MpegEncContext *s)
 {
     static int done = 0;
 
@@ -118,18 +118,18 @@ void h263_decode_init_vlc(MpegEncContext *s)
                  &ff_h263_cbpy_tab[0][1], 2, 1,
                  &ff_h263_cbpy_tab[0][0], 2, 1, 64);
         INIT_VLC_STATIC(&mv_vlc, MV_VLC_BITS, 33,
-                 &mvtab[0][1], 2, 1,
-                 &mvtab[0][0], 2, 1, 538);
-        init_rl(&ff_h263_rl_inter, ff_h263_static_rl_table_store[0]);
-        init_rl(&rl_intra_aic, ff_h263_static_rl_table_store[1]);
+                 &ff_mvtab[0][1], 2, 1,
+                 &ff_mvtab[0][0], 2, 1, 538);
+        ff_init_rl(&ff_h263_rl_inter, ff_h263_static_rl_table_store[0]);
+        ff_init_rl(&ff_rl_intra_aic, ff_h263_static_rl_table_store[1]);
         INIT_VLC_RL(ff_h263_rl_inter, 554);
-        INIT_VLC_RL(rl_intra_aic, 554);
+        INIT_VLC_RL(ff_rl_intra_aic, 554);
         INIT_VLC_STATIC(&h263_mbtype_b_vlc, H263_MBTYPE_B_VLC_BITS, 15,
-                 &h263_mbtype_b_tab[0][1], 2, 1,
-                 &h263_mbtype_b_tab[0][0], 2, 1, 80);
+                 &ff_h263_mbtype_b_tab[0][1], 2, 1,
+                 &ff_h263_mbtype_b_tab[0][0], 2, 1, 80);
         INIT_VLC_STATIC(&cbpc_b_vlc, CBPC_B_VLC_BITS, 4,
-                 &cbpc_b_tab[0][1], 2, 1,
-                 &cbpc_b_tab[0][0], 2, 1, 8);
+                 &ff_cbpc_b_tab[0][1], 2, 1,
+                 &ff_cbpc_b_tab[0][0], 2, 1, 8);
     }
 }
 
@@ -269,7 +269,7 @@ int ff_h263_resync(MpegEncContext *s){
     return -1;
 }
 
-int h263_decode_motion(MpegEncContext * s, int pred, int f_code)
+int ff_h263_decode_motion(MpegEncContext * s, int pred, int f_code)
 {
     int code, val, sign, shift;
     code = get_vlc2(&s->gb, mv_vlc.table, MV_VLC_BITS, 2);
@@ -379,16 +379,16 @@ static void preview_obmc(MpegEncContext *s){
         if ((cbpc & 16) == 0) {
                 s->current_picture.f.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
                 /* 16x16 motion prediction */
-                mot_val= h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+                mot_val= ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
                 if (s->umvplus)
                    mx = h263p_decode_umotion(s, pred_x);
                 else
-                   mx = h263_decode_motion(s, pred_x, 1);
+                   mx = ff_h263_decode_motion(s, pred_x, 1);
 
                 if (s->umvplus)
                    my = h263p_decode_umotion(s, pred_y);
                 else
-                   my = h263_decode_motion(s, pred_y, 1);
+                   my = ff_h263_decode_motion(s, pred_y, 1);
 
                 mot_val[0       ]= mot_val[2       ]=
                 mot_val[0+stride]= mot_val[2+stride]= mx;
@@ -397,16 +397,16 @@ static void preview_obmc(MpegEncContext *s){
         } else {
             s->current_picture.f.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
             for(i=0;i<4;i++) {
-                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
+                mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
                 if (s->umvplus)
                   mx = h263p_decode_umotion(s, pred_x);
                 else
-                  mx = h263_decode_motion(s, pred_x, 1);
+                  mx = ff_h263_decode_motion(s, pred_x, 1);
 
                 if (s->umvplus)
                   my = h263p_decode_umotion(s, pred_y);
                 else
-                  my = h263_decode_motion(s, pred_y, 1);
+                  my = ff_h263_decode_motion(s, pred_y, 1);
                 if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)
                   skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */
                 mot_val[0] = mx;
@@ -430,7 +430,7 @@ static void h263_decode_dquant(MpegEncContext *s){
 
     if(s->modified_quant){
         if(get_bits1(&s->gb))
-            s->qscale= modified_quant_tab[get_bits1(&s->gb)][ s->qscale ];
+            s->qscale= ff_modified_quant_tab[get_bits1(&s->gb)][ s->qscale ];
         else
             s->qscale= get_bits(&s->gb, 5);
     }else
@@ -448,7 +448,7 @@ static int h263_decode_block(MpegEncContext * s, DCTELEM * block,
 
     scan_table = s->intra_scantable.permutated;
     if (s->h263_aic && s->mb_intra) {
-        rl = &rl_intra_aic;
+        rl = &ff_rl_intra_aic;
         i = 0;
         if (s->ac_pred) {
             if (s->h263_aic_dir)
@@ -537,7 +537,7 @@ retry:
         if (i >= 64){
             if(s->alt_inter_vlc && rl == &ff_h263_rl_inter && !s->mb_intra){
                 //Looks like a hack but no, it's the way it is supposed to work ...
-                rl = &rl_intra_aic;
+                rl = &ff_rl_intra_aic;
                 i = 0;
                 s->gb= gb;
                 s->dsp.clear_block(block);
@@ -554,7 +554,7 @@ retry:
     }
 not_coded:
     if (s->mb_intra && s->h263_aic) {
-        h263_pred_acdc(s, block, n);
+        ff_h263_pred_acdc(s, block, n);
         i = 63;
     }
     s->block_last_index[n] = i;
@@ -653,11 +653,11 @@ int ff_h263_decode_mb(MpegEncContext *s,
             s->current_picture.f.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
             /* 16x16 motion prediction */
             s->mv_type = MV_TYPE_16X16;
-            h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+            ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
             if (s->umvplus)
                mx = h263p_decode_umotion(s, pred_x);
             else
-               mx = h263_decode_motion(s, pred_x, 1);
+               mx = ff_h263_decode_motion(s, pred_x, 1);
 
             if (mx >= 0xffff)
                 return -1;
@@ -665,7 +665,7 @@ int ff_h263_decode_mb(MpegEncContext *s,
             if (s->umvplus)
                my = h263p_decode_umotion(s, pred_y);
             else
-               my = h263_decode_motion(s, pred_y, 1);
+               my = ff_h263_decode_motion(s, pred_y, 1);
 
             if (my >= 0xffff)
                 return -1;
@@ -678,18 +678,18 @@ int ff_h263_decode_mb(MpegEncContext *s,
             s->current_picture.f.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
             s->mv_type = MV_TYPE_8X8;
             for(i=0;i<4;i++) {
-                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
+                mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
                 if (s->umvplus)
                   mx = h263p_decode_umotion(s, pred_x);
                 else
-                  mx = h263_decode_motion(s, pred_x, 1);
+                  mx = ff_h263_decode_motion(s, pred_x, 1);
                 if (mx >= 0xffff)
                     return -1;
 
                 if (s->umvplus)
                   my = h263p_decode_umotion(s, pred_y);
                 else
-                  my = h263_decode_motion(s, pred_y, 1);
+                  my = ff_h263_decode_motion(s, pred_y, 1);
                 if (my >= 0xffff)
                     return -1;
                 s->mv[0][i][0] = mx;
@@ -761,11 +761,11 @@ int ff_h263_decode_mb(MpegEncContext *s,
 //FIXME UMV
 
             if(USES_LIST(mb_type, 0)){
-                int16_t *mot_val= h263_pred_motion(s, 0, 0, &mx, &my);
+                int16_t *mot_val= ff_h263_pred_motion(s, 0, 0, &mx, &my);
                 s->mv_dir = MV_DIR_FORWARD;
 
-                mx = h263_decode_motion(s, mx, 1);
-                my = h263_decode_motion(s, my, 1);
+                mx = ff_h263_decode_motion(s, mx, 1);
+                my = ff_h263_decode_motion(s, my, 1);
 
                 s->mv[0][0][0] = mx;
                 s->mv[0][0][1] = my;
@@ -774,11 +774,11 @@ int ff_h263_decode_mb(MpegEncContext *s,
             }
 
             if(USES_LIST(mb_type, 1)){
-                int16_t *mot_val= h263_pred_motion(s, 0, 1, &mx, &my);
+                int16_t *mot_val= ff_h263_pred_motion(s, 0, 1, &mx, &my);
                 s->mv_dir |= MV_DIR_BACKWARD;
 
-                mx = h263_decode_motion(s, mx, 1);
-                my = h263_decode_motion(s, my, 1);
+                mx = ff_h263_decode_motion(s, mx, 1);
+                my = ff_h263_decode_motion(s, my, 1);
 
                 s->mv[1][0][0] = mx;
                 s->mv[1][0][1] = my;
@@ -829,8 +829,8 @@ intra:
     }
 
     while(pb_mv_count--){
-        h263_decode_motion(s, 0, 1);
-        h263_decode_motion(s, 0, 1);
+        ff_h263_decode_motion(s, 0, 1);
+        ff_h263_decode_motion(s, 0, 1);
     }
 
     /* decode each block */
@@ -864,7 +864,7 @@ end:
 }
 
 /* most is hardcoded. should extend to handle all h263 streams */
-int h263_decode_picture_header(MpegEncContext *s)
+int ff_h263_decode_picture_header(MpegEncContext *s)
 {
     int format, width, height, i;
     uint32_t startcode;
@@ -916,8 +916,8 @@ int h263_decode_picture_header(MpegEncContext *s)
     if (format != 7 && format != 6) {
         s->h263_plus = 0;
         /* H.263v1 */
-        width = h263_format[format][0];
-        height = h263_format[format][1];
+        width = ff_h263_format[format][0];
+        height = ff_h263_format[format][1];
         if (!width)
             return -1;
 
@@ -1024,8 +1024,8 @@ int h263_decode_picture_header(MpegEncContext *s)
                     s->avctx->sample_aspect_ratio= ff_h263_pixel_aspect[s->aspect_ratio_info];
                 }
             } else {
-                width = h263_format[format][0];
-                height = h263_format[format][1];
+                width = ff_h263_format[format][0];
+                height = ff_h263_format[format][1];
                 s->avctx->sample_aspect_ratio= (AVRational){12,11};
             }
             if ((width == 0) || (height == 0))
diff --git a/libavcodec/ituh263enc.c b/libavcodec/ituh263enc.c
index 6efba2d..752b307 100644
--- a/libavcodec/ituh263enc.c
+++ b/libavcodec/ituh263enc.c
@@ -102,7 +102,7 @@ av_const int ff_h263_aspect_to_info(AVRational aspect){
     return FF_ASPECT_EXTENDED;
 }
 
-void h263_encode_picture_header(MpegEncContext * s, int picture_number)
+void ff_h263_encode_picture_header(MpegEncContext * s, int picture_number)
 {
     int format, coded_frame_rate, coded_frame_rate_base, i, temp_ref;
     int best_clock_code=1;
@@ -141,7 +141,7 @@ void h263_encode_picture_header(MpegEncContext * s, int picture_number)
     put_bits(&s->pb, 1, 0);     /* camera  off */
     put_bits(&s->pb, 1, 0);     /* freeze picture release off */
 
-    format = ff_match_2uint16(h263_format, FF_ARRAY_ELEMS(h263_format), s->width, s->height);
+    format = ff_match_2uint16(ff_h263_format, FF_ARRAY_ELEMS(ff_h263_format), s->width, s->height);
     if (!s->h263_plus) {
         /* H.263v1 */
         put_bits(&s->pb, 3, format);
@@ -247,7 +247,7 @@ void h263_encode_picture_header(MpegEncContext * s, int picture_number)
 /**
  * Encode a group of blocks header.
  */
-void h263_encode_gob_header(MpegEncContext * s, int mb_line)
+void ff_h263_encode_gob_header(MpegEncContext * s, int mb_line)
 {
     put_bits(&s->pb, 17, 1); /* GBSC */
 
@@ -333,7 +333,7 @@ static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
     } else {
         i = 0;
         if (s->h263_aic && s->mb_intra)
-            rl = &rl_intra_aic;
+            rl = &ff_rl_intra_aic;
 
         if(s->alt_inter_vlc && !s->mb_intra){
             int aic_vlc_bits=0;
@@ -353,14 +353,14 @@ static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
                     if(level<0) level= -level;
 
                     code = get_rl_index(rl, last, run, level);
-                    aic_code = get_rl_index(&rl_intra_aic, last, run, level);
+                    aic_code = get_rl_index(&ff_rl_intra_aic, last, run, level);
                     inter_vlc_bits += rl->table_vlc[code][1]+1;
-                    aic_vlc_bits   += rl_intra_aic.table_vlc[aic_code][1]+1;
+                    aic_vlc_bits   += ff_rl_intra_aic.table_vlc[aic_code][1]+1;
 
                     if (code == rl->n) {
                         inter_vlc_bits += 1+6+8-1;
                     }
-                    if (aic_code == rl_intra_aic.n) {
+                    if (aic_code == ff_rl_intra_aic.n) {
                         aic_vlc_bits += 1+6+8-1;
                         wrong_pos += run + 1;
                     }else
@@ -370,7 +370,7 @@ static void h263_encode_block(MpegEncContext * s, DCTELEM * block, int n)
             }
             i = 0;
             if(aic_vlc_bits < inter_vlc_bits && wrong_pos > 63)
-                rl = &rl_intra_aic;
+                rl = &ff_rl_intra_aic;
         }
     }
 
@@ -454,9 +454,9 @@ static void h263p_encode_umotion(MpegEncContext * s, int val)
     }
 }
 
-void h263_encode_mb(MpegEncContext * s,
-                    DCTELEM block[6][64],
-                    int motion_x, int motion_y)
+void ff_h263_encode_mb(MpegEncContext * s,
+                       DCTELEM block[6][64],
+                       int motion_x, int motion_y)
 {
     int cbpc, cbpy, i, cbp, pred_x, pred_y;
     int16_t pred_dc;
@@ -500,7 +500,7 @@ void h263_encode_mb(MpegEncContext * s,
             }
 
             /* motion vectors: 16x16 mode */
-            h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+            ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
 
             if (!s->umvplus) {
                 ff_h263_encode_motion_vector(s, motion_x - pred_x,
@@ -527,7 +527,7 @@ void h263_encode_mb(MpegEncContext * s,
 
             for(i=0; i<4; i++){
                 /* motion vectors: 8x8 mode*/
-                h263_pred_motion(s, i, 0, &pred_x, &pred_y);
+                ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
 
                 motion_x = s->current_picture.f.motion_val[0][s->block_index[i]][0];
                 motion_y = s->current_picture.f.motion_val[0][s->block_index[i]][1];
@@ -561,7 +561,7 @@ void h263_encode_mb(MpegEncContext * s,
                 if(i<4) scale= s->y_dc_scale;
                 else    scale= s->c_dc_scale;
 
-                pred_dc = h263_pred_dc(s, i, &dc_ptr[i]);
+                pred_dc = ff_h263_pred_dc(s, i, &dc_ptr[i]);
                 level -= pred_dc;
                 /* Quant */
                 if (level >= 0)
@@ -662,7 +662,7 @@ void ff_h263_encode_motion(MpegEncContext * s, int val, int f_code)
     if (val == 0) {
         /* zero vector */
         code = 0;
-        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
+        put_bits(&s->pb, ff_mvtab[code][1], ff_mvtab[code][0]);
     } else {
         bit_size = f_code - 1;
         range = 1 << bit_size;
@@ -676,7 +676,7 @@ void ff_h263_encode_motion(MpegEncContext * s, int val, int f_code)
         code = (val >> bit_size) + 1;
         bits = val & (range - 1);
 
-        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign);
+        put_bits(&s->pb, ff_mvtab[code][1] + 1, (ff_mvtab[code][0] << 1) | sign);
         if (bit_size > 0) {
             put_bits(&s->pb, bit_size, bits);
         }
@@ -692,7 +692,7 @@ static void init_mv_penalty_and_fcode(MpegEncContext *s)
         for(mv=-MAX_MV; mv<=MAX_MV; mv++){
             int len;
 
-            if(mv==0) len= mvtab[0][1];
+            if(mv==0) len= ff_mvtab[0][1];
             else{
                 int val, bit_size, code;
 
@@ -704,9 +704,9 @@ static void init_mv_penalty_and_fcode(MpegEncContext *s)
                 val--;
                 code = (val >> bit_size) + 1;
                 if(code<33){
-                    len= mvtab[code][1] + 1 + bit_size;
+                    len= ff_mvtab[code][1] + 1 + bit_size;
                 }else{
-                    len= mvtab[32][1] + av_log2(code>>5) + 2 + bit_size;
+                    len= ff_mvtab[32][1] + av_log2(code>>5) + 2 + bit_size;
                 }
             }
 
@@ -768,17 +768,17 @@ static void init_uni_h263_rl_tab(RLTable *rl, uint32_t *bits_tab, uint8_t *len_t
     }
 }
 
-void h263_encode_init(MpegEncContext *s)
+void ff_h263_encode_init(MpegEncContext *s)
 {
     static int done = 0;
 
     if (!done) {
         done = 1;
 
-        init_rl(&ff_h263_rl_inter, ff_h263_static_rl_table_store[0]);
-        init_rl(&rl_intra_aic, ff_h263_static_rl_table_store[1]);
+        ff_init_rl(&ff_h263_rl_inter, ff_h263_static_rl_table_store[0]);
+        ff_init_rl(&ff_rl_intra_aic, ff_h263_static_rl_table_store[1]);
 
-        init_uni_h263_rl_tab(&rl_intra_aic, NULL, uni_h263_intra_aic_rl_len);
+        init_uni_h263_rl_tab(&ff_rl_intra_aic, NULL, uni_h263_intra_aic_rl_len);
         init_uni_h263_rl_tab(&ff_h263_rl_inter    , NULL, uni_h263_inter_rl_len);
 
         init_mv_penalty_and_fcode(s);
diff --git a/libavcodec/ivi_common.c b/libavcodec/ivi_common.c
index eedcd28..db33767 100644
--- a/libavcodec/ivi_common.c
+++ b/libavcodec/ivi_common.c
@@ -123,6 +123,10 @@ int ff_ivi_dec_huff_desc(GetBitContext *gb, int desc_coded, int which_tab,
         if (huff_tab->tab_sel == 7) {
             /* custom huffman table (explicitly encoded) */
             new_huff.num_rows = get_bits(gb, 4);
+            if (!new_huff.num_rows) {
+                av_log(avctx, AV_LOG_ERROR, "Empty custom Huffman table!\n");
+                return AVERROR_INVALIDDATA;
+            }
 
             for (i = 0; i < new_huff.num_rows; i++)
                 new_huff.xbits[i] = get_bits(gb, 4);
@@ -132,13 +136,14 @@ int ff_ivi_dec_huff_desc(GetBitContext *gb, int desc_coded, int which_tab,
                 ff_ivi_huff_desc_copy(&huff_tab->cust_desc, &new_huff);
 
                 if (huff_tab->cust_tab.table)
-                    free_vlc(&huff_tab->cust_tab);
+                    ff_free_vlc(&huff_tab->cust_tab);
                 result = ff_ivi_create_huff_from_desc(&huff_tab->cust_desc,
                         &huff_tab->cust_tab, 0);
                 if (result) {
+                    huff_tab->cust_desc.num_rows = 0; // reset faulty description
                     av_log(avctx, AV_LOG_ERROR,
                            "Error while initializing custom vlc table!\n");
-                    return -1;
+                    return result;
                 }
             }
             huff_tab->tab = &huff_tab->cust_tab;
@@ -207,14 +212,15 @@ int av_cold ff_ivi_init_planes(IVIPlaneDesc *planes, const IVIPicConfig *cfg)
             band->width    = b_width;
             band->height   = b_height;
             band->pitch    = width_aligned;
-            band->bufs[0]  = av_malloc(buf_size);
-            band->bufs[1]  = av_malloc(buf_size);
+            band->aheight  = height_aligned;
+            band->bufs[0]  = av_mallocz(buf_size);
+            band->bufs[1]  = av_mallocz(buf_size);
             if (!band->bufs[0] || !band->bufs[1])
                 return AVERROR(ENOMEM);
 
             /* allocate the 3rd band buffer for scalability mode */
             if (cfg->luma_bands > 1) {
-                band->bufs[2] = av_malloc(buf_size);
+                band->bufs[2] = av_mallocz(buf_size);
                 if (!band->bufs[2])
                     return AVERROR(ENOMEM);
             }
@@ -237,7 +243,7 @@ void av_cold ff_ivi_free_buffers(IVIPlaneDesc *planes)
             av_freep(&planes[p].bands[b].bufs[2]);
 
             if (planes[p].bands[b].blk_vlc.cust_tab.table)
-                free_vlc(&planes[p].bands[b].blk_vlc.cust_tab);
+                ff_free_vlc(&planes[p].bands[b].blk_vlc.cust_tab);
             for (t = 0; t < planes[p].bands[b].num_tiles; t++)
                 av_freep(&planes[p].bands[b].tiles[t].mbs);
             av_freep(&planes[p].bands[b].tiles);
@@ -282,6 +288,7 @@ int av_cold ff_ivi_init_tiles(IVIPlaneDesc *planes, int tile_width, int tile_hei
                 for (x = 0; x < band->width; x += t_width) {
                     tile->xpos     = x;
                     tile->ypos     = y;
+                    tile->mb_size  = band->mb_size;
                     tile->width    = FFMIN(band->width - x,  t_width);
                     tile->height   = FFMIN(band->height - y, t_height);
                     tile->is_empty = tile->data_size = 0;
@@ -377,6 +384,21 @@ int ff_ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile)
                 mv_x >>= 1;
                 mv_y >>= 1; /* convert halfpel vectors into fullpel ones */
             }
+            if (mb->type) {
+                int dmv_x, dmv_y, cx, cy;
+
+                dmv_x = mb->mv_x >> band->is_halfpel;
+                dmv_y = mb->mv_y >> band->is_halfpel;
+                cx    = mb->mv_x &  band->is_halfpel;
+                cy    = mb->mv_y &  band->is_halfpel;
+
+                if (   mb->xpos + dmv_x < 0
+                    || mb->xpos + dmv_x + band->mb_size + cx > band->pitch
+                    || mb->ypos + dmv_y < 0
+                    || mb->ypos + dmv_y + band->mb_size + cy > band->aheight) {
+                    return AVERROR_INVALIDDATA;
+                }
+            }
         }
 
         for (blk = 0; blk < num_blocks; blk++) {
@@ -469,8 +491,17 @@ int ff_ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile)
     return 0;
 }
 
-void ff_ivi_process_empty_tile(AVCodecContext *avctx, IVIBandDesc *band,
-                               IVITile *tile, int32_t mv_scale)
+/**
+ *  Handle empty tiles by performing data copying and motion
+ *  compensation respectively.
+ *
+ *  @param[in]  avctx     ptr to the AVCodecContext
+ *  @param[in]  band      pointer to the band descriptor
+ *  @param[in]  tile      pointer to the tile descriptor
+ *  @param[in]  mv_scale  scaling factor for motion vectors
+ */
+static int ivi_process_empty_tile(AVCodecContext *avctx, IVIBandDesc *band,
+                                  IVITile *tile, int32_t mv_scale)
 {
     int             x, y, need_mc, mbn, blk, num_blocks, mv_x, mv_y, mc_type;
     int             offs, mb_offset, row_offset;
@@ -480,6 +511,13 @@ void ff_ivi_process_empty_tile(AVCodecContext *avctx, IVIBandDesc *band,
     void (*mc_no_delta_func)(int16_t *buf, const int16_t *ref_buf, uint32_t pitch,
                              int mc_type);
 
+    if (tile->num_MBs != IVI_MBs_PER_TILE(tile->width, tile->height, band->mb_size)) {
+        av_log(avctx, AV_LOG_ERROR, "Allocated tile size %d mismatches "
+               "parameters %d in ivi_process_empty_tile()\n",
+               tile->num_MBs, IVI_MBs_PER_TILE(tile->width, tile->height, band->mb_size));
+        return AVERROR_INVALIDDATA;
+    }
+
     offs       = tile->ypos * band->pitch + tile->xpos;
     mb         = tile->mbs;
     ref_mb     = tile->ref_mbs;
@@ -560,6 +598,8 @@ void ff_ivi_process_empty_tile(AVCodecContext *avctx, IVIBandDesc *band,
             dst += band->pitch;
         }
     }
+
+    return 0;
 }
 
 
@@ -622,6 +662,226 @@ void ff_ivi_output_plane(IVIPlaneDesc *plane, uint8_t *dst, int dst_pitch)
     }
 }
 
+/**
+ *  Decode an Indeo 4 or 5 band.
+ *
+ *  @param[in,out]  ctx    ptr to the decoder context
+ *  @param[in,out]  band   ptr to the band descriptor
+ *  @param[in]      avctx  ptr to the AVCodecContext
+ *  @return         result code: 0 = OK, -1 = error
+ */
+static int decode_band(IVI45DecContext *ctx, int plane_num,
+                       IVIBandDesc *band, AVCodecContext *avctx)
+{
+    int         result, i, t, idx1, idx2, pos;
+    IVITile     *tile;
+
+    band->buf     = band->bufs[ctx->dst_buf];
+    band->ref_buf = band->bufs[ctx->ref_buf];
+    band->data_ptr = ctx->frame_data + (get_bits_count(&ctx->gb) >> 3);
+
+    result = ctx->decode_band_hdr(ctx, band, avctx);
+    if (result) {
+        av_log(avctx, AV_LOG_ERROR, "Error while decoding band header: %d\n",
+               result);
+        return result;
+    }
+
+    if (band->is_empty) {
+        av_log(avctx, AV_LOG_ERROR, "Empty band encountered!\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    band->rv_map = &ctx->rvmap_tabs[band->rvmap_sel];
+
+    /* apply corrections to the selected rvmap table if present */
+    for (i = 0; i < band->num_corr; i++) {
+        idx1 = band->corr[i * 2];
+        idx2 = band->corr[i * 2 + 1];
+        FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);
+        FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);
+    }
+
+    pos = get_bits_count(&ctx->gb);
+
+    for (t = 0; t < band->num_tiles; t++) {
+        tile = &band->tiles[t];
+
+        if (tile->mb_size != band->mb_size) {
+            av_log(avctx, AV_LOG_ERROR, "MB sizes mismatch: %d vs. %d\n",
+                   band->mb_size, tile->mb_size);
+            return AVERROR_INVALIDDATA;
+        }
+        tile->is_empty = get_bits1(&ctx->gb);
+        if (tile->is_empty) {
+            result = ivi_process_empty_tile(avctx, band, tile,
+                                      (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3));
+            if (result < 0)
+                break;
+            av_dlog(avctx, "Empty tile encountered!\n");
+        } else {
+            tile->data_size = ff_ivi_dec_tile_data_size(&ctx->gb);
+            if (!tile->data_size) {
+                av_log(avctx, AV_LOG_ERROR, "Tile data size is zero!\n");
+                return AVERROR_INVALIDDATA;
+            }
+
+            result = ctx->decode_mb_info(ctx, band, tile, avctx);
+            if (result < 0)
+                break;
+
+            result = ff_ivi_decode_blocks(&ctx->gb, band, tile);
+            if (result < 0 || ((get_bits_count(&ctx->gb) - pos) >> 3) != tile->data_size) {
+                av_log(avctx, AV_LOG_ERROR, "Corrupted tile data encountered!\n");
+                break;
+            }
+
+            pos += tile->data_size << 3; // skip to next tile
+        }
+    }
+
+    /* restore the selected rvmap table by applying its corrections in reverse order */
+    for (i = band->num_corr-1; i >= 0; i--) {
+        idx1 = band->corr[i*2];
+        idx2 = band->corr[i*2+1];
+        FFSWAP(uint8_t, band->rv_map->runtab[idx1], band->rv_map->runtab[idx2]);
+        FFSWAP(int16_t, band->rv_map->valtab[idx1], band->rv_map->valtab[idx2]);
+    }
+
+#ifdef DEBUG
+    if (band->checksum_present) {
+        uint16_t chksum = ivi_calc_band_checksum(band);
+        if (chksum != band->checksum) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "Band checksum mismatch! Plane %d, band %d, received: %x, calculated: %x\n",
+                   band->plane, band->band_num, band->checksum, chksum);
+        }
+    }
+#endif
+
+    align_get_bits(&ctx->gb);
+
+    return result;
+}
+
+int ff_ivi_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
+                        AVPacket *avpkt)
+{
+    IVI45DecContext *ctx = avctx->priv_data;
+    const uint8_t   *buf = avpkt->data;
+    int             buf_size = avpkt->size;
+    int             result, p, b;
+
+    init_get_bits(&ctx->gb, buf, buf_size * 8);
+    ctx->frame_data = buf;
+    ctx->frame_size = buf_size;
+
+    result = ctx->decode_pic_hdr(ctx, avctx);
+    if (result) {
+        av_log(avctx, AV_LOG_ERROR,
+               "Error while decoding picture header: %d\n", result);
+        return -1;
+    }
+    if (ctx->gop_invalid)
+        return AVERROR_INVALIDDATA;
+
+    if (ctx->gop_flags & IVI5_IS_PROTECTED) {
+        av_log(avctx, AV_LOG_ERROR, "Password-protected clip!\n");
+        return -1;
+    }
+
+    ctx->switch_buffers(ctx);
+
+    //{ START_TIMER;
+
+    if (ctx->is_nonnull_frame(ctx)) {
+        for (p = 0; p < 3; p++) {
+            for (b = 0; b < ctx->planes[p].num_bands; b++) {
+                result = decode_band(ctx, p, &ctx->planes[p].bands[b], avctx);
+                if (result) {
+                    av_log(avctx, AV_LOG_ERROR,
+                           "Error while decoding band: %d, plane: %d\n", b, p);
+                    return -1;
+                }
+            }
+        }
+    }
+
+    //STOP_TIMER("decode_planes"); }
+
+    /* If the bidirectional mode is enabled, next I and the following P frame will */
+    /* be sent together. Unfortunately the approach below seems to be the only way */
+    /* to handle the B-frames mode. That's exactly the same Intel decoders do.     */
+    if (avctx->codec_id == CODEC_ID_INDEO4 && ctx->frame_type == 0/*FRAMETYPE_INTRA*/) {
+        while (get_bits(&ctx->gb, 8)); // skip version string
+        skip_bits_long(&ctx->gb, 64);  // skip padding, TODO: implement correct 8-bytes alignment
+        if (get_bits_left(&ctx->gb) > 18 && show_bits(&ctx->gb, 18) == 0x3FFF8)
+            av_log(avctx, AV_LOG_ERROR, "Buffer contains IP frames!\n");
+    }
+
+    if (ctx->frame.data[0])
+        avctx->release_buffer(avctx, &ctx->frame);
+
+    ctx->frame.reference = 0;
+    avcodec_set_dimensions(avctx, ctx->planes[0].width, ctx->planes[0].height);
+    if ((result = avctx->get_buffer(avctx, &ctx->frame)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return result;
+    }
+
+    if (ctx->is_scalable) {
+        if (avctx->codec_id == CODEC_ID_INDEO4)
+            ff_ivi_recompose_haar(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0], 4);
+        else
+            ff_ivi_recompose53   (&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0], 4);
+    } else {
+        ff_ivi_output_plane(&ctx->planes[0], ctx->frame.data[0], ctx->frame.linesize[0]);
+    }
+
+    ff_ivi_output_plane(&ctx->planes[2], ctx->frame.data[1], ctx->frame.linesize[1]);
+    ff_ivi_output_plane(&ctx->planes[1], ctx->frame.data[2], ctx->frame.linesize[2]);
+
+    *data_size = sizeof(AVFrame);
+    *(AVFrame*)data = ctx->frame;
+
+    return buf_size;
+}
+
+/**
+ *  Close Indeo5 decoder and clean up its context.
+ */
+av_cold int ff_ivi_decode_close(AVCodecContext *avctx)
+{
+    IVI45DecContext *ctx = avctx->priv_data;
+
+    ff_ivi_free_buffers(&ctx->planes[0]);
+
+    if (ctx->mb_vlc.cust_tab.table)
+        ff_free_vlc(&ctx->mb_vlc.cust_tab);
+
+    if (ctx->frame.data[0])
+        avctx->release_buffer(avctx, &ctx->frame);
+
+#if IVI4_STREAM_ANALYSER
+    if (avctx->codec_id == CODEC_ID_INDEO4) {
+    if (ctx->is_scalable)
+        av_log(avctx, AV_LOG_ERROR, "This video uses scalability mode!\n");
+    if (ctx->uses_tiling)
+        av_log(avctx, AV_LOG_ERROR, "This video uses local decoding!\n");
+    if (ctx->has_b_frames)
+        av_log(avctx, AV_LOG_ERROR, "This video contains B-frames!\n");
+    if (ctx->has_transp)
+        av_log(avctx, AV_LOG_ERROR, "Transparency mode is enabled!\n");
+    if (ctx->uses_haar)
+        av_log(avctx, AV_LOG_ERROR, "This video uses Haar transform!\n");
+    if (ctx->uses_fullpel)
+        av_log(avctx, AV_LOG_ERROR, "This video uses fullpel motion vectors!\n");
+    }
+#endif
+
+    return 0;
+}
+
 
 /**
  * These are 2x8 predefined Huffman codebooks for coding macroblock/block
diff --git a/libavcodec/ivi_common.h b/libavcodec/ivi_common.h
index 4b2ae06..07736f2 100644
--- a/libavcodec/ivi_common.h
+++ b/libavcodec/ivi_common.h
@@ -34,6 +34,8 @@
 #include <stdint.h>
 
 #define IVI_VLC_BITS 13 ///< max number of bits of the ivi's huffman codes
+#define IVI4_STREAM_ANALYSER    0
+#define IVI5_IS_PROTECTED       0x20
 
 /**
  *  huffman codebook descriptor
@@ -116,6 +118,7 @@ typedef struct {
     int         ypos;
     int         width;
     int         height;
+    int         mb_size;
     int         is_empty;  ///< = 1 if this tile doesn't contain any data
     int         data_size; ///< size of the data in bytes
     int         num_MBs;   ///< number of macroblocks in this tile
@@ -132,6 +135,7 @@ typedef struct {
     int             band_num;       ///< band number
     int             width;
     int             height;
+    int             aheight;        ///< aligned band height
     const uint8_t   *data_ptr;      ///< ptr to the first byte of the band data
     int             data_size;      ///< size of the band data
     int16_t         *buf;           ///< pointer to the output buffer for this band
@@ -192,6 +196,62 @@ typedef struct {
     uint8_t     chroma_bands;
 } IVIPicConfig;
 
+typedef struct IVI45DecContext {
+    GetBitContext   gb;
+    AVFrame         frame;
+    RVMapDesc       rvmap_tabs[9];   ///< local corrected copy of the static rvmap tables
+
+    uint32_t        frame_num;
+    int             frame_type;
+    int             prev_frame_type; ///< frame type of the previous frame
+    uint32_t        data_size;       ///< size of the frame data in bytes from picture header
+    int             is_scalable;
+    int             transp_status;   ///< transparency mode status: 1 - enabled
+    const uint8_t   *frame_data;     ///< input frame data pointer
+    int             inter_scal;      ///< signals a sequence of scalable inter frames
+    uint32_t        frame_size;      ///< frame size in bytes
+    uint32_t        pic_hdr_size;    ///< picture header size in bytes
+    uint8_t         frame_flags;
+    uint16_t        checksum;        ///< frame checksum
+
+    IVIPicConfig    pic_conf;
+    IVIPlaneDesc    planes[3];       ///< color planes
+
+    int             buf_switch;      ///< used to switch between three buffers
+    int             dst_buf;         ///< buffer index for the currently decoded frame
+    int             ref_buf;         ///< inter frame reference buffer index
+    int             ref2_buf;        ///< temporal storage for switching buffers
+
+    IVIHuffTab      mb_vlc;          ///< current macroblock table descriptor
+    IVIHuffTab      blk_vlc;         ///< current block table descriptor
+
+    uint8_t         rvmap_sel;
+    uint8_t         in_imf;
+    uint8_t         in_q;            ///< flag for explicitly stored quantiser delta
+    uint8_t         pic_glob_quant;
+    uint8_t         unknown1;
+
+    uint16_t        gop_hdr_size;
+    uint8_t         gop_flags;
+    uint32_t        lock_word;
+
+#if IVI4_STREAM_ANALYSER
+    uint8_t         has_b_frames;
+    uint8_t         has_transp;
+    uint8_t         uses_tiling;
+    uint8_t         uses_haar;
+    uint8_t         uses_fullpel;
+#endif
+
+    int             (*decode_pic_hdr)  (struct IVI45DecContext *ctx, AVCodecContext *avctx);
+    int             (*decode_band_hdr) (struct IVI45DecContext *ctx, IVIBandDesc *band, AVCodecContext *avctx);
+    int             (*decode_mb_info)  (struct IVI45DecContext *ctx, IVIBandDesc *band, IVITile *tile, AVCodecContext *avctx);
+    void            (*switch_buffers)  (struct IVI45DecContext *ctx);
+    int             (*is_nonnull_frame)(struct IVI45DecContext *ctx);
+
+    int gop_invalid;
+} IVI45DecContext;
+
 /** compare some properties of two pictures */
 static inline int ivi_pic_config_cmp(IVIPicConfig *str1, IVIPicConfig *str2)
 {
@@ -316,18 +376,6 @@ int  ff_ivi_dec_tile_data_size(GetBitContext *gb);
 int  ff_ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile);
 
 /**
- *  Handle empty tiles by performing data copying and motion
- *  compensation respectively.
- *
- *  @param[in]  avctx     ptr to the AVCodecContext
- *  @param[in]  band      pointer to the band descriptor
- *  @param[in]  tile      pointer to the tile descriptor
- *  @param[in]  mv_scale  scaling factor for motion vectors
- */
-void ff_ivi_process_empty_tile(AVCodecContext *avctx, IVIBandDesc *band,
-                               IVITile *tile, int32_t mv_scale);
-
-/**
  *  Convert and output the current plane.
  *  This conversion is done by adding back the bias value of 128
  *  (subtracted in the encoder) and clipping the result.
@@ -348,4 +396,8 @@ uint16_t ivi_calc_band_checksum (IVIBandDesc *band);
  */
 int ivi_check_band (IVIBandDesc *band, const uint8_t *ref, int pitch);
 
+int ff_ivi_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
+                        AVPacket *avpkt);
+av_cold int ff_ivi_decode_close(AVCodecContext *avctx);
+
 #endif /* AVCODEC_IVI_COMMON_H */
diff --git a/libavcodec/lagarith.c b/libavcodec/lagarith.c
index 6828ba8..f04d89b 100644
--- a/libavcodec/lagarith.c
+++ b/libavcodec/lagarith.c
@@ -326,6 +326,11 @@ static int lag_decode_zero_run_line(LagarithContext *l, uint8_t *dst,
 output_zeros:
     if (l->zeros_rem) {
         count = FFMIN(l->zeros_rem, width - i);
+        if (end - dst < count) {
+            av_log(l->avctx, AV_LOG_ERROR, "Too many zeros remaining.\n");
+            return AVERROR_INVALIDDATA;
+        }
+
         memset(dst, 0, count);
         l->zeros_rem -= count;
         dst += count;
diff --git a/libavcodec/libvorbis.c b/libavcodec/libvorbis.c
index 25e6006..60235d7 100644
--- a/libavcodec/libvorbis.c
+++ b/libavcodec/libvorbis.c
@@ -29,6 +29,7 @@
 #include "libavutil/opt.h"
 #include "avcodec.h"
 #include "bytestream.h"
+#include "internal.h"
 #include "vorbis.h"
 #include "libavutil/mathematics.h"
 
@@ -59,6 +60,12 @@ static const AVOption options[] = {
     { "iblock", "Sets the impulse block bias", offsetof(OggVorbisContext, iblock), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, -15, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
     { NULL }
 };
+
+static const AVCodecDefault defaults[] = {
+    { "b",  "0" },
+    { NULL },
+};
+
 static const AVClass class = { "libvorbis", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
 
 static av_cold int oggvorbis_init_encoder(vorbis_info *vi, AVCodecContext *avccontext)
@@ -66,20 +73,27 @@ static av_cold int oggvorbis_init_encoder(vorbis_info *vi, AVCodecContext *avcco
     OggVorbisContext *context = avccontext->priv_data;
     double cfreq;
 
-    if (avccontext->flags & CODEC_FLAG_QSCALE) {
-        /* variable bitrate */
+    if (avccontext->flags & CODEC_FLAG_QSCALE || !avccontext->bit_rate) {
+        /* variable bitrate
+         * NOTE: we use the oggenc range of -1 to 10 for global_quality for
+         *       user convenience, but libvorbis uses -0.1 to 1.0.
+         */
+        float q = avccontext->global_quality / (float)FF_QP2LAMBDA;
+        /* default to 3 if the user did not set quality or bitrate */
+        if (!(avccontext->flags & CODEC_FLAG_QSCALE))
+            q = 3.0;
         if (vorbis_encode_setup_vbr(vi, avccontext->channels,
                                     avccontext->sample_rate,
-                                    avccontext->global_quality / (float)FF_QP2LAMBDA / 10.0))
+                                    q / 10.0))
             return -1;
     } else {
         int minrate = avccontext->rc_min_rate > 0 ? avccontext->rc_min_rate : -1;
-        int maxrate = avccontext->rc_min_rate > 0 ? avccontext->rc_max_rate : -1;
+        int maxrate = avccontext->rc_max_rate > 0 ? avccontext->rc_max_rate : -1;
 
         /* constant bitrate */
         if (vorbis_encode_setup_managed(vi, avccontext->channels,
-                                        avccontext->sample_rate, minrate,
-                                        avccontext->bit_rate, maxrate))
+                                        avccontext->sample_rate, maxrate,
+                                        avccontext->bit_rate, minrate))
             return -1;
 
         /* variable bitrate by estimate, disable slow rate management */
@@ -262,4 +276,5 @@ AVCodec ff_libvorbis_encoder = {
     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("libvorbis Vorbis"),
     .priv_class     = &class,
+    .defaults       = defaults,
 };
diff --git a/libavcodec/mimic.c b/libavcodec/mimic.c
index fd03b97..013dc2e 100644
--- a/libavcodec/mimic.c
+++ b/libavcodec/mimic.c
@@ -413,7 +413,7 @@ static av_cold int mimic_decode_end(AVCodecContext *avctx)
     for(i = 0; i < 16; i++)
         if(ctx->buf_ptrs[i].data[0])
             ff_thread_release_buffer(avctx, &ctx->buf_ptrs[i]);
-    free_vlc(&ctx->vlc);
+    ff_free_vlc(&ctx->vlc);
 
     return 0;
 }
diff --git a/libavcodec/mjpegdec.c b/libavcodec/mjpegdec.c
index 7f12fc1..542de98 100644
--- a/libavcodec/mjpegdec.c
+++ b/libavcodec/mjpegdec.c
@@ -62,8 +62,8 @@ static int build_vlc(VLC *vlc, const uint8_t *bits_table,
     if (is_ac)
         huff_sym[0] = 16 * 256;
 
-    return init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
-                           huff_code, 2, 2, huff_sym, 2, 2, use_static);
+    return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
+                              huff_code, 2, 2, huff_sym, 2, 2, use_static);
 }
 
 static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)
@@ -195,7 +195,7 @@ int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
         len -= n;
 
         /* build VLC and flush previous vlc if present */
-        free_vlc(&s->vlcs[class][index]);
+        ff_free_vlc(&s->vlcs[class][index]);
         av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
                class, index, code_max + 1);
         if (build_vlc(&s->vlcs[class][index], bits_table, val_table,
@@ -203,7 +203,7 @@ int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
             return -1;
 
         if (class > 0) {
-            free_vlc(&s->vlcs[2][index]);
+            ff_free_vlc(&s->vlcs[2][index]);
             if (build_vlc(&s->vlcs[2][index], bits_table, val_table,
                           code_max + 1, 0, 0) < 0)
                 return -1;
@@ -1642,7 +1642,7 @@ av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
 
     for (i = 0; i < 3; i++) {
         for (j = 0; j < 4; j++)
-            free_vlc(&s->vlcs[i][j]);
+            ff_free_vlc(&s->vlcs[i][j]);
     }
     for (i = 0; i < MAX_COMPONENTS; i++) {
         av_freep(&s->blocks[i]);
diff --git a/libavcodec/motionpixels.c b/libavcodec/motionpixels.c
index 8259447..0e1da3a 100644
--- a/libavcodec/motionpixels.c
+++ b/libavcodec/motionpixels.c
@@ -292,7 +292,7 @@ static int mp_decode_frame(AVCodecContext *avctx,
     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);
+    ff_free_vlc(&mp->vlc);
 
 end:
     *data_size = sizeof(AVFrame);
diff --git a/libavcodec/mpc8.c b/libavcodec/mpc8.c
index b97f3ed..f5eb4d6 100644
--- a/libavcodec/mpc8.c
+++ b/libavcodec/mpc8.c
@@ -182,13 +182,13 @@ static av_cold int mpc8_decode_init(AVCodecContext * avctx)
 
     q3_vlc[0].table = q3_0_table;
     q3_vlc[0].table_allocated = 512;
-    init_vlc_sparse(&q3_vlc[0], MPC8_Q3_BITS, MPC8_Q3_SIZE,
+    ff_init_vlc_sparse(&q3_vlc[0], MPC8_Q3_BITS, MPC8_Q3_SIZE,
              mpc8_q3_bits,  1, 1,
              mpc8_q3_codes, 1, 1,
              mpc8_q3_syms,  1, 1, INIT_VLC_USE_NEW_STATIC);
     q3_vlc[1].table = q3_1_table;
     q3_vlc[1].table_allocated = 516;
-    init_vlc_sparse(&q3_vlc[1], MPC8_Q4_BITS, MPC8_Q4_SIZE,
+    ff_init_vlc_sparse(&q3_vlc[1], MPC8_Q4_BITS, MPC8_Q4_SIZE,
              mpc8_q4_bits,  1, 1,
              mpc8_q4_codes, 1, 1,
              mpc8_q4_syms,  1, 1, INIT_VLC_USE_NEW_STATIC);
diff --git a/libavcodec/mpeg12.c b/libavcodec/mpeg12.c
index d79cf70..65dfe47 100644
--- a/libavcodec/mpeg12.c
+++ b/libavcodec/mpeg12.c
@@ -693,8 +693,8 @@ av_cold void ff_mpeg12_init_vlcs(void)
         INIT_VLC_STATIC(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 11,
                         &table_mb_btype[0][1], 2, 1,
                         &table_mb_btype[0][0], 2, 1, 64);
-        init_rl(&ff_rl_mpeg1, ff_mpeg12_static_rl_table_store[0]);
-        init_rl(&ff_rl_mpeg2, ff_mpeg12_static_rl_table_store[1]);
+        ff_init_rl(&ff_rl_mpeg1, ff_mpeg12_static_rl_table_store[0]);
+        ff_init_rl(&ff_rl_mpeg2, ff_mpeg12_static_rl_table_store[1]);
 
         INIT_2D_VLC_RL(ff_rl_mpeg1, 680);
         INIT_2D_VLC_RL(ff_rl_mpeg2, 674);
diff --git a/libavcodec/mpeg12enc.c b/libavcodec/mpeg12enc.c
index 17097db..b0950b8 100644
--- a/libavcodec/mpeg12enc.c
+++ b/libavcodec/mpeg12enc.c
@@ -722,8 +722,8 @@ void ff_mpeg1_encode_init(MpegEncContext *s)
         int i;
 
         done=1;
-        init_rl(&ff_rl_mpeg1, ff_mpeg12_static_rl_table_store[0]);
-        init_rl(&ff_rl_mpeg2, ff_mpeg12_static_rl_table_store[1]);
+        ff_init_rl(&ff_rl_mpeg1, ff_mpeg12_static_rl_table_store[0]);
+        ff_init_rl(&ff_rl_mpeg2, ff_mpeg12_static_rl_table_store[1]);
 
         for(i=0; i<64; i++)
         {
diff --git a/libavcodec/mpeg4videodec.c b/libavcodec/mpeg4videodec.c
index e15c348..b243a23 100644
--- a/libavcodec/mpeg4videodec.c
+++ b/libavcodec/mpeg4videodec.c
@@ -651,13 +651,13 @@ try_again:
                     if ((cbpc & 16) == 0) {
                         /* 16x16 motion prediction */
 
-                        h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+                        ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
                         if(!s->mcsel){
-                            mx = h263_decode_motion(s, pred_x, s->f_code);
+                            mx = ff_h263_decode_motion(s, pred_x, s->f_code);
                             if (mx >= 0xffff)
                                 return -1;
 
-                            my = h263_decode_motion(s, pred_y, s->f_code);
+                            my = ff_h263_decode_motion(s, pred_y, s->f_code);
                             if (my >= 0xffff)
                                 return -1;
                             s->current_picture.f.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
@@ -675,12 +675,12 @@ try_again:
                         int i;
                         s->current_picture.f.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
                         for(i=0;i<4;i++) {
-                            int16_t *mot_val= h263_pred_motion(s, i, 0, &pred_x, &pred_y);
-                            mx = h263_decode_motion(s, pred_x, s->f_code);
+                            int16_t *mot_val= ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
+                            mx = ff_h263_decode_motion(s, pred_x, s->f_code);
                             if (mx >= 0xffff)
                                 return -1;
 
-                            my = h263_decode_motion(s, pred_y, s->f_code);
+                            my = ff_h263_decode_motion(s, pred_y, s->f_code);
                             if (my >= 0xffff)
                                 return -1;
                             mot_val[0] = mx;
@@ -1223,14 +1223,14 @@ static int mpeg4_decode_mb(MpegEncContext *s,
                 s->field_select[0][0]= get_bits1(&s->gb);
                 s->field_select[0][1]= get_bits1(&s->gb);
 
-                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
 
                 for(i=0; i<2; i++){
-                    mx = h263_decode_motion(s, pred_x, s->f_code);
+                    mx = ff_h263_decode_motion(s, pred_x, s->f_code);
                     if (mx >= 0xffff)
                         return -1;
 
-                    my = h263_decode_motion(s, pred_y/2, s->f_code);
+                    my = ff_h263_decode_motion(s, pred_y/2, s->f_code);
                     if (my >= 0xffff)
                         return -1;
 
@@ -1241,13 +1241,13 @@ static int mpeg4_decode_mb(MpegEncContext *s,
                 s->current_picture.f.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
                 /* 16x16 motion prediction */
                 s->mv_type = MV_TYPE_16X16;
-                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
-                mx = h263_decode_motion(s, pred_x, s->f_code);
+                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+                mx = ff_h263_decode_motion(s, pred_x, s->f_code);
 
                 if (mx >= 0xffff)
                     return -1;
 
-                my = h263_decode_motion(s, pred_y, s->f_code);
+                my = ff_h263_decode_motion(s, pred_y, s->f_code);
 
                 if (my >= 0xffff)
                     return -1;
@@ -1258,12 +1258,12 @@ static int mpeg4_decode_mb(MpegEncContext *s,
             s->current_picture.f.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
             s->mv_type = MV_TYPE_8X8;
             for(i=0;i<4;i++) {
-                mot_val = h263_pred_motion(s, i, 0, &pred_x, &pred_y);
-                mx = h263_decode_motion(s, pred_x, s->f_code);
+                mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
+                mx = ff_h263_decode_motion(s, pred_x, s->f_code);
                 if (mx >= 0xffff)
                     return -1;
 
-                my = h263_decode_motion(s, pred_y, s->f_code);
+                my = ff_h263_decode_motion(s, pred_y, s->f_code);
                 if (my >= 0xffff)
                     return -1;
                 s->mv[0][i][0] = mx;
@@ -1359,8 +1359,8 @@ static int mpeg4_decode_mb(MpegEncContext *s,
                 if(USES_LIST(mb_type, 0)){
                     s->mv_dir = MV_DIR_FORWARD;
 
-                    mx = h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
-                    my = h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
+                    mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
+                    my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
                     s->last_mv[0][1][0]= s->last_mv[0][0][0]= s->mv[0][0][0] = mx;
                     s->last_mv[0][1][1]= s->last_mv[0][0][1]= s->mv[0][0][1] = my;
                 }
@@ -1368,8 +1368,8 @@ static int mpeg4_decode_mb(MpegEncContext *s,
                 if(USES_LIST(mb_type, 1)){
                     s->mv_dir |= MV_DIR_BACKWARD;
 
-                    mx = h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
-                    my = h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
+                    mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
+                    my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
                     s->last_mv[1][1][0]= s->last_mv[1][0][0]= s->mv[1][0][0] = mx;
                     s->last_mv[1][1][1]= s->last_mv[1][0][1]= s->mv[1][0][1] = my;
                 }
@@ -1380,8 +1380,8 @@ static int mpeg4_decode_mb(MpegEncContext *s,
                     s->mv_dir = MV_DIR_FORWARD;
 
                     for(i=0; i<2; i++){
-                        mx = h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
-                        my = h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
+                        mx = ff_h263_decode_motion(s, s->last_mv[0][i][0]  , s->f_code);
+                        my = ff_h263_decode_motion(s, s->last_mv[0][i][1]/2, s->f_code);
                         s->last_mv[0][i][0]=  s->mv[0][i][0] = mx;
                         s->last_mv[0][i][1]= (s->mv[0][i][1] = my)*2;
                     }
@@ -1391,8 +1391,8 @@ static int mpeg4_decode_mb(MpegEncContext *s,
                     s->mv_dir |= MV_DIR_BACKWARD;
 
                     for(i=0; i<2; i++){
-                        mx = h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
-                        my = h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
+                        mx = ff_h263_decode_motion(s, s->last_mv[1][i][0]  , s->b_code);
+                        my = ff_h263_decode_motion(s, s->last_mv[1][i][1]/2, s->b_code);
                         s->last_mv[1][i][0]=  s->mv[1][i][0] = mx;
                         s->last_mv[1][i][1]= (s->mv[1][i][1] = my)*2;
                     }
@@ -1404,8 +1404,8 @@ static int mpeg4_decode_mb(MpegEncContext *s,
             if(IS_SKIP(mb_type))
                 mx=my=0;
             else{
-                mx = h263_decode_motion(s, 0, 1);
-                my = h263_decode_motion(s, 0, 1);
+                mx = ff_h263_decode_motion(s, 0, 1);
+                my = ff_h263_decode_motion(s, 0, 1);
             }
 
             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
@@ -2205,9 +2205,9 @@ static av_cold int decode_init(AVCodecContext *avctx)
     if (!done) {
         done = 1;
 
-        init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
-        init_rl(&rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
-        init_rl(&rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
+        ff_init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
+        ff_init_rl(&rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
+        ff_init_rl(&rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
         INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
         INIT_VLC_RL(rvlc_rl_inter, 1072);
         INIT_VLC_RL(rvlc_rl_intra, 1072);
diff --git a/libavcodec/mpeg4videoenc.c b/libavcodec/mpeg4videoenc.c
index 41c153d..b7c2da7 100644
--- a/libavcodec/mpeg4videoenc.c
+++ b/libavcodec/mpeg4videoenc.c
@@ -693,7 +693,7 @@ void mpeg4_encode_mb(MpegEncContext * s,
                 }
 
                 /* motion vectors: 16x16 mode */
-                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
 
                 ff_h263_encode_motion_vector(s, motion_x - pred_x,
                                                 motion_y - pred_y, s->f_code);
@@ -717,7 +717,7 @@ void mpeg4_encode_mb(MpegEncContext * s,
                 }
 
                 /* motion vectors: 16x8 interlaced mode */
-                h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
                 pred_y /=2;
 
                 put_bits(&s->pb, 1, s->field_select[0][0]);
@@ -745,7 +745,7 @@ void mpeg4_encode_mb(MpegEncContext * s,
 
                 for(i=0; i<4; i++){
                     /* motion vectors: 8x8 mode*/
-                    h263_pred_motion(s, i, 0, &pred_x, &pred_y);
+                    ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
 
                     ff_h263_encode_motion_vector(s, s->current_picture.f.motion_val[0][ s->block_index[i] ][0] - pred_x,
                                                     s->current_picture.f.motion_val[0][ s->block_index[i] ][1] - pred_y, s->f_code);
@@ -1230,7 +1230,7 @@ static av_cold int encode_init(AVCodecContext *avctx)
 
         init_uni_dc_tab();
 
-        init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
+        ff_init_rl(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
 
         init_uni_mpeg4_rl_tab(&ff_mpeg4_rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
         init_uni_mpeg4_rl_tab(&ff_h263_rl_inter, uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
diff --git a/libavcodec/mpegaudiodec.c b/libavcodec/mpegaudiodec.c
index d902573..bb1baef 100644
--- a/libavcodec/mpegaudiodec.c
+++ b/libavcodec/mpegaudiodec.c
@@ -208,7 +208,7 @@ static void ff_compute_band_indexes(MPADecodeContext *s, GranuleDef *g)
             else
                 g->long_end = 4; /* 8000 Hz */
 
-            g->short_start = 2 + (s->sample_rate_index != 8);
+            g->short_start = 3;
         } else {
             g->long_end    = 0;
             g->short_start = 0;
diff --git a/libavcodec/mpegvideo.c b/libavcodec/mpegvideo.c
index 7aaf398..fa89886 100644
--- a/libavcodec/mpegvideo.c
+++ b/libavcodec/mpegvideo.c
@@ -1005,8 +1005,8 @@ void MPV_common_end(MpegEncContext *s)
         avcodec_default_free_buffers(s->avctx);
 }
 
-void init_rl(RLTable *rl,
-             uint8_t static_store[2][2 * MAX_RUN + MAX_LEVEL + 3])
+void ff_init_rl(RLTable *rl,
+                uint8_t static_store[2][2 * MAX_RUN + MAX_LEVEL + 3])
 {
     int8_t  max_level[MAX_RUN + 1], max_run[MAX_LEVEL + 1];
     uint8_t index_run[MAX_RUN + 1];
@@ -1057,7 +1057,7 @@ void init_rl(RLTable *rl,
     }
 }
 
-void init_vlc_rl(RLTable *rl)
+void ff_init_vlc_rl(RLTable *rl)
 {
     int i, q;
 
diff --git a/libavcodec/mpegvideo_common.h b/libavcodec/mpegvideo_common.h
index 9f6307e..e8daf2e 100644
--- a/libavcodec/mpegvideo_common.h
+++ b/libavcodec/mpegvideo_common.h
@@ -725,7 +725,8 @@ static av_always_inline void MPV_motion_internal(MpegEncContext *s,
                         0, 0, 0,
                         ref_picture, pix_op, qpix_op,
                         s->mv[dir][0][0], s->mv[dir][0][1], 16);
-        }else if(!is_mpeg12 && (CONFIG_WMV2_DECODER || CONFIG_WMV2_ENCODER) && s->mspel){
+        } else if (!is_mpeg12 && (CONFIG_WMV2_DECODER || CONFIG_WMV2_ENCODER) &&
+                   s->mspel && s->codec_id == CODEC_ID_WMV2) {
             ff_mspel_motion(s, dest_y, dest_cb, dest_cr,
                         ref_picture, pix_op,
                         s->mv[dir][0][0], s->mv[dir][0][1], 16);
diff --git a/libavcodec/mpegvideo_enc.c b/libavcodec/mpegvideo_enc.c
index 08484a7..af72806 100644
--- a/libavcodec/mpegvideo_enc.c
+++ b/libavcodec/mpegvideo_enc.c
@@ -708,7 +708,7 @@ av_cold int MPV_encode_init(AVCodecContext *avctx)
     case CODEC_ID_H263:
         if (!CONFIG_H263_ENCODER)
         return -1;
-        if (ff_match_2uint16(h263_format, FF_ARRAY_ELEMS(h263_format),
+        if (ff_match_2uint16(ff_h263_format, FF_ARRAY_ELEMS(ff_h263_format),
                              s->width, s->height) == 8) {
             av_log(avctx, AV_LOG_INFO,
                    "The specified picture size of %dx%d is not valid for "
@@ -844,7 +844,7 @@ av_cold int MPV_encode_init(AVCodecContext *avctx)
     if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)
         ff_h261_encode_init(s);
     if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)
-        h263_encode_init(s);
+        ff_h263_encode_init(s);
     if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
         ff_msmpeg4_encode_init(s);
     if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
@@ -2078,7 +2078,7 @@ static av_always_inline void encode_mb_internal(MpegEncContext *s,
     case CODEC_ID_RV10:
     case CODEC_ID_RV20:
         if (CONFIG_H263_ENCODER)
-            h263_encode_mb(s, s->block, motion_x, motion_y);
+            ff_h263_encode_mb(s, s->block, motion_x, motion_y);
         break;
     case CODEC_ID_MJPEG:
         if (CONFIG_MJPEG_ENCODER)
@@ -2508,7 +2508,7 @@ static int encode_thread(AVCodecContext *c, void *arg){
                     case CODEC_ID_H263:
                     case CODEC_ID_H263P:
                         if (CONFIG_H263_ENCODER)
-                            h263_encode_gob_header(s, mb_y);
+                            ff_h263_encode_gob_header(s, mb_y);
                     break;
                     }
 
@@ -3258,7 +3258,7 @@ static int encode_picture(MpegEncContext *s, int picture_number)
         else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
             ff_flv_encode_picture_header(s, picture_number);
         else if (CONFIG_H263_ENCODER)
-            h263_encode_picture_header(s, picture_number);
+            ff_h263_encode_picture_header(s, picture_number);
         break;
     case FMT_MPEG1:
         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
diff --git a/libavcodec/msmpeg4.c b/libavcodec/msmpeg4.c
index 11a1915..a58d135 100644
--- a/libavcodec/msmpeg4.c
+++ b/libavcodec/msmpeg4.c
@@ -262,7 +262,7 @@ av_cold void ff_msmpeg4_encode_init(MpegEncContext *s)
         init_mv_table(&mv_tables[0]);
         init_mv_table(&mv_tables[1]);
         for(i=0;i<NB_RL_TABLES;i++)
-            init_rl(&rl_table[i], static_rl_table_store[i]);
+            ff_init_rl(&rl_table[i], static_rl_table_store[i]);
 
         for(i=0; i<NB_RL_TABLES; i++){
             int level;
@@ -507,7 +507,7 @@ static void msmpeg4v2_encode_motion(MpegEncContext * s, int val)
     if (val == 0) {
         /* zero vector */
         code = 0;
-        put_bits(&s->pb, mvtab[code][1], mvtab[code][0]);
+        put_bits(&s->pb, ff_mvtab[code][1], ff_mvtab[code][0]);
     } else {
         bit_size = s->f_code - 1;
         range = 1 << bit_size;
@@ -526,7 +526,7 @@ static void msmpeg4v2_encode_motion(MpegEncContext * s, int val)
         code = (val >> bit_size) + 1;
         bits = val & (range - 1);
 
-        put_bits(&s->pb, mvtab[code][1] + 1, (mvtab[code][0] << 1) | sign);
+        put_bits(&s->pb, ff_mvtab[code][1] + 1, (ff_mvtab[code][0] << 1) | sign);
         if (bit_size > 0) {
             put_bits(&s->pb, bit_size, bits);
         }
@@ -575,7 +575,7 @@ void msmpeg4_encode_mb(MpegEncContext * s,
 
             s->misc_bits += get_bits_diff(s);
 
-            h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+            ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
             msmpeg4v2_encode_motion(s, motion_x - pred_x);
             msmpeg4v2_encode_motion(s, motion_y - pred_y);
         }else{
@@ -586,7 +586,7 @@ void msmpeg4_encode_mb(MpegEncContext * s,
             s->misc_bits += get_bits_diff(s);
 
             /* motion vector */
-            h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+            ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
             ff_msmpeg4_encode_motion(s, motion_x - pred_x,
                                   motion_y - pred_y);
         }
@@ -1134,7 +1134,7 @@ static int msmpeg4v12_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
         cbp|= cbpy<<2;
         if(s->msmpeg4_version==1 || (cbp&3) != 3) cbp^= 0x3C;
 
-        h263_pred_motion(s, 0, 0, &mx, &my);
+        ff_h263_pred_motion(s, 0, 0, &mx, &my);
         mx= msmpeg4v2_decode_motion(s, mx, 1);
         my= msmpeg4v2_decode_motion(s, my, 1);
 
@@ -1220,7 +1220,7 @@ static int msmpeg4v34_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
             s->rl_table_index = decode012(&s->gb);
             s->rl_chroma_table_index = s->rl_table_index;
         }
-        h263_pred_motion(s, 0, 0, &mx, &my);
+        ff_h263_pred_motion(s, 0, 0, &mx, &my);
         if (ff_msmpeg4_decode_motion(s, &mx, &my) < 0)
             return -1;
         s->mv_dir = MV_DIR_FORWARD;
@@ -1271,7 +1271,7 @@ av_cold int ff_msmpeg4_decode_init(AVCodecContext *avctx)
         done = 1;
 
         for(i=0;i<NB_RL_TABLES;i++) {
-            init_rl(&rl_table[i], static_rl_table_store[i]);
+            ff_init_rl(&rl_table[i], static_rl_table_store[i]);
         }
         INIT_VLC_RL(rl_table[0], 642);
         INIT_VLC_RL(rl_table[1], 1104);
@@ -1316,8 +1316,8 @@ av_cold int ff_msmpeg4_decode_init(AVCodecContext *avctx)
                  &v2_mb_type[0][1], 2, 1,
                  &v2_mb_type[0][0], 2, 1, 128);
         INIT_VLC_STATIC(&v2_mv_vlc, V2_MV_VLC_BITS, 33,
-                 &mvtab[0][1], 2, 1,
-                 &mvtab[0][0], 2, 1, 538);
+                 &ff_mvtab[0][1], 2, 1,
+                 &ff_mvtab[0][0], 2, 1, 538);
 
         INIT_VLC_STATIC(&ff_mb_non_intra_vlc[0], MB_NON_INTRA_VLC_BITS, 128,
                      &wmv2_inter_table[0][0][1], 8, 4,
diff --git a/libavcodec/msmpeg4data.c b/libavcodec/msmpeg4data.c
index 6799a9c..e51c725 100644
--- a/libavcodec/msmpeg4data.c
+++ b/libavcodec/msmpeg4data.c
@@ -592,9 +592,9 @@ static const int8_t table4_run[168] = {
  29, 30, 31, 32, 33, 34, 35, 36,
 };
 
-extern const uint16_t inter_vlc[103][2];
-extern const int8_t inter_level[102];
-extern const int8_t inter_run[102];
+extern const uint16_t ff_inter_vlc[103][2];
+extern const int8_t ff_inter_level[102];
+extern const int8_t ff_inter_run[102];
 
 extern const uint16_t ff_mpeg4_intra_vlc[103][2];
 extern const int8_t ff_mpeg4_intra_level[102];
@@ -647,9 +647,9 @@ RLTable rl_table[NB_RL_TABLES] = {
     {
         102,
         58,
-        inter_vlc,
-        inter_run,
-        inter_level,
+        ff_inter_vlc,
+        ff_inter_run,
+        ff_inter_level,
     },
 };
 
diff --git a/libavcodec/nuv.c b/libavcodec/nuv.c
index 94962b5..519b550 100644
--- a/libavcodec/nuv.c
+++ b/libavcodec/nuv.c
@@ -184,8 +184,9 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
     }
     if (c->codec_frameheader) {
         int w, h, q;
-        if (buf[0] != 'V' || buf_size < 12) {
-            av_log(avctx, AV_LOG_ERROR, "invalid nuv video frame (wrong codec_tag?)\n");
+        if (buf_size < RTJPEG_HEADER_SIZE || buf[4] != RTJPEG_HEADER_SIZE ||
+            buf[5] != RTJPEG_FILE_VERSION) {
+            av_log(avctx, AV_LOG_ERROR, "invalid nuv video frame\n");
             return AVERROR_INVALIDDATA;
         }
         w = AV_RL16(&buf[6]);
@@ -193,8 +194,8 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
         q = buf[10];
         if (!codec_reinit(avctx, w, h, q))
             return -1;
-        buf = &buf[12];
-        buf_size -= 12;
+        buf = &buf[RTJPEG_HEADER_SIZE];
+        buf_size -= RTJPEG_HEADER_SIZE;
     }
 
     if (keyframe && c->pic.data[0])
diff --git a/libavcodec/options.c b/libavcodec/options.c
index 26f3ab3..d6e36cb 100644
--- a/libavcodec/options.c
+++ b/libavcodec/options.c
@@ -219,15 +219,13 @@ static const AVOption options[]={
 {"parse_only", NULL, OFFSET(parse_only), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
 #endif
 {"mpeg_quant", "use MPEG quantizers instead of H.263", OFFSET(mpeg_quant), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
-{"stats_out", NULL, OFFSET(stats_out), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX},
-{"stats_in", NULL, OFFSET(stats_in), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX},
 {"qsquish", "how to keep quantizer between qmin and qmax (0 = clip, 1 = use differentiable function)", OFFSET(rc_qsquish), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, 0, 99, V|E},
 {"rc_qmod_amp", "experimental quantizer modulation", OFFSET(rc_qmod_amp), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, -FLT_MAX, FLT_MAX, V|E},
 {"rc_qmod_freq", "experimental quantizer modulation", OFFSET(rc_qmod_freq), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
 {"rc_override_count", NULL, OFFSET(rc_override_count), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX},
 {"rc_eq", "set rate control equation", OFFSET(rc_eq), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, V|E},
-{"maxrate", "set max video bitrate tolerance (in bits/s)", OFFSET(rc_max_rate), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
-{"minrate", "set min video bitrate tolerance (in bits/s)", OFFSET(rc_min_rate), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
+{"maxrate", "set max bitrate tolerance (in bits/s)", OFFSET(rc_max_rate), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|A|E},
+{"minrate", "set min bitrate tolerance (in bits/s)", OFFSET(rc_min_rate), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|A|E},
 {"bufsize", "set ratecontrol buffer size (in bits)", OFFSET(rc_buffer_size), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, A|V|E},
 {"rc_buf_aggressivity", "currently useless", OFFSET(rc_buffer_aggressivity), AV_OPT_TYPE_FLOAT, {.dbl = 1.0 }, -FLT_MAX, FLT_MAX, V|E},
 {"i_qfactor", "qp factor between P and I frames", OFFSET(i_quant_factor), AV_OPT_TYPE_FLOAT, {.dbl = -0.8 }, -FLT_MAX, FLT_MAX, V|E},
diff --git a/libavcodec/rl.h b/libavcodec/rl.h
index 9c1ad7a..367cc98 100644
--- a/libavcodec/rl.h
+++ b/libavcodec/rl.h
@@ -53,8 +53,8 @@ typedef struct RLTable {
  * @param static_store static uint8_t array[2][2*MAX_RUN + MAX_LEVEL + 3] which will hold
  *                     the level and run tables, if this is NULL av_malloc() will be used
  */
-void init_rl(RLTable *rl, uint8_t static_store[2][2*MAX_RUN + MAX_LEVEL + 3]);
-void init_vlc_rl(RLTable *rl);
+void ff_init_rl(RLTable *rl, uint8_t static_store[2][2*MAX_RUN + MAX_LEVEL + 3]);
+void ff_init_vlc_rl(RLTable *rl);
 
 #define INIT_VLC_RL(rl, static_size)\
 {\
@@ -68,7 +68,7 @@ void init_vlc_rl(RLTable *rl);
         for(q=0; q<32; q++)\
             rl.rl_vlc[q]= rl_vlc_table[q];\
 \
-        init_vlc_rl(&rl);\
+        ff_init_vlc_rl(&rl);\
     }\
 }
 
diff --git a/libavcodec/rtjpeg.h b/libavcodec/rtjpeg.h
index d537c93..4b46689 100644
--- a/libavcodec/rtjpeg.h
+++ b/libavcodec/rtjpeg.h
@@ -25,6 +25,9 @@
 #include <stdint.h>
 #include "dsputil.h"
 
+#define RTJPEG_FILE_VERSION 0
+#define RTJPEG_HEADER_SIZE 12
+
 typedef struct {
     int w, h;
     DSPContext *dsp;
diff --git a/libavcodec/rv10.c b/libavcodec/rv10.c
index ff6c9c3..58604d1 100644
--- a/libavcodec/rv10.c
+++ b/libavcodec/rv10.c
@@ -471,7 +471,7 @@ static av_cold int rv10_decode_init(AVCodecContext *avctx)
     if (MPV_common_init(s) < 0)
         return -1;
 
-    h263_decode_init_vlc(s);
+    ff_h263_decode_init_vlc(s);
 
     /* init rv vlc */
     if (!done) {
diff --git a/libavcodec/rv34.c b/libavcodec/rv34.c
index 0aecc23..c05b71b 100644
--- a/libavcodec/rv34.c
+++ b/libavcodec/rv34.c
@@ -131,10 +131,10 @@ static void rv34_gen_vlc(const uint8_t *bits, int size, VLC *vlc, const uint8_t
 
     vlc->table = &table_data[table_offs[num]];
     vlc->table_allocated = table_offs[num + 1] - table_offs[num];
-    init_vlc_sparse(vlc, FFMIN(maxbits, 9), realsize,
-                    bits2, 1, 1,
-                    cw,    2, 2,
-                    syms,  2, 2, INIT_VLC_USE_NEW_STATIC);
+    ff_init_vlc_sparse(vlc, FFMIN(maxbits, 9), realsize,
+                       bits2, 1, 1,
+                       cw,    2, 2,
+                       syms,  2, 2, INIT_VLC_USE_NEW_STATIC);
 }
 
 /**
@@ -1411,7 +1411,7 @@ static int rv34_decode_slice(RV34DecContext *r, int end, const uint8_t* buf, int
 {
     MpegEncContext *s = &r->s;
     GetBitContext *gb = &s->gb;
-    int mb_pos;
+    int mb_pos, slice_type;
     int res;
 
     init_get_bits(&r->s.gb, buf, buf_size*8);
@@ -1421,60 +1421,10 @@ static int rv34_decode_slice(RV34DecContext *r, int end, const uint8_t* buf, int
         return -1;
     }
 
-    if ((s->mb_x == 0 && s->mb_y == 0) || s->current_picture_ptr==NULL) {
-        if (s->width != r->si.width || s->height != r->si.height) {
-            int err;
-
-            av_log(s->avctx, AV_LOG_WARNING, "Changing dimensions to %dx%d\n",
-                   r->si.width, r->si.height);
-            MPV_common_end(s);
-            s->width  = r->si.width;
-            s->height = r->si.height;
-            avcodec_set_dimensions(s->avctx, s->width, s->height);
-            if ((err = MPV_common_init(s)) < 0)
-                return err;
-            if ((err = rv34_decoder_realloc(r)) < 0)
-                return err;
-        }
-        s->pict_type = r->si.type ? r->si.type : AV_PICTURE_TYPE_I;
-        if(MPV_frame_start(s, s->avctx) < 0)
-            return -1;
-        ff_er_frame_start(s);
-        if (!r->tmp_b_block_base) {
-            int i;
-
-            r->tmp_b_block_base = av_malloc(s->linesize * 48);
-            for (i = 0; i < 2; i++)
-                r->tmp_b_block_y[i] = r->tmp_b_block_base + i * 16 * s->linesize;
-            for (i = 0; i < 4; i++)
-                r->tmp_b_block_uv[i] = r->tmp_b_block_base + 32 * s->linesize
-                                       + (i >> 1) * 8 * s->uvlinesize + (i & 1) * 16;
-        }
-        r->cur_pts = r->si.pts;
-        if(s->pict_type != AV_PICTURE_TYPE_B){
-            r->last_pts = r->next_pts;
-            r->next_pts = r->cur_pts;
-        }else{
-            int refdist = GET_PTS_DIFF(r->next_pts, r->last_pts);
-            int dist0   = GET_PTS_DIFF(r->cur_pts,  r->last_pts);
-            int dist1   = GET_PTS_DIFF(r->next_pts, r->cur_pts);
-
-            if(!refdist){
-                r->weight1 = r->weight2 = 8192;
-            }else{
-                r->weight1 = (dist0 << 14) / refdist;
-                r->weight2 = (dist1 << 14) / refdist;
-            }
-        }
-        s->mb_x = s->mb_y = 0;
-        ff_thread_finish_setup(s->avctx);
-    } else {
-        int slice_type = r->si.type ? r->si.type : AV_PICTURE_TYPE_I;
-
-        if (slice_type != s->pict_type) {
-            av_log(s->avctx, AV_LOG_ERROR, "Slice type mismatch\n");
-            return AVERROR_INVALIDDATA;
-        }
+    slice_type = r->si.type ? r->si.type : AV_PICTURE_TYPE_I;
+    if (slice_type != s->pict_type) {
+        av_log(s->avctx, AV_LOG_ERROR, "Slice type mismatch\n");
+        return AVERROR_INVALIDDATA;
     }
 
     r->si.end = end;
@@ -1624,10 +1574,6 @@ int ff_rv34_decode_update_thread_context(AVCodecContext *dst, const AVCodecConte
 
     memset(&r->si, 0, sizeof(r->si));
 
-    /* necessary since it is it the condition checked for in decode_slice
-     * to call MPV_frame_start. cmp. comment at the end of decode_frame */
-    s->current_picture_ptr = NULL;
-
     return 0;
 }
 
@@ -1637,8 +1583,33 @@ static int get_slice_offset(AVCodecContext *avctx, const uint8_t *buf, int n)
     else                   return AV_RL32(buf + n*8 - 4) == 1 ? AV_RL32(buf + n*8) :  AV_RB32(buf + n*8);
 }
 
+static int finish_frame(AVCodecContext *avctx, AVFrame *pict)
+{
+    RV34DecContext *r = avctx->priv_data;
+    MpegEncContext *s = &r->s;
+    int got_picture = 0;
+
+    ff_er_frame_end(s);
+    MPV_frame_end(s);
+
+    if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
+        ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
+
+    if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
+        *pict = s->current_picture_ptr->f;
+        got_picture = 1;
+    } else if (s->last_picture_ptr != NULL) {
+        *pict = s->last_picture_ptr->f;
+        got_picture = 1;
+    }
+    if (got_picture)
+        ff_print_debug_info(s, pict);
+
+    return got_picture;
+}
+
 int ff_rv34_decode_frame(AVCodecContext *avctx,
-                            void *data, int *data_size,
+                            void *data, int *got_picture_ptr,
                             AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
@@ -1656,10 +1627,10 @@ int ff_rv34_decode_frame(AVCodecContext *avctx,
     if (buf_size == 0) {
         /* special case for last picture */
         if (s->low_delay==0 && s->next_picture_ptr) {
-            *pict = *(AVFrame*)s->next_picture_ptr;
+            *pict = s->next_picture_ptr->f;
             s->next_picture_ptr = NULL;
 
-            *data_size = sizeof(AVFrame);
+            *got_picture_ptr = 1;
         }
         return 0;
     }
@@ -1676,20 +1647,95 @@ int ff_rv34_decode_frame(AVCodecContext *avctx,
     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;
+        return AVERROR_INVALIDDATA;
     }
     init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, 0), (buf_size-get_slice_offset(avctx, slices_hdr, 0))*8);
     if(r->parse_slice_header(r, &r->s.gb, &si) < 0 || si.start){
         av_log(avctx, AV_LOG_ERROR, "First slice header is incorrect\n");
-        return -1;
+        return AVERROR_INVALIDDATA;
+    }
+    if ((!s->last_picture_ptr || !s->last_picture_ptr->f.data[0]) &&
+        si.type == AV_PICTURE_TYPE_B) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid decoder state: B-frame without "
+               "reference data.\n");
+        return AVERROR_INVALIDDATA;
     }
-    if ((!s->last_picture_ptr || !s->last_picture_ptr->f.data[0]) && si.type == AV_PICTURE_TYPE_B)
-        return -1;
     if(   (avctx->skip_frame >= AVDISCARD_NONREF && si.type==AV_PICTURE_TYPE_B)
        || (avctx->skip_frame >= AVDISCARD_NONKEY && si.type!=AV_PICTURE_TYPE_I)
        ||  avctx->skip_frame >= AVDISCARD_ALL)
         return avpkt->size;
 
+    /* first slice */
+    if (si.start == 0) {
+        if (s->mb_num_left > 0) {
+            av_log(avctx, AV_LOG_ERROR, "New frame but still %d MB left.",
+                   s->mb_num_left);
+            ff_er_frame_end(s);
+            MPV_frame_end(s);
+        }
+
+        if (s->width != si.width || s->height != si.height) {
+            int err;
+
+            if (HAVE_THREADS &&
+                (s->avctx->active_thread_type & FF_THREAD_FRAME)) {
+                av_log_missing_feature(s->avctx, "Width/height changing with "
+                                       "frame threading is", 0);
+                return AVERROR_PATCHWELCOME;
+            }
+
+            av_log(s->avctx, AV_LOG_WARNING, "Changing dimensions to %dx%d\n",
+                   si.width, si.height);
+            MPV_common_end(s);
+            s->width  = si.width;
+            s->height = si.height;
+            avcodec_set_dimensions(s->avctx, s->width, s->height);
+            if ((err = MPV_common_init(s)) < 0)
+                return err;
+            if ((err = rv34_decoder_realloc(r)) < 0)
+                return err;
+        }
+        s->pict_type = si.type ? si.type : AV_PICTURE_TYPE_I;
+        if (MPV_frame_start(s, s->avctx) < 0)
+            return -1;
+        ff_er_frame_start(s);
+        if (!r->tmp_b_block_base) {
+            int i;
+
+            r->tmp_b_block_base = av_malloc(s->linesize * 48);
+            for (i = 0; i < 2; i++)
+                r->tmp_b_block_y[i] = r->tmp_b_block_base
+                                      + i * 16 * s->linesize;
+            for (i = 0; i < 4; i++)
+                r->tmp_b_block_uv[i] = r->tmp_b_block_base + 32 * s->linesize
+                                       + (i >> 1) * 8 * s->uvlinesize
+                                       + (i &  1) * 16;
+        }
+        r->cur_pts = si.pts;
+        if (s->pict_type != AV_PICTURE_TYPE_B) {
+            r->last_pts = r->next_pts;
+            r->next_pts = r->cur_pts;
+        } else {
+            int refdist = GET_PTS_DIFF(r->next_pts, r->last_pts);
+            int dist0   = GET_PTS_DIFF(r->cur_pts,  r->last_pts);
+            int dist1   = GET_PTS_DIFF(r->next_pts, r->cur_pts);
+
+            if (!refdist) {
+                r->weight1 = r->weight2 = 8192;
+            } else {
+                r->weight1 = (dist0 << 14) / refdist;
+                r->weight2 = (dist1 << 14) / refdist;
+            }
+        }
+        s->mb_x = s->mb_y = 0;
+        ff_thread_finish_setup(s->avctx);
+    } else if (HAVE_THREADS &&
+               (s->avctx->active_thread_type & FF_THREAD_FRAME)) {
+        av_log(s->avctx, AV_LOG_ERROR, "Decoder needs full frames in frame "
+               "multithreading mode (start MB is %d).\n", si.start);
+        return AVERROR_INVALIDDATA;
+    }
+
     for(i = 0; i < slice_count; i++){
         int offset = get_slice_offset(avctx, slices_hdr, i);
         int size;
@@ -1704,6 +1750,8 @@ int ff_rv34_decode_frame(AVCodecContext *avctx,
         }
 
         r->si.end = s->mb_width * s->mb_height;
+        s->mb_num_left = r->s.mb_x + r->s.mb_y*r->s.mb_width - r->si.start;
+
         if(i+1 < slice_count){
             if (get_slice_offset(avctx, slices_hdr, i+1) < 0 ||
                 get_slice_offset(avctx, slices_hdr, i+1) > buf_size) {
@@ -1724,32 +1772,28 @@ int ff_rv34_decode_frame(AVCodecContext *avctx,
             break;
         }
         last = rv34_decode_slice(r, r->si.end, buf + offset, size);
-        s->mb_num_left = r->s.mb_x + r->s.mb_y*r->s.mb_width - r->si.start;
         if(last)
             break;
     }
 
-    if(last && s->current_picture_ptr){
-        if(r->loop_filter)
-            r->loop_filter(r, s->mb_height - 1);
-        ff_er_frame_end(s);
-        MPV_frame_end(s);
+    if (s->current_picture_ptr) {
+        if (last) {
+            if(r->loop_filter)
+                r->loop_filter(r, s->mb_height - 1);
 
-        if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
+            *got_picture_ptr = finish_frame(avctx, pict);
+        } else if (HAVE_THREADS &&
+                   (s->avctx->active_thread_type & FF_THREAD_FRAME)) {
+            av_log(avctx, AV_LOG_INFO, "marking unfished frame as finished\n");
+            /* always mark the current frame as finished, frame-mt supports
+             * only complete frames */
+            ff_er_frame_end(s);
+            MPV_frame_end(s);
             ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
-
-        if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
-            *pict = *(AVFrame*)s->current_picture_ptr;
-        } else if (s->last_picture_ptr != NULL) {
-            *pict = *(AVFrame*)s->last_picture_ptr;
-        }
-
-        if(s->last_picture_ptr || s->low_delay){
-            *data_size = sizeof(AVFrame);
-            ff_print_debug_info(s, pict);
+            return AVERROR_INVALIDDATA;
         }
-        s->current_picture_ptr = NULL; //so we can detect if frame_end wasnt called (find some nicer solution...)
     }
+
     return avpkt->size;
 }
 
diff --git a/libavcodec/rv34data.h b/libavcodec/rv34data.h
index 41c5b20..3064124 100644
--- a/libavcodec/rv34data.h
+++ b/libavcodec/rv34data.h
@@ -101,7 +101,7 @@ static const uint8_t rv34_quant_to_vlc_set[2][31] = {
 
 /**
  * table for obtaining the quantizer difference
- * @todo Use with modified_quant_tab from h263data.h.
+ * @todo Use with ff_modified_quant_tab from h263data.h.
  */
 static const uint8_t rv34_dquant_tab[2][32]={
 //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
diff --git a/libavcodec/rv40.c b/libavcodec/rv40.c
index c55a07a..3f2a824 100644
--- a/libavcodec/rv40.c
+++ b/libavcodec/rv40.c
@@ -80,18 +80,18 @@ static av_cold void rv40_init_tables(void)
     for(i = 0; i < NUM_PTYPE_VLCS; i++){
         ptype_vlc[i].table = &ptype_table[i << PTYPE_VLC_BITS];
         ptype_vlc[i].table_allocated = 1 << PTYPE_VLC_BITS;
-        init_vlc_sparse(&ptype_vlc[i], PTYPE_VLC_BITS, PTYPE_VLC_SIZE,
-                         ptype_vlc_bits[i],  1, 1,
-                         ptype_vlc_codes[i], 1, 1,
-                         ptype_vlc_syms,     1, 1, INIT_VLC_USE_NEW_STATIC);
+        ff_init_vlc_sparse(&ptype_vlc[i], PTYPE_VLC_BITS, PTYPE_VLC_SIZE,
+                            ptype_vlc_bits[i],  1, 1,
+                            ptype_vlc_codes[i], 1, 1,
+                            ptype_vlc_syms,     1, 1, INIT_VLC_USE_NEW_STATIC);
     }
     for(i = 0; i < NUM_BTYPE_VLCS; i++){
         btype_vlc[i].table = &btype_table[i << BTYPE_VLC_BITS];
         btype_vlc[i].table_allocated = 1 << BTYPE_VLC_BITS;
-        init_vlc_sparse(&btype_vlc[i], BTYPE_VLC_BITS, BTYPE_VLC_SIZE,
-                         btype_vlc_bits[i],  1, 1,
-                         btype_vlc_codes[i], 1, 1,
-                         btype_vlc_syms,     1, 1, INIT_VLC_USE_NEW_STATIC);
+        ff_init_vlc_sparse(&btype_vlc[i], BTYPE_VLC_BITS, BTYPE_VLC_SIZE,
+                            btype_vlc_bits[i],  1, 1,
+                            btype_vlc_codes[i], 1, 1,
+                            btype_vlc_syms,     1, 1, INIT_VLC_USE_NEW_STATIC);
     }
 }
 
diff --git a/libavcodec/sipr.c b/libavcodec/sipr.c
index 4502fa5..818524c 100644
--- a/libavcodec/sipr.c
+++ b/libavcodec/sipr.c
@@ -486,8 +486,13 @@ static av_cold int sipr_decoder_init(AVCodecContext * avctx)
     case 29: ctx->mode = MODE_6k5; break;
     case 37: ctx->mode = MODE_5k0; break;
     default:
-        av_log(avctx, AV_LOG_ERROR, "Invalid block_align: %d\n", avctx->block_align);
-        return AVERROR(EINVAL);
+        if      (avctx->bit_rate > 12200) ctx->mode = MODE_16k;
+        else if (avctx->bit_rate > 7500 ) ctx->mode = MODE_8k5;
+        else if (avctx->bit_rate > 5750 ) ctx->mode = MODE_6k5;
+        else                              ctx->mode = MODE_5k0;
+        av_log(avctx, AV_LOG_WARNING,
+               "Invalid block_align: %d. Mode %s guessed based on bitrate: %d\n",
+               avctx->block_align, modes[ctx->mode].mode_name, avctx->bit_rate);
     }
 
     av_log(avctx, AV_LOG_DEBUG, "Mode: %s\n", modes[ctx->mode].mode_name);
diff --git a/libavcodec/smacker.c b/libavcodec/smacker.c
index 4714fa0..3928d8f 100644
--- a/libavcodec/smacker.c
+++ b/libavcodec/smacker.c
@@ -267,9 +267,9 @@ static int smacker_decode_header_tree(SmackVContext *smk, GetBitContext *gb, int
     *recodes = huff.values;
 
     if(vlc[0].table)
-        free_vlc(&vlc[0]);
+        ff_free_vlc(&vlc[0]);
     if(vlc[1].table)
-        free_vlc(&vlc[1]);
+        ff_free_vlc(&vlc[1]);
     av_free(tmp1.bits);
     av_free(tmp1.lengths);
     av_free(tmp1.values);
@@ -662,7 +662,7 @@ static int smka_decode_frame(AVCodecContext *avctx, void *data,
     }
     if(bits) { //decode 16-bit data
         for(i = stereo; i >= 0; i--)
-            pred[i] = av_bswap16(get_bits(&gb, 16));
+            pred[i] = sign_extend(av_bswap16(get_bits(&gb, 16)), 16);
         for(i = 0; i <= stereo; i++)
             *samples++ = pred[i];
         for(; i < unp_size / 2; i++) {
@@ -720,7 +720,7 @@ static int smka_decode_frame(AVCodecContext *avctx, void *data,
 
     for(i = 0; i < 4; i++) {
         if(vlc[i].table)
-            free_vlc(&vlc[i]);
+            ff_free_vlc(&vlc[i]);
         av_free(h[i].bits);
         av_free(h[i].lengths);
         av_free(h[i].values);
diff --git a/libavcodec/snow.c b/libavcodec/snow.c
index 905e02a..612f56a 100644
--- a/libavcodec/snow.c
+++ b/libavcodec/snow.c
@@ -385,7 +385,7 @@ mca( 8, 8,8)
 av_cold int ff_snow_common_init(AVCodecContext *avctx){
     SnowContext *s = avctx->priv_data;
     int width, height;
-    int i, j;
+    int i, j, ret;
 
     s->avctx= avctx;
     s->max_ref_frames=1; //just make sure its not an invalid value in case of no initial keyframe
@@ -438,17 +438,22 @@ av_cold int ff_snow_common_init(AVCodecContext *avctx){
     width= s->avctx->width;
     height= s->avctx->height;
 
-    s->spatial_idwt_buffer= av_mallocz(width*height*sizeof(IDWTELEM));
-    s->spatial_dwt_buffer= av_mallocz(width*height*sizeof(DWTELEM)); //FIXME this does not belong here
+    FF_ALLOCZ_OR_GOTO(avctx, s->spatial_idwt_buffer, width * height * sizeof(IDWTELEM), fail);
+    FF_ALLOCZ_OR_GOTO(avctx, s->spatial_dwt_buffer,  width * height * sizeof(DWTELEM),  fail); //FIXME this does not belong here
 
     for(i=0; i<MAX_REF_FRAMES; i++)
         for(j=0; j<MAX_REF_FRAMES; j++)
             scale_mv_ref[i][j] = 256*(i+1)/(j+1);
 
-    s->avctx->get_buffer(s->avctx, &s->mconly_picture);
-    s->scratchbuf = av_malloc(s->mconly_picture.linesize[0]*7*MB_SIZE);
+    if ((ret = s->avctx->get_buffer(s->avctx, &s->mconly_picture)) < 0) {
+        av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
+    }
+    FF_ALLOC_OR_GOTO(avctx, s->scratchbuf, s->mconly_picture.linesize[0]*7*MB_SIZE, fail);
 
     return 0;
+fail:
+    return AVERROR(ENOMEM);
 }
 
 int ff_snow_common_init_after_header(AVCodecContext *avctx) {
diff --git a/libavcodec/snowdec.c b/libavcodec/snowdec.c
index 70c5d4a..049d4a6 100644
--- a/libavcodec/snowdec.c
+++ b/libavcodec/snowdec.c
@@ -354,9 +354,14 @@ static int decode_header(SnowContext *s){
 
 static av_cold int decode_init(AVCodecContext *avctx)
 {
+    int ret;
+
     avctx->pix_fmt= PIX_FMT_YUV420P;
 
-    ff_snow_common_init(avctx);
+    if ((ret = ff_snow_common_init(avctx)) < 0) {
+        ff_snow_common_end(avctx->priv_data);
+        return ret;
+    }
 
     return 0;
 }
diff --git a/libavcodec/snowenc.c b/libavcodec/snowenc.c
index cd60c3a..d9fba96 100644
--- a/libavcodec/snowenc.c
+++ b/libavcodec/snowenc.c
@@ -156,7 +156,7 @@ static void dwt_quantize(SnowContext *s, Plane *p, DWTELEM *buffer, int width, i
 static av_cold int encode_init(AVCodecContext *avctx)
 {
     SnowContext *s = avctx->priv_data;
-    int plane_index;
+    int plane_index, ret;
 
     if(avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL){
         av_log(avctx, AV_LOG_ERROR, "This codec is under development, files encoded with it may not be decodable with future versions!!!\n"
@@ -185,7 +185,10 @@ static av_cold int encode_init(AVCodecContext *avctx)
         s->plane[plane_index].fast_mc= 1;
     }
 
-    ff_snow_common_init(avctx);
+    if ((ret = ff_snow_common_init(avctx)) < 0) {
+        ff_snow_common_end(avctx->priv_data);
+        return ret;
+    }
     ff_snow_alloc_blocks(s);
 
     s->version=0;
@@ -199,7 +202,7 @@ static av_cold int encode_init(AVCodecContext *avctx)
     s->m.me.map       = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));
     s->m.me.score_map = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));
     s->m.obmc_scratchpad= av_mallocz(MB_SIZE*MB_SIZE*12*sizeof(uint32_t));
-    h263_encode_init(&s->m); //mv_penalty
+    ff_h263_encode_init(&s->m); //mv_penalty
 
     s->max_ref_frames = FFMAX(FFMIN(avctx->refs, MAX_REF_FRAMES), 1);
 
diff --git a/libavcodec/svq1dec.c b/libavcodec/svq1dec.c
index 69dbd1b..1cbf1f5 100644
--- a/libavcodec/svq1dec.c
+++ b/libavcodec/svq1dec.c
@@ -43,7 +43,7 @@
 #undef NDEBUG
 #include <assert.h>
 
-extern const uint8_t mvtab[33][2];
+extern const uint8_t ff_mvtab[33][2];
 
 static VLC svq1_block_type;
 static VLC svq1_motion_component;
@@ -769,8 +769,8 @@ static av_cold int svq1_decode_init(AVCodecContext *avctx)
         &ff_svq1_block_type_vlc[0][0], 2, 1, 6);
 
     INIT_VLC_STATIC(&svq1_motion_component, 7, 33,
-        &mvtab[0][1], 2, 1,
-        &mvtab[0][0], 2, 1, 176);
+        &ff_mvtab[0][1], 2, 1,
+        &ff_mvtab[0][0], 2, 1, 176);
 
     for (i = 0; i < 6; i++) {
         static const uint8_t sizes[2][6] = {{14, 10, 14, 18, 16, 18}, {10, 10, 14, 14, 14, 16}};
diff --git a/libavcodec/svq1enc.c b/libavcodec/svq1enc.c
index 80bae3c..ef136b9 100644
--- a/libavcodec/svq1enc.c
+++ b/libavcodec/svq1enc.c
@@ -402,7 +402,7 @@ static int svq1_encode_plane(SVQ1Context *s, int plane, unsigned char *src_plane
                 int mx, my, pred_x, pred_y, dxy;
                 int16_t *motion_ptr;
 
-                motion_ptr= h263_pred_motion(&s->m, 0, 0, &pred_x, &pred_y);
+                motion_ptr= ff_h263_pred_motion(&s->m, 0, 0, &pred_x, &pred_y);
                 if(s->m.mb_type[x + y*s->m.mb_stride]&CANDIDATE_MB_TYPE_INTER){
                     for(i=0; i<6; i++)
                         init_put_bits(&s->reorder_pb[i], reorder_buffer[1][i], 7*32);
@@ -492,7 +492,7 @@ static av_cold int svq1_encode_init(AVCodecContext *avctx)
     s->m.me.score_map = av_mallocz(ME_MAP_SIZE*sizeof(uint32_t));
     s->mb_type        = av_mallocz((s->y_block_width+1)*s->y_block_height*sizeof(int16_t));
     s->dummy          = av_mallocz((s->y_block_width+1)*s->y_block_height*sizeof(int32_t));
-    h263_encode_init(&s->m); //mv_penalty
+    ff_h263_encode_init(&s->m); //mv_penalty
 
     return 0;
 }
diff --git a/libavcodec/tiffenc.c b/libavcodec/tiffenc.c
index 3b2b829..af9a870 100644
--- a/libavcodec/tiffenc.c
+++ b/libavcodec/tiffenc.c
@@ -316,6 +316,10 @@ static int encode_frame(AVCodecContext * avctx, unsigned char *buf,
 
     strip_sizes = av_mallocz(sizeof(*strip_sizes) * strips);
     strip_offsets = av_mallocz(sizeof(*strip_offsets) * strips);
+    if (!strip_sizes || !strip_offsets) {
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
 
     bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp
                     * s->subsampling[0] * s->subsampling[1] + 7) >> 3;
@@ -323,6 +327,7 @@ static int encode_frame(AVCodecContext * avctx, unsigned char *buf,
         yuv_line = av_malloc(bytes_per_row);
         if (yuv_line == NULL){
             av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");
+            ret = AVERROR(ENOMEM);
             goto fail;
         }
     }
@@ -335,6 +340,10 @@ static int encode_frame(AVCodecContext * avctx, unsigned char *buf,
 
         zlen = bytes_per_row * s->rps;
         zbuf = av_malloc(zlen);
+        if (!zbuf) {
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
         strip_offsets[0] = ptr - buf;
         zn = 0;
         for (j = 0; j < s->rps; j++) {
@@ -359,8 +368,13 @@ static int encode_frame(AVCodecContext * avctx, unsigned char *buf,
     } else
 #endif
     {
-        if(s->compr == TIFF_LZW)
+        if (s->compr == TIFF_LZW) {
             s->lzws = av_malloc(ff_lzw_encode_state_size);
+            if (!s->lzws) {
+                ret = AVERROR(ENOMEM);
+                goto fail;
+            }
+        }
         for (i = 0; i < s->height; i++) {
             if (strip_sizes[i / s->rps] == 0) {
                 if(s->compr == TIFF_LZW){
diff --git a/libavcodec/truemotion2.c b/libavcodec/truemotion2.c
index 81dc84a..09d9e27 100644
--- a/libavcodec/truemotion2.c
+++ b/libavcodec/truemotion2.c
@@ -190,7 +190,7 @@ static void tm2_free_codes(TM2Codes *code)
 {
     av_free(code->recode);
     if(code->vlc.table)
-        free_vlc(&code->vlc);
+        ff_free_vlc(&code->vlc);
 }
 
 static inline int tm2_get_token(GetBitContext *gb, TM2Codes *code)
diff --git a/libavcodec/utvideo.c b/libavcodec/utvideo.c
index 7fe024d..fdce255 100644
--- a/libavcodec/utvideo.c
+++ b/libavcodec/utvideo.c
@@ -103,10 +103,10 @@ static int build_huff(const uint8_t *src, VLC *vlc, int *fsym)
         code += 0x80000000u >> (he[i].len - 1);
     }
 
-    return init_vlc_sparse(vlc, FFMIN(he[last].len, 9), last + 1,
-                           bits,  sizeof(*bits),  sizeof(*bits),
-                           codes, sizeof(*codes), sizeof(*codes),
-                           syms,  sizeof(*syms),  sizeof(*syms), 0);
+    return ff_init_vlc_sparse(vlc, FFMIN(he[last].len, 9), last + 1,
+                              bits,  sizeof(*bits),  sizeof(*bits),
+                              codes, sizeof(*codes), sizeof(*codes),
+                              syms,  sizeof(*syms),  sizeof(*syms), 0);
 }
 
 static int decode_plane(UtvideoContext *c, int plane_no,
@@ -207,11 +207,11 @@ static int decode_plane(UtvideoContext *c, int plane_no,
                    get_bits_left(&gb));
     }
 
-    free_vlc(&vlc);
+    ff_free_vlc(&vlc);
 
     return 0;
 fail:
-    free_vlc(&vlc);
+    ff_free_vlc(&vlc);
     return AVERROR_INVALIDDATA;
 }
 
diff --git a/libavcodec/vc1dec.c b/libavcodec/vc1dec.c
index 3d1abc7..38b08a5 100644
--- a/libavcodec/vc1dec.c
+++ b/libavcodec/vc1dec.c
@@ -5710,6 +5710,12 @@ static int vc1_decode_frame(AVCodecContext *avctx, void *data,
         mb_height = s->mb_height >> v->field_mode;
         for (i = 0; i <= n_slices; i++) {
             if (i > 0 &&  slices[i - 1].mby_start >= mb_height) {
+                if (v->field_mode <= 0) {
+                    av_log(v->s.avctx, AV_LOG_ERROR, "Slice %d starts beyond "
+                           "picture boundary (%d >= %d)\n", i,
+                           slices[i - 1].mby_start, mb_height);
+                    continue;
+                }
                 v->second_field = 1;
                 v->blocks_off   = s->mb_width  * s->mb_height << 1;
                 v->mb_off       = s->mb_stride * s->mb_height >> 1;
@@ -5812,6 +5818,7 @@ AVCodec ff_vc1_decoder = {
     .init           = vc1_decode_init,
     .close          = vc1_decode_end,
     .decode         = vc1_decode_frame,
+    .flush          = ff_mpeg_flush,
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-1"),
     .pix_fmts       = ff_hwaccel_pixfmt_list_420,
@@ -5827,6 +5834,7 @@ AVCodec ff_wmv3_decoder = {
     .init           = vc1_decode_init,
     .close          = vc1_decode_end,
     .decode         = vc1_decode_frame,
+    .flush          = ff_mpeg_flush,
     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9"),
     .pix_fmts       = ff_hwaccel_pixfmt_list_420,
diff --git a/libavcodec/vorbis.c b/libavcodec/vorbis.c
index 52ded8b..16fb998 100644
--- a/libavcodec/vorbis.c
+++ b/libavcodec/vorbis.c
@@ -119,7 +119,8 @@ int ff_vorbis_len2vlc(uint8_t *bits, uint32_t *codes, unsigned num)
     return 0;
 }
 
-void ff_vorbis_ready_floor1_list(vorbis_floor1_entry * list, int values)
+int ff_vorbis_ready_floor1_list(AVCodecContext *avccontext,
+                                vorbis_floor1_entry *list, int values)
 {
     int i;
     list[0].sort = 0;
@@ -143,6 +144,11 @@ void ff_vorbis_ready_floor1_list(vorbis_floor1_entry * list, int values)
     for (i = 0; i < values - 1; i++) {
         int j;
         for (j = i + 1; j < values; j++) {
+            if (list[i].x == list[j].x) {
+                av_log(avccontext, AV_LOG_ERROR,
+                       "Duplicate value found in floor 1 X coordinates\n");
+                return AVERROR_INVALIDDATA;
+            }
             if (list[list[i].sort].x > list[list[j].sort].x) {
                 int tmp = list[i].sort;
                 list[i].sort = list[j].sort;
@@ -150,6 +156,7 @@ void ff_vorbis_ready_floor1_list(vorbis_floor1_entry * list, int values)
             }
         }
     }
+    return 0;
 }
 
 static inline void render_line_unrolled(intptr_t x, int y, int x1,
diff --git a/libavcodec/vorbis.h b/libavcodec/vorbis.h
index a55523f..baa5af2 100644
--- a/libavcodec/vorbis.h
+++ b/libavcodec/vorbis.h
@@ -36,7 +36,8 @@ typedef struct {
     uint16_t high;
 } vorbis_floor1_entry;
 
-void ff_vorbis_ready_floor1_list(vorbis_floor1_entry * list, int values);
+int ff_vorbis_ready_floor1_list(AVCodecContext *avccontext,
+                                vorbis_floor1_entry *list, int values);
 unsigned int ff_vorbis_nth_root(unsigned int x, unsigned int n); // x^(1/n)
 int ff_vorbis_len2vlc(uint8_t *bits, uint32_t *codes, unsigned num);
 void ff_vorbis_floor1_render_list(vorbis_floor1_entry * list, int values,
diff --git a/libavcodec/vorbisdec.c b/libavcodec/vorbisdec.c
index 22a2cf7..3c13947 100644
--- a/libavcodec/vorbisdec.c
+++ b/libavcodec/vorbisdec.c
@@ -203,7 +203,7 @@ static void vorbis_free(vorbis_context *vc)
 
     for (i = 0; i < vc->codebook_count; ++i) {
         av_free(vc->codebooks[i].codevectors);
-        free_vlc(&vc->codebooks[i].vlc);
+        ff_free_vlc(&vc->codebooks[i].vlc);
     }
     av_freep(&vc->codebooks);
 
@@ -574,7 +574,11 @@ static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
             }
 
 // Precalculate order of x coordinates - needed for decode
-            ff_vorbis_ready_floor1_list(floor_setup->data.t1.list, floor_setup->data.t1.x_list_dim);
+            if (ff_vorbis_ready_floor1_list(vc->avccontext,
+                                            floor_setup->data.t1.list,
+                                            floor_setup->data.t1.x_list_dim)) {
+                return AVERROR_INVALIDDATA;
+            }
         } else if (floor_setup->floor_type == 0) {
             unsigned max_codebook_dim = 0;
 
diff --git a/libavcodec/vorbisenc.c b/libavcodec/vorbisenc.c
index 00fe402..2cab6b3 100644
--- a/libavcodec/vorbisenc.c
+++ b/libavcodec/vorbisenc.c
@@ -155,7 +155,7 @@ static int cb_lookup_vals(int lookup, int dimentions, int entries)
     return 0;
 }
 
-static void ready_codebook(vorbis_enc_codebook *cb)
+static int ready_codebook(vorbis_enc_codebook *cb)
 {
     int i;
 
@@ -167,6 +167,8 @@ static void ready_codebook(vorbis_enc_codebook *cb)
         int vals = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
         cb->dimentions = av_malloc(sizeof(float) * cb->nentries * cb->ndimentions);
         cb->pow2 = av_mallocz(sizeof(float) * cb->nentries);
+        if (!cb->dimentions || !cb->pow2)
+            return AVERROR(ENOMEM);
         for (i = 0; i < cb->nentries; i++) {
             float last = 0;
             int j;
@@ -187,13 +189,16 @@ static void ready_codebook(vorbis_enc_codebook *cb)
             cb->pow2[i] /= 2.;
         }
     }
+    return 0;
 }
 
-static void ready_residue(vorbis_enc_residue *rc, vorbis_enc_context *venc)
+static int ready_residue(vorbis_enc_residue *rc, vorbis_enc_context *venc)
 {
     int i;
     assert(rc->type == 2);
     rc->maxes = av_mallocz(sizeof(float[2]) * rc->classifications);
+    if (!rc->maxes)
+        return AVERROR(ENOMEM);
     for (i = 0; i < rc->classifications; i++) {
         int j;
         vorbis_enc_codebook * cb;
@@ -223,15 +228,16 @@ static void ready_residue(vorbis_enc_residue *rc, vorbis_enc_context *venc)
         rc->maxes[i][0] += 0.8;
         rc->maxes[i][1] += 0.8;
     }
+    return 0;
 }
 
-static void create_vorbis_context(vorbis_enc_context *venc,
-                                  AVCodecContext *avccontext)
+static int create_vorbis_context(vorbis_enc_context *venc,
+                                 AVCodecContext *avccontext)
 {
     vorbis_enc_floor   *fc;
     vorbis_enc_residue *rc;
     vorbis_enc_mapping *mc;
-    int i, book;
+    int i, book, ret;
 
     venc->channels    = avccontext->channels;
     venc->sample_rate = avccontext->sample_rate;
@@ -239,6 +245,8 @@ static void create_vorbis_context(vorbis_enc_context *venc,
 
     venc->ncodebooks = FF_ARRAY_ELEMS(cvectors);
     venc->codebooks  = av_malloc(sizeof(vorbis_enc_codebook) * venc->ncodebooks);
+    if (!venc->codebooks)
+        return AVERROR(ENOMEM);
 
     // codebook 0..14 - floor1 book, values 0..255
     // codebook 15 residue masterbook
@@ -255,27 +263,36 @@ static void create_vorbis_context(vorbis_enc_context *venc,
 
         cb->lens      = av_malloc(sizeof(uint8_t)  * cb->nentries);
         cb->codewords = av_malloc(sizeof(uint32_t) * cb->nentries);
+        if (!cb->lens || !cb->codewords)
+            return AVERROR(ENOMEM);
         memcpy(cb->lens, cvectors[book].clens, cvectors[book].len);
         memset(cb->lens + cvectors[book].len, 0, cb->nentries - cvectors[book].len);
 
         if (cb->lookup) {
             vals = cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries);
             cb->quantlist = av_malloc(sizeof(int) * vals);
+            if (!cb->quantlist)
+                return AVERROR(ENOMEM);
             for (i = 0; i < vals; i++)
                 cb->quantlist[i] = cvectors[book].quant[i];
         } else {
             cb->quantlist = NULL;
         }
-        ready_codebook(cb);
+        if ((ret = ready_codebook(cb)) < 0)
+            return ret;
     }
 
     venc->nfloors = 1;
     venc->floors  = av_malloc(sizeof(vorbis_enc_floor) * venc->nfloors);
+    if (!venc->floors)
+        return AVERROR(ENOMEM);
 
     // just 1 floor
     fc = &venc->floors[0];
     fc->partitions         = NUM_FLOOR_PARTITIONS;
     fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);
+    if (!fc->partition_to_class)
+        return AVERROR(ENOMEM);
     fc->nclasses           = 0;
     for (i = 0; i < fc->partitions; i++) {
         static const int a[] = {0, 1, 2, 2, 3, 3, 4, 4};
@@ -284,6 +301,8 @@ static void create_vorbis_context(vorbis_enc_context *venc,
     }
     fc->nclasses++;
     fc->classes = av_malloc(sizeof(vorbis_enc_floor_class) * fc->nclasses);
+    if (!fc->classes)
+        return AVERROR(ENOMEM);
     for (i = 0; i < fc->nclasses; i++) {
         vorbis_enc_floor_class * c = &fc->classes[i];
         int j, books;
@@ -292,6 +311,8 @@ static void create_vorbis_context(vorbis_enc_context *venc,
         c->masterbook = floor_classes[i].masterbook;
         books         = (1 << c->subclass);
         c->books      = av_malloc(sizeof(int) * books);
+        if (!c->books)
+            return AVERROR(ENOMEM);
         for (j = 0; j < books; j++)
             c->books[j] = floor_classes[i].nbooks[j];
     }
@@ -303,6 +324,8 @@ static void create_vorbis_context(vorbis_enc_context *venc,
         fc->values += fc->classes[fc->partition_to_class[i]].dim;
 
     fc->list = av_malloc(sizeof(vorbis_floor1_entry) * fc->values);
+    if (!fc->list)
+        return AVERROR(ENOMEM);
     fc->list[0].x = 0;
     fc->list[1].x = 1 << fc->rangebits;
     for (i = 2; i < fc->values; i++) {
@@ -313,10 +336,13 @@ static void create_vorbis_context(vorbis_enc_context *venc,
         };
         fc->list[i].x = a[i - 2];
     }
-    ff_vorbis_ready_floor1_list(fc->list, fc->values);
+    if (ff_vorbis_ready_floor1_list(avccontext, fc->list, fc->values))
+        return AVERROR_BUG;
 
     venc->nresidues = 1;
     venc->residues  = av_malloc(sizeof(vorbis_enc_residue) * venc->nresidues);
+    if (!venc->residues)
+        return AVERROR(ENOMEM);
 
     // single residue
     rc = &venc->residues[0];
@@ -327,6 +353,8 @@ static void create_vorbis_context(vorbis_enc_context *venc,
     rc->classifications = 10;
     rc->classbook       = 15;
     rc->books           = av_malloc(sizeof(*rc->books) * rc->classifications);
+    if (!rc->books)
+        return AVERROR(ENOMEM);
     {
         static const int8_t a[10][8] = {
             { -1, -1, -1, -1, -1, -1, -1, -1, },
@@ -342,19 +370,26 @@ static void create_vorbis_context(vorbis_enc_context *venc,
         };
         memcpy(rc->books, a, sizeof a);
     }
-    ready_residue(rc, venc);
+    if ((ret = ready_residue(rc, venc)) < 0)
+        return ret;
 
     venc->nmappings = 1;
     venc->mappings  = av_malloc(sizeof(vorbis_enc_mapping) * venc->nmappings);
+    if (!venc->mappings)
+        return AVERROR(ENOMEM);
 
     // single mapping
     mc = &venc->mappings[0];
     mc->submaps = 1;
     mc->mux     = av_malloc(sizeof(int) * venc->channels);
+    if (!mc->mux)
+        return AVERROR(ENOMEM);
     for (i = 0; i < venc->channels; i++)
         mc->mux[i] = 0;
     mc->floor   = av_malloc(sizeof(int) * mc->submaps);
     mc->residue = av_malloc(sizeof(int) * mc->submaps);
+    if (!mc->floor || !mc->residue)
+        return AVERROR(ENOMEM);
     for (i = 0; i < mc->submaps; i++) {
         mc->floor[i]   = 0;
         mc->residue[i] = 0;
@@ -362,6 +397,8 @@ static void create_vorbis_context(vorbis_enc_context *venc,
     mc->coupling_steps = venc->channels == 2 ? 1 : 0;
     mc->magnitude      = av_malloc(sizeof(int) * mc->coupling_steps);
     mc->angle          = av_malloc(sizeof(int) * mc->coupling_steps);
+    if (!mc->magnitude || !mc->angle)
+        return AVERROR(ENOMEM);
     if (mc->coupling_steps) {
         mc->magnitude[0] = 0;
         mc->angle[0]     = 1;
@@ -369,6 +406,8 @@ static void create_vorbis_context(vorbis_enc_context *venc,
 
     venc->nmodes = 1;
     venc->modes  = av_malloc(sizeof(vorbis_enc_mode) * venc->nmodes);
+    if (!venc->modes)
+        return AVERROR(ENOMEM);
 
     // single mode
     venc->modes[0].blockflag = 0;
@@ -379,12 +418,18 @@ static void create_vorbis_context(vorbis_enc_context *venc,
     venc->samples    = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]));
     venc->floor      = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
     venc->coeffs     = av_malloc(sizeof(float) * venc->channels * (1 << venc->log2_blocksize[1]) / 2);
+    if (!venc->saved || !venc->samples || !venc->floor || !venc->coeffs)
+        return AVERROR(ENOMEM);
 
     venc->win[0] = ff_vorbis_vwin[venc->log2_blocksize[0] - 6];
     venc->win[1] = ff_vorbis_vwin[venc->log2_blocksize[1] - 6];
 
-    ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0, 1.0);
-    ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0, 1.0);
+    if ((ret = ff_mdct_init(&venc->mdct[0], venc->log2_blocksize[0], 0, 1.0)) < 0)
+        return ret;
+    if ((ret = ff_mdct_init(&venc->mdct[1], venc->log2_blocksize[1], 0, 1.0)) < 0)
+        return ret;
+
+    return 0;
 }
 
 static void put_float(PutBitContext *pb, float f)
@@ -647,6 +692,8 @@ static int put_main_header(vorbis_enc_context *venc, uint8_t **out)
 
     len = hlens[0] + hlens[1] + hlens[2];
     p = *out = av_mallocz(64 + len + len/255);
+    if (!p)
+        return AVERROR(ENOMEM);
 
     *p++ = 2;
     p += av_xiphlacing(p, hlens[0]);
@@ -952,32 +999,6 @@ static int apply_window_and_mdct(vorbis_enc_context *venc, const signed short *a
     return 1;
 }
 
-static av_cold int vorbis_encode_init(AVCodecContext *avccontext)
-{
-    vorbis_enc_context *venc = avccontext->priv_data;
-
-    if (avccontext->channels != 2) {
-        av_log(avccontext, AV_LOG_ERROR, "Current Libav Vorbis encoder only supports 2 channels.\n");
-        return -1;
-    }
-
-    create_vorbis_context(venc, avccontext);
-
-    if (avccontext->flags & CODEC_FLAG_QSCALE)
-        venc->quality = avccontext->global_quality / (float)FF_QP2LAMBDA / 10.;
-    else
-        venc->quality = 0.03;
-    venc->quality *= venc->quality;
-
-    avccontext->extradata_size = put_main_header(venc, (uint8_t**)&avccontext->extradata);
-
-    avccontext->frame_size     = 1 << (venc->log2_blocksize[0] - 1);
-
-    avccontext->coded_frame            = avcodec_alloc_frame();
-    avccontext->coded_frame->key_frame = 1;
-
-    return 0;
-}
 
 static int vorbis_encode_frame(AVCodecContext *avccontext,
                                unsigned char *packets,
@@ -1102,6 +1123,43 @@ static av_cold int vorbis_encode_close(AVCodecContext *avccontext)
     return 0 ;
 }
 
+static av_cold int vorbis_encode_init(AVCodecContext *avccontext)
+{
+    vorbis_enc_context *venc = avccontext->priv_data;
+    int ret;
+
+    if (avccontext->channels != 2) {
+        av_log(avccontext, AV_LOG_ERROR, "Current Libav Vorbis encoder only supports 2 channels.\n");
+        return -1;
+    }
+
+    if ((ret = create_vorbis_context(venc, avccontext)) < 0)
+        goto error;
+
+    if (avccontext->flags & CODEC_FLAG_QSCALE)
+        venc->quality = avccontext->global_quality / (float)FF_QP2LAMBDA / 10.;
+    else
+        venc->quality = 0.03;
+    venc->quality *= venc->quality;
+
+    if ((ret = put_main_header(venc, (uint8_t**)&avccontext->extradata)) < 0)
+        goto error;
+    avccontext->extradata_size = ret;
+
+    avccontext->frame_size = 1 << (venc->log2_blocksize[0] - 1);
+
+    avccontext->coded_frame = avcodec_alloc_frame();
+    if (!avccontext->coded_frame) {
+        ret = AVERROR(ENOMEM);
+        goto error;
+    }
+
+    return 0;
+error:
+    vorbis_encode_close(avccontext);
+    return ret;
+}
+
 AVCodec ff_vorbis_encoder = {
     .name           = "vorbis",
     .type           = AVMEDIA_TYPE_AUDIO,
diff --git a/libavcodec/vp3.c b/libavcodec/vp3.c
index 602b5fa..da70e66 100644
--- a/libavcodec/vp3.c
+++ b/libavcodec/vp3.c
@@ -292,17 +292,17 @@ static av_cold int vp3_decode_end(AVCodecContext *avctx)
         return 0;
 
     for (i = 0; i < 16; i++) {
-        free_vlc(&s->dc_vlc[i]);
-        free_vlc(&s->ac_vlc_1[i]);
-        free_vlc(&s->ac_vlc_2[i]);
-        free_vlc(&s->ac_vlc_3[i]);
-        free_vlc(&s->ac_vlc_4[i]);
+        ff_free_vlc(&s->dc_vlc[i]);
+        ff_free_vlc(&s->ac_vlc_1[i]);
+        ff_free_vlc(&s->ac_vlc_2[i]);
+        ff_free_vlc(&s->ac_vlc_3[i]);
+        ff_free_vlc(&s->ac_vlc_4[i]);
     }
 
-    free_vlc(&s->superblock_run_length_vlc);
-    free_vlc(&s->fragment_run_length_vlc);
-    free_vlc(&s->mode_code_vlc);
-    free_vlc(&s->motion_vector_vlc);
+    ff_free_vlc(&s->superblock_run_length_vlc);
+    ff_free_vlc(&s->fragment_run_length_vlc);
+    ff_free_vlc(&s->mode_code_vlc);
+    ff_free_vlc(&s->motion_vector_vlc);
 
     /* release all frames */
     vp3_decode_flush(avctx);
diff --git a/libavcodec/vp6.c b/libavcodec/vp6.c
index 9137701..861a2da 100644
--- a/libavcodec/vp6.c
+++ b/libavcodec/vp6.c
@@ -237,7 +237,7 @@ static int vp6_build_huff_tree(VP56Context *s, uint8_t coeff_model[],
         nodes[map[2*i+1]].count = b + !b;
     }
 
-    free_vlc(vlc);
+    ff_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);
@@ -615,11 +615,11 @@ static av_cold int vp6_decode_free(AVCodecContext *avctx)
     ff_vp56_free(avctx);
 
     for (pt=0; pt<2; pt++) {
-        free_vlc(&s->dccv_vlc[pt]);
-        free_vlc(&s->runv_vlc[pt]);
+        ff_free_vlc(&s->dccv_vlc[pt]);
+        ff_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]);
+                ff_free_vlc(&s->ract_vlc[pt][ct][cg]);
     }
     return 0;
 }
diff --git a/libavcodec/wma.c b/libavcodec/wma.c
index d82fde7..63ddb6c 100644
--- a/libavcodec/wma.c
+++ b/libavcodec/wma.c
@@ -417,13 +417,13 @@ int ff_wma_end(AVCodecContext *avctx)
         ff_mdct_end(&s->mdct_ctx[i]);
 
     if (s->use_exp_vlc) {
-        free_vlc(&s->exp_vlc);
+        ff_free_vlc(&s->exp_vlc);
     }
     if (s->use_noise_coding) {
-        free_vlc(&s->hgain_vlc);
+        ff_free_vlc(&s->hgain_vlc);
     }
     for (i = 0; i < 2; i++) {
-        free_vlc(&s->coef_vlc[i]);
+        ff_free_vlc(&s->coef_vlc[i]);
         av_free(s->run_table[i]);
         av_free(s->level_table[i]);
         av_free(s->int_table[i]);
diff --git a/libavcodec/wmaprodec.c b/libavcodec/wmaprodec.c
index a1b82db..9804cc2 100644
--- a/libavcodec/wmaprodec.c
+++ b/libavcodec/wmaprodec.c
@@ -330,6 +330,11 @@ static av_cold int decode_init(AVCodecContext *avctx)
         return AVERROR_INVALIDDATA;
     }
 
+    if (s->avctx->sample_rate <= 0) {
+        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     s->num_channels = avctx->channels;
 
     if (s->num_channels < 0) {
@@ -1166,7 +1171,12 @@ static int decode_subframe(WMAProDecodeCtx *s)
             int num_bits = av_log2((s->subframe_len + 3)/4) + 1;
             for (i = 0; i < s->channels_for_cur_subframe; i++) {
                 int c = s->channel_indexes_for_cur_subframe[i];
-                s->channel[c].num_vec_coeffs = get_bits(&s->gb, num_bits) << 2;
+                int num_vec_coeffs = get_bits(&s->gb, num_bits) << 2;
+                if (num_vec_coeffs > WMAPRO_BLOCK_MAX_SIZE) {
+                    av_log(s->avctx, AV_LOG_ERROR, "num_vec_coeffs %d is too large\n", num_vec_coeffs);
+                    return AVERROR_INVALIDDATA;
+                }
+                s->channel[c].num_vec_coeffs = num_vec_coeffs;
             }
         } else {
             for (i = 0; i < s->channels_for_cur_subframe; i++) {
diff --git a/libavcodec/wmv2enc.c b/libavcodec/wmv2enc.c
index 9879cb8..78acad1 100644
--- a/libavcodec/wmv2enc.c
+++ b/libavcodec/wmv2enc.c
@@ -171,7 +171,7 @@ void ff_wmv2_encode_mb(MpegEncContext * s,
                  wmv2_inter_table[w->cbp_table_index][cbp + 64][0]);
 
         /* motion vector */
-        h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
+        ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
         ff_msmpeg4_encode_motion(s, motion_x - pred_x,
                               motion_y - pred_y);
     } else {
diff --git a/libavfilter/formats.c b/libavfilter/formats.c
index 8c5041a..7eca639 100644
--- a/libavfilter/formats.c
+++ b/libavfilter/formats.c
@@ -45,6 +45,9 @@ AVFilterFormats *avfilter_merge_formats(AVFilterFormats *a, AVFilterFormats *b)
     AVFilterFormats *ret;
     unsigned i, j, k = 0, m_count;
 
+    if (a == b)
+        return a;
+
     ret = av_mallocz(sizeof(AVFilterFormats));
 
     /* merge list of formats */
diff --git a/libavfilter/vf_pad.c b/libavfilter/vf_pad.c
index 9ba91ed..0b60d5b 100644
--- a/libavfilter/vf_pad.c
+++ b/libavfilter/vf_pad.c
@@ -156,7 +156,7 @@ static int config_input(AVFilterLink *inlink)
     var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
     var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
     var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
-    var_values[VAR_A]     = (float) inlink->w / inlink->h;
+    var_values[VAR_A]     = (double) inlink->w / inlink->h;
     var_values[VAR_HSUB]  = 1<<pad->hsub;
     var_values[VAR_VSUB]  = 1<<pad->vsub;
 
@@ -300,6 +300,7 @@ static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
 {
     PadContext *pad = inlink->dst->priv;
     AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
+    AVFilterBufferRef *for_next_filter;
     int plane;
 
     for (plane = 0; plane < 4 && outpicref->data[plane]; plane++) {
@@ -336,12 +337,14 @@ static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
     outpicref->video->w = pad->w;
     outpicref->video->h = pad->h;
 
-    avfilter_start_frame(inlink->dst->outputs[0], outpicref);
+    for_next_filter = avfilter_ref_buffer(outpicref, ~0);
+    avfilter_start_frame(inlink->dst->outputs[0], for_next_filter);
 }
 
 static void end_frame(AVFilterLink *link)
 {
     avfilter_end_frame(link->dst->outputs[0]);
+    avfilter_unref_buffer(link->dst->outputs[0]->out_buf);
     avfilter_unref_buffer(link->cur_buf);
 }
 
diff --git a/libavfilter/vf_scale.c b/libavfilter/vf_scale.c
index dd2f7e1..ec69d7b 100644
--- a/libavfilter/vf_scale.c
+++ b/libavfilter/vf_scale.c
@@ -151,9 +151,9 @@ static int config_props(AVFilterLink *outlink)
     var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
     var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
     var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
-    var_values[VAR_DAR]   = var_values[VAR_A]  = (float) inlink->w / inlink->h;
+    var_values[VAR_DAR]   = var_values[VAR_A]  = (double) inlink->w / inlink->h;
     var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
-        (float) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
+        (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
     var_values[VAR_HSUB]  = 1<<av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
     var_values[VAR_VSUB]  = 1<<av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
 
diff --git a/libavformat/avidec.c b/libavformat/avidec.c
index b4ccfb5..af6ee8e 100644
--- a/libavformat/avidec.c
+++ b/libavformat/avidec.c
@@ -1116,13 +1116,13 @@ resync:
             }
             ast->frame_offset += get_duration(ast, pkt->size);
         }
-        ast->remaining -= size;
+        ast->remaining -= err;
         if(!ast->remaining){
             avi->stream_index= -1;
             ast->packet_size= 0;
         }
 
-        return size;
+        return 0;
     }
 
     if ((err = avi_sync(s, 0)) < 0)
diff --git a/libavformat/mov.c b/libavformat/mov.c
index f6be6a8..1dbf63f 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -1995,9 +1995,6 @@ static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 #if CONFIG_H263_DECODER
     case CODEC_ID_H263:
 #endif
-#if CONFIG_H264_DECODER
-    case CODEC_ID_H264:
-#endif
 #if CONFIG_MPEG4_DECODER
     case CODEC_ID_MPEG4:
 #endif
diff --git a/libavformat/utils.c b/libavformat/utils.c
index 0c355ce..240cd94 100644
--- a/libavformat/utils.c
+++ b/libavformat/utils.c
@@ -634,7 +634,7 @@ int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputForma
     }
 
     s->duration = s->start_time = AV_NOPTS_VALUE;
-    av_strlcpy(s->filename, filename, sizeof(s->filename));
+    av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
 
     /* allocate private data */
     if (s->iformat->priv_data_size > 0) {
diff --git a/libavformat/wav.c b/libavformat/wav.c
index 47cb5f8..b873166 100644
--- a/libavformat/wav.c
+++ b/libavformat/wav.c
@@ -469,7 +469,7 @@ static int wav_read_header(AVFormatContext *s,
             break;
         case MKTAG('L', 'I', 'S', 'T'):
             list_type = avio_rl32(pb);
-            if (size <= 4) {
+            if (size < 4) {
                 av_log(s, AV_LOG_ERROR, "too short LIST");
                 return AVERROR_INVALIDDATA;
             }
diff --git a/libavformat/yuv4mpeg.c b/libavformat/yuv4mpeg.c
index 698ee68..09aabed 100644
--- a/libavformat/yuv4mpeg.c
+++ b/libavformat/yuv4mpeg.c
@@ -364,7 +364,7 @@ static int yuv4_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     int i;
     char header[MAX_FRAME_HEADER+1];
-    int packet_size, width, height;
+    int packet_size, width, height, ret;
     AVStream *st = s->streams[0];
     struct frame_attributes *s1 = s->priv_data;
 
@@ -375,20 +375,28 @@ static int yuv4_read_packet(AVFormatContext *s, AVPacket *pkt)
             break;
         }
     }
-    if (i == MAX_FRAME_HEADER)
-        return -1;
+    if (s->pb->error)
+        return s->pb->error;
+    else if (s->pb->eof_reached)
+        return AVERROR_EOF;
+    else if (i == MAX_FRAME_HEADER)
+        return AVERROR_INVALIDDATA;
+
     if (strncmp(header, Y4M_FRAME_MAGIC, strlen(Y4M_FRAME_MAGIC)))
-        return -1;
+        return AVERROR_INVALIDDATA;
 
     width  = st->codec->width;
     height = st->codec->height;
 
     packet_size = avpicture_get_size(st->codec->pix_fmt, width, height);
     if (packet_size < 0)
-        return -1;
+        return packet_size;
 
-    if (av_get_packet(s->pb, pkt, packet_size) != packet_size)
-        return AVERROR(EIO);
+    ret = av_get_packet(s->pb, pkt, packet_size);
+    if (ret < 0)
+        return ret;
+    else if (ret != packet_size)
+        return s->pb->eof_reached ? AVERROR_EOF : AVERROR(EIO);
 
     if (st->codec->coded_frame) {
         st->codec->coded_frame->interlaced_frame = s1->interlaced_frame;
diff --git a/libavutil/eval.c b/libavutil/eval.c
index 9941ed7..44d1428 100644
--- a/libavutil/eval.c
+++ b/libavutil/eval.c
@@ -277,8 +277,8 @@ static int parse_primary(AVExpr **e, Parser *p)
     else if (strmatch(next, "eq"    )) d->type = e_eq;
     else if (strmatch(next, "gte"   )) d->type = e_gte;
     else if (strmatch(next, "gt"    )) d->type = e_gt;
-    else if (strmatch(next, "lte"   )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
-    else if (strmatch(next, "lt"    )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
+    else if (strmatch(next, "lte"   )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gte; }
+    else if (strmatch(next, "lt"    )) { AVExpr *tmp = d->param[1]; d->param[1] = d->param[0]; d->param[0] = tmp; d->type = e_gt; }
     else if (strmatch(next, "ld"    )) d->type = e_ld;
     else if (strmatch(next, "isnan" )) d->type = e_isnan;
     else if (strmatch(next, "st"    )) d->type = e_st;
diff --git a/tests/ref/fate/eval b/tests/ref/fate/eval
index ef50292..c16527c 100644
--- a/tests/ref/fate/eval
+++ b/tests/ref/fate/eval
@@ -95,16 +95,16 @@ Evaluating 'st(1, 123); ld(1)'
 'st(1, 123); ld(1)' -> 123.000000
 
 Evaluating 'st(0, 1); while(lte(ld(0), 100), st(1, ld(1)+ld(0));st(0, ld(0)+1)); ld(1)'
-'st(0, 1); while(lte(ld(0), 100), st(1, ld(1)+ld(0));st(0, ld(0)+1)); ld(1)' -> 4950.000000
+'st(0, 1); while(lte(ld(0), 100), st(1, ld(1)+ld(0));st(0, ld(0)+1)); ld(1)' -> 5050.000000
 
 Evaluating 'st(1, 1); st(2, 2); st(0, 1); while(lte(ld(0),10), st(3, ld(1)+ld(2)); st(1, ld(2)); st(2, ld(3)); st(0, ld(0)+1)); ld(3)'
-'st(1, 1); st(2, 2); st(0, 1); while(lte(ld(0),10), st(3, ld(1)+ld(2)); st(1, ld(2)); st(2, ld(3)); st(0, ld(0)+1)); ld(3)' -> 144.000000
+'st(1, 1); st(2, 2); st(0, 1); while(lte(ld(0),10), st(3, ld(1)+ld(2)); st(1, ld(2)); st(2, ld(3)); st(0, ld(0)+1)); ld(3)' -> 233.000000
 
 Evaluating 'while(0, 10)'
 'while(0, 10)' -> nan
 
 Evaluating 'st(0, 1); while(lte(ld(0),100), st(1, ld(1)+ld(0)); st(0, ld(0)+1))'
-'st(0, 1); while(lte(ld(0),100), st(1, ld(1)+ld(0)); st(0, ld(0)+1))' -> 100.000000
+'st(0, 1); while(lte(ld(0),100), st(1, ld(1)+ld(0)); st(0, ld(0)+1))' -> 101.000000
 
 Evaluating 'isnan(1)'
 'isnan(1)' -> 0.000000

-- 
Libav/FFmpeg packaging



More information about the pkg-multimedia-commits mailing list