[SCM] libav/master: Imported Upstream version 0.8~beta2

siretart at users.alioth.debian.org siretart at users.alioth.debian.org
Wed Jan 11 16:09:00 UTC 2012


The following commit has been merged in the master branch:
commit 7029d763619551fe45ca54403a9e2882d5b723bf
Author: Reinhard Tartler <siretart at tauware.de>
Date:   Wed Jan 11 16:35:27 2012 +0100

    Imported Upstream version 0.8~beta2

diff --git a/Changelog b/Changelog
index 19ba73a..e69bde5 100644
--- a/Changelog
+++ b/Changelog
@@ -2,6 +2,15 @@ Entries are sorted chronologically from oldest to youngest within each release,
 releases are sorted from youngest to oldest.
 
 
+version 0.8_beta2:
+
+- Automatic thread count based on detection number of (available) CPU cores
+- Deprecate libpostproc. If desired, the switch --enable-postproc will
+  enable it but it may be removed in a later Libav release.
+- rv34: frame-level multi-threading
+- optimized iMDCT transform on x86 using SSE for for mpegaudiodec
+
+
 version 0.8_beta1:
 
 - BWF muxer
@@ -103,7 +112,7 @@ easier to use. The changes are:
 - Discworld II BMV decoding support
 - VBLE Decoder
 - OS X Video Decoder Acceleration (VDA) support
-- CRI ADX audio format demuxer
+- CRI ADX audio format muxer and demuxer
 - Playstation Portable PMP format demuxer
 - PCM format support in OMA demuxer
 - CLJR encoder
diff --git a/RELEASE b/RELEASE
index 8e0f8bc..ce377b1 100644
--- a/RELEASE
+++ b/RELEASE
@@ -1 +1 @@
-0.8_beta1
+0.8_beta2
diff --git a/avconv.c b/avconv.c
index f3e6e28..c96cc73 100644
--- a/avconv.c
+++ b/avconv.c
@@ -76,6 +76,11 @@
 
 #include "libavutil/avassert.h"
 
+#define VSYNC_AUTO       -1
+#define VSYNC_PASSTHROUGH 0
+#define VSYNC_CFR         1
+#define VSYNC_VFR         2
+
 const char program_name[] = "avconv";
 const int program_birth_year = 2000;
 
@@ -111,7 +116,7 @@ static int do_hex_dump = 0;
 static int do_pkt_dump = 0;
 static int do_pass = 0;
 static char *pass_logfilename_prefix = NULL;
-static int video_sync_method = -1;
+static int video_sync_method = VSYNC_AUTO;
 static int audio_sync_method = 0;
 static float audio_drift_threshold = 0.1;
 static int copy_ts = 0;
@@ -603,7 +608,6 @@ static int configure_video_filters(InputStream *ist, OutputStream *ost)
 
         if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, inputs, outputs, NULL)) < 0)
             return ret;
-        av_freep(&ost->avfilter);
     } else {
         if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
             return ret;
@@ -667,6 +671,19 @@ void exit_program(int ret)
         avformat_free_context(s);
         av_dict_free(&output_files[i].opts);
     }
+    for (i = 0; i < nb_output_streams; i++) {
+        AVBitStreamFilterContext *bsfc = output_streams[i].bitstream_filters;
+        while (bsfc) {
+            AVBitStreamFilterContext *next = bsfc->next;
+            av_bitstream_filter_close(bsfc);
+            bsfc = next;
+        }
+        output_streams[i].bitstream_filters = NULL;
+
+#if CONFIG_AVFILTER
+        av_freep(&output_streams[i].avfilter);
+#endif
+    }
     for (i = 0; i < nb_input_files; i++) {
         avformat_close_input(&input_files[i].ctx);
     }
@@ -846,8 +863,10 @@ get_sync_ipts(const OutputStream *ost)
     return (double)(ist->pts - of->start_time) / AV_TIME_BASE;
 }
 
-static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc)
+static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
 {
+    AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
+    AVCodecContext          *avctx = ost->st->codec;
     int ret;
 
     while (bsfc) {
@@ -877,6 +896,7 @@ static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx
         print_error("av_interleaved_write_frame()", ret);
         exit_program(1);
     }
+    ost->frame_number++;
 }
 
 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
@@ -1091,7 +1111,7 @@ need_realloc:
             if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
                 pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
             pkt.flags |= AV_PKT_FLAG_KEY;
-            write_frame(s, &pkt, enc, ost->bitstream_filters);
+            write_frame(s, &pkt, ost);
 
             ost->sync_opts += enc->frame_size;
         }
@@ -1126,7 +1146,7 @@ need_realloc:
         if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
             pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
         pkt.flags |= AV_PKT_FLAG_KEY;
-        write_frame(s, &pkt, enc, ost->bitstream_filters);
+        write_frame(s, &pkt, ost);
     }
 }
 
@@ -1228,13 +1248,14 @@ static void do_subtitle_out(AVFormatContext *s,
             else
                 pkt.pts += 90 * sub->end_display_time;
         }
-        write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
+        write_frame(s, &pkt, ost);
     }
 }
 
 static int bit_buffer_size = 1024 * 256;
 static uint8_t *bit_buffer = NULL;
 
+#if !CONFIG_AVFILTER
 static void do_video_resample(OutputStream *ost,
                               InputStream *ist,
                               AVFrame *in_picture,
@@ -1258,7 +1279,6 @@ static void do_video_resample(OutputStream *ost,
             ost->video_resample = 1;
     }
 
-#if !CONFIG_AVFILTER
     if (ost->video_resample) {
         *out_picture = &ost->pict_tmp;
         if (resample_changed) {
@@ -1280,21 +1300,13 @@ static void do_video_resample(OutputStream *ost,
         sws_scale(ost->img_resample_ctx, in_picture->data, in_picture->linesize,
               0, ost->resample_height, (*out_picture)->data, (*out_picture)->linesize);
     }
-#else
-    if (resample_changed) {
-        avfilter_graph_free(&ost->graph);
-        if (configure_video_filters(ist, ost)) {
-            av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
-            exit_program(1);
-        }
-    }
-#endif
     if (resample_changed) {
         ost->resample_width   = dec->width;
         ost->resample_height  = dec->height;
         ost->resample_pix_fmt = dec->pix_fmt;
     }
 }
+#endif
 
 
 static void do_video_out(AVFormatContext *s,
@@ -1318,16 +1330,16 @@ static void do_video_out(AVFormatContext *s,
     *frame_size = 0;
 
     format_video_sync = video_sync_method;
-    if (format_video_sync < 0)
-        format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? 0 :
-                            (s->oformat->flags & AVFMT_VARIABLE_FPS) ? 2 : 1;
+    if (format_video_sync == VSYNC_AUTO)
+        format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
+                            (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
 
-    if (format_video_sync) {
+    if (format_video_sync != VSYNC_PASSTHROUGH) {
         double vdelta = sync_ipts - ost->sync_opts;
         // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
         if (vdelta < -1.1)
             nb_frames = 0;
-        else if (format_video_sync == 2) {
+        else if (format_video_sync == VSYNC_VFR) {
             if (vdelta <= -0.6) {
                 nb_frames = 0;
             } else if (vdelta > 0.6)
@@ -1349,7 +1361,11 @@ static void do_video_out(AVFormatContext *s,
     if (nb_frames <= 0)
         return;
 
+#if !CONFIG_AVFILTER
     do_video_resample(ost, ist, in_picture, &final_picture);
+#else
+    final_picture = in_picture;
+#endif
 
     /* duplicates frame if needed */
     for (i = 0; i < nb_frames; i++) {
@@ -1369,7 +1385,7 @@ static void do_video_out(AVFormatContext *s,
             pkt.pts    = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
             pkt.flags |= AV_PKT_FLAG_KEY;
 
-            write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
+            write_frame(s, &pkt, ost);
         } else {
             AVFrame big_picture;
 
@@ -1417,7 +1433,7 @@ static void do_video_out(AVFormatContext *s,
 
                 if (enc->coded_frame->key_frame)
                     pkt.flags |= AV_PKT_FLAG_KEY;
-                write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
+                write_frame(s, &pkt, ost);
                 *frame_size = ret;
                 video_size += ret;
                 // fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
@@ -1429,7 +1445,6 @@ static void do_video_out(AVFormatContext *s,
             }
         }
         ost->sync_opts++;
-        ost->frame_number++;
     }
 }
 
@@ -1678,7 +1693,7 @@ static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
             pkt.size = ret;
             if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
                 pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
-            write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
+            write_frame(os, &pkt, ost);
         }
     }
 }
@@ -1754,9 +1769,8 @@ static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *p
         opkt.size = pkt->size;
     }
 
-    write_frame(of->ctx, &opkt, ost->st->codec, ost->bitstream_filters);
+    write_frame(of->ctx, &opkt, ost);
     ost->st->codec->frame_number++;
-    ost->frame_number++;
     av_free_packet(&opkt);
 }
 
@@ -1921,12 +1935,33 @@ static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int
 
     for (i = 0; i < nb_output_streams; i++) {
         OutputStream *ost = &output_streams[i];
-        int frame_size;
+        int frame_size, resample_changed;
 
         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
             continue;
 
 #if CONFIG_AVFILTER
+        resample_changed = ost->resample_width   != decoded_frame->width  ||
+                           ost->resample_height  != decoded_frame->height ||
+                           ost->resample_pix_fmt != decoded_frame->format;
+        if (resample_changed) {
+            av_log(NULL, AV_LOG_INFO,
+                    "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
+                    ist->file_index, ist->st->index,
+                    ost->resample_width,  ost->resample_height,  av_get_pix_fmt_name(ost->resample_pix_fmt),
+                    decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
+
+            avfilter_graph_free(&ost->graph);
+            if (configure_video_filters(ist, ost)) {
+                av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
+                exit_program(1);
+            }
+
+            ost->resample_width   = decoded_frame->width;
+            ost->resample_height  = decoded_frame->height;
+            ost->resample_pix_fmt = decoded_frame->format;
+        }
+
         if (ist->st->sample_aspect_ratio.num)
             decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
         if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
@@ -3072,7 +3107,7 @@ static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *
  */
 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
 {
-    int i, rfps, rfps_base;
+    int i;
 
     for (i = 0; i < ic->nb_streams; i++) {
         AVStream *st = ic->streams[i];
@@ -3097,21 +3132,12 @@ static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
                 st->discard = AVDISCARD_ALL;
             break;
         case AVMEDIA_TYPE_VIDEO:
-            rfps      = ic->streams[i]->r_frame_rate.num;
-            rfps_base = ic->streams[i]->r_frame_rate.den;
             if (dec->lowres) {
                 dec->flags |= CODEC_FLAG_EMU_EDGE;
                 dec->height >>= dec->lowres;
                 dec->width  >>= dec->lowres;
             }
 
-            if (dec->time_base.den != rfps * dec->ticks_per_frame || dec->time_base.num != rfps_base) {
-
-                av_log(NULL, AV_LOG_INFO,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
-                       i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
-                       (float)rfps / rfps_base, rfps, rfps_base);
-            }
-
             if (o->video_disable)
                 st->discard = AVDISCARD_ALL;
             else if (video_discard)
@@ -3612,13 +3638,13 @@ static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
         ost->top_field_first = -1;
         MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
 
-        MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
-
 #if CONFIG_AVFILTER
         MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
         if (filters)
             ost->avfilter = av_strdup(filters);
 #endif
+    } else {
+        MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
     }
 
     return ost;
@@ -4308,6 +4334,17 @@ static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg
     return parse_option(o, "filter:v", arg, options);
 }
 
+static int opt_vsync(const char *opt, const char *arg)
+{
+    if      (!av_strcasecmp(arg, "cfr"))         video_sync_method = VSYNC_CFR;
+    else if (!av_strcasecmp(arg, "vfr"))         video_sync_method = VSYNC_VFR;
+    else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
+
+    if (video_sync_method == VSYNC_AUTO)
+        video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
+    return 0;
+}
+
 #define OFFSET(x) offsetof(OptionsContext, x)
 static const OptionDef options[] = {
     /* main options */
@@ -4338,7 +4375,7 @@ static const OptionDef options[] = {
       "when dumping packets, also dump the payload" },
     { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
     { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
-    { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
+    { "vsync", HAS_ARG | OPT_EXPERT, {(void*)opt_vsync}, "video sync method", "" },
     { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
     { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
     { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
diff --git a/avplay.c b/avplay.c
index c217010..3bbb7ef 100644
--- a/avplay.c
+++ b/avplay.c
@@ -80,7 +80,7 @@ const int program_birth_year = 2003;
 #define AUDIO_DIFF_AVG_NB   20
 
 /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
-#define SAMPLE_ARRAY_SIZE (2*65536)
+#define SAMPLE_ARRAY_SIZE (2 * 65536)
 
 static int sws_flags = SWS_BICUBIC;
 
@@ -97,9 +97,9 @@ typedef struct PacketQueue {
 #define SUBPICTURE_QUEUE_SIZE 4
 
 typedef struct VideoPicture {
-    double pts;                                  ///<presentation time stamp for this picture
-    double target_clock;                         ///<av_gettime() time at which this should be displayed ideally
-    int64_t pos;                                 ///<byte position in file
+    double pts;                                  ///< presentation time stamp for this picture
+    double target_clock;                         ///< av_gettime() time at which this should be displayed ideally
+    int64_t pos;                                 ///< byte position in file
     SDL_Overlay *bmp;
     int width, height; /* source height & width */
     int allocated;
@@ -186,13 +186,13 @@ typedef struct VideoState {
     double frame_timer;
     double frame_last_pts;
     double frame_last_delay;
-    double video_clock;                          ///<pts of last decoded frame / predicted pts of next decoded frame
+    double video_clock;                          ///< pts of last decoded frame / predicted pts of next decoded frame
     int video_stream;
     AVStream *video_st;
     PacketQueue videoq;
-    double video_current_pts;                    ///<current displayed pts (different from video_clock if frame fifos are used)
-    double video_current_pts_drift;              ///<video_current_pts - time (av_gettime) at which we updated video_current_pts - used to have running video pts
-    int64_t video_current_pos;                   ///<current displayed file pos
+    double video_current_pts;                    ///< current displayed pts (different from video_clock if frame fifos are used)
+    double video_current_pts_drift;              ///< video_current_pts - time (av_gettime) at which we updated video_current_pts - used to have running video pts
+    int64_t video_current_pos;                   ///< current displayed file pos
     VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
     int pictq_size, pictq_rindex, pictq_windex;
     SDL_mutex *pictq_mutex;
@@ -208,7 +208,7 @@ typedef struct VideoState {
     PtsCorrectionContext pts_ctx;
 
 #if CONFIG_AVFILTER
-    AVFilterContext *out_video_filter;          ///<the last filter in the video chain
+    AVFilterContext *out_video_filter;          ///< the last filter in the video chain
 #endif
 
     float skip_frames;
@@ -224,16 +224,16 @@ static const char *input_filename;
 static const char *window_title;
 static int fs_screen_width;
 static int fs_screen_height;
-static int screen_width = 0;
+static int screen_width  = 0;
 static int screen_height = 0;
 static int audio_disable;
 static int video_disable;
-static int wanted_stream[AVMEDIA_TYPE_NB]={
-    [AVMEDIA_TYPE_AUDIO]=-1,
-    [AVMEDIA_TYPE_VIDEO]=-1,
-    [AVMEDIA_TYPE_SUBTITLE]=-1,
+static int wanted_stream[AVMEDIA_TYPE_NB] = {
+    [AVMEDIA_TYPE_AUDIO]    = -1,
+    [AVMEDIA_TYPE_VIDEO]    = -1,
+    [AVMEDIA_TYPE_SUBTITLE] = -1,
 };
-static int seek_by_bytes=-1;
+static int seek_by_bytes = -1;
 static int display_disable;
 static int show_status = 1;
 static int av_sync_type = AV_SYNC_AUDIO_MASTER;
@@ -248,19 +248,19 @@ static int fast = 0;
 static int genpts = 0;
 static int lowres = 0;
 static int idct = FF_IDCT_AUTO;
-static enum AVDiscard skip_frame= AVDISCARD_DEFAULT;
-static enum AVDiscard skip_idct= AVDISCARD_DEFAULT;
-static enum AVDiscard skip_loop_filter= AVDISCARD_DEFAULT;
+static enum AVDiscard skip_frame       = AVDISCARD_DEFAULT;
+static enum AVDiscard skip_idct        = AVDISCARD_DEFAULT;
+static enum AVDiscard skip_loop_filter = AVDISCARD_DEFAULT;
 static int error_recognition = FF_ER_CAREFUL;
 static int error_concealment = 3;
-static int decoder_reorder_pts= -1;
+static int decoder_reorder_pts = -1;
 static int autoexit;
 static int exit_on_keydown;
 static int exit_on_mousedown;
-static int loop=1;
-static int framedrop=1;
+static int loop = 1;
+static int framedrop = 1;
 
-static int rdftspeed=20;
+static int rdftspeed = 20;
 #if CONFIG_AVFILTER
 static char *vfilters = NULL;
 #endif
@@ -299,7 +299,7 @@ static void packet_queue_flush(PacketQueue *q)
     AVPacketList *pkt, *pkt1;
 
     SDL_LockMutex(q->mutex);
-    for(pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
+    for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
         pkt1 = pkt->next;
         av_free_packet(&pkt->pkt);
         av_freep(&pkt);
@@ -323,7 +323,7 @@ static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
     AVPacketList *pkt1;
 
     /* duplicate the packet */
-    if (pkt!=&flush_pkt && av_dup_packet(pkt) < 0)
+    if (pkt != &flush_pkt && av_dup_packet(pkt) < 0)
         return -1;
 
     pkt1 = av_malloc(sizeof(AVPacketList));
@@ -369,7 +369,7 @@ static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
 
     SDL_LockMutex(q->mutex);
 
-    for(;;) {
+    for (;;) {
         if (q->abort_request) {
             ret = -1;
             break;
@@ -451,8 +451,8 @@ static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw,
     dstx = av_clip(rect->x, 0, imgw - dstw);
     dsty = av_clip(rect->y, 0, imgh - dsth);
     lum = dst->data[0] + dsty * dst->linesize[0];
-    cb = dst->data[1] + (dsty >> 1) * dst->linesize[1];
-    cr = dst->data[2] + (dsty >> 1) * dst->linesize[2];
+    cb  = dst->data[1] + (dsty >> 1) * dst->linesize[1];
+    cr  = dst->data[2] + (dsty >> 1) * dst->linesize[2];
 
     width2 = ((dstw + 1) >> 1) + (dstx & ~dstw & 1);
     skip2 = dstx >> 1;
@@ -476,7 +476,7 @@ static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw,
             lum++;
             p += BPP;
         }
-        for(w = dstw - (dstx & 1); w >= 2; w -= 2) {
+        for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
             YUVA_IN(y, u, v, a, p, pal);
             u1 = u;
             v1 = v;
@@ -508,7 +508,7 @@ static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw,
         cb += dst->linesize[1] - width2 - skip2;
         cr += dst->linesize[2] - width2 - skip2;
     }
-    for(h = dsth - (dsty & 1); h >= 2; h -= 2) {
+    for (h = dsth - (dsty & 1); h >= 2; h -= 2) {
         lum += dstx;
         cb += skip2;
         cr += skip2;
@@ -533,7 +533,7 @@ static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw,
             p += -wrap3 + BPP;
             lum += -wrap + 1;
         }
-        for(w = dstw - (dstx & 1); w >= 2; w -= 2) {
+        for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
             YUVA_IN(y, u, v, a, p, pal);
             u1 = u;
             v1 = v;
@@ -609,7 +609,7 @@ static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw,
             lum++;
             p += BPP;
         }
-        for(w = dstw - (dstx & 1); w >= 2; w -= 2) {
+        for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
             YUVA_IN(y, u, v, a, p, pal);
             u1 = u;
             v1 = v;
@@ -742,15 +742,15 @@ static void video_audio_display(VideoState *s)
     int16_t time_diff;
     int rdft_bits, nb_freq;
 
-    for(rdft_bits=1; (1<<rdft_bits)<2*s->height; rdft_bits++)
+    for (rdft_bits = 1; (1 << rdft_bits) < 2 * s->height; rdft_bits++)
         ;
-    nb_freq= 1<<(rdft_bits-1);
+    nb_freq = 1 << (rdft_bits - 1);
 
     /* compute display index : center on currently output samples */
     channels = s->audio_st->codec->channels;
     nb_display_channels = channels;
     if (!s->paused) {
-        int data_used= s->show_audio==1 ? s->width : (2*nb_freq);
+        int data_used = s->show_audio == 1 ? s->width : (2 * nb_freq);
         n = 2 * channels;
         delay = audio_write_get_buf_size(s);
         delay /= n;
@@ -762,23 +762,23 @@ static void video_audio_display(VideoState *s)
             delay -= (time_diff * s->audio_st->codec->sample_rate) / 1000000;
         }
 
-        delay += 2*data_used;
+        delay += 2 * data_used;
         if (delay < data_used)
             delay = data_used;
 
         i_start= x = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
-        if(s->show_audio==1){
-            h= INT_MIN;
-            for(i=0; i<1000; i+=channels){
-                int idx= (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;
-                int a= s->sample_array[idx];
-                int b= s->sample_array[(idx + 4*channels)%SAMPLE_ARRAY_SIZE];
-                int c= s->sample_array[(idx + 5*channels)%SAMPLE_ARRAY_SIZE];
-                int d= s->sample_array[(idx + 9*channels)%SAMPLE_ARRAY_SIZE];
-                int score= a-d;
-                if(h<score && (b^c)<0){
-                    h= score;
-                    i_start= idx;
+        if (s->show_audio == 1) {
+            h = INT_MIN;
+            for (i = 0; i < 1000; i += channels) {
+                int idx = (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;
+                int a = s->sample_array[idx];
+                int b = s->sample_array[(idx + 4 * channels) % SAMPLE_ARRAY_SIZE];
+                int c = s->sample_array[(idx + 5 * channels) % SAMPLE_ARRAY_SIZE];
+                int d = s->sample_array[(idx + 9 * channels) % SAMPLE_ARRAY_SIZE];
+                int score = a - d;
+                if (h < score && (b ^ c) < 0) {
+                    h = score;
+                    i_start = idx;
                 }
             }
         }
@@ -789,7 +789,7 @@ static void video_audio_display(VideoState *s)
     }
 
     bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
-    if(s->show_audio==1){
+    if (s->show_audio == 1) {
         fill_rectangle(screen,
                        s->xleft, s->ytop, s->width, s->height,
                        bgcolor);
@@ -800,10 +800,10 @@ static void video_audio_display(VideoState *s)
         h = s->height / nb_display_channels;
         /* graph height / 2 */
         h2 = (h * 9) / 20;
-        for(ch = 0;ch < nb_display_channels; ch++) {
+        for (ch = 0; ch < nb_display_channels; ch++) {
             i = i_start + ch;
             y1 = s->ytop + ch * h + (h / 2); /* position of center line */
-            for(x = 0; x < s->width; x++) {
+            for (x = 0; x < s->width; x++) {
                 y = (s->sample_array[i] * h2) >> 15;
                 if (y < 0) {
                     y = -y;
@@ -822,45 +822,45 @@ static void video_audio_display(VideoState *s)
 
         fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);
 
-        for(ch = 1;ch < nb_display_channels; ch++) {
+        for (ch = 1; ch < nb_display_channels; ch++) {
             y = s->ytop + ch * h;
             fill_rectangle(screen,
                            s->xleft, y, s->width, 1,
                            fgcolor);
         }
         SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
-    }else{
+    } else {
         nb_display_channels= FFMIN(nb_display_channels, 2);
-        if(rdft_bits != s->rdft_bits){
+        if (rdft_bits != s->rdft_bits) {
             av_rdft_end(s->rdft);
             av_free(s->rdft_data);
             s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
-            s->rdft_bits= rdft_bits;
-            s->rdft_data= av_malloc(4*nb_freq*sizeof(*s->rdft_data));
+            s->rdft_bits = rdft_bits;
+            s->rdft_data = av_malloc(4 * nb_freq * sizeof(*s->rdft_data));
         }
         {
             FFTSample *data[2];
-            for(ch = 0;ch < nb_display_channels; ch++) {
-                data[ch] = s->rdft_data + 2*nb_freq*ch;
+            for (ch = 0; ch < nb_display_channels; ch++) {
+                data[ch] = s->rdft_data + 2 * nb_freq * ch;
                 i = i_start + ch;
-                for(x = 0; x < 2*nb_freq; x++) {
-                    double w= (x-nb_freq)*(1.0/nb_freq);
-                    data[ch][x]= s->sample_array[i]*(1.0-w*w);
+                for (x = 0; x < 2 * nb_freq; x++) {
+                    double w = (x-nb_freq) * (1.0 / nb_freq);
+                    data[ch][x] = s->sample_array[i] * (1.0 - w * w);
                     i += channels;
                     if (i >= SAMPLE_ARRAY_SIZE)
                         i -= SAMPLE_ARRAY_SIZE;
                 }
                 av_rdft_calc(s->rdft, data[ch]);
             }
-            //least efficient way to do this, we should of course directly access it but its more than fast enough
-            for(y=0; y<s->height; y++){
-                double w= 1/sqrt(nb_freq);
-                int a= sqrt(w*sqrt(data[0][2*y+0]*data[0][2*y+0] + data[0][2*y+1]*data[0][2*y+1]));
-                int b= (nb_display_channels == 2 ) ? sqrt(w*sqrt(data[1][2*y+0]*data[1][2*y+0]
-                       + data[1][2*y+1]*data[1][2*y+1])) : a;
-                a= FFMIN(a,255);
-                b= FFMIN(b,255);
-                fgcolor = SDL_MapRGB(screen->format, a, b, (a+b)/2);
+            // least efficient way to do this, we should of course directly access it but its more than fast enough
+            for (y = 0; y < s->height; y++) {
+                double w = 1 / sqrt(nb_freq);
+                int a = sqrt(w * sqrt(data[0][2 * y + 0] * data[0][2 * y + 0] + data[0][2 * y + 1] * data[0][2 * y + 1]));
+                int b = (nb_display_channels == 2 ) ? sqrt(w * sqrt(data[1][2 * y + 0] * data[1][2 * y + 0]
+                       + data[1][2 * y + 1] * data[1][2 * y + 1])) : a;
+                a = FFMIN(a, 255);
+                b = FFMIN(b, 255);
+                fgcolor = SDL_MapRGB(screen->format, a, b, (a + b) / 2);
 
                 fill_rectangle(screen,
                             s->xpos, s->height-y, 1, 1,
@@ -869,30 +869,31 @@ static void video_audio_display(VideoState *s)
         }
         SDL_UpdateRect(screen, s->xpos, s->ytop, 1, s->height);
         s->xpos++;
-        if(s->xpos >= s->width)
+        if (s->xpos >= s->width)
             s->xpos= s->xleft;
     }
 }
 
-static int video_open(VideoState *is){
-    int flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;
+static int video_open(VideoState *is)
+{
+    int flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;
     int w,h;
 
-    if(is_full_screen) flags |= SDL_FULLSCREEN;
-    else               flags |= SDL_RESIZABLE;
+    if (is_full_screen) flags |= SDL_FULLSCREEN;
+    else                flags |= SDL_RESIZABLE;
 
     if (is_full_screen && fs_screen_width) {
         w = fs_screen_width;
         h = fs_screen_height;
-    } else if(!is_full_screen && screen_width){
+    } else if (!is_full_screen && screen_width) {
         w = screen_width;
         h = screen_height;
 #if CONFIG_AVFILTER
-    }else if (is->out_video_filter && is->out_video_filter->inputs[0]){
+    } else if (is->out_video_filter && is->out_video_filter->inputs[0]) {
         w = is->out_video_filter->inputs[0]->w;
         h = is->out_video_filter->inputs[0]->h;
 #else
-    }else if (is->video_st && is->video_st->codec->width){
+    } else if (is->video_st && is->video_st->codec->width) {
         w = is->video_st->codec->width;
         h = is->video_st->codec->height;
 #endif
@@ -900,7 +901,7 @@ static int video_open(VideoState *is){
         w = 640;
         h = 480;
     }
-    if(screen && is->width == screen->w && screen->w == w
+    if (screen && is->width == screen->w && screen->w == w
        && is->height== screen->h && screen->h == h)
         return 0;
 
@@ -918,7 +919,7 @@ static int video_open(VideoState *is){
         window_title = input_filename;
     SDL_WM_SetCaption(window_title, window_title);
 
-    is->width = screen->w;
+    is->width  = screen->w;
     is->height = screen->h;
 
     return 0;
@@ -927,7 +928,7 @@ static int video_open(VideoState *is){
 /* display the current picture, if any */
 static void video_display(VideoState *is)
 {
-    if(!screen)
+    if (!screen)
         video_open(cur_stream);
     if (is->audio_st && is->show_audio)
         video_audio_display(is);
@@ -938,15 +939,15 @@ static void video_display(VideoState *is)
 static int refresh_thread(void *opaque)
 {
     VideoState *is= opaque;
-    while(!is->abort_request){
+    while (!is->abort_request) {
         SDL_Event event;
         event.type = FF_REFRESH_EVENT;
         event.user.data1 = opaque;
-        if(!is->refresh){
-            is->refresh=1;
+        if (!is->refresh) {
+            is->refresh = 1;
             SDL_PushEvent(&event);
         }
-        usleep(is->audio_st && is->show_audio ? rdftspeed*1000 : 5000); //FIXME ideally we should wait the correct time but SDLs event passing is so slow it would be silly
+        usleep(is->audio_st && is->show_audio ? rdftspeed * 1000 : 5000); // FIXME ideally we should wait the correct time but SDLs event passing is so slow it would be silly
     }
     return 0;
 }
@@ -961,7 +962,7 @@ static double get_audio_clock(VideoState *is)
     bytes_per_sec = 0;
     if (is->audio_st) {
         bytes_per_sec = is->audio_st->codec->sample_rate *
-            2 * is->audio_st->codec->channels;
+                        2 * is->audio_st->codec->channels;
     }
     if (bytes_per_sec)
         pts -= (double)hw_buf_size / bytes_per_sec;
@@ -1025,7 +1026,7 @@ static void stream_pause(VideoState *is)
 {
     if (is->paused) {
         is->frame_timer += av_gettime() / 1000000.0 + is->video_current_pts_drift - is->video_current_pts;
-        if(is->read_pause_return != AVERROR(ENOSYS)){
+        if (is->read_pause_return != AVERROR(ENOSYS)) {
             is->video_current_pts = is->video_current_pts_drift + av_gettime() / 1000000.0;
         }
         is->video_current_pts_drift = is->video_current_pts - av_gettime() / 1000000.0;
@@ -1084,29 +1085,29 @@ static void video_refresh_timer(void *opaque)
     if (is->video_st) {
 retry:
         if (is->pictq_size == 0) {
-            //nothing to do, no picture to display in the que
+            // nothing to do, no picture to display in the que
         } else {
-            double time= av_gettime()/1000000.0;
+            double time = av_gettime() / 1000000.0;
             double next_target;
             /* dequeue the picture */
             vp = &is->pictq[is->pictq_rindex];
 
-            if(time < vp->target_clock)
+            if (time < vp->target_clock)
                 return;
             /* update current video pts */
             is->video_current_pts = vp->pts;
             is->video_current_pts_drift = is->video_current_pts - time;
             is->video_current_pos = vp->pos;
-            if(is->pictq_size > 1){
-                VideoPicture *nextvp= &is->pictq[(is->pictq_rindex+1)%VIDEO_PICTURE_QUEUE_SIZE];
+            if (is->pictq_size > 1) {
+                VideoPicture *nextvp = &is->pictq[(is->pictq_rindex + 1) % VIDEO_PICTURE_QUEUE_SIZE];
                 assert(nextvp->target_clock >= vp->target_clock);
                 next_target= nextvp->target_clock;
-            }else{
-                next_target= vp->target_clock + is->video_clock - vp->pts; //FIXME pass durations cleanly
+            } else {
+                next_target = vp->target_clock + is->video_clock - vp->pts; // FIXME pass durations cleanly
             }
-            if(framedrop && time > next_target){
+            if (framedrop && time > next_target) {
                 is->skip_frames *= 1.0 + FRAME_SKIP_FACTOR;
-                if(is->pictq_size > 1 || time > next_target + 0.5){
+                if (is->pictq_size > 1 || time > next_target + 0.5) {
                     /* update queue size and signal for next picture */
                     if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
                         is->pictq_rindex = 0;
@@ -1119,7 +1120,7 @@ retry:
                 }
             }
 
-            if(is->subtitle_st) {
+            if (is->subtitle_st) {
                 if (is->subtitle_stream_changed) {
                     SDL_LockMutex(is->subpq_mutex);
 
@@ -1207,7 +1208,8 @@ retry:
             if (is->audio_st && is->video_st)
                 av_diff = get_audio_clock(is) - get_video_clock(is);
             printf("%7.2f A-V:%7.3f s:%3.1f aq=%5dKB vq=%5dKB sq=%5dB f=%"PRId64"/%"PRId64"   \r",
-                   get_master_clock(is), av_diff, FFMAX(is->skip_frames-1, 0), aqsize / 1024, vqsize / 1024, sqsize, is->pts_ctx.num_faulty_dts, is->pts_ctx.num_faulty_pts);
+                   get_master_clock(is), av_diff, FFMAX(is->skip_frames - 1, 0), aqsize / 1024,
+                   vqsize / 1024, sqsize, is->pts_ctx.num_faulty_dts, is->pts_ctx.num_faulty_pts);
             fflush(stdout);
             last_time = cur_time;
         }
@@ -1224,7 +1226,7 @@ static void stream_close(VideoState *is)
     SDL_WaitThread(is->refresh_tid, NULL);
 
     /* free all pictures */
-    for(i=0;i<VIDEO_PICTURE_QUEUE_SIZE; i++) {
+    for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++) {
         vp = &is->pictq[i];
 #if CONFIG_AVFILTER
         if (vp->picref) {
@@ -1325,8 +1327,8 @@ static int queue_picture(VideoState *is, AVFrame *src_frame, double pts, int64_t
     /* wait until we have space to put a new picture */
     SDL_LockMutex(is->pictq_mutex);
 
-    if(is->pictq_size>=VIDEO_PICTURE_QUEUE_SIZE && !is->refresh)
-        is->skip_frames= FFMAX(1.0 - FRAME_SKIP_FACTOR, is->skip_frames * (1.0-FRAME_SKIP_FACTOR));
+    if (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE && !is->refresh)
+        is->skip_frames = FFMAX(1.0 - FRAME_SKIP_FACTOR, is->skip_frames * (1.0 - FRAME_SKIP_FACTOR));
 
     while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE &&
            !is->videoq.abort_request) {
@@ -1374,7 +1376,7 @@ static int queue_picture(VideoState *is, AVFrame *src_frame, double pts, int64_t
     if (vp->bmp) {
         AVPicture pict;
 #if CONFIG_AVFILTER
-        if(vp->picref)
+        if (vp->picref)
             avfilter_unref_buffer(vp->picref);
         vp->picref = src_frame->opaque;
 #endif
@@ -1382,7 +1384,7 @@ static int queue_picture(VideoState *is, AVFrame *src_frame, double pts, int64_t
         /* get a pointer on the bitmap */
         SDL_LockYUVOverlay (vp->bmp);
 
-        memset(&pict,0,sizeof(AVPicture));
+        memset(&pict, 0, sizeof(AVPicture));
         pict.data[0] = vp->bmp->pixels[0];
         pict.data[1] = vp->bmp->pixels[2];
         pict.data[2] = vp->bmp->pixels[1];
@@ -1400,7 +1402,7 @@ static int queue_picture(VideoState *is, AVFrame *src_frame, double pts, int64_t
         pict_src.linesize[1] = src_frame->linesize[1];
         pict_src.linesize[2] = src_frame->linesize[2];
 
-        //FIXME use direct rendering
+        // FIXME use direct rendering
         av_picture_copy(&pict, &pict_src,
                         vp->pix_fmt, vp->width, vp->height);
 #else
@@ -1425,7 +1427,7 @@ static int queue_picture(VideoState *is, AVFrame *src_frame, double pts, int64_t
         if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
             is->pictq_windex = 0;
         SDL_LockMutex(is->pictq_mutex);
-        vp->target_clock= compute_target_time(vp->pts, is);
+        vp->target_clock = compute_target_time(vp->pts, is);
 
         is->pictq_size++;
         SDL_UnlockMutex(is->pictq_mutex);
@@ -1470,7 +1472,7 @@ static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacke
         avcodec_flush_buffers(is->video_st->codec);
 
         SDL_LockMutex(is->pictq_mutex);
-        //Make sure there are no long delay timers (ideally we should just flush the que but thats harder)
+        // Make sure there are no long delay timers (ideally we should just flush the que but thats harder)
         for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++) {
             is->pictq[i].target_clock= 0;
         }
@@ -1505,7 +1507,7 @@ static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacke
         }
 
         is->skip_frames_index += 1;
-        if(is->skip_frames_index >= is->skip_frames){
+        if (is->skip_frames_index >= is->skip_frames) {
             is->skip_frames_index -= FFMAX(is->skip_frames, 1.0);
             return 1;
         }
@@ -1533,12 +1535,12 @@ static int input_get_buffer(AVCodecContext *codec, AVFrame *pic)
     if (codec->codec->capabilities & CODEC_CAP_NEG_LINESIZES)
         perms |= AV_PERM_NEG_LINESIZES;
 
-    if(pic->buffer_hints & FF_BUFFER_HINTS_VALID) {
-        if(pic->buffer_hints & FF_BUFFER_HINTS_READABLE) perms |= AV_PERM_READ;
-        if(pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) perms |= AV_PERM_PRESERVE;
-        if(pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) perms |= AV_PERM_REUSE2;
+    if (pic->buffer_hints & FF_BUFFER_HINTS_VALID) {
+        if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE) perms |= AV_PERM_READ;
+        if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) perms |= AV_PERM_PRESERVE;
+        if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) perms |= AV_PERM_REUSE2;
     }
-    if(pic->reference) perms |= AV_PERM_READ | AV_PERM_PRESERVE;
+    if (pic->reference) perms |= AV_PERM_READ | AV_PERM_PRESERVE;
 
     w = codec->width;
     h = codec->height;
@@ -1547,13 +1549,13 @@ static int input_get_buffer(AVCodecContext *codec, AVFrame *pic)
     w += edge << 1;
     h += edge << 1;
 
-    if(!(ref = avfilter_get_video_buffer(ctx->outputs[0], perms, w, h)))
+    if (!(ref = avfilter_get_video_buffer(ctx->outputs[0], perms, w, h)))
         return -1;
 
-    pixel_size = av_pix_fmt_descriptors[ref->format].comp[0].step_minus1+1;
+    pixel_size = av_pix_fmt_descriptors[ref->format].comp[0].step_minus1 + 1;
     ref->video->w = codec->width;
     ref->video->h = codec->height;
-    for(i = 0; i < 4; i ++) {
+    for (i = 0; i < 4; i ++) {
         unsigned hshift = (i == 1 || i == 2) ? av_pix_fmt_descriptors[ref->format].log2_chroma_w : 0;
         unsigned vshift = (i == 1 || i == 2) ? av_pix_fmt_descriptors[ref->format].log2_chroma_h : 0;
 
@@ -1566,8 +1568,8 @@ static int input_get_buffer(AVCodecContext *codec, AVFrame *pic)
     pic->opaque = ref;
     pic->type   = FF_BUFFER_TYPE_USER;
     pic->reordered_opaque = codec->reordered_opaque;
-    if(codec->pkt) pic->pkt_pts = codec->pkt->pts;
-    else           pic->pkt_pts = AV_NOPTS_VALUE;
+    if (codec->pkt) pic->pkt_pts = codec->pkt->pts;
+    else            pic->pkt_pts = AV_NOPTS_VALUE;
     return 0;
 }
 
@@ -1593,8 +1595,8 @@ static int input_reget_buffer(AVCodecContext *codec, AVFrame *pic)
     }
 
     pic->reordered_opaque = codec->reordered_opaque;
-    if(codec->pkt) pic->pkt_pts = codec->pkt->pts;
-    else           pic->pkt_pts = AV_NOPTS_VALUE;
+    if (codec->pkt) pic->pkt_pts = codec->pkt->pts;
+    else            pic->pkt_pts = AV_NOPTS_VALUE;
     return 0;
 }
 
@@ -1602,12 +1604,12 @@ static int input_init(AVFilterContext *ctx, const char *args, void *opaque)
 {
     FilterPriv *priv = ctx->priv;
     AVCodecContext *codec;
-    if(!opaque) return -1;
+    if (!opaque) return -1;
 
     priv->is = opaque;
     codec    = priv->is->video_st->codec;
     codec->opaque = ctx;
-    if(codec->codec->capabilities & CODEC_CAP_DR1) {
+    if (codec->codec->capabilities & CODEC_CAP_DR1) {
         priv->use_dr1 = 1;
         codec->get_buffer     = input_get_buffer;
         codec->release_buffer = input_release_buffer;
@@ -1639,7 +1641,7 @@ static int input_request_frame(AVFilterLink *link)
     if (ret < 0)
         return -1;
 
-    if(priv->use_dr1) {
+    if (priv->use_dr1) {
         picref = avfilter_ref_buffer(priv->frame->opaque, ~0);
     } else {
         picref = avfilter_get_video_buffer(link, AV_PERM_WRITE, link->w, link->h);
@@ -1717,7 +1719,7 @@ static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const c
                                             NULL, &ffsink_ctx, graph)) < 0)
         return ret;
 
-    if(vfilters) {
+    if (vfilters) {
         AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));
         AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));
 
@@ -1752,7 +1754,7 @@ static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const c
 static int video_thread(void *arg)
 {
     VideoState *is = arg;
-    AVFrame *frame= avcodec_alloc_frame();
+    AVFrame *frame = avcodec_alloc_frame();
     int64_t pts_int;
     double pts;
     int ret;
@@ -1769,7 +1771,7 @@ static int video_thread(void *arg)
     filt_out = is->out_video_filter;
 #endif
 
-    for(;;) {
+    for (;;) {
 #if !CONFIG_AVFILTER
         AVPacket pkt;
 #else
@@ -1810,12 +1812,13 @@ static int video_thread(void *arg)
         ret = get_video_frame(is, frame, &pts_int, &pkt);
 #endif
 
-        if (ret < 0) goto the_end;
+        if (ret < 0)
+            goto the_end;
 
         if (!ret)
             continue;
 
-        pts = pts_int*av_q2d(is->video_st->time_base);
+        pts = pts_int * av_q2d(is->video_st->time_base);
 
 #if CONFIG_AVFILTER
         ret = output_picture2(is, frame, pts, pos);
@@ -1848,14 +1851,14 @@ static int subtitle_thread(void *arg)
     int i, j;
     int r, g, b, y, u, v, a;
 
-    for(;;) {
+    for (;;) {
         while (is->paused && !is->subtitleq.abort_request) {
             SDL_Delay(10);
         }
         if (packet_queue_get(&is->subtitleq, pkt, 1) < 0)
             break;
 
-        if(pkt->data == flush_pkt.data){
+        if (pkt->data == flush_pkt.data) {
             avcodec_flush_buffers(is->subtitle_st->codec);
             continue;
         }
@@ -1875,7 +1878,7 @@ static int subtitle_thread(void *arg)
            this packet, if any */
         pts = 0;
         if (pkt->pts != AV_NOPTS_VALUE)
-            pts = av_q2d(is->subtitle_st->time_base)*pkt->pts;
+            pts = av_q2d(is->subtitle_st->time_base) * pkt->pts;
 
         avcodec_decode_subtitle2(is->subtitle_st->codec, &sp->sub,
                                  &got_subtitle, pkt);
@@ -1994,7 +1997,7 @@ static int synchronize_audio(VideoState *is, short *samples,
             /* too big difference : may be initial PTS errors, so
                reset A-V filter */
             is->audio_diff_avg_count = 0;
-            is->audio_diff_cum = 0;
+            is->audio_diff_cum       = 0;
         }
     }
 
@@ -2006,13 +2009,13 @@ static int audio_decode_frame(VideoState *is, double *pts_ptr)
 {
     AVPacket *pkt_temp = &is->audio_pkt_temp;
     AVPacket *pkt = &is->audio_pkt;
-    AVCodecContext *dec= is->audio_st->codec;
+    AVCodecContext *dec = is->audio_st->codec;
     int n, len1, data_size, got_frame;
     double pts;
     int new_packet = 0;
     int flush_complete = 0;
 
-    for(;;) {
+    for (;;) {
         /* NOTE: the audio packet can contain several frames */
         while (pkt_temp->size > 0 || (!pkt_temp->data && new_packet)) {
             if (!is->frame) {
@@ -2059,25 +2062,25 @@ static int audio_decode_frame(VideoState *is, double *pts_ptr)
             }
 
             if (is->reformat_ctx) {
-                const void *ibuf[6]= { is->frame->data[0] };
+                const void *ibuf[6] = { is->frame->data[0] };
                 void *obuf[6];
-                int istride[6]= {av_get_bytes_per_sample(dec->sample_fmt)};
-                int ostride[6]= {2};
+                int istride[6] = { av_get_bytes_per_sample(dec->sample_fmt) };
+                int ostride[6] = { 2 };
                 int len= data_size/istride[0];
                 obuf[0] = av_realloc(is->audio_buf1, FFALIGN(len * ostride[0], 32));
                 if (!obuf[0]) {
                     return AVERROR(ENOMEM);
                 }
                 is->audio_buf1 = obuf[0];
-                if (av_audio_convert(is->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
+                if (av_audio_convert(is->reformat_ctx, obuf, ostride, ibuf, istride, len) < 0) {
                     printf("av_audio_convert() failed\n");
                     break;
                 }
                 is->audio_buf = is->audio_buf1;
                 /* FIXME: existing code assume that data_size equals framesize*channels*2
                           remove this legacy cruft */
-                data_size= len*2;
-            }else{
+                data_size = len * 2;
+            } else {
                 is->audio_buf = is->frame->data[0];
             }
 
@@ -2176,19 +2179,20 @@ static int stream_component_open(VideoState *is, int stream_index)
     opts = filter_codec_opts(codec_opts, avctx->codec_id, ic, ic->streams[stream_index]);
 
     codec = avcodec_find_decoder(avctx->codec_id);
-    avctx->debug_mv = debug_mv;
-    avctx->debug = debug;
-    avctx->workaround_bugs = workaround_bugs;
-    avctx->lowres = lowres;
-    if(lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
-    avctx->idct_algo= idct;
-    if(fast) avctx->flags2 |= CODEC_FLAG2_FAST;
-    avctx->skip_frame= skip_frame;
-    avctx->skip_idct= skip_idct;
-    avctx->skip_loop_filter= skip_loop_filter;
-    avctx->error_recognition= error_recognition;
-    avctx->error_concealment= error_concealment;
-    avctx->thread_count= thread_count;
+    avctx->debug_mv          = debug_mv;
+    avctx->debug             = debug;
+    avctx->workaround_bugs   = workaround_bugs;
+    avctx->lowres            = lowres;
+    avctx->idct_algo         = idct;
+    avctx->skip_frame        = skip_frame;
+    avctx->skip_idct         = skip_idct;
+    avctx->skip_loop_filter  = skip_loop_filter;
+    avctx->error_recognition = error_recognition;
+    avctx->error_concealment = error_concealment;
+    avctx->thread_count      = thread_count;
+
+    if (lowres) avctx->flags  |= CODEC_FLAG_EMU_EDGE;
+    if (fast)   avctx->flags2 |= CODEC_FLAG2_FAST;
 
     if (!codec ||
         avcodec_open2(avctx, codec, &opts) < 0)
@@ -2212,19 +2216,19 @@ static int stream_component_open(VideoState *is, int stream_index)
             return -1;
         }
         is->audio_hw_buf_size = spec.size;
-        is->audio_src_fmt= AV_SAMPLE_FMT_S16;
+        is->audio_src_fmt = AV_SAMPLE_FMT_S16;
     }
 
     ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
-    switch(avctx->codec_type) {
+    switch (avctx->codec_type) {
     case AVMEDIA_TYPE_AUDIO:
         is->audio_stream = stream_index;
         is->audio_st = ic->streams[stream_index];
-        is->audio_buf_size = 0;
+        is->audio_buf_size  = 0;
         is->audio_buf_index = 0;
 
         /* init averaging filter */
-        is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
+        is->audio_diff_avg_coef  = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
         is->audio_diff_avg_count = 0;
         /* since we do not have a precise anough audio fifo fullness,
            we correct audio sync only if larger than this threshold */
@@ -2263,7 +2267,7 @@ static void stream_component_close(VideoState *is, int stream_index)
         return;
     avctx = ic->streams[stream_index]->codec;
 
-    switch(avctx->codec_type) {
+    switch (avctx->codec_type) {
     case AVMEDIA_TYPE_AUDIO:
         packet_queue_abort(&is->audioq);
 
@@ -2319,7 +2323,7 @@ static void stream_component_close(VideoState *is, int stream_index)
 
     ic->streams[stream_index]->discard = AVDISCARD_ALL;
     avcodec_close(avctx);
-    switch(avctx->codec_type) {
+    switch (avctx->codec_type) {
     case AVMEDIA_TYPE_AUDIO:
         is->audio_st = NULL;
         is->audio_stream = -1;
@@ -2343,7 +2347,7 @@ static VideoState *global_video_state;
 
 static int decode_interrupt_cb(void *ctx)
 {
-    return (global_video_state && global_video_state->abort_request);
+    return global_video_state && global_video_state->abort_request;
 }
 
 /* this thread gets the stream from the disk or the network */
@@ -2354,7 +2358,7 @@ static int decode_thread(void *arg)
     int err, i, ret;
     int st_index[AVMEDIA_TYPE_NB];
     AVPacket pkt1, *pkt = &pkt1;
-    int eof=0;
+    int eof = 0;
     int pkt_in_play_range = 0;
     AVDictionaryEntry *t;
     AVDictionary **opts;
@@ -2382,7 +2386,7 @@ static int decode_thread(void *arg)
     }
     is->ic = ic;
 
-    if(genpts)
+    if (genpts)
         ic->flags |= AVFMT_FLAG_GENPTS;
 
     opts = setup_find_stream_info_opts(ic, codec_opts);
@@ -2398,11 +2402,11 @@ static int decode_thread(void *arg)
         av_dict_free(&opts[i]);
     av_freep(&opts);
 
-    if(ic->pb)
-        ic->pb->eof_reached= 0; //FIXME hack, avplay maybe should not use url_feof() to test for the end
+    if (ic->pb)
+        ic->pb->eof_reached = 0; // FIXME hack, avplay maybe should not use url_feof() to test for the end
 
-    if(seek_by_bytes<0)
-        seek_by_bytes= !!(ic->iformat->flags & AVFMT_TS_DISCONT);
+    if (seek_by_bytes < 0)
+        seek_by_bytes = !!(ic->iformat->flags & AVFMT_TS_DISCONT);
 
     /* if seeking requested, we execute it */
     if (start_time != AV_NOPTS_VALUE) {
@@ -2448,12 +2452,12 @@ static int decode_thread(void *arg)
         stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);
     }
 
-    ret=-1;
+    ret = -1;
     if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
-        ret= stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);
+        ret = stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);
     }
     is->refresh_tid = SDL_CreateThread(refresh_thread, is);
-    if(ret<0) {
+    if (ret < 0) {
         if (!display_disable)
             is->show_audio = 2;
     }
@@ -2468,13 +2472,13 @@ static int decode_thread(void *arg)
         goto fail;
     }
 
-    for(;;) {
+    for (;;) {
         if (is->abort_request)
             break;
         if (is->paused != is->last_paused) {
             is->last_paused = is->paused;
             if (is->paused)
-                is->read_pause_return= av_read_pause(ic);
+                is->read_pause_return = av_read_pause(ic);
             else
                 av_read_play(ic);
         }
@@ -2487,16 +2491,16 @@ static int decode_thread(void *arg)
         }
 #endif
         if (is->seek_req) {
-            int64_t seek_target= is->seek_pos;
-            int64_t seek_min= is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;
-            int64_t seek_max= is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;
-//FIXME the +-2 is due to rounding being not done in the correct direction in generation
+            int64_t seek_target = is->seek_pos;
+            int64_t seek_min    = is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;
+            int64_t seek_max    = is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;
+// FIXME the +-2 is due to rounding being not done in the correct direction in generation
 //      of the seek_pos/seek_rel variables
 
             ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);
             if (ret < 0) {
                 fprintf(stderr, "%s: error while seeking\n", is->ic->filename);
-            }else{
+            } else {
                 if (is->audio_stream >= 0) {
                     packet_queue_flush(&is->audioq);
                     packet_queue_put(&is->audioq, &flush_pkt);
@@ -2511,24 +2515,24 @@ static int decode_thread(void *arg)
                 }
             }
             is->seek_req = 0;
-            eof= 0;
+            eof = 0;
         }
 
         /* if the queue are full, no need to read more */
         if (   is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE
-            || (   (is->audioq   .size  > MIN_AUDIOQ_SIZE || is->audio_stream<0)
-                && (is->videoq   .nb_packets > MIN_FRAMES || is->video_stream<0)
-                && (is->subtitleq.nb_packets > MIN_FRAMES || is->subtitle_stream<0))) {
+            || (   (is->audioq   .size  > MIN_AUDIOQ_SIZE || is->audio_stream < 0)
+                && (is->videoq   .nb_packets > MIN_FRAMES || is->video_stream < 0)
+                && (is->subtitleq.nb_packets > MIN_FRAMES || is->subtitle_stream < 0))) {
             /* wait 10 ms */
             SDL_Delay(10);
             continue;
         }
-        if(eof) {
-            if(is->video_stream >= 0){
+        if (eof) {
+            if (is->video_stream >= 0) {
                 av_init_packet(pkt);
-                pkt->data=NULL;
-                pkt->size=0;
-                pkt->stream_index= is->video_stream;
+                pkt->data = NULL;
+                pkt->size = 0;
+                pkt->stream_index = is->video_stream;
                 packet_queue_put(&is->videoq, pkt);
             }
             if (is->audio_stream >= 0 &&
@@ -2540,11 +2544,11 @@ static int decode_thread(void *arg)
                 packet_queue_put(&is->audioq, pkt);
             }
             SDL_Delay(10);
-            if(is->audioq.size + is->videoq.size + is->subtitleq.size ==0){
-                if(loop!=1 && (!loop || --loop)){
+            if (is->audioq.size + is->videoq.size + is->subtitleq.size == 0) {
+                if (loop != 1 && (!loop || --loop)) {
                     stream_seek(cur_stream, start_time != AV_NOPTS_VALUE ? start_time : 0, 0, 0);
-                }else if(autoexit){
-                    ret=AVERROR_EOF;
+                } else if (autoexit) {
+                    ret = AVERROR_EOF;
                     goto fail;
                 }
             }
@@ -2553,7 +2557,7 @@ static int decode_thread(void *arg)
         ret = av_read_frame(ic, pkt);
         if (ret < 0) {
             if (ret == AVERROR_EOF || (ic->pb && ic->pb->eof_reached))
-                eof=1;
+                eof = 1;
             if (ic->pb && ic->pb->error)
                 break;
             SDL_Delay(100); /* wait for user event */
@@ -2563,8 +2567,8 @@ static int decode_thread(void *arg)
         pkt_in_play_range = duration == AV_NOPTS_VALUE ||
                 (pkt->pts - ic->streams[pkt->stream_index]->start_time) *
                 av_q2d(ic->streams[pkt->stream_index]->time_base) -
-                (double)(start_time != AV_NOPTS_VALUE ? start_time : 0)/1000000
-                <= ((double)duration/1000000);
+                (double)(start_time != AV_NOPTS_VALUE ? start_time : 0) / 1000000
+                <= ((double)duration / 1000000);
         if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {
             packet_queue_put(&is->audioq, pkt);
         } else if (pkt->stream_index == is->video_stream && pkt_in_play_range) {
@@ -2595,7 +2599,6 @@ static int decode_thread(void *arg)
     if (is->ic) {
         avformat_close_input(&is->ic);
     }
-    avio_set_interrupt_cb(NULL);
 
     if (ret != 0) {
         SDL_Event event;
@@ -2616,18 +2619,18 @@ static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
         return NULL;
     av_strlcpy(is->filename, filename, sizeof(is->filename));
     is->iformat = iformat;
-    is->ytop = 0;
-    is->xleft = 0;
+    is->ytop    = 0;
+    is->xleft   = 0;
 
     /* start video display */
     is->pictq_mutex = SDL_CreateMutex();
-    is->pictq_cond = SDL_CreateCond();
+    is->pictq_cond  = SDL_CreateCond();
 
     is->subpq_mutex = SDL_CreateMutex();
-    is->subpq_cond = SDL_CreateCond();
+    is->subpq_cond  = SDL_CreateCond();
 
     is->av_sync_type = av_sync_type;
-    is->parse_tid = SDL_CreateThread(decode_thread, is);
+    is->parse_tid    = SDL_CreateThread(decode_thread, is);
     if (!is->parse_tid) {
         av_free(is);
         return NULL;
@@ -2650,7 +2653,7 @@ static void stream_cycle_channel(VideoState *is, int codec_type)
     if (start_index < (codec_type == AVMEDIA_TYPE_SUBTITLE ? -1 : 0))
         return;
     stream_index = start_index;
-    for(;;) {
+    for (;;) {
         if (++stream_index >= is->ic->nb_streams)
         {
             if (codec_type == AVMEDIA_TYPE_SUBTITLE)
@@ -2665,7 +2668,7 @@ static void stream_cycle_channel(VideoState *is, int codec_type)
         st = ic->streams[stream_index];
         if (st->codec->codec_type == codec_type) {
             /* check that parameters are OK */
-            switch(codec_type) {
+            switch (codec_type) {
             case AVMEDIA_TYPE_AUDIO:
                 if (st->codec->sample_rate != 0 &&
                     st->codec->channels != 0)
@@ -2720,8 +2723,8 @@ static void toggle_audio_display(void)
         int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
         cur_stream->show_audio = (cur_stream->show_audio + 1) % 3;
         fill_rectangle(screen,
-                    cur_stream->xleft, cur_stream->ytop, cur_stream->width, cur_stream->height,
-                    bgcolor);
+                       cur_stream->xleft, cur_stream->ytop, cur_stream->width, cur_stream->height,
+                       bgcolor);
         SDL_UpdateRect(screen, cur_stream->xleft, cur_stream->ytop, cur_stream->width, cur_stream->height);
     }
 }
@@ -2732,16 +2735,16 @@ static void event_loop(void)
     SDL_Event event;
     double incr, pos, frac;
 
-    for(;;) {
+    for (;;) {
         double x;
         SDL_WaitEvent(&event);
-        switch(event.type) {
+        switch (event.type) {
         case SDL_KEYDOWN:
             if (exit_on_keydown) {
                 do_exit();
                 break;
             }
-            switch(event.key.keysym.sym) {
+            switch (event.key.keysym.sym) {
             case SDLK_ESCAPE:
             case SDLK_q:
                 do_exit();
@@ -2753,7 +2756,7 @@ static void event_loop(void)
             case SDLK_SPACE:
                 toggle_pause();
                 break;
-            case SDLK_s: //S: Step to next frame
+            case SDLK_s: // S: Step to next frame
                 step_to_next_frame();
                 break;
             case SDLK_a:
@@ -2785,11 +2788,11 @@ static void event_loop(void)
             do_seek:
                 if (cur_stream) {
                     if (seek_by_bytes) {
-                        if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos>=0){
-                            pos= cur_stream->video_current_pos;
-                        }else if(cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos>=0){
-                            pos= cur_stream->audio_pkt.pos;
-                        }else
+                        if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos >= 0) {
+                            pos = cur_stream->video_current_pos;
+                        } else if (cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos >= 0) {
+                            pos = cur_stream->audio_pkt.pos;
+                        } else
                             pos = avio_tell(cur_stream->ic->pb);
                         if (cur_stream->ic->bit_rate)
                             incr *= cur_stream->ic->bit_rate / 8.0;
@@ -2814,33 +2817,33 @@ static void event_loop(void)
                 break;
             }
         case SDL_MOUSEMOTION:
-            if(event.type ==SDL_MOUSEBUTTONDOWN){
-                x= event.button.x;
-            }else{
-                if(event.motion.state != SDL_PRESSED)
+            if (event.type == SDL_MOUSEBUTTONDOWN) {
+                x = event.button.x;
+            } else {
+                if (event.motion.state != SDL_PRESSED)
                     break;
-                x= event.motion.x;
+                x = event.motion.x;
             }
             if (cur_stream) {
-                if(seek_by_bytes || cur_stream->ic->duration<=0){
-                    uint64_t size=  avio_size(cur_stream->ic->pb);
+                if (seek_by_bytes || cur_stream->ic->duration <= 0) {
+                    uint64_t size =  avio_size(cur_stream->ic->pb);
                     stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);
-                }else{
+                } else {
                     int64_t ts;
                     int ns, hh, mm, ss;
                     int tns, thh, tmm, tss;
-                    tns = cur_stream->ic->duration/1000000LL;
-                    thh = tns/3600;
-                    tmm = (tns%3600)/60;
-                    tss = (tns%60);
-                    frac = x/cur_stream->width;
-                    ns = frac*tns;
-                    hh = ns/3600;
-                    mm = (ns%3600)/60;
-                    ss = (ns%60);
+                    tns  = cur_stream->ic->duration / 1000000LL;
+                    thh  = tns / 3600;
+                    tmm  = (tns % 3600) / 60;
+                    tss  = (tns % 60);
+                    frac = x / cur_stream->width;
+                    ns   = frac * tns;
+                    hh   = ns / 3600;
+                    mm   = (ns % 3600) / 60;
+                    ss   = (ns % 60);
                     fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d)       \n", frac*100,
                             hh, mm, ss, thh, tmm, tss);
-                    ts = frac*cur_stream->ic->duration;
+                    ts = frac * cur_stream->ic->duration;
                     if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
                         ts += cur_stream->ic->start_time;
                     stream_seek(cur_stream, ts, 0, 0);
@@ -2851,8 +2854,8 @@ static void event_loop(void)
             if (cur_stream) {
                 screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
                                           SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
-                screen_width = cur_stream->width = event.resize.w;
-                screen_height= cur_stream->height= event.resize.h;
+                screen_width  = cur_stream->width  = event.resize.w;
+                screen_height = cur_stream->height = event.resize.h;
             }
             break;
         case SDL_QUIT:
@@ -2865,7 +2868,7 @@ static void event_loop(void)
             break;
         case FF_REFRESH_EVENT:
             video_refresh_timer(event.user.data1);
-            cur_stream->refresh=0;
+            cur_stream->refresh = 0;
             break;
         default:
             break;
@@ -2951,7 +2954,7 @@ static int opt_vismv(const char *opt, const char *arg)
 
 static int opt_thread_count(const char *opt, const char *arg)
 {
-    thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
+    thread_count = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
 #if !HAVE_THREADS
     fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
 #endif
@@ -2960,49 +2963,49 @@ static int opt_thread_count(const char *opt, const char *arg)
 
 static const OptionDef options[] = {
 #include "cmdutils_common_opts.h"
-    { "x", HAS_ARG, {(void*)opt_width}, "force displayed width", "width" },
-    { "y", HAS_ARG, {(void*)opt_height}, "force displayed height", "height" },
-    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
-    { "fs", OPT_BOOL, {(void*)&is_full_screen}, "force full screen" },
-    { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
-    { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
-    { "ast", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&wanted_stream[AVMEDIA_TYPE_AUDIO]}, "select desired audio stream", "stream_number" },
-    { "vst", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&wanted_stream[AVMEDIA_TYPE_VIDEO]}, "select desired video stream", "stream_number" },
-    { "sst", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&wanted_stream[AVMEDIA_TYPE_SUBTITLE]}, "select desired subtitle stream", "stream_number" },
-    { "ss", HAS_ARG, {(void*)&opt_seek}, "seek to a given position in seconds", "pos" },
-    { "t", HAS_ARG, {(void*)&opt_duration}, "play  \"duration\" seconds of audio/video", "duration" },
-    { "bytes", OPT_INT | HAS_ARG, {(void*)&seek_by_bytes}, "seek by bytes 0=off 1=on -1=auto", "val" },
-    { "nodisp", OPT_BOOL, {(void*)&display_disable}, "disable graphical display" },
-    { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
-    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
-    { "stats", OPT_BOOL | OPT_EXPERT, {(void*)&show_status}, "show status", "" },
-    { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
-    { "bug", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&workaround_bugs}, "workaround bugs", "" },
-    { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
-    { "fast", OPT_BOOL | OPT_EXPERT, {(void*)&fast}, "non spec compliant optimizations", "" },
-    { "genpts", OPT_BOOL | OPT_EXPERT, {(void*)&genpts}, "generate pts", "" },
-    { "drp", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&decoder_reorder_pts}, "let decoder reorder pts 0=off 1=on -1=auto", ""},
-    { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&lowres}, "", "" },
-    { "skiploop", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&skip_loop_filter}, "", "" },
-    { "skipframe", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&skip_frame}, "", "" },
-    { "skipidct", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&skip_idct}, "", "" },
-    { "idct", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&idct}, "set idct algo",  "algo" },
-    { "er", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&error_recognition}, "set error detection threshold (0-4)",  "threshold" },
-    { "ec", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&error_concealment}, "set error concealment options",  "bit_mask" },
-    { "sync", HAS_ARG | OPT_EXPERT, {(void*)opt_sync}, "set audio-video sync. type (type=audio/video/ext)", "type" },
-    { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
-    { "autoexit", OPT_BOOL | OPT_EXPERT, {(void*)&autoexit}, "exit at the end", "" },
-    { "exitonkeydown", OPT_BOOL | OPT_EXPERT, {(void*)&exit_on_keydown}, "exit on key down", "" },
-    { "exitonmousedown", OPT_BOOL | OPT_EXPERT, {(void*)&exit_on_mousedown}, "exit on mouse down", "" },
-    { "loop", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&loop}, "set number of times the playback shall be looped", "loop count" },
-    { "framedrop", OPT_BOOL | OPT_EXPERT, {(void*)&framedrop}, "drop frames when cpu is too slow", "" },
-    { "window_title", OPT_STRING | HAS_ARG, {(void*)&window_title}, "set window title", "window title" },
+    { "x", HAS_ARG, { (void*)opt_width }, "force displayed width", "width" },
+    { "y", HAS_ARG, { (void*)opt_height }, "force displayed height", "height" },
+    { "s", HAS_ARG | OPT_VIDEO, { (void*)opt_frame_size }, "set frame size (WxH or abbreviation)", "size" },
+    { "fs", OPT_BOOL, { (void*)&is_full_screen }, "force full screen" },
+    { "an", OPT_BOOL, { (void*)&audio_disable }, "disable audio" },
+    { "vn", OPT_BOOL, { (void*)&video_disable }, "disable video" },
+    { "ast", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&wanted_stream[AVMEDIA_TYPE_AUDIO] }, "select desired audio stream", "stream_number" },
+    { "vst", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&wanted_stream[AVMEDIA_TYPE_VIDEO] }, "select desired video stream", "stream_number" },
+    { "sst", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&wanted_stream[AVMEDIA_TYPE_SUBTITLE] }, "select desired subtitle stream", "stream_number" },
+    { "ss", HAS_ARG, { (void*)&opt_seek }, "seek to a given position in seconds", "pos" },
+    { "t", HAS_ARG, { (void*)&opt_duration }, "play  \"duration\" seconds of audio/video", "duration" },
+    { "bytes", OPT_INT | HAS_ARG, { (void*)&seek_by_bytes }, "seek by bytes 0=off 1=on -1=auto", "val" },
+    { "nodisp", OPT_BOOL, { (void*)&display_disable }, "disable graphical display" },
+    { "f", HAS_ARG, { (void*)opt_format }, "force format", "fmt" },
+    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { (void*)opt_frame_pix_fmt }, "set pixel format", "format" },
+    { "stats", OPT_BOOL | OPT_EXPERT, { (void*)&show_status }, "show status", "" },
+    { "debug", HAS_ARG | OPT_EXPERT, { (void*)opt_debug }, "print specific debug info", "" },
+    { "bug", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&workaround_bugs }, "workaround bugs", "" },
+    { "vismv", HAS_ARG | OPT_EXPERT, { (void*)opt_vismv }, "visualize motion vectors", "" },
+    { "fast", OPT_BOOL | OPT_EXPERT, { (void*)&fast }, "non spec compliant optimizations", "" },
+    { "genpts", OPT_BOOL | OPT_EXPERT, { (void*)&genpts }, "generate pts", "" },
+    { "drp", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&decoder_reorder_pts }, "let decoder reorder pts 0=off 1=on -1=auto", ""},
+    { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&lowres }, "", "" },
+    { "skiploop", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&skip_loop_filter }, "", "" },
+    { "skipframe", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&skip_frame }, "", "" },
+    { "skipidct", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&skip_idct }, "", "" },
+    { "idct", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&idct }, "set idct algo",  "algo" },
+    { "er", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&error_recognition }, "set error detection threshold (0-4)",  "threshold" },
+    { "ec", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&error_concealment }, "set error concealment options",  "bit_mask" },
+    { "sync", HAS_ARG | OPT_EXPERT, { (void*)opt_sync }, "set audio-video sync. type (type=audio/video/ext)", "type" },
+    { "threads", HAS_ARG | OPT_EXPERT, { (void*)opt_thread_count }, "thread count", "count" },
+    { "autoexit", OPT_BOOL | OPT_EXPERT, { (void*)&autoexit }, "exit at the end", "" },
+    { "exitonkeydown", OPT_BOOL | OPT_EXPERT, { (void*)&exit_on_keydown }, "exit on key down", "" },
+    { "exitonmousedown", OPT_BOOL | OPT_EXPERT, { (void*)&exit_on_mousedown }, "exit on mouse down", "" },
+    { "loop", OPT_INT | HAS_ARG | OPT_EXPERT, { (void*)&loop }, "set number of times the playback shall be looped", "loop count" },
+    { "framedrop", OPT_BOOL | OPT_EXPERT, { (void*)&framedrop }, "drop frames when cpu is too slow", "" },
+    { "window_title", OPT_STRING | HAS_ARG, { (void*)&window_title }, "set window title", "window title" },
 #if CONFIG_AVFILTER
-    { "vf", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
+    { "vf", OPT_STRING | HAS_ARG, { (void*)&vfilters }, "video filters", "filter list" },
 #endif
-    { "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, {(void*)&rdftspeed}, "rdft speed", "msecs" },
-    { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
-    { "i", 0, {NULL}, "avconv compatibility dummy option", ""},
+    { "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, { (void*)&rdftspeed }, "rdft speed", "msecs" },
+    { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, { (void*)opt_default }, "generic catch all option", "" },
+    { "i", 0, { NULL }, "avconv compatibility dummy option", ""},
     { NULL, },
 };
 
@@ -3111,7 +3114,7 @@ int main(int argc, char **argv)
     SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
 
     av_init_packet(&flush_pkt);
-    flush_pkt.data= "FLUSH";
+    flush_pkt.data = "FLUSH";
 
     cur_stream = stream_open(input_filename, file_iformat);
 
diff --git a/cmdutils.c b/cmdutils.c
index c5c2c1c..f2e3490 100644
--- a/cmdutils.c
+++ b/cmdutils.c
@@ -33,7 +33,9 @@
 #include "libavfilter/avfilter.h"
 #include "libavdevice/avdevice.h"
 #include "libswscale/swscale.h"
+#if CONFIG_POSTPROC
 #include "libpostproc/postprocess.h"
+#endif
 #include "libavutil/avstring.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/parseutils.h"
@@ -58,7 +60,8 @@ static const int this_year = 2011;
 void init_opts(void)
 {
 #if CONFIG_SWSCALE
-    sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC, NULL, NULL, NULL);
+    sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
+                              NULL, NULL, NULL);
 #endif
 }
 
@@ -72,24 +75,25 @@ void uninit_opts(void)
     av_dict_free(&codec_opts);
 }
 
-void log_callback_help(void* ptr, int level, const char* fmt, va_list vl)
+void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
 {
     vfprintf(stdout, fmt, vl);
 }
 
-double parse_number_or_die(const char *context, const char *numstr, int type, double min, double max)
+double parse_number_or_die(const char *context, const char *numstr, int type,
+                           double min, double max)
 {
     char *tail;
     const char *error;
     double d = av_strtod(numstr, &tail);
     if (*tail)
-        error= "Expected number for %s but found: %s\n";
+        error = "Expected number for %s but found: %s\n";
     else if (d < min || d > max)
-        error= "The value for %s was %s which is not within %f - %f\n";
-    else if(type == OPT_INT64 && (int64_t)d != d)
-        error= "Expected int64 for %s but found %s\n";
+        error = "The value for %s was %s which is not within %f - %f\n";
+    else if (type == OPT_INT64 && (int64_t)d != d)
+        error = "Expected int64 for %s but found %s\n";
     else if (type == OPT_INT && (int)d != d)
-        error= "Expected int for %s but found %s\n";
+        error = "Expected int for %s but found %s\n";
     else
         return d;
     av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
@@ -97,7 +101,8 @@ double parse_number_or_die(const char *context, const char *numstr, int type, do
     return 0;
 }
 
-int64_t parse_time_or_die(const char *context, const char *timestr, int is_duration)
+int64_t parse_time_or_die(const char *context, const char *timestr,
+                          int is_duration)
 {
     int64_t us;
     if (av_parse_time(&us, timestr, is_duration) < 0) {
@@ -108,13 +113,14 @@ int64_t parse_time_or_die(const char *context, const char *timestr, int is_durat
     return us;
 }
 
-void show_help_options(const OptionDef *options, const char *msg, int mask, int value)
+void show_help_options(const OptionDef *options, const char *msg, int mask,
+                       int value)
 {
     const OptionDef *po;
     int first;
 
     first = 1;
-    for(po = options; po->name != NULL; po++) {
+    for (po = options; po->name != NULL; po++) {
         char buf[64];
         if ((po->flags & mask) == value) {
             if (first) {
@@ -141,7 +147,8 @@ void show_help_children(const AVClass *class, int flags)
         show_help_children(child, flags);
 }
 
-static const OptionDef* find_option(const OptionDef *po, const char *name){
+static const OptionDef *find_option(const OptionDef *po, const char *name)
+{
     const char *p = strchr(name, ':');
     int len = p ? p - name : strlen(name);
 
@@ -188,8 +195,8 @@ static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
         buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
                                         NULL, 0, NULL, NULL);
 
-    win32_argv_utf8 = av_mallocz(sizeof(char*) * (win32_argc + 1) + buffsize);
-    argstr_flat     = (char*)win32_argv_utf8 + sizeof(char*) * (win32_argc + 1);
+    win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
+    argstr_flat     = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
     if (win32_argv_utf8 == NULL) {
         LocalFree(argv_w);
         return;
@@ -214,7 +221,8 @@ static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
 }
 #endif /* WIN32 && !__MINGW32CE__ */
 
-int parse_option(void *optctx, const char *opt, const char *arg, const OptionDef *options)
+int parse_option(void *optctx, const char *opt, const char *arg,
+                 const OptionDef *options)
 {
     const OptionDef *po;
     int bool_val = 1;
@@ -243,13 +251,14 @@ unknown_opt:
 
     /* new-style options contain an offset into optctx, old-style address of
      * a global var*/
-    dst = po->flags & (OPT_OFFSET|OPT_SPEC) ? (uint8_t*)optctx + po->u.off : po->u.dst_ptr;
+    dst = po->flags & (OPT_OFFSET | OPT_SPEC) ? (uint8_t *)optctx + po->u.off
+                                              : po->u.dst_ptr;
 
     if (po->flags & OPT_SPEC) {
         SpecifierOpt **so = dst;
         char *p = strchr(opt, ':');
 
-        dstcount = (int*)(so + 1);
+        dstcount = (int *)(so + 1);
         *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
         (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
         dst = &(*so)[*dstcount - 1].u;
@@ -258,24 +267,25 @@ unknown_opt:
     if (po->flags & OPT_STRING) {
         char *str;
         str = av_strdup(arg);
-        *(char**)dst = str;
+        *(char **)dst = str;
     } else if (po->flags & OPT_BOOL) {
-        *(int*)dst = bool_val;
+        *(int *)dst = bool_val;
     } else if (po->flags & OPT_INT) {
-        *(int*)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
+        *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
     } else if (po->flags & OPT_INT64) {
-        *(int64_t*)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
+        *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
     } else if (po->flags & OPT_TIME) {
-        *(int64_t*)dst = parse_time_or_die(opt, arg, 1);
+        *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
     } else if (po->flags & OPT_FLOAT) {
-        *(float*)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
+        *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
     } else if (po->flags & OPT_DOUBLE) {
-        *(double*)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
+        *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
     } else if (po->u.func_arg) {
-        int ret = po->flags & OPT_FUNC2 ? po->u.func2_arg(optctx, opt, arg) :
-                                          po->u.func_arg(opt, arg);
+        int ret = po->flags & OPT_FUNC2 ? po->u.func2_arg(optctx, opt, arg)
+                                        : po->u.func_arg(opt, arg);
         if (ret < 0) {
-            av_log(NULL, AV_LOG_ERROR, "Failed to set value '%s' for option '%s'\n", arg, opt);
+            av_log(NULL, AV_LOG_ERROR,
+                   "Failed to set value '%s' for option '%s'\n", arg, opt);
             return ret;
         }
     }
@@ -285,7 +295,7 @@ unknown_opt:
 }
 
 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
-                   void (* parse_arg_function)(void *, const char*))
+                   void (*parse_arg_function)(void *, const char*))
 {
     const char *opt;
     int optindex, handleoptions = 1, ret;
@@ -318,7 +328,8 @@ void parse_options(void *optctx, int argc, char **argv, const OptionDef *options
 /*
  * Return index of option opt in argv or 0 if not found.
  */
-static int locate_option(int argc, char **argv, const OptionDef *options, const char *optname)
+static int locate_option(int argc, char **argv, const OptionDef *options,
+                         const char *optname)
 {
     const OptionDef *po;
     int i;
@@ -364,13 +375,16 @@ int opt_default(const char *opt, const char *arg)
         p = opt + strlen(opt);
     av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
 
-    if ((o = av_opt_find(&cc, opt_stripped, NULL, 0, AV_OPT_SEARCH_CHILDREN|AV_OPT_SEARCH_FAKE_OBJ)) ||
-         ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
-          (o = av_opt_find(&cc, opt+1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
+    if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
+                         AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
+        ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
+         (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
         av_dict_set(&codec_opts, opt, arg, FLAGS);
-    else if ((o = av_opt_find(&fc, opt, NULL, 0, AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
+    else if ((o = av_opt_find(&fc, opt, NULL, 0,
+                              AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
         av_dict_set(&format_opts, opt, arg, FLAGS);
-    else if ((o = av_opt_find(&sc, opt, NULL, 0, AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
+    else if ((o = av_opt_find(&sc, opt, NULL, 0,
+                              AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
         // XXX we only support sws_flags, not arbitrary sws options
         int ret = av_opt_set(sws_opts, opt, arg, 0);
         if (ret < 0) {
@@ -484,12 +498,15 @@ static void print_all_libs_info(int flags, int level)
     PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
     PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
     PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);
+#if CONFIG_POSTPROC
     PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
+#endif
 }
 
 void show_banner(void)
 {
-    av_log(NULL, AV_LOG_INFO, "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
+    av_log(NULL, AV_LOG_INFO,
+           "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
            program_name, program_birth_year, this_year);
     av_log(NULL, AV_LOG_INFO, "  built on %s %s with %s %s\n",
            __DATE__, __TIME__, CC_TYPE, CC_VERSION);
@@ -575,93 +592,92 @@ void show_license(void)
 
 void show_formats(void)
 {
-    AVInputFormat *ifmt=NULL;
-    AVOutputFormat *ofmt=NULL;
+    AVInputFormat *ifmt  = NULL;
+    AVOutputFormat *ofmt = NULL;
     const char *last_name;
 
-    printf(
-        "File formats:\n"
-        " D. = Demuxing supported\n"
-        " .E = Muxing supported\n"
-        " --\n");
-    last_name= "000";
-    for(;;){
-        int decode=0;
-        int encode=0;
-        const char *name=NULL;
-        const char *long_name=NULL;
-
-        while((ofmt= av_oformat_next(ofmt))) {
-            if((name == NULL || strcmp(ofmt->name, name)<0) &&
-                strcmp(ofmt->name, last_name)>0){
-                name= ofmt->name;
-                long_name= ofmt->long_name;
-                encode=1;
+    printf("File formats:\n"
+           " D. = Demuxing supported\n"
+           " .E = Muxing supported\n"
+           " --\n");
+    last_name = "000";
+    for (;;) {
+        int decode = 0;
+        int encode = 0;
+        const char *name      = NULL;
+        const char *long_name = NULL;
+
+        while ((ofmt = av_oformat_next(ofmt))) {
+            if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
+                strcmp(ofmt->name, last_name) > 0) {
+                name      = ofmt->name;
+                long_name = ofmt->long_name;
+                encode    = 1;
             }
         }
-        while((ifmt= av_iformat_next(ifmt))) {
-            if((name == NULL || strcmp(ifmt->name, name)<0) &&
-                strcmp(ifmt->name, last_name)>0){
-                name= ifmt->name;
-                long_name= ifmt->long_name;
-                encode=0;
+        while ((ifmt = av_iformat_next(ifmt))) {
+            if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
+                strcmp(ifmt->name, last_name) > 0) {
+                name      = ifmt->name;
+                long_name = ifmt->long_name;
+                encode    = 0;
             }
-            if(name && strcmp(ifmt->name, name)==0)
-                decode=1;
+            if (name && strcmp(ifmt->name, name) == 0)
+                decode = 1;
         }
-        if(name==NULL)
+        if (name == NULL)
             break;
-        last_name= name;
+        last_name = name;
 
-        printf(
-            " %s%s %-15s %s\n",
-            decode ? "D":" ",
-            encode ? "E":" ",
-            name,
+        printf(" %s%s %-15s %s\n",
+               decode ? "D" : " ",
+               encode ? "E" : " ",
+               name,
             long_name ? long_name:" ");
     }
 }
 
 void show_codecs(void)
 {
-    AVCodec *p=NULL, *p2;
+    AVCodec *p = NULL, *p2;
     const char *last_name;
-    printf(
-        "Codecs:\n"
-        " D..... = Decoding supported\n"
-        " .E.... = Encoding supported\n"
-        " ..V... = Video codec\n"
-        " ..A... = Audio codec\n"
-        " ..S... = Subtitle codec\n"
-        " ...S.. = Supports draw_horiz_band\n"
-        " ....D. = Supports direct rendering method 1\n"
-        " .....T = Supports weird frame truncation\n"
-        " ------\n");
+    printf("Codecs:\n"
+           " D..... = Decoding supported\n"
+           " .E.... = Encoding supported\n"
+           " ..V... = Video codec\n"
+           " ..A... = Audio codec\n"
+           " ..S... = Subtitle codec\n"
+           " ...S.. = Supports draw_horiz_band\n"
+           " ....D. = Supports direct rendering method 1\n"
+           " .....T = Supports weird frame truncation\n"
+           " ------\n");
     last_name= "000";
-    for(;;){
-        int decode=0;
-        int encode=0;
-        int cap=0;
+    for (;;) {
+        int decode = 0;
+        int encode = 0;
+        int cap    = 0;
         const char *type_str;
 
-        p2=NULL;
-        while((p= av_codec_next(p))) {
-            if((p2==NULL || strcmp(p->name, p2->name)<0) &&
-                strcmp(p->name, last_name)>0){
-                p2= p;
-                decode= encode= cap=0;
+        p2 = NULL;
+        while ((p = av_codec_next(p))) {
+            if ((p2 == NULL || strcmp(p->name, p2->name) < 0) &&
+                strcmp(p->name, last_name) > 0) {
+                p2 = p;
+                decode = encode = cap = 0;
             }
-            if(p2 && strcmp(p->name, p2->name)==0){
-                if(p->decode) decode=1;
-                if(p->encode) encode=1;
+            if (p2 && strcmp(p->name, p2->name) == 0) {
+                if (p->decode)
+                    decode = 1;
+                if (p->encode)
+                    encode = 1;
                 cap |= p->capabilities;
             }
         }
-        if(p2==NULL)
+        if (p2 == NULL)
             break;
-        last_name= p2->name;
+        last_name = p2->name;
 
-        switch(p2->type) {
+        switch (p2->type) {
         case AVMEDIA_TYPE_VIDEO:
             type_str = "V";
             break;
@@ -675,35 +691,35 @@ void show_codecs(void)
             type_str = "?";
             break;
         }
-        printf(
-            " %s%s%s%s%s%s %-15s %s",
-            decode ? "D": (/*p2->decoder ? "d":*/" "),
-            encode ? "E":" ",
-            type_str,
-            cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
-            cap & CODEC_CAP_DR1 ? "D":" ",
-            cap & CODEC_CAP_TRUNCATED ? "T":" ",
-            p2->name,
-            p2->long_name ? p2->long_name : "");
-       /* if(p2->decoder && decode==0)
-            printf(" use %s for decoding", p2->decoder->name);*/
+        printf(" %s%s%s%s%s%s %-15s %s",
+               decode ? "D" : (/* p2->decoder ? "d" : */ " "),
+               encode ? "E" : " ",
+               type_str,
+               cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S" : " ",
+               cap & CODEC_CAP_DR1 ? "D" : " ",
+               cap & CODEC_CAP_TRUNCATED ? "T" : " ",
+               p2->name,
+               p2->long_name ? p2->long_name : "");
+#if 0
+            if (p2->decoder && decode == 0)
+                printf(" use %s for decoding", p2->decoder->name);
+#endif
         printf("\n");
     }
     printf("\n");
-    printf(
-"Note, the names of encoders and decoders do not always match, so there are\n"
-"several cases where the above table shows encoder only or decoder only entries\n"
-"even though both encoding and decoding are supported. For example, the h263\n"
-"decoder corresponds to the h263 and h263p encoders, for file formats it is even\n"
-"worse.\n");
+    printf("Note, the names of encoders and decoders do not always match, so there are\n"
+           "several cases where the above table shows encoder only or decoder only entries\n"
+           "even though both encoding and decoding are supported. For example, the h263\n"
+           "decoder corresponds to the h263 and h263p encoders, for file formats it is even\n"
+           "worse.\n");
 }
 
 void show_bsfs(void)
 {
-    AVBitStreamFilter *bsf=NULL;
+    AVBitStreamFilter *bsf = NULL;
 
     printf("Bitstream filters:\n");
-    while((bsf = av_bitstream_filter_next(bsf)))
+    while ((bsf = av_bitstream_filter_next(bsf)))
         printf("%s\n", bsf->name);
     printf("\n");
 }
@@ -737,15 +753,14 @@ void show_pix_fmts(void)
 {
     enum PixelFormat pix_fmt;
 
-    printf(
-        "Pixel formats:\n"
-        "I.... = Supported Input  format for conversion\n"
-        ".O... = Supported Output format for conversion\n"
-        "..H.. = Hardware accelerated format\n"
-        "...P. = Paletted format\n"
-        "....B = Bitstream format\n"
-        "FLAGS NAME            NB_COMPONENTS BITS_PER_PIXEL\n"
-        "-----\n");
+    printf("Pixel formats:\n"
+           "I.... = Supported Input  format for conversion\n"
+           ".O... = Supported Output format for conversion\n"
+           "..H.. = Hardware accelerated format\n"
+           "...P. = Paletted format\n"
+           "....B = Bitstream format\n"
+           "FLAGS NAME            NB_COMPONENTS BITS_PER_PIXEL\n"
+           "-----\n");
 
 #if !CONFIG_SWSCALE
 #   define sws_isSupportedInput(x)  0
@@ -792,7 +807,8 @@ int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
     FILE *f = fopen(filename, "rb");
 
     if (!f) {
-        av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename, strerror(errno));
+        av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
+               strerror(errno));
         return AVERROR(errno);
     }
     fseek(f, 0, SEEK_END);
@@ -828,7 +844,8 @@ void init_pts_correction(PtsCorrectionContext *ctx)
     ctx->last_pts = ctx->last_dts = INT64_MIN;
 }
 
-int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts, int64_t dts)
+int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
+                          int64_t dts)
 {
     int64_t pts = AV_NOPTS_VALUE;
 
@@ -841,7 +858,7 @@ int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts, int6
         ctx->last_pts = reordered_pts;
     }
     if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
-       && reordered_pts != AV_NOPTS_VALUE)
+        && reordered_pts != AV_NOPTS_VALUE)
         pts = reordered_pts;
     else
         pts = dts;
@@ -850,14 +867,14 @@ int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts, int6
 }
 
 FILE *get_preset_file(char *filename, size_t filename_size,
-                      const char *preset_name, int is_path, const char *codec_name)
+                      const char *preset_name, int is_path,
+                      const char *codec_name)
 {
     FILE *f = NULL;
     int i;
-    const char *base[3]= { getenv("AVCONV_DATADIR"),
-                           getenv("HOME"),
-                           AVCONV_DATADIR,
-                         };
+    const char *base[3] = { getenv("AVCONV_DATADIR"),
+                            getenv("HOME"),
+                            AVCONV_DATADIR, };
 
     if (is_path) {
         av_strlcpy(filename, preset_name, filename_size);
@@ -866,11 +883,14 @@ FILE *get_preset_file(char *filename, size_t filename_size,
         for (i = 0; i < 3 && !f; i++) {
             if (!base[i])
                 continue;
-            snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i], i != 1 ? "" : "/.avconv", preset_name);
+            snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
+                     i != 1 ? "" : "/.avconv", preset_name);
             f = fopen(filename, "r");
             if (!f && codec_name) {
                 snprintf(filename, filename_size,
-                         "%s%s/%s-%s.ffpreset", base[i],  i != 1 ? "" : "/.avconv", codec_name, preset_name);
+                         "%s%s/%s-%s.ffpreset",
+                         base[i], i != 1 ? "" : "/.avconv", codec_name,
+                         preset_name);
                 f = fopen(filename, "r");
             }
         }
@@ -881,21 +901,22 @@ FILE *get_preset_file(char *filename, size_t filename_size,
 
 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
 {
-    if (*spec <= '9' && *spec >= '0')                                        /* opt:index */
+    if (*spec <= '9' && *spec >= '0') /* opt:index */
         return strtol(spec, NULL, 0) == st->index;
-    else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' || *spec == 't') { /* opt:[vasdt] */
+    else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
+             *spec == 't') { /* opt:[vasdt] */
         enum AVMediaType type;
 
         switch (*spec++) {
-        case 'v': type = AVMEDIA_TYPE_VIDEO;    break;
-        case 'a': type = AVMEDIA_TYPE_AUDIO;    break;
-        case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
-        case 'd': type = AVMEDIA_TYPE_DATA;     break;
+        case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
+        case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
+        case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
+        case 'd': type = AVMEDIA_TYPE_DATA;       break;
         case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
         }
         if (type != st->codec->codec_type)
             return 0;
-        if (*spec++ == ':') {                                   /* possibly followed by :index */
+        if (*spec++ == ':') { /* possibly followed by :index */
             int i, index = strtol(spec, NULL, 0);
             for (i = 0; i < s->nb_streams; i++)
                 if (s->streams[i]->codec->codec_type == type && index-- == 0)
@@ -914,8 +935,9 @@ int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
 
             if (*endptr++ == ':') {
                 int stream_idx = strtol(endptr, NULL, 0);
-                return (stream_idx >= 0 && stream_idx < s->programs[i]->nb_stream_indexes &&
-                        st->index == s->programs[i]->stream_index[stream_idx]);
+                return stream_idx >= 0 &&
+                    stream_idx < s->programs[i]->nb_stream_indexes &&
+                    st->index == s->programs[i]->stream_index[stream_idx];
             }
 
             for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
@@ -930,12 +952,15 @@ int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
     return AVERROR(EINVAL);
 }
 
-AVDictionary *filter_codec_opts(AVDictionary *opts, enum CodecID codec_id, AVFormatContext *s, AVStream *st)
+AVDictionary *filter_codec_opts(AVDictionary *opts, enum CodecID codec_id,
+                                AVFormatContext *s, AVStream *st)
 {
     AVDictionary    *ret = NULL;
     AVDictionaryEntry *t = NULL;
-    AVCodec       *codec = s->oformat ? avcodec_find_encoder(codec_id) : avcodec_find_decoder(codec_id);
-    int            flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM : AV_OPT_FLAG_DECODING_PARAM;
+    AVCodec       *codec = s->oformat ? avcodec_find_encoder(codec_id)
+                                      : avcodec_find_decoder(codec_id);
+    int            flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
+                                      : AV_OPT_FLAG_DECODING_PARAM;
     char          prefix = 0;
     const AVClass    *cc = avcodec_get_class();
 
@@ -943,9 +968,18 @@ AVDictionary *filter_codec_opts(AVDictionary *opts, enum CodecID codec_id, AVFor
         return NULL;
 
     switch (codec->type) {
-    case AVMEDIA_TYPE_VIDEO:    prefix = 'v'; flags |= AV_OPT_FLAG_VIDEO_PARAM;    break;
-    case AVMEDIA_TYPE_AUDIO:    prefix = 'a'; flags |= AV_OPT_FLAG_AUDIO_PARAM;    break;
-    case AVMEDIA_TYPE_SUBTITLE: prefix = 's'; flags |= AV_OPT_FLAG_SUBTITLE_PARAM; break;
+    case AVMEDIA_TYPE_VIDEO:
+        prefix  = 'v';
+        flags  |= AV_OPT_FLAG_VIDEO_PARAM;
+        break;
+    case AVMEDIA_TYPE_AUDIO:
+        prefix  = 'a';
+        flags  |= AV_OPT_FLAG_AUDIO_PARAM;
+        break;
+    case AVMEDIA_TYPE_SUBTITLE:
+        prefix  = 's';
+        flags  |= AV_OPT_FLAG_SUBTITLE_PARAM;
+        break;
     }
 
     while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
@@ -960,10 +994,14 @@ AVDictionary *filter_codec_opts(AVDictionary *opts, enum CodecID codec_id, AVFor
             }
 
         if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
-            (codec && codec->priv_class && av_opt_find(&codec->priv_class, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ)))
+            (codec && codec->priv_class &&
+             av_opt_find(&codec->priv_class, t->key, NULL, flags,
+                         AV_OPT_SEARCH_FAKE_OBJ)))
             av_dict_set(&ret, t->key, t->value, 0);
-        else if (t->key[0] == prefix && av_opt_find(&cc, t->key+1, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ))
-            av_dict_set(&ret, t->key+1, t->value, 0);
+        else if (t->key[0] == prefix &&
+                 av_opt_find(&cc, t->key + 1, NULL, flags,
+                             AV_OPT_SEARCH_FAKE_OBJ))
+            av_dict_set(&ret, t->key + 1, t->value, 0);
 
         if (p)
             *p = ':';
@@ -971,7 +1009,8 @@ AVDictionary *filter_codec_opts(AVDictionary *opts, enum CodecID codec_id, AVFor
     return ret;
 }
 
-AVDictionary **setup_find_stream_info_opts(AVFormatContext *s, AVDictionary *codec_opts)
+AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
+                                           AVDictionary *codec_opts)
 {
     int i;
     AVDictionary **opts;
@@ -980,11 +1019,13 @@ AVDictionary **setup_find_stream_info_opts(AVFormatContext *s, AVDictionary *cod
         return NULL;
     opts = av_mallocz(s->nb_streams * sizeof(*opts));
     if (!opts) {
-        av_log(NULL, AV_LOG_ERROR, "Could not alloc memory for stream options.\n");
+        av_log(NULL, AV_LOG_ERROR,
+               "Could not alloc memory for stream options.\n");
         return NULL;
     }
     for (i = 0; i < s->nb_streams; i++)
-        opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id, s, s->streams[i]);
+        opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
+                                    s, s->streams[i]);
     return opts;
 }
 
@@ -1043,10 +1084,10 @@ int get_filtered_video_frame(AVFilterContext *ctx, AVFrame *frame,
 
     memcpy(frame->data,     picref->data,     sizeof(frame->data));
     memcpy(frame->linesize, picref->linesize, sizeof(frame->linesize));
-    frame->interlaced_frame = picref->video->interlaced;
-    frame->top_field_first  = picref->video->top_field_first;
-    frame->key_frame        = picref->video->key_frame;
-    frame->pict_type        = picref->video->pict_type;
+    frame->interlaced_frame    = picref->video->interlaced;
+    frame->top_field_first     = picref->video->top_field_first;
+    frame->key_frame           = picref->video->key_frame;
+    frame->pict_type           = picref->video->pict_type;
     frame->sample_aspect_ratio = picref->video->pixel_aspect;
 
     return 1;
diff --git a/configure b/configure
index 413c02f..526aa77 100755
--- a/configure
+++ b/configure
@@ -89,7 +89,7 @@ Configuration options:
   --disable-avcodec        disable libavcodec build
   --disable-avformat       disable libavformat build
   --disable-swscale        disable libswscale build
-  --disable-postproc       disable libpostproc build
+  --enable-postproc        enable libpostproc build (deprecated) [no]
   --disable-avfilter       disable video filter support [no]
   --disable-pthreads       disable pthreads [auto]
   --disable-w32threads     disable Win32 threads [auto]
@@ -1084,9 +1084,9 @@ HAVE_LIST="
     fork
     getaddrinfo
     gethrtime
+    GetProcessAffinityMask
     GetProcessMemoryInfo
     GetProcessTimes
-    GetSystemInfo
     getrusage
     gnu_as
     ibm_asm
@@ -1135,9 +1135,11 @@ HAVE_LIST="
     struct_sockaddr_in6
     struct_sockaddr_sa_len
     struct_sockaddr_storage
+    struct_v4l2_frmivalenum_discrete
     symver
     symver_asm_label
     symver_gnu_asm
+    sysconf
     sysctl
     sys_mman_h
     sys_param_h
@@ -1678,7 +1680,6 @@ enable avdevice
 enable avfilter
 enable avformat
 enable avutil
-enable postproc
 enable swscale
 
 enable asm
@@ -2858,12 +2859,13 @@ check_func  strerror_r
 check_func  strptime
 check_func  strtok_r
 check_func  sched_getaffinity
+check_func  sysconf
 check_func  sysctl
 check_func_headers io.h setmode
 check_func_headers lzo/lzo1x.h lzo1x_999_compress
 check_lib2 "windows.h psapi.h" GetProcessMemoryInfo -lpsapi
+check_func_headers windows.h GetProcessAffinityMask
 check_func_headers windows.h GetProcessTimes
-check_func_headers windows.h GetSystemInfo
 check_func_headers windows.h MapViewOfFile
 check_func_headers windows.h VirtualAlloc
 
@@ -2991,6 +2993,8 @@ texi2html -version > /dev/null 2>&1 && enable texi2html || disable texi2html
 check_header linux/fb.h
 check_header linux/videodev.h
 check_header linux/videodev2.h
+check_struct linux/videodev2.h "struct v4l2_frmivalenum" discrete
+
 check_header sys/videoio.h
 
 check_func_headers "windows.h vfw.h" capCreateCaptureWindow "$vfwcap_indev_extralibs"
diff --git a/doc/APIchanges b/doc/APIchanges
index 29a537d..e94c656 100644
--- a/doc/APIchanges
+++ b/doc/APIchanges
@@ -6,13 +6,16 @@ libavcodec:  2011-04-18
 libavdevice: 2011-04-18
 libavfilter: 2011-04-18
 libavformat: 2011-04-18
-libpostproc: 2011-04-18
+libpostproc: 2011-04-18 (deprecated, to be removed later)
 libswscale:  2011-06-20
 libavutil:   2011-04-18
 
 
 API changes, most recent first:
 
+2011-01-03 - b73ec05 - lavu 51.21.0
+  Add av_popcount64
+
 2011-12-25 - lavfi 2.14.0
   e1d9dbf Add a new installed header - buffersrc.h
   It contains a new function av_buffersrc_buffer() that allows passing
@@ -30,18 +33,18 @@ API changes, most recent first:
 2011-12-18 - 8400b12 - lavc 53.28.1
   Deprecate AVFrame.age. The field is unused.
 
-2011-xx-xx - xxxxxxx - lavf 53.17.0
-  Add avformat_open_input().
+2011-12-12 - 5266045 - lavf 53.17.0
+  Add avformat_close_input().
   Deprecate av_close_input_file() and av_close_input_stream().
 
-2011-xx-xx - xxxxxxx - lavc 53.25.0
+2011-12-02 - 0eea212 - lavc 53.25.0
   Add nb_samples and extended_data fields to AVFrame.
   Deprecate AVCODEC_MAX_AUDIO_FRAME_SIZE.
   Deprecate avcodec_decode_audio3() in favor of avcodec_decode_audio4().
   avcodec_decode_audio4() writes output samples to an AVFrame, which allows
   audio decoders to use get_buffer().
 
-2011-xx-xx - xxxxxxx - lavc 53.24.0
+2011-12-04 - 560f773 - lavc 53.24.0
   Change AVFrame.data[4]/base[4]/linesize[4]/error[4] to [8] at next major bump.
   Change AVPicture.data[4]/linesize[4] to [8] at next major bump.
   Change AVCodecContext.error[4] to [8] at next major bump.
@@ -121,8 +124,10 @@ API changes, most recent first:
 2011-09-03 - c11fb82 - lavu 51.10.0
   Add AV_OPT_SEARCH_FAKE_OBJ flag for av_opt_find() function.
 
-2011-08-26 - f2011ed - lavu 51.9.0
-  Add av_fifo_peek2(), deprecate av_fifo_peek().
+2011-08-26 - lavu 51.9.0
+  - f2011ed Add av_fifo_peek2(), deprecate av_fifo_peek().
+  - add41de..abc78a5 Do not include intfloat_readwrite.h,
+    mathematics.h, rational.h, pixfmt.h, or log.h from avutil.h.
 
 2011-08-16 - 48f9e45 - lavf 53.4.0
   Add avformat_query_codec().
diff --git a/doc/RELEASE_NOTES b/doc/RELEASE_NOTES
index f857a18..b5ced86 100644
--- a/doc/RELEASE_NOTES
+++ b/doc/RELEASE_NOTES
@@ -9,8 +9,11 @@ General notes
 This release continues the API cleanups that have begun with the
 previous release. While it is binary compatible with 0.7, many parts of
 the public API were deprecated and will be removed in the git master and
-later releases. Please consult the doc/APIchanges file to see intended
-replacements for the deprecated APIs.
+later releases. Note that a couple of header includes have been cleaned
+up, which may require code changes in your applications. In particular,
+the header "libavutil/mathematics.h" is no longer included from
+"libavcodec/avcodec.h". Please consult the doc/APIchanges file to see
+intended replacements for the deprecated APIs.
 
 Furthermore, our work on the 'ffmpeg' command-line tool has resulted in
 major revisions to its interface. In order to not break existing scripts
diff --git a/doc/avconv.texi b/doc/avconv.texi
index 157e233..0a83326 100644
--- a/doc/avconv.texi
+++ b/doc/avconv.texi
@@ -746,15 +746,15 @@ Thread count.
 Video sync method.
 
 @table @option
- at item 0
+ at item passthrough
 Each frame is passed with its timestamp from the demuxer to the muxer.
- at item 1
+ at item cfr
 Frames will be duplicated and dropped to achieve exactly the requested
 constant framerate.
- at item 2
+ at item vfr
 Frames are passed through with their timestamp or dropped so as to
 prevent 2 frames from having the same timestamp.
- at item -1
+ at item auto
 Chooses between 1 and 2 depending on muxer capabilities. This is the
 default method.
 @end table
diff --git a/doc/faq.texi b/doc/faq.texi
index 8044200..7c5373c 100644
--- a/doc/faq.texi
+++ b/doc/faq.texi
@@ -359,4 +359,16 @@ to use them you have to append -D__STDC_CONSTANT_MACROS to your CXXFLAGS
 You have to implement a URLProtocol, see @file{libavformat/file.c} in
 Libav and @file{libmpdemux/demux_lavf.c} in MPlayer sources.
 
+ at section Why is @code{make fate} not running all tests?
+
+Make sure you have the fate-suite samples and the @code{SAMPLES} Make variable
+or @code{FATE_SAMPLES} environment variable or the @code{--samples}
+ at command{configure} option is set to the right path.
+
+ at section Why is @code{make fate} not finding the samples?
+
+Do you happen to have a @code{~} character in the samples path to indicate a
+home directory? The value is used in ways where the shell cannot expand it,
+causing FATE to not find files. Just replace @code{~} by the full path.
+
 @bye
diff --git a/doc/filters.texi b/doc/filters.texi
index e022b46..4e7ede2 100644
--- a/doc/filters.texi
+++ b/doc/filters.texi
@@ -470,7 +470,7 @@ drawbox=10:20:200:60:red@@0.5"
 Draw text string or text from specified file on top of video using the
 libfreetype library.
 
-To enable compilation of this filter you need to configure FFmpeg with
+To enable compilation of this filter you need to configure Libav with
 @code{--enable-libfreetype}.
 
 The filter also recognizes strftime() sequences in the provided text
diff --git a/doc/general.texi b/doc/general.texi
index 8eaa97b..65d65bb 100644
--- a/doc/general.texi
+++ b/doc/general.texi
@@ -122,7 +122,7 @@ library:
 @item Brute Force & Ignorance   @tab   @tab X
     @tab Used in the game Flash Traffic: City of Angels.
 @item BWF                       @tab X @tab X
- at item CRI ADX                   @tab   @tab X
+ at item CRI ADX                   @tab X @tab X
     @tab Audio-only format used in console video games.
 @item Discworld II BMV          @tab   @tab X
 @item Interplay C93             @tab   @tab X
diff --git a/doc/indevs.texi b/doc/indevs.texi
index 4405a5b..e1b4ddd 100644
--- a/doc/indevs.texi
+++ b/doc/indevs.texi
@@ -267,7 +267,7 @@ the device.
 Video4Linux and Video4Linux2 devices only support a limited set of
 @var{width}x at var{height} sizes and framerates. You can check which are
 supported for example with the command @file{dov4l} for Video4Linux
-devices and the command @file{v4l-info} for Video4Linux2 devices.
+devices and using @command{-list_formats all} for Video4Linux2 devices.
 
 If the size for the device is set to 0x0, the input device will
 try to autodetect the size to use.
diff --git a/libavcodec/4xm.c b/libavcodec/4xm.c
index 83f0a12..52edc99 100644
--- a/libavcodec/4xm.c
+++ b/libavcodec/4xm.c
@@ -614,16 +614,24 @@ static int decode_i2_frame(FourXContext *f, const uint8_t *buf, int length){
     int x, y, x2, y2;
     const int width= f->avctx->width;
     const int height= f->avctx->height;
+    const int mbs = (FFALIGN(width, 16) >> 4) * (FFALIGN(height, 16) >> 4);
     uint16_t *dst= (uint16_t*)f->current_picture.data[0];
     const int stride= f->current_picture.linesize[0]>>1;
+    GetByteContext g3;
+
+    if(length < mbs * 8) {
+        av_log(f->avctx, AV_LOG_ERROR, "packet size too small\n");
+        return AVERROR_INVALIDDATA;
+    }
+    bytestream2_init(&g3, buf, length);
 
     for(y=0; y<height; y+=16){
         for(x=0; x<width; x+=16){
             unsigned int color[4], bits;
             memset(color, 0, sizeof(color));
 //warning following is purely guessed ...
-            color[0]= bytestream_get_le16(&buf);
-            color[1]= bytestream_get_le16(&buf);
+            color[0]= bytestream2_get_le16u(&g3);
+            color[1]= bytestream2_get_le16u(&g3);
 
             if(color[0]&0x8000) av_log(NULL, AV_LOG_ERROR, "unk bit 1\n");
             if(color[1]&0x8000) av_log(NULL, AV_LOG_ERROR, "unk bit 2\n");
@@ -631,7 +639,7 @@ static int decode_i2_frame(FourXContext *f, const uint8_t *buf, int length){
             color[2]= mix(color[0], color[1]);
             color[3]= mix(color[1], color[0]);
 
-            bits= bytestream_get_le32(&buf);
+            bits= bytestream2_get_le32u(&g3);
             for(y2=0; y2<16; y2++){
                 for(x2=0; x2<16; x2++){
                     int index= 2*(x2>>2) + 8*(y2>>2);
@@ -640,7 +648,7 @@ static int decode_i2_frame(FourXContext *f, const uint8_t *buf, int length){
             }
             dst+=16;
         }
-        dst += 16*stride - width;
+        dst += 16 * stride - x;
     }
 
     return 0;
@@ -786,7 +794,7 @@ static int decode_frame(AVCodecContext *avctx,
 
     if(frame_4cc == AV_RL32("ifr2")){
         p->pict_type= AV_PICTURE_TYPE_I;
-        if(decode_i2_frame(f, buf-4, frame_size) < 0)
+        if(decode_i2_frame(f, buf-4, frame_size + 4) < 0)
             return -1;
     }else if(frame_4cc == AV_RL32("ifrm")){
         p->pict_type= AV_PICTURE_TYPE_I;
diff --git a/libavcodec/aac.h b/libavcodec/aac.h
index 30491fe..a36080c 100644
--- a/libavcodec/aac.h
+++ b/libavcodec/aac.h
@@ -84,6 +84,7 @@ enum BandType {
 #define IS_CODEBOOK_UNSIGNED(x) ((x - 1) & 10)
 
 enum ChannelPosition {
+    AAC_CHANNEL_OFF   = 0,
     AAC_CHANNEL_FRONT = 1,
     AAC_CHANNEL_SIDE  = 2,
     AAC_CHANNEL_BACK  = 3,
diff --git a/libavcodec/aacdec.c b/libavcodec/aacdec.c
index 4d3f1ff..b2fc740 100644
--- a/libavcodec/aacdec.c
+++ b/libavcodec/aacdec.c
@@ -163,6 +163,19 @@ static ChannelElement *get_che(AACContext *ac, int type, int elem_id)
     }
 }
 
+static int count_channels(enum ChannelPosition che_pos[4][MAX_ELEM_ID])
+{
+    int i, type, sum = 0;
+    for (i = 0; i < MAX_ELEM_ID; i++) {
+        for (type = 0; type < 4; type++) {
+            sum += (1 + (type == TYPE_CPE)) *
+                (che_pos[type][i] != AAC_CHANNEL_OFF &&
+                 che_pos[type][i] != AAC_CHANNEL_CC);
+        }
+    }
+    return sum;
+}
+
 /**
  * Check for the channel element in the current channel position configuration.
  * If it exists, make sure the appropriate element is allocated and map the
@@ -418,6 +431,12 @@ static int decode_ga_specific_config(AACContext *ac, AVCodecContext *avctx,
         if ((ret = set_default_channel_config(avctx, new_che_pos, channel_config)))
             return ret;
     }
+
+    if (count_channels(new_che_pos) > 1) {
+        m4ac->ps = 0;
+    } else if (m4ac->sbr == 1 && m4ac->ps == -1)
+        m4ac->ps = 1;
+
     if (ac && (ret = output_configure(ac, ac->che_pos, new_che_pos, channel_config, OC_GLOBAL_HDR)))
         return ret;
 
@@ -476,8 +495,6 @@ static int decode_audio_specific_config(AACContext *ac,
         av_log(avctx, AV_LOG_ERROR, "invalid sampling rate index %d\n", m4ac->sampling_index);
         return -1;
     }
-    if (m4ac->sbr == 1 && m4ac->ps == -1)
-        m4ac->ps = 1;
 
     skip_bits_long(&gb, i);
 
diff --git a/libavcodec/aacps.c b/libavcodec/aacps.c
index d7d6ef8..3da912c 100644
--- a/libavcodec/aacps.c
+++ b/libavcodec/aacps.c
@@ -223,7 +223,7 @@ int ff_ps_read_data(AVCodecContext *avctx, GetBitContext *gb_host, PSContext *ps
             cnt -= 2 + ps_read_extension_data(gb, ps, ps_extension_id);
         }
         if (cnt < 0) {
-            av_log(avctx, AV_LOG_ERROR, "ps extension overflow %d", cnt);
+            av_log(avctx, AV_LOG_ERROR, "ps extension overflow %d\n", cnt);
             goto err;
         }
         skip_bits(gb, cnt);
diff --git a/libavcodec/aacsbr.c b/libavcodec/aacsbr.c
index 81b0b4c..0bfcabb 100644
--- a/libavcodec/aacsbr.c
+++ b/libavcodec/aacsbr.c
@@ -1181,14 +1181,15 @@ static void sbr_qmf_synthesis(DSPContext *dsp, FFTContext *mdct,
 {
     int i, n;
     const float *sbr_qmf_window = div ? sbr_qmf_window_ds : sbr_qmf_window_us;
+    const int step = 128 >> div;
     float *v;
     for (i = 0; i < 32; i++) {
-        if (*v_off == 0) {
+        if (*v_off < step) {
             int saved_samples = (1280 - 128) >> div;
             memcpy(&v0[SBR_SYNTHESIS_BUF_SIZE - saved_samples], v0, saved_samples * sizeof(float));
-            *v_off = SBR_SYNTHESIS_BUF_SIZE - saved_samples - (128 >> div);
+            *v_off = SBR_SYNTHESIS_BUF_SIZE - saved_samples - step;
         } else {
-            *v_off -= 128 >> div;
+            *v_off -= step;
         }
         v = v0 + *v_off;
         if (div) {
diff --git a/libavcodec/ac3dec.c b/libavcodec/ac3dec.c
index 83cfa0a..662ea91 100644
--- a/libavcodec/ac3dec.c
+++ b/libavcodec/ac3dec.c
@@ -223,7 +223,7 @@ static int ac3_parse_header(AC3DecodeContext *s)
     int i;
 
     /* read the rest of the bsi. read twice for dual mono mode. */
-    i = !(s->channel_mode);
+    i = !s->channel_mode;
     do {
         skip_bits(gbc, 5); // skip dialog normalization
         if (get_bits1(gbc))
@@ -792,7 +792,7 @@ static int decode_audio_block(AC3DecodeContext *s, int blk)
     }
 
     /* dynamic range */
-    i = !(s->channel_mode);
+    i = !s->channel_mode;
     do {
         if (get_bits1(gbc)) {
             s->dynamic_range[i] = ((dynamic_range_tab[get_bits(gbc, 8)] - 1.0) *
diff --git a/libavcodec/adpcm.c b/libavcodec/adpcm.c
index 2081ef6..b319635 100644
--- a/libavcodec/adpcm.c
+++ b/libavcodec/adpcm.c
@@ -91,9 +91,13 @@ typedef struct ADPCMDecodeContext {
 static av_cold int adpcm_decode_init(AVCodecContext * avctx)
 {
     ADPCMDecodeContext *c = avctx->priv_data;
+    unsigned int min_channels = 1;
     unsigned int max_channels = 2;
 
     switch(avctx->codec->id) {
+    case CODEC_ID_ADPCM_EA:
+        min_channels = 2;
+        break;
     case CODEC_ID_ADPCM_EA_R1:
     case CODEC_ID_ADPCM_EA_R2:
     case CODEC_ID_ADPCM_EA_R3:
@@ -101,7 +105,7 @@ static av_cold int adpcm_decode_init(AVCodecContext * avctx)
         max_channels = 6;
         break;
     }
-    if (avctx->channels <= 0 || avctx->channels > max_channels) {
+    if (avctx->channels < min_channels || avctx->channels > max_channels) {
         av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
         return AVERROR(EINVAL);
     }
diff --git a/libavcodec/adx.c b/libavcodec/adx.c
index aa90fd8..1e5d89c 100644
--- a/libavcodec/adx.c
+++ b/libavcodec/adx.c
@@ -58,7 +58,7 @@ int avpriv_adx_decode_header(AVCodecContext *avctx, const uint8_t *buf,
 
     /* channels */
     avctx->channels = buf[7];
-    if (avctx->channels > 2)
+    if (avctx->channels <= 0 || avctx->channels > 2)
         return AVERROR_INVALIDDATA;
 
     /* sample rate */
diff --git a/libavcodec/adx_parser.c b/libavcodec/adx_parser.c
index ebcb137..de3b1b0 100644
--- a/libavcodec/adx_parser.c
+++ b/libavcodec/adx_parser.c
@@ -22,7 +22,7 @@
  * @file
  * ADX audio parser
  *
- * Reads header to extradata and splits packets into individual blocks.
+ * Splits packets into individual blocks.
  */
 
 #include "libavutil/intreadwrite.h"
@@ -33,11 +33,9 @@ typedef struct ADXParseContext {
     ParseContext pc;
     int header_size;
     int block_size;
-    int buf_pos;
+    int remaining;
 } ADXParseContext;
 
-#define MIN_HEADER_SIZE 24
-
 static int adx_parse(AVCodecParserContext *s1,
                            AVCodecContext *avctx,
                            const uint8_t **poutbuf, int *poutbuf_size,
@@ -46,45 +44,36 @@ static int adx_parse(AVCodecParserContext *s1,
     ADXParseContext *s = s1->priv_data;
     ParseContext *pc = &s->pc;
     int next = END_NOT_FOUND;
+    int i;
+    uint64_t state = pc->state64;
 
-    if (!avctx->extradata_size) {
-        int ret;
-
-        ff_combine_frame(pc, END_NOT_FOUND, &buf, &buf_size);
-
-        if (!s->header_size && pc->index >= MIN_HEADER_SIZE) {
-            if (ret = avpriv_adx_decode_header(avctx, pc->buffer, pc->index,
-                                               &s->header_size, NULL))
-                return AVERROR_INVALIDDATA;
-            s->block_size = BLOCK_SIZE * avctx->channels;
-        }
-        if (s->header_size && s->header_size <= pc->index) {
-            avctx->extradata = av_mallocz(s->header_size + FF_INPUT_BUFFER_PADDING_SIZE);
-            if (!avctx->extradata)
-                return AVERROR(ENOMEM);
-            avctx->extradata_size = s->header_size;
-            memcpy(avctx->extradata, pc->buffer, s->header_size);
-            memmove(pc->buffer, pc->buffer + s->header_size, s->header_size);
-            pc->index -= s->header_size;
+    if (!s->header_size) {
+        for (i = 0; i < buf_size; i++) {
+            state = (state << 8) | buf[i];
+            /* check for fixed fields in ADX header for possible match */
+            if ((state & 0xFFFF0000FFFFFF00) == 0x8000000003120400ULL) {
+                int channels    = state & 0xFF;
+                int header_size = ((state >> 32) & 0xFFFF) + 4;
+                if (channels > 0 && header_size >= 8) {
+                    s->header_size = header_size;
+                    s->block_size  = BLOCK_SIZE * channels;
+                    s->remaining   = i - 7 + s->header_size + s->block_size;
+                    break;
+                }
+            }
         }
-        *poutbuf      = NULL;
-        *poutbuf_size = 0;
-        return buf_size;
+        pc->state64 = state;
     }
 
-    if (pc->index - s->buf_pos >= s->block_size) {
-        *poutbuf      = &pc->buffer[s->buf_pos];
-        *poutbuf_size = s->block_size;
-        s->buf_pos   += s->block_size;
-        return 0;
-    }
-    if (pc->index && s->buf_pos) {
-        memmove(pc->buffer, &pc->buffer[s->buf_pos], pc->index - s->buf_pos);
-        pc->index -= s->buf_pos;
-        s->buf_pos = 0;
+    if (s->header_size) {
+        if (!s->remaining)
+            s->remaining = s->block_size;
+        if (s->remaining <= buf_size) {
+            next = s->remaining;
+            s->remaining = 0;
+        } else
+            s->remaining -= buf_size;
     }
-    if (buf_size + pc->index >= s->block_size)
-        next = s->block_size - pc->index;
 
     if (ff_combine_frame(pc, next, &buf, &buf_size) < 0 || !buf_size) {
         *poutbuf      = NULL;
diff --git a/libavcodec/adxdec.c b/libavcodec/adxdec.c
index e910413..3f7f5f4 100644
--- a/libavcodec/adxdec.c
+++ b/libavcodec/adxdec.c
@@ -38,16 +38,16 @@ static av_cold int adx_decode_init(AVCodecContext *avctx)
     ADXContext *c = avctx->priv_data;
     int ret, header_size;
 
-    if (avctx->extradata_size < 24)
-        return AVERROR_INVALIDDATA;
-
-    if ((ret = avpriv_adx_decode_header(avctx, avctx->extradata,
-                                        avctx->extradata_size, &header_size,
-                                        c->coeff)) < 0) {
-        av_log(avctx, AV_LOG_ERROR, "error parsing ADX header\n");
-        return AVERROR_INVALIDDATA;
+    if (avctx->extradata_size >= 24) {
+        if ((ret = avpriv_adx_decode_header(avctx, avctx->extradata,
+                                            avctx->extradata_size, &header_size,
+                                            c->coeff)) < 0) {
+            av_log(avctx, AV_LOG_ERROR, "error parsing ADX header\n");
+            return AVERROR_INVALIDDATA;
+        }
+        c->channels      = avctx->channels;
+        c->header_parsed = 1;
     }
-    c->channels = avctx->channels;
 
     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
 
@@ -107,6 +107,23 @@ static int adx_decode_frame(AVCodecContext *avctx, void *data,
         return buf_size;
     }
 
+    if (!c->header_parsed && buf_size >= 2 && AV_RB16(buf) == 0x8000) {
+        int header_size;
+        if ((ret = avpriv_adx_decode_header(avctx, buf, buf_size, &header_size,
+                                            c->coeff)) < 0) {
+            av_log(avctx, AV_LOG_ERROR, "error parsing ADX header\n");
+            return AVERROR_INVALIDDATA;
+        }
+        c->channels      = avctx->channels;
+        c->header_parsed = 1;
+        if (buf_size < header_size)
+            return AVERROR_INVALIDDATA;
+        buf      += header_size;
+        buf_size -= header_size;
+    }
+    if (!c->header_parsed)
+        return AVERROR_INVALIDDATA;
+
     /* calculate number of blocks in the packet */
     num_blocks = buf_size / (BLOCK_SIZE * c->channels);
 
@@ -148,6 +165,13 @@ static int adx_decode_frame(AVCodecContext *avctx, void *data,
     return buf - avpkt->data;
 }
 
+static void adx_decode_flush(AVCodecContext *avctx)
+{
+    ADXContext *c = avctx->priv_data;
+    memset(c->prev, 0, sizeof(c->prev));
+    c->eof = 0;
+}
+
 AVCodec ff_adpcm_adx_decoder = {
     .name           = "adpcm_adx",
     .type           = AVMEDIA_TYPE_AUDIO,
@@ -155,6 +179,7 @@ AVCodec ff_adpcm_adx_decoder = {
     .priv_data_size = sizeof(ADXContext),
     .init           = adx_decode_init,
     .decode         = adx_decode_frame,
+    .flush          = adx_decode_flush,
     .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("SEGA CRI ADX ADPCM"),
 };
diff --git a/libavcodec/adxenc.c b/libavcodec/adxenc.c
index ae4b9f7..20f2798 100644
--- a/libavcodec/adxenc.c
+++ b/libavcodec/adxenc.c
@@ -19,9 +19,9 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#include "libavutil/intreadwrite.h"
 #include "avcodec.h"
 #include "adx.h"
+#include "bytestream.h"
 #include "put_bits.h"
 
 /**
@@ -33,167 +33,135 @@
  * adx2wav & wav2adx http://www.geocities.co.jp/Playtown/2004/
  */
 
-/* 18 bytes <-> 32 samples */
-
-static void adx_encode(ADXContext *c, unsigned char *adx, const short *wav,
-                       ADXChannelState *prev)
+static void adx_encode(ADXContext *c, uint8_t *adx, const int16_t *wav,
+                       ADXChannelState *prev, int channels)
 {
     PutBitContext pb;
     int scale;
-    int i;
-    int s0,s1,s2,d;
-    int max=0;
-    int min=0;
-    int data[32];
+    int i, j;
+    int s0, s1, s2, d;
+    int max = 0;
+    int min = 0;
+    int data[BLOCK_SAMPLES];
 
     s1 = prev->s1;
     s2 = prev->s2;
-    for(i=0;i<32;i++) {
+    for (i = 0, j = 0; j < 32; i += channels, j++) {
         s0 = wav[i];
         d = ((s0 << COEFF_BITS) - c->coeff[0] * s1 - c->coeff[1] * s2) >> COEFF_BITS;
-        data[i]=d;
-        if (max<d) max=d;
-        if (min>d) min=d;
+        data[j] = d;
+        if (max < d)
+            max = d;
+        if (min > d)
+            min = d;
         s2 = s1;
         s1 = s0;
     }
     prev->s1 = s1;
     prev->s2 = s2;
 
-    /* -8..+7 */
-
-    if (max==0 && min==0) {
-        memset(adx,0,18);
+    if (max == 0 && min == 0) {
+        memset(adx, 0, BLOCK_SIZE);
         return;
     }
 
-    if (max/7>-min/8) scale = max/7;
-    else scale = -min/8;
+    if (max / 7 > -min / 8)
+        scale = max / 7;
+    else
+        scale = -min / 8;
 
-    if (scale==0) scale=1;
+    if (scale == 0)
+        scale = 1;
 
     AV_WB16(adx, scale);
 
     init_put_bits(&pb, adx + 2, 16);
-    for (i = 0; i < 32; i++)
-        put_sbits(&pb, 4, av_clip(data[i]/scale, -8, 7));
+    for (i = 0; i < BLOCK_SAMPLES; i++)
+        put_sbits(&pb, 4, av_clip(data[i] / scale, -8, 7));
     flush_put_bits(&pb);
 }
 
-static int adx_encode_header(AVCodecContext *avctx,unsigned char *buf,size_t bufsize)
+#define HEADER_SIZE 36
+
+static int adx_encode_header(AVCodecContext *avctx, uint8_t *buf, int bufsize)
 {
-#if 0
-    struct {
-        uint32_t offset; /* 0x80000000 + sample start - 4 */
-        unsigned char unknown1[3]; /* 03 12 04 */
-        unsigned char channel; /* 1 or 2 */
-        uint32_t freq;
-        uint32_t size;
-        uint32_t unknown2; /* 01 f4 03 00 */
-        uint32_t unknown3; /* 00 00 00 00 */
-        uint32_t unknown4; /* 00 00 00 00 */
-
-    /* if loop
-        unknown3 00 15 00 01
-        unknown4 00 00 00 01
-        long loop_start_sample;
-        long loop_start_byte;
-        long loop_end_sample;
-        long loop_end_byte;
-        long
-    */
-    } adxhdr; /* big endian */
-    /* offset-6 "(c)CRI" */
-#endif
     ADXContext *c = avctx->priv_data;
 
-    AV_WB32(buf+0x00,0x80000000|0x20);
-    AV_WB32(buf+0x04,0x03120400|avctx->channels);
-    AV_WB32(buf+0x08,avctx->sample_rate);
-    AV_WB32(buf+0x0c,0); /* FIXME: set after */
-    AV_WB16(buf + 0x10, c->cutoff);
-    AV_WB32(buf + 0x12, 0x03000000);
-    AV_WB32(buf + 0x16, 0x00000000);
-    AV_WB32(buf + 0x1a, 0x00000000);
-    memcpy (buf + 0x1e, "(c)CRI", 6);
-    return 0x20+4;
+    if (bufsize < HEADER_SIZE)
+        return AVERROR(EINVAL);
+
+    bytestream_put_be16(&buf, 0x8000);              /* header signature */
+    bytestream_put_be16(&buf, HEADER_SIZE - 4);     /* copyright offset */
+    bytestream_put_byte(&buf, 3);                   /* encoding */
+    bytestream_put_byte(&buf, BLOCK_SIZE);          /* block size */
+    bytestream_put_byte(&buf, 4);                   /* sample size */
+    bytestream_put_byte(&buf, avctx->channels);     /* channels */
+    bytestream_put_be32(&buf, avctx->sample_rate);  /* sample rate */
+    bytestream_put_be32(&buf, 0);                   /* total sample count */
+    bytestream_put_be16(&buf, c->cutoff);           /* cutoff frequency */
+    bytestream_put_byte(&buf, 3);                   /* version */
+    bytestream_put_byte(&buf, 0);                   /* flags */
+    bytestream_put_be32(&buf, 0);                   /* unknown */
+    bytestream_put_be32(&buf, 0);                   /* loop enabled */
+    bytestream_put_be16(&buf, 0);                   /* padding */
+    bytestream_put_buffer(&buf, "(c)CRI", 6);       /* copyright signature */
+
+    return HEADER_SIZE;
 }
 
 static av_cold int adx_encode_init(AVCodecContext *avctx)
 {
     ADXContext *c = avctx->priv_data;
 
-    if (avctx->channels > 2)
-        return -1; /* only stereo or mono =) */
-    avctx->frame_size = 32;
-
-    avctx->coded_frame= avcodec_alloc_frame();
-    avctx->coded_frame->key_frame= 1;
+    if (avctx->channels > 2) {
+        av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
+        return AVERROR(EINVAL);
+    }
+    avctx->frame_size = BLOCK_SAMPLES;
 
-//    avctx->bit_rate = avctx->sample_rate*avctx->channels*18*8/32;
+    avctx->coded_frame = avcodec_alloc_frame();
 
     /* the cutoff can be adjusted, but this seems to work pretty well */
     c->cutoff = 500;
     ff_adx_calculate_coeffs(c->cutoff, avctx->sample_rate, COEFF_BITS, c->coeff);
 
-    av_log(avctx, AV_LOG_DEBUG, "adx encode init\n");
-
     return 0;
 }
 
 static av_cold int adx_encode_close(AVCodecContext *avctx)
 {
     av_freep(&avctx->coded_frame);
-
     return 0;
 }
 
-static int adx_encode_frame(AVCodecContext *avctx,
-                uint8_t *frame, int buf_size, void *data)
+static int adx_encode_frame(AVCodecContext *avctx, uint8_t *frame,
+                            int buf_size, void *data)
 {
-    ADXContext *c = avctx->priv_data;
-    const short *samples = data;
-    unsigned char *dst = frame;
-    int rest = avctx->frame_size;
-
-/*
-    input data size =
-    avconv.c:do_audio_out()
-    frame_bytes = enc->frame_size * 2 * enc->channels;
-*/
+    ADXContext *c          = avctx->priv_data;
+    const int16_t *samples = data;
+    uint8_t *dst           = frame;
+    int ch;
 
-//    printf("sz=%d ",buf_size); fflush(stdout);
     if (!c->header_parsed) {
-        int hdrsize = adx_encode_header(avctx,dst,buf_size);
-        dst+=hdrsize;
+        int hdrsize;
+        if ((hdrsize = adx_encode_header(avctx, dst, buf_size)) < 0) {
+            av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
+            return AVERROR(EINVAL);
+        }
+        dst      += hdrsize;
+        buf_size -= hdrsize;
         c->header_parsed = 1;
     }
+    if (buf_size < BLOCK_SIZE * avctx->channels) {
+        av_log(avctx, AV_LOG_ERROR, "output buffer is too small\n");
+        return AVERROR(EINVAL);
+    }
 
-    if (avctx->channels==1) {
-        while(rest>=32) {
-            adx_encode(c, dst, samples, c->prev);
-            dst+=18;
-            samples+=32;
-            rest-=32;
-        }
-    } else {
-        while(rest>=32*2) {
-            short tmpbuf[32*2];
-            int i;
-
-            for(i=0;i<32;i++) {
-                tmpbuf[i] = samples[i*2];
-                tmpbuf[i+32] = samples[i*2+1];
-            }
-
-            adx_encode(c, dst,      tmpbuf,      c->prev);
-            adx_encode(c, dst + 18, tmpbuf + 32, c->prev + 1);
-            dst+=18*2;
-            samples+=32*2;
-            rest-=32*2;
-        }
+    for (ch = 0; ch < avctx->channels; ch++) {
+        adx_encode(c, dst, samples + ch, &c->prev[ch], avctx->channels);
+        dst += BLOCK_SIZE;
     }
-    return dst-frame;
+    return dst - frame;
 }
 
 AVCodec ff_adpcm_adx_encoder = {
@@ -204,6 +172,7 @@ AVCodec ff_adpcm_adx_encoder = {
     .init           = adx_encode_init,
     .encode         = adx_encode_frame,
     .close          = adx_encode_close,
-    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
-    .long_name = NULL_IF_CONFIG_SMALL("SEGA CRI ADX ADPCM"),
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16,
+                                                      AV_SAMPLE_FMT_NONE },
+    .long_name      = NULL_IF_CONFIG_SMALL("SEGA CRI ADX ADPCM"),
 };
diff --git a/libavcodec/alac.c b/libavcodec/alac.c
index 47234ec..278cc99 100644
--- a/libavcodec/alac.c
+++ b/libavcodec/alac.c
@@ -25,27 +25,23 @@
  * @author 2005 David Hammerton
  * @see http://crazney.net/programs/itunes/alac.html
  *
- * Note: This decoder expects a 36- (0x24-)byte QuickTime atom to be
+ * Note: This decoder expects a 36-byte QuickTime atom to be
  * passed through the extradata[_size] fields. This atom is tacked onto
  * the end of an 'alac' stsd atom and has the following format:
- *  bytes 0-3   atom size (0x24), big-endian
- *  bytes 4-7   atom type ('alac', not the 'alac' tag from start of stsd)
- *  bytes 8-35  data bytes needed by decoder
  *
- * Extradata:
- * 32bit  size
- * 32bit  tag (=alac)
- * 32bit  zero?
- * 32bit  max sample per frame
- *  8bit  ?? (zero?)
+ * 32bit  atom size
+ * 32bit  tag                  ("alac")
+ * 32bit  tag version          (0)
+ * 32bit  samples per frame    (used when not set explicitly in the frames)
+ *  8bit  compatible version   (0)
  *  8bit  sample size
- *  8bit  history mult
- *  8bit  initial history
- *  8bit  kmodifier
- *  8bit  channels?
- * 16bit  ??
- * 32bit  max coded frame size
- * 32bit  bitrate?
+ *  8bit  history mult         (40)
+ *  8bit  initial history      (14)
+ *  8bit  kmodifier            (10)
+ *  8bit  channels
+ * 16bit  maxRun               (255)
+ * 32bit  max coded frame size (0 means unknown)
+ * 32bit  average bitrate      (0 means unknown)
  * 32bit  samplerate
  */
 
@@ -456,24 +452,29 @@ static int alac_decode_frame(AVCodecContext *avctx, void *data,
                                         ricemodifier[ch] * alac->setinfo_rice_historymult / 4,
                                         (1 << alac->setinfo_rice_kmodifier) - 1);
 
-            if (prediction_type[ch] == 0) {
-                /* adaptive fir */
-                predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
-                                               alac->outputsamples_buffer[ch],
-                                               outputsamples,
-                                               readsamplesize,
-                                               predictor_coef_table[ch],
-                                               predictor_coef_num[ch],
-                                               prediction_quantitization[ch]);
-            } else {
-                av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[ch]);
-                /* I think the only other prediction type (or perhaps this is
-                 * just a boolean?) runs adaptive fir twice.. like:
-                 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
-                 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
-                 * little strange..
+            /* adaptive FIR filter */
+            if (prediction_type[ch] == 15) {
+                /* Prediction type 15 runs the adaptive FIR twice.
+                 * The first pass uses the special-case coef_num = 31, while
+                 * the second pass uses the coefs from the bitstream.
+                 *
+                 * However, this prediction type is not currently used by the
+                 * reference encoder.
                  */
+                predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
+                                               alac->predicterror_buffer[ch],
+                                               outputsamples, readsamplesize,
+                                               NULL, 31, 0);
+            } else if (prediction_type[ch] > 0) {
+                av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
+                       prediction_type[ch]);
             }
+            predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
+                                           alac->outputsamples_buffer[ch],
+                                           outputsamples, readsamplesize,
+                                           predictor_coef_table[ch],
+                                           predictor_coef_num[ch],
+                                           prediction_quantitization[ch]);
         }
     } else {
         /* not compressed, easy case */
@@ -574,7 +575,7 @@ static int alac_set_info(ALACContext *alac)
 
     ptr += 4; /* size */
     ptr += 4; /* alac */
-    ptr += 4; /* 0 ? */
+    ptr += 4; /* version */
 
     if(AV_RB32(ptr) >= UINT_MAX/4){
         av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
@@ -583,15 +584,15 @@ static int alac_set_info(ALACContext *alac)
 
     /* buffer size / 2 ? */
     alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
-    ptr++;                          /* ??? */
+    ptr++;                          /* compatible version */
     alac->setinfo_sample_size           = *ptr++;
     alac->setinfo_rice_historymult      = *ptr++;
     alac->setinfo_rice_initialhistory   = *ptr++;
     alac->setinfo_rice_kmodifier        = *ptr++;
     alac->numchannels                   = *ptr++;
-    bytestream_get_be16(&ptr);      /* ??? */
+    bytestream_get_be16(&ptr);      /* maxRun */
     bytestream_get_be32(&ptr);      /* max coded frame size */
-    bytestream_get_be32(&ptr);      /* bitrate ? */
+    bytestream_get_be32(&ptr);      /* average bitrate */
     bytestream_get_be32(&ptr);      /* samplerate */
 
     return 0;
diff --git a/libavcodec/alacenc.c b/libavcodec/alacenc.c
index 7e29a24..89d8e09 100644
--- a/libavcodec/alacenc.c
+++ b/libavcodec/alacenc.c
@@ -348,6 +348,7 @@ static void alac_entropy_coder(AlacEncodeContext *s)
 static void write_compressed_frame(AlacEncodeContext *s)
 {
     int i, j;
+    int prediction_type = 0;
 
     if (s->avctx->channels == 2)
         alac_stereo_decorrelation(s);
@@ -358,7 +359,7 @@ static void write_compressed_frame(AlacEncodeContext *s)
 
         calc_predictor_params(s, i);
 
-        put_bits(&s->pbctx, 4, 0);  // prediction type : currently only type 0 has been RE'd
+        put_bits(&s->pbctx, 4, prediction_type);
         put_bits(&s->pbctx, 4, s->lpc[i].lpc_quant);
 
         put_bits(&s->pbctx, 3, s->rc.rice_modifier);
@@ -373,6 +374,14 @@ static void write_compressed_frame(AlacEncodeContext *s)
 
     for (i = 0; i < s->avctx->channels; i++) {
         alac_linear_predictor(s, i);
+
+        // TODO: determine when this will actually help. for now it's not used.
+        if (prediction_type == 15) {
+            // 2nd pass 1st order filter
+            for (j = s->avctx->frame_size - 1; j > 0; j--)
+                s->predictor_buf[j] -= s->predictor_buf[j - 1];
+        }
+
         alac_entropy_coder(s);
     }
 }
@@ -391,6 +400,14 @@ static av_cold int alac_encode_init(AVCodecContext *avctx)
         return -1;
     }
 
+    /* TODO: Correctly implement multi-channel ALAC.
+             It is similar to multi-channel AAC, in that it has a series of
+             single-channel (SCE), channel-pair (CPE), and LFE elements. */
+    if (avctx->channels > 2) {
+        av_log(avctx, AV_LOG_ERROR, "only mono or stereo input is currently supported\n");
+        return AVERROR_PATCHWELCOME;
+    }
+
     // Set default compression level
     if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
         s->compression_level = 2;
diff --git a/libavcodec/amrnbdec.c b/libavcodec/amrnbdec.c
index 926014f..fff0e72 100644
--- a/libavcodec/amrnbdec.c
+++ b/libavcodec/amrnbdec.c
@@ -977,6 +977,10 @@ static int amrnb_decode_frame(AVCodecContext *avctx, void *data,
 
         pitch_sharpening(p, subframe, p->cur_frame_mode, &fixed_sparse);
 
+        if (fixed_sparse.pitch_lag == 0) {
+            av_log(avctx, AV_LOG_ERROR, "The file is corrupted, pitch_lag = 0 is not allowed\n");
+            return AVERROR_INVALIDDATA;
+        }
         ff_set_fixed_vector(p->fixed_vector, &fixed_sparse, 1.0,
                             AMR_SUBFRAME_SIZE);
 
diff --git a/libavcodec/arm/rv34dsp_init_neon.c b/libavcodec/arm/rv34dsp_init_neon.c
index acf2a7d..9a09fde 100644
--- a/libavcodec/arm/rv34dsp_init_neon.c
+++ b/libavcodec/arm/rv34dsp_init_neon.c
@@ -25,12 +25,9 @@
 
 void ff_rv34_inv_transform_neon(DCTELEM *block);
 void ff_rv34_inv_transform_noround_neon(DCTELEM *block);
-void ff_rv34_dequant4x4_neon(DCTELEM *block, int Qdc, int Q);
 
 void ff_rv34dsp_init_neon(RV34DSPContext *c, DSPContext* dsp)
 {
     c->rv34_inv_transform_tab[0] = ff_rv34_inv_transform_neon;
     c->rv34_inv_transform_tab[1] = ff_rv34_inv_transform_noround_neon;
-
-    c->rv34_dequant4x4 = ff_rv34_dequant4x4_neon;
 }
diff --git a/libavcodec/arm/rv34dsp_neon.S b/libavcodec/arm/rv34dsp_neon.S
index 423b537..f700f5c 100644
--- a/libavcodec/arm/rv34dsp_neon.S
+++ b/libavcodec/arm/rv34dsp_neon.S
@@ -107,27 +107,3 @@ function ff_rv34_inv_transform_noround_neon, export=1
         vst4.16         {d0[3], d1[3], d2[3], d3[3]}, [r2,:64], r1
         bx              lr
 endfunc
-
-function ff_rv34_dequant4x4_neon, export=1
-        mov             r3,  r0
-        mov             r12, #16
-        vdup.16         q0,  r2
-        vmov.16         d0[0], r1
-        vld1.16         {d2},     [r0,:64], r12
-        vld1.16         {d4},     [r0,:64], r12
-        vld1.16         {d6},     [r0,:64], r12
-        vld1.16         {d16},    [r0,:64], r12
-        vmull.s16       q1,  d2,  d0
-        vmull.s16       q2,  d4,  d1
-        vmull.s16       q3,  d6,  d1
-        vmull.s16       q8,  d16, d1
-        vqrshrn.s32     d2,  q1,  #4
-        vqrshrn.s32     d4,  q2,  #4
-        vqrshrn.s32     d6,  q3,  #4
-        vqrshrn.s32     d16, q8,  #4
-        vst1.16         {d2},     [r3,:64], r12
-        vst1.16         {d4},     [r3,:64], r12
-        vst1.16         {d6},     [r3,:64], r12
-        vst1.16         {d16},    [r3,:64], r12
-        bx              lr
-endfunc
diff --git a/libavcodec/atrac3.c b/libavcodec/atrac3.c
index 744ef17..6dec6a3 100644
--- a/libavcodec/atrac3.c
+++ b/libavcodec/atrac3.c
@@ -742,7 +742,7 @@ static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf,
 
         result = decodeChannelSoundUnit(q,&q->gb, q->pUnits, out_samples[0], 0, JOINT_STEREO);
         if (result != 0)
-            return (result);
+            return result;
 
         /* Framedata of the su2 in the joint-stereo mode is encoded in
          * reverse byte order so we need to swap it first. */
@@ -783,7 +783,7 @@ static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf,
         /* Decode Sound Unit 2. */
         result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[1], out_samples[1], 1, JOINT_STEREO);
         if (result != 0)
-            return (result);
+            return result;
 
         /* Reconstruct the channel coefficients. */
         reverseMatrixing(out_samples[0], out_samples[1], q->matrix_coeff_index_prev, q->matrix_coeff_index_now);
@@ -802,7 +802,7 @@ static int decodeFrame(ATRAC3Context *q, const uint8_t* databuf,
 
             result = decodeChannelSoundUnit(q,&q->gb, &q->pUnits[i], out_samples[i], i, q->codingMode);
             if (result != 0)
-                return (result);
+                return result;
         }
     }
 
diff --git a/libavcodec/avcodec.h b/libavcodec/avcodec.h
index 4f24f72..c195ad5 100644
--- a/libavcodec/avcodec.h
+++ b/libavcodec/avcodec.h
@@ -725,10 +725,22 @@ typedef struct RcOverride{
 /* Codec can export data for HW decoding (XvMC). */
 #define CODEC_CAP_HWACCEL         0x0010
 /**
- * Codec has a nonzero delay and needs to be fed with avpkt->data=NULL,
+ * Encoder or decoder requires flushing with NULL input at the end in order to
+ * give the complete and correct output.
+ *
+ * NOTE: If this flag is not set, the codec is guaranteed to never be fed with
+ *       with NULL data. The user can still send NULL data to the public encode
+ *       or decode function, but libavcodec will not pass it along to the codec
+ *       unless this flag is set.
+ *
+ * Decoders:
+ * The decoder has a non-zero delay and needs to be fed with avpkt->data=NULL,
  * avpkt->size=0 at the end to get the delayed data until the decoder no longer
- * returns frames. If this is not set, the codec is guaranteed to never be fed
- * with NULL data.
+ * returns frames.
+ *
+ * Encoders:
+ * The encoder needs to be fed with NULL data at the end of encoding until the
+ * encoder no longer returns data.
  */
 #define CODEC_CAP_DELAY           0x0020
 /**
@@ -777,6 +789,10 @@ typedef struct RcOverride{
  * Codec supports changed parameters at any point.
  */
 #define CODEC_CAP_PARAM_CHANGE     0x4000
+/**
+ * Codec supports avctx->thread_count == 0 (auto).
+ */
+#define CODEC_CAP_AUTO_THREADS     0x8000
 
 //The following defines may change, don't expect compatibility if you use them.
 #define MB_TYPE_INTRA4x4   0x0001
@@ -4196,9 +4212,9 @@ void avsubtitle_free(AVSubtitle *sub);
  * Encode an audio frame from samples into buf.
  *
  * @note The output buffer should be at least FF_MIN_BUFFER_SIZE bytes large.
- * However, for PCM audio the user will know how much space is needed
- * because it depends on the value passed in buf_size as described
- * below. In that case a lower value can be used.
+ * However, for codecs with avctx->frame_size equal to 0 (e.g. PCM) the user
+ * will know how much space is needed because it depends on the value passed
+ * in buf_size as described below. In that case a lower value can be used.
  *
  * @param avctx the codec context
  * @param[out] buf the output buffer
@@ -4206,8 +4222,11 @@ void avsubtitle_free(AVSubtitle *sub);
  * @param[in] samples the input buffer containing the samples
  * The number of samples read from this buffer is frame_size*channels,
  * both of which are defined in avctx.
- * For PCM audio the number of samples read from samples is equal to
- * buf_size * input_sample_size / output_sample_size.
+ * For codecs which have avctx->frame_size equal to 0 (e.g. PCM) the number of
+ * samples read from samples is equal to:
+ * buf_size * 8 / (avctx->channels * av_get_bits_per_sample(avctx->codec_id))
+ * This also implies that av_get_bits_per_sample() must not return 0 for these
+ * codecs.
  * @return On error a negative value is returned, on success zero or the number
  * of bytes used to encode the data read from the input buffer.
  */
diff --git a/libavcodec/bethsoftvideo.c b/libavcodec/bethsoftvideo.c
index f4020d6..fa0457c 100644
--- a/libavcodec/bethsoftvideo.c
+++ b/libavcodec/bethsoftvideo.c
@@ -34,6 +34,7 @@
 
 typedef struct BethsoftvidContext {
     AVFrame frame;
+    GetByteContext g;
 } BethsoftvidContext;
 
 static av_cold int bethsoftvid_decode_init(AVCodecContext *avctx)
@@ -46,18 +47,18 @@ static av_cold int bethsoftvid_decode_init(AVCodecContext *avctx)
     return 0;
 }
 
-static int set_palette(AVFrame * frame, const uint8_t * palette_buffer, int buf_size)
+static int set_palette(BethsoftvidContext *ctx)
 {
-    uint32_t * palette = (uint32_t *)frame->data[1];
+    uint32_t *palette = (uint32_t *)ctx->frame.data[1];
     int a;
 
-    if (buf_size < 256*3)
+    if (bytestream2_get_bytes_left(&ctx->g) < 256*3)
         return AVERROR_INVALIDDATA;
 
     for(a = 0; a < 256; a++){
-        palette[a] = AV_RB24(&palette_buffer[a * 3]) * 4;
+        palette[a] = bytestream2_get_be24u(&ctx->g) * 4;
     }
-    frame->palette_has_changed = 1;
+    ctx->frame.palette_has_changed = 1;
     return 256*3;
 }
 
@@ -65,8 +66,6 @@ static int bethsoftvid_decode_frame(AVCodecContext *avctx,
                               void *data, int *data_size,
                               AVPacket *avpkt)
 {
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
     BethsoftvidContext * vid = avctx->priv_data;
     char block_type;
     uint8_t * dst;
@@ -80,29 +79,32 @@ static int bethsoftvid_decode_frame(AVCodecContext *avctx,
         av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
         return -1;
     }
+
+    bytestream2_init(&vid->g, avpkt->data, avpkt->size);
     dst = vid->frame.data[0];
     frame_end = vid->frame.data[0] + vid->frame.linesize[0] * avctx->height;
 
-    switch(block_type = *buf++){
-        case PALETTE_BLOCK:
-            return set_palette(&vid->frame, buf, buf_size);
+    switch(block_type = bytestream2_get_byte(&vid->g)){
+        case PALETTE_BLOCK: {
+            return set_palette(vid);
+        }
         case VIDEO_YOFF_P_FRAME:
-            yoffset = bytestream_get_le16(&buf);
+            yoffset = bytestream2_get_le16(&vid->g);
             if(yoffset >= avctx->height)
                 return -1;
             dst += vid->frame.linesize[0] * yoffset;
     }
 
     // main code
-    while((code = *buf++)){
+    while((code = bytestream2_get_byte(&vid->g))){
         int length = code & 0x7f;
 
         // copy any bytes starting at the current position, and ending at the frame width
         while(length > remaining){
             if(code < 0x80)
-                bytestream_get_buffer(&buf, dst, remaining);
+                bytestream2_get_buffer(&vid->g, dst, remaining);
             else if(block_type == VIDEO_I_FRAME)
-                memset(dst, buf[0], remaining);
+                memset(dst, bytestream2_peek_byte(&vid->g), remaining);
             length -= remaining;      // decrement the number of bytes to be copied
             dst += remaining + wrap_to_next_line;    // skip over extra bytes at end of frame
             remaining = avctx->width;
@@ -112,9 +114,9 @@ static int bethsoftvid_decode_frame(AVCodecContext *avctx,
 
         // copy any remaining bytes after / if line overflows
         if(code < 0x80)
-            bytestream_get_buffer(&buf, dst, length);
+            bytestream2_get_buffer(&vid->g, dst, length);
         else if(block_type == VIDEO_I_FRAME)
-            memset(dst, *buf++, length);
+            memset(dst, bytestream2_get_byte(&vid->g), length);
         remaining -= length;
         dst += length;
     }
@@ -123,7 +125,7 @@ static int bethsoftvid_decode_frame(AVCodecContext *avctx,
     *data_size = sizeof(AVFrame);
     *(AVFrame*)data = vid->frame;
 
-    return buf_size;
+    return avpkt->size;
 }
 
 static av_cold int bethsoftvid_decode_end(AVCodecContext *avctx)
diff --git a/libavcodec/bfi.c b/libavcodec/bfi.c
index 3c66226..542ba54 100644
--- a/libavcodec/bfi.c
+++ b/libavcodec/bfi.c
@@ -36,7 +36,7 @@ typedef struct BFIContext {
     uint8_t *dst;
 } BFIContext;
 
-static av_cold int bfi_decode_init(AVCodecContext * avctx)
+static av_cold int bfi_decode_init(AVCodecContext *avctx)
 {
     BFIContext *bfi = avctx->priv_data;
     avctx->pix_fmt = PIX_FMT_PAL8;
@@ -44,10 +44,10 @@ static av_cold int bfi_decode_init(AVCodecContext * avctx)
     return 0;
 }
 
-static int bfi_decode_frame(AVCodecContext * avctx, void *data,
+static int bfi_decode_frame(AVCodecContext *avctx, void *data,
                             int *data_size, AVPacket *avpkt)
 {
-    const uint8_t *buf = avpkt->data, *buf_end = avpkt->data + avpkt->size;
+    GetByteContext g;
     int buf_size = avpkt->size;
     BFIContext *bfi = avctx->priv_data;
     uint8_t *dst = bfi->dst;
@@ -66,16 +66,18 @@ static int bfi_decode_frame(AVCodecContext * avctx, void *data,
         return -1;
     }
 
+    bytestream2_init(&g, avpkt->data, buf_size);
+
     /* Set frame parameters and palette, if necessary */
     if (!avctx->frame_number) {
         bfi->frame.pict_type = AV_PICTURE_TYPE_I;
         bfi->frame.key_frame = 1;
         /* Setting the palette */
-        if(avctx->extradata_size>768) {
+        if (avctx->extradata_size > 768) {
             av_log(NULL, AV_LOG_ERROR, "Palette is too large.\n");
             return -1;
         }
-        pal = (uint32_t *) bfi->frame.data[1];
+        pal = (uint32_t *)bfi->frame.data[1];
         for (i = 0; i < avctx->extradata_size / 3; i++) {
             int shift = 16;
             *pal = 0;
@@ -91,46 +93,47 @@ static int bfi_decode_frame(AVCodecContext * avctx, void *data,
         bfi->frame.key_frame = 0;
     }
 
-    buf += 4; //Unpacked size, not required.
+    bytestream2_skip(&g, 4); // Unpacked size, not required.
 
     while (dst != frame_end) {
-        static const uint8_t lentab[4]={0,2,0,1};
-        unsigned int byte = *buf++, av_uninit(offset);
-        unsigned int code = byte >> 6;
+        static const uint8_t lentab[4] = { 0, 2, 0, 1 };
+        unsigned int byte   = bytestream2_get_byte(&g), av_uninit(offset);
+        unsigned int code   = byte >> 6;
         unsigned int length = byte & ~0xC0;
 
-        if (buf >= buf_end) {
-            av_log(avctx, AV_LOG_ERROR, "Input resolution larger than actual frame.\n");
+        if (!bytestream2_get_bytes_left(&g)) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "Input resolution larger than actual frame.\n");
             return -1;
         }
 
         /* Get length and offset(if required) */
         if (length == 0) {
             if (code == 1) {
-                length = bytestream_get_byte(&buf);
-                offset = bytestream_get_le16(&buf);
+                length = bytestream2_get_byte(&g);
+                offset = bytestream2_get_le16(&g);
             } else {
-                length = bytestream_get_le16(&buf);
+                length = bytestream2_get_le16(&g);
                 if (code == 2 && length == 0)
                     break;
             }
         } else {
             if (code == 1)
-                offset = bytestream_get_byte(&buf);
+                offset = bytestream2_get_byte(&g);
         }
 
         /* Do boundary check */
-        if (dst + (length<<lentab[code]) > frame_end)
+        if (dst + (length << lentab[code]) > frame_end)
             break;
 
         switch (code) {
 
         case 0:                //Normal Chain
-            if (length >= buf_end - buf) {
+            if (length >= bytestream2_get_bytes_left(&g)) {
                 av_log(avctx, AV_LOG_ERROR, "Frame larger than buffer.\n");
                 return -1;
             }
-            bytestream_get_buffer(&buf, dst, length);
+            bytestream2_get_buffer(&g, dst, length);
             dst += length;
             break;
 
@@ -148,8 +151,8 @@ static int bfi_decode_frame(AVCodecContext * avctx, void *data,
             break;
 
         case 3:                //Fill Chain
-            colour1 = bytestream_get_byte(&buf);
-            colour2 = bytestream_get_byte(&buf);
+            colour1 = bytestream2_get_byte(&g);
+            colour2 = bytestream2_get_byte(&g);
             while (length--) {
                 *dst++ = colour1;
                 *dst++ = colour2;
@@ -167,7 +170,7 @@ static int bfi_decode_frame(AVCodecContext * avctx, void *data,
         dst += bfi->frame.linesize[0];
     }
     *data_size = sizeof(AVFrame);
-    *(AVFrame *) data = bfi->frame;
+    *(AVFrame *)data = bfi->frame;
     return buf_size;
 }
 
diff --git a/libavcodec/bgmc.c b/libavcodec/bgmc.c
index b8aaa8d..b17c3b1 100644
--- a/libavcodec/bgmc.c
+++ b/libavcodec/bgmc.c
@@ -474,7 +474,8 @@ int ff_bgmc_init(AVCodecContext *avctx, uint8_t **cf_lut, int **cf_lut_status)
         av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
         return AVERROR(ENOMEM);
     } else {
-        // initialize lut_status buffer to a value never used to compare against
+        // initialize lut_status buffer to a value never used to compare
+        // against
         memset(*cf_lut_status, -1, sizeof(*cf_lut_status) * LUT_BUFF);
     }
 
@@ -494,7 +495,7 @@ void ff_bgmc_end(uint8_t **cf_lut, int **cf_lut_status)
 /** Initialize decoding and reads the first value
  */
 void ff_bgmc_decode_init(GetBitContext *gb,
-                      unsigned int *h, unsigned int *l, unsigned int *v)
+                         unsigned int *h, unsigned int *l, unsigned int *v)
 {
     *h = TOP_VALUE;
     *l = 0;
@@ -513,9 +514,9 @@ void ff_bgmc_decode_end(GetBitContext *gb)
 /** Read and decode a block Gilbert-Moore coded symbol
  */
 void ff_bgmc_decode(GetBitContext *gb, unsigned int num, int32_t *dst,
-                 int delta, unsigned int sx,
-                 unsigned int *h, unsigned int *l, unsigned int *v,
-                 uint8_t *cf_lut, int *cf_lut_status)
+                    int delta, unsigned int sx,
+                    unsigned int *h, unsigned int *l, unsigned int *v,
+                    uint8_t *cf_lut, int *cf_lut_status)
 {
     unsigned int i;
     uint8_t *lut = bgmc_lut_getp(cf_lut, cf_lut_status, delta);
@@ -567,4 +568,3 @@ void ff_bgmc_decode(GetBitContext *gb, unsigned int num, int32_t *dst,
     *l = low;
     *v = value;
 }
-
diff --git a/libavcodec/bmp.c b/libavcodec/bmp.c
index f438d10..1f725f5 100644
--- a/libavcodec/bmp.c
+++ b/libavcodec/bmp.c
@@ -162,8 +162,18 @@ static int bmp_decode_frame(AVCodecContext *avctx,
     case 16:
         if(comp == BMP_RGB)
             avctx->pix_fmt = PIX_FMT_RGB555;
-        if(comp == BMP_BITFIELDS)
-            avctx->pix_fmt = rgb[1] == 0x07E0 ? PIX_FMT_RGB565 : PIX_FMT_RGB555;
+        else if (comp == BMP_BITFIELDS) {
+            if (rgb[0] == 0xF800 && rgb[1] == 0x07E0 && rgb[2] == 0x001F)
+               avctx->pix_fmt = PIX_FMT_RGB565;
+            else if (rgb[0] == 0x7C00 && rgb[1] == 0x03E0 && rgb[2] == 0x001F)
+               avctx->pix_fmt = PIX_FMT_RGB555;
+            else if (rgb[0] == 0x0F00 && rgb[1] == 0x00F0 && rgb[2] == 0x000F)
+               avctx->pix_fmt = PIX_FMT_RGB444;
+            else {
+               av_log(avctx, AV_LOG_ERROR, "Unknown bitfields %0X %0X %0X\n", rgb[0], rgb[1], rgb[2]);
+               return AVERROR(EINVAL);
+            }
+        }
         break;
     case 8:
         if(hsize - ihsize - 14 > 0)
diff --git a/libavcodec/bmpenc.c b/libavcodec/bmpenc.c
index 9cd7adb..ca2951a 100644
--- a/libavcodec/bmpenc.c
+++ b/libavcodec/bmpenc.c
@@ -27,6 +27,7 @@
 
 static const uint32_t monoblack_pal[] = { 0x000000, 0xFFFFFF };
 static const uint32_t rgb565_masks[]  = { 0xF800, 0x07E0, 0x001F };
+static const uint32_t rgb444_masks[]  = { 0x0F00, 0x00F0, 0x000F };
 
 static av_cold int bmp_encode_init(AVCodecContext *avctx){
     BMPContext *s = avctx->priv_data;
@@ -39,9 +40,8 @@ static av_cold int bmp_encode_init(AVCodecContext *avctx){
         avctx->bits_per_coded_sample = 24;
         break;
     case PIX_FMT_RGB555:
-        avctx->bits_per_coded_sample = 16;
-        break;
     case PIX_FMT_RGB565:
+    case PIX_FMT_RGB444:
         avctx->bits_per_coded_sample = 16;
         break;
     case PIX_FMT_RGB8:
@@ -77,6 +77,11 @@ static int bmp_encode_frame(AVCodecContext *avctx, unsigned char *buf, int buf_s
     p->pict_type= AV_PICTURE_TYPE_I;
     p->key_frame= 1;
     switch (avctx->pix_fmt) {
+    case PIX_FMT_RGB444:
+        compression = BMP_BITFIELDS;
+        pal = rgb444_masks; // abuse pal to hold color masks
+        pal_entries = 3;
+        break;
     case PIX_FMT_RGB565:
         compression = BMP_BITFIELDS;
         pal = rgb565_masks; // abuse pal to hold color masks
@@ -158,7 +163,7 @@ AVCodec ff_bmp_encoder = {
     .encode         = bmp_encode_frame,
     .pix_fmts = (const enum PixelFormat[]){
         PIX_FMT_BGR24,
-        PIX_FMT_RGB555, PIX_FMT_RGB565,
+        PIX_FMT_RGB555, PIX_FMT_RGB444, PIX_FMT_RGB565,
         PIX_FMT_RGB8, PIX_FMT_BGR8, PIX_FMT_RGB4_BYTE, PIX_FMT_BGR4_BYTE, PIX_FMT_GRAY8, PIX_FMT_PAL8,
         PIX_FMT_MONOBLACK,
         PIX_FMT_NONE},
diff --git a/libavcodec/bmv.c b/libavcodec/bmv.c
index 86d1e91..49346a4 100644
--- a/libavcodec/bmv.c
+++ b/libavcodec/bmv.c
@@ -285,12 +285,17 @@ static av_cold int decode_end(AVCodecContext *avctx)
     return 0;
 }
 
+typedef struct BMVAudioDecContext {
+    AVFrame frame;
+} BMVAudioDecContext;
+
 static const int bmv_aud_mults[16] = {
     16512, 8256, 4128, 2064, 1032, 516, 258, 192, 129, 88, 64, 56, 48, 40, 36, 32
 };
 
 static av_cold int bmv_aud_decode_init(AVCodecContext *avctx)
 {
+    BMVAudioDecContext *c = avctx->priv_data;
 
     if (avctx->channels != 2) {
         av_log(avctx, AV_LOG_INFO, "invalid number of channels\n");
@@ -299,17 +304,21 @@ static av_cold int bmv_aud_decode_init(AVCodecContext *avctx)
 
     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
 
+    avcodec_get_frame_defaults(&c->frame);
+    avctx->coded_frame = &c->frame;
+
     return 0;
 }
 
-static int bmv_aud_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
-                                AVPacket *avpkt)
+static int bmv_aud_decode_frame(AVCodecContext *avctx, void *data,
+                                int *got_frame_ptr, AVPacket *avpkt)
 {
+    BMVAudioDecContext *c = avctx->priv_data;
     const uint8_t *buf = avpkt->data;
     int buf_size = avpkt->size;
     int blocks = 0, total_blocks, i;
-    int out_size;
-    int16_t *output_samples = data;
+    int ret;
+    int16_t *output_samples;
     int scale[2];
 
     total_blocks = *buf++;
@@ -318,11 +327,14 @@ static int bmv_aud_decode_frame(AVCodecContext *avctx, void *data, int *data_siz
                total_blocks * 65 + 1, buf_size);
         return AVERROR_INVALIDDATA;
     }
-    out_size = total_blocks * 64 * sizeof(*output_samples);
-    if (*data_size < out_size) {
-        av_log(avctx, AV_LOG_ERROR, "Output buffer is too small\n");
-        return AVERROR(EINVAL);
+
+    /* get output buffer */
+    c->frame.nb_samples = total_blocks * 32;
+    if ((ret = avctx->get_buffer(avctx, &c->frame)) < 0) {
+        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+        return ret;
     }
+    output_samples = (int16_t *)c->frame.data[0];
 
     for (blocks = 0; blocks < total_blocks; blocks++) {
         uint8_t code = *buf++;
@@ -335,7 +347,9 @@ static int bmv_aud_decode_frame(AVCodecContext *avctx, void *data, int *data_siz
         }
     }
 
-    *data_size = out_size;
+    *got_frame_ptr   = 1;
+    *(AVFrame *)data = c->frame;
+
     return buf_size;
 }
 
@@ -354,7 +368,9 @@ AVCodec ff_bmv_audio_decoder = {
     .name           = "bmv_audio",
     .type           = AVMEDIA_TYPE_AUDIO,
     .id             = CODEC_ID_BMV_AUDIO,
+    .priv_data_size = sizeof(BMVAudioDecContext),
     .init           = bmv_aud_decode_init,
     .decode         = bmv_aud_decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
     .long_name      = NULL_IF_CONFIG_SMALL("Discworld II BMV audio"),
 };
diff --git a/libavcodec/bytestream.h b/libavcodec/bytestream.h
index ba3e4e8..9ec74cf 100644
--- a/libavcodec/bytestream.h
+++ b/libavcodec/bytestream.h
@@ -27,7 +27,7 @@
 #include "libavutil/intreadwrite.h"
 
 typedef struct {
-    const uint8_t *buffer, *buffer_end;
+    const uint8_t *buffer, *buffer_end, *buffer_start;
 } GetByteContext;
 
 #define DEF_T(type, name, bytes, read, write)                             \
@@ -39,11 +39,15 @@ static av_always_inline void bytestream_put_ ##name(uint8_t **b, const type valu
     write(*b, value);\
     (*b) += bytes;\
 }\
+static av_always_inline type bytestream2_get_ ## name ## u(GetByteContext *g)\
+{\
+    return bytestream_get_ ## name(&g->buffer);\
+}\
 static av_always_inline type bytestream2_get_ ## name(GetByteContext *g)\
 {\
     if (g->buffer_end - g->buffer < bytes)\
         return 0;\
-    return bytestream_get_ ## name(&g->buffer);\
+    return bytestream2_get_ ## name ## u(g);\
 }\
 static av_always_inline type bytestream2_peek_ ## name(GetByteContext *g)\
 {\
@@ -75,6 +79,7 @@ static av_always_inline void bytestream2_init(GetByteContext *g,
                                               const uint8_t *buf, int buf_size)
 {
     g->buffer =  buf;
+    g->buffer_start = buf;
     g->buffer_end = buf + buf_size;
 }
 
@@ -89,6 +94,34 @@ static av_always_inline void bytestream2_skip(GetByteContext *g,
     g->buffer += FFMIN(g->buffer_end - g->buffer, size);
 }
 
+static av_always_inline int bytestream2_tell(GetByteContext *g)
+{
+    return (int)(g->buffer - g->buffer_start);
+}
+
+static av_always_inline int bytestream2_seek(GetByteContext *g, int offset,
+                                             int whence)
+{
+    switch (whence) {
+    case SEEK_CUR:
+        offset = av_clip(offset, -(g->buffer - g->buffer_start),
+                         g->buffer_end - g->buffer);
+        g->buffer += offset;
+        break;
+    case SEEK_END:
+        offset = av_clip(offset, -(g->buffer_end - g->buffer_start), 0);
+        g->buffer = g->buffer_end + offset;
+        break;
+    case SEEK_SET:
+        offset = av_clip(offset, 0, g->buffer_end - g->buffer_start);
+        g->buffer = g->buffer_start + offset;
+        break;
+    default:
+        return AVERROR(EINVAL);
+    }
+    return bytestream2_tell(g);
+}
+
 static av_always_inline unsigned int bytestream2_get_buffer(GetByteContext *g,
                                                             uint8_t *dst,
                                                             unsigned int size)
diff --git a/libavcodec/cabac.c b/libavcodec/cabac.c
index 57ab395..54414fa 100644
--- a/libavcodec/cabac.c
+++ b/libavcodec/cabac.c
@@ -109,10 +109,6 @@ void ff_init_cabac_encoder(CABACContext *c, uint8_t *buf, int buf_size){
     c->low= 0;
     c->range= 0x1FE;
     c->outstanding_count= 0;
-#ifdef STRICT_LIMITS
-    c->sym_count =0;
-#endif
-
     c->pb.bit_left++; //avoids firstBitFlag
 }
 
@@ -166,6 +162,31 @@ void ff_init_cabac_states(CABACContext *c){
 #include "avcodec.h"
 #include "cabac.h"
 
+static inline void put_cabac_bit(CABACContext *c, int b){
+    put_bits(&c->pb, 1, b);
+    for(;c->outstanding_count; c->outstanding_count--){
+        put_bits(&c->pb, 1, 1-b);
+    }
+}
+
+static inline void renorm_cabac_encoder(CABACContext *c){
+    while(c->range < 0x100){
+        //FIXME optimize
+        if(c->low<0x100){
+            put_cabac_bit(c, 0);
+        }else if(c->low<0x200){
+            c->outstanding_count++;
+            c->low -= 0x100;
+        }else{
+            put_cabac_bit(c, 1);
+            c->low -= 0x200;
+        }
+
+        c->range+= c->range;
+        c->low += c->low;
+    }
+}
+
 static void put_cabac(CABACContext *c, uint8_t * const state, int bit){
     int RangeLPS= ff_h264_lps_range[2*(c->range&0xC0) + *state];
 
@@ -179,10 +200,6 @@ static void put_cabac(CABACContext *c, uint8_t * const state, int bit){
     }
 
     renorm_cabac_encoder(c);
-
-#ifdef STRICT_LIMITS
-    c->symCount++;
-#endif
 }
 
 /**
@@ -204,10 +221,6 @@ static void put_cabac_bypass(CABACContext *c, int bit){
         put_cabac_bit(c, 1);
         c->low -= 0x400;
     }
-
-#ifdef STRICT_LIMITS
-    c->symCount++;
-#endif
 }
 
 /**
@@ -232,74 +245,9 @@ static int put_cabac_terminate(CABACContext *c, int bit){
         flush_put_bits(&c->pb); //FIXME FIXME FIXME XXX wrong
     }
 
-#ifdef STRICT_LIMITS
-    c->symCount++;
-#endif
-
     return (put_bits_count(&c->pb)+7)>>3;
 }
 
-/**
- * put (truncated) unary binarization.
- */
-static void put_cabac_u(CABACContext *c, uint8_t * state, int v, int max, int max_index, int truncated){
-    int i;
-
-    assert(v <= max);
-
-    for(i=0; i<v; i++){
-        put_cabac(c, state, 1);
-        if(i < max_index) state++;
-    }
-    if(truncated==0 || v<max)
-        put_cabac(c, state, 0);
-}
-
-/**
- * put unary exp golomb k-th order binarization.
- */
-static void put_cabac_ueg(CABACContext *c, uint8_t * state, int v, int max, int is_signed, int k, int max_index){
-    int i;
-
-    if(v==0)
-        put_cabac(c, state, 0);
-    else{
-        const int sign= v < 0;
-
-        if(is_signed) v= FFABS(v);
-
-        if(v<max){
-            for(i=0; i<v; i++){
-                put_cabac(c, state, 1);
-                if(i < max_index) state++;
-            }
-
-            put_cabac(c, state, 0);
-        }else{
-            int m= 1<<k;
-
-            for(i=0; i<max; i++){
-                put_cabac(c, state, 1);
-                if(i < max_index) state++;
-            }
-
-            v -= max;
-            while(v >= m){ //FIXME optimize
-                put_cabac_bypass(c, 1);
-                v-= m;
-                m+= m;
-            }
-            put_cabac_bypass(c, 0);
-            while(m>>=1){
-                put_cabac_bypass(c, v&m);
-            }
-        }
-
-        if(is_signed)
-            put_cabac_bypass(c, sign);
-    }
-}
-
 int main(void){
     CABACContext c;
     uint8_t b[9*SIZE];
@@ -328,18 +276,6 @@ START_TIMER
 STOP_TIMER("put_cabac")
     }
 
-    for(i=0; i<SIZE; i++){
-START_TIMER
-        put_cabac_u(&c, state, r[i], 6, 3, i&1);
-STOP_TIMER("put_cabac_u")
-    }
-
-    for(i=0; i<SIZE; i++){
-START_TIMER
-        put_cabac_ueg(&c, state, r[i], 3, 0, 1, 2);
-STOP_TIMER("put_cabac_ueg")
-    }
-
     put_cabac_terminate(&c, 1);
 
     ff_init_cabac_decoder(&c, b, SIZE);
@@ -359,21 +295,6 @@ START_TIMER
             av_log(NULL, AV_LOG_ERROR, "CABAC failure at %d\n", i);
 STOP_TIMER("get_cabac")
     }
-#if 0
-    for(i=0; i<SIZE; i++){
-START_TIMER
-        if( r[i] != get_cabac_u(&c, state, (i&1) ? 6 : 7, 3, i&1) )
-            av_log(NULL, AV_LOG_ERROR, "CABAC unary (truncated) binarization failure at %d\n", i);
-STOP_TIMER("get_cabac_u")
-    }
-
-    for(i=0; i<SIZE; i++){
-START_TIMER
-        if( r[i] != get_cabac_ueg(&c, state, 3, 0, 1, 2))
-            av_log(NULL, AV_LOG_ERROR, "CABAC unary (truncated) binarization failure at %d\n", i);
-STOP_TIMER("get_cabac_ueg")
-    }
-#endif
     if(!get_cabac_terminate(&c))
         av_log(NULL, AV_LOG_ERROR, "where's the Terminator?\n");
 
diff --git a/libavcodec/cabac.h b/libavcodec/cabac.h
index 1260642..dda6348 100644
--- a/libavcodec/cabac.h
+++ b/libavcodec/cabac.h
@@ -41,9 +41,6 @@ typedef struct CABACContext{
     int low;
     int range;
     int outstanding_count;
-#ifdef STRICT_LIMITS
-    int symCount;
-#endif
     const uint8_t *bytestream_start;
     const uint8_t *bytestream;
     const uint8_t *bytestream_end;
@@ -65,31 +62,6 @@ void ff_init_cabac_decoder(CABACContext *c, const uint8_t *buf, int buf_size);
 void ff_init_cabac_states(CABACContext *c);
 
 
-static inline void put_cabac_bit(CABACContext *c, int b){
-    put_bits(&c->pb, 1, b);
-    for(;c->outstanding_count; c->outstanding_count--){
-        put_bits(&c->pb, 1, 1-b);
-    }
-}
-
-static inline void renorm_cabac_encoder(CABACContext *c){
-    while(c->range < 0x100){
-        //FIXME optimize
-        if(c->low<0x100){
-            put_cabac_bit(c, 0);
-        }else if(c->low<0x200){
-            c->outstanding_count++;
-            c->low -= 0x100;
-        }else{
-            put_cabac_bit(c, 1);
-            c->low -= 0x200;
-        }
-
-        c->range+= c->range;
-        c->low += c->low;
-    }
-}
-
 static void refill(CABACContext *c){
 #if CABAC_BITS == 16
         c->low+= (c->bytestream[0]<<9) + (c->bytestream[1]<<1);
@@ -100,15 +72,6 @@ static void refill(CABACContext *c){
     c->bytestream+= CABAC_BITS/8;
 }
 
-static inline void renorm_cabac_decoder(CABACContext *c){
-    while(c->range < 0x100){
-        c->range+= c->range;
-        c->low+= c->low;
-        if(!(c->low & CABAC_MASK))
-            refill(c);
-    }
-}
-
 static inline void renorm_cabac_decoder_once(CABACContext *c){
     int shift= (uint32_t)(c->range - 0x100)>>31;
     c->range<<= shift;
@@ -216,62 +179,4 @@ static int av_unused get_cabac_terminate(CABACContext *c){
     }
 }
 
-#if 0
-/**
- * Get (truncated) unary binarization.
- */
-static int get_cabac_u(CABACContext *c, uint8_t * state, int max, int max_index, int truncated){
-    int i;
-
-    for(i=0; i<max; i++){
-        if(get_cabac(c, state)==0)
-            return i;
-
-        if(i< max_index) state++;
-    }
-
-    return truncated ? max : -1;
-}
-
-/**
- * get unary exp golomb k-th order binarization.
- */
-static int get_cabac_ueg(CABACContext *c, uint8_t * state, int max, int is_signed, int k, int max_index){
-    int i, v;
-    int m= 1<<k;
-
-    if(get_cabac(c, state)==0)
-        return 0;
-
-    if(0 < max_index) state++;
-
-    for(i=1; i<max; i++){
-        if(get_cabac(c, state)==0){
-            if(is_signed && get_cabac_bypass(c)){
-                return -i;
-            }else
-                return i;
-        }
-
-        if(i < max_index) state++;
-    }
-
-    while(get_cabac_bypass(c)){
-        i+= m;
-        m+= m;
-    }
-
-    v=0;
-    while(m>>=1){
-        v+= v + get_cabac_bypass(c);
-    }
-    i += v;
-
-    if(is_signed && get_cabac_bypass(c)){
-        return -i;
-    }else
-        return i;
-}
-#endif /* 0 */
-
 #endif /* AVCODEC_CABAC_H */
diff --git a/libavcodec/cavs.c b/libavcodec/cavs.c
index 6f63c23..9ff0e51 100644
--- a/libavcodec/cavs.c
+++ b/libavcodec/cavs.c
@@ -658,8 +658,8 @@ void ff_cavs_init_top_lines(AVSContext *h) {
     h->top_mv[1]    = av_malloc((h->mb_width*2+1)*sizeof(cavs_vector));
     h->top_pred_Y   = av_malloc( h->mb_width*2*sizeof(*h->top_pred_Y));
     h->top_border_y = av_malloc((h->mb_width+1)*16);
-    h->top_border_u = av_malloc((h->mb_width)*10);
-    h->top_border_v = av_malloc((h->mb_width)*10);
+    h->top_border_u = av_malloc( h->mb_width * 10);
+    h->top_border_v = av_malloc( h->mb_width * 10);
 
     /* alloc space for co-located MVs and types */
     h->col_mv       = av_malloc( h->mb_width*h->mb_height*4*sizeof(cavs_vector));
diff --git a/libavcodec/cavsdec.c b/libavcodec/cavsdec.c
index 514752a..2f4b6e3 100644
--- a/libavcodec/cavsdec.c
+++ b/libavcodec/cavsdec.c
@@ -490,7 +490,7 @@ static int decode_pic(AVSContext *h) {
             skip_bits(&s->gb,24);//time_code
         /* old sample clips were all progressive and no low_delay,
            bump stream revision if detected otherwise */
-        if((s->low_delay) || !(show_bits(&s->gb,9) & 1))
+        if (s->low_delay || !(show_bits(&s->gb,9) & 1))
             h->stream_revision = 1;
         /* similarly test top_field_first and repeat_first_field */
         else if(show_bits(&s->gb,11) & 3)
diff --git a/libavcodec/cook.c b/libavcodec/cook.c
index 81a1aae..d2ed819 100644
--- a/libavcodec/cook.c
+++ b/libavcodec/cook.c
@@ -57,7 +57,7 @@
 #define MONO            0x1000001
 #define STEREO          0x1000002
 #define JOINT_STEREO    0x1000003
-#define MC_COOK         0x2000000   //multichannel Cook, not supported
+#define MC_COOK         0x2000000   // multichannel Cook, not supported
 
 #define SUBBAND_SIZE    20
 #define MAX_SUBPACKETS   5
@@ -102,24 +102,24 @@ typedef struct cook {
      * The following 5 functions provide the lowlevel arithmetic on
      * the internal audio buffers.
      */
-    void (* scalar_dequant)(struct cook *q, int index, int quant_index,
-                            int* subband_coef_index, int* subband_coef_sign,
-                            float* mlt_p);
+    void (*scalar_dequant)(struct cook *q, int index, int quant_index,
+                           int *subband_coef_index, int *subband_coef_sign,
+                           float *mlt_p);
 
-    void (* decouple) (struct cook *q,
-                       COOKSubpacket *p,
-                       int subband,
-                       float f1, float f2,
-                       float *decode_buffer,
-                       float *mlt_buffer1, float *mlt_buffer2);
+    void (*decouple)(struct cook *q,
+                     COOKSubpacket *p,
+                     int subband,
+                     float f1, float f2,
+                     float *decode_buffer,
+                     float *mlt_buffer1, float *mlt_buffer2);
 
-    void (* imlt_window) (struct cook *q, float *buffer1,
-                          cook_gains *gains_ptr, float *previous_buffer);
+    void (*imlt_window)(struct cook *q, float *buffer1,
+                        cook_gains *gains_ptr, float *previous_buffer);
 
-    void (* interpolate) (struct cook *q, float* buffer,
-                          int gain_index, int gain_index_next);
+    void (*interpolate)(struct cook *q, float *buffer,
+                        int gain_index, int gain_index_next);
 
-    void (* saturate_output) (struct cook *q, int chan, float *out);
+    void (*saturate_output)(struct cook *q, int chan, float *out);
 
     AVCodecContext*     avctx;
     AVFrame             frame;
@@ -140,7 +140,7 @@ typedef struct cook {
 
     /* VLC data */
     VLC                 envelope_quant_index[13];
-    VLC                 sqvh[7];          //scalar quantization
+    VLC                 sqvh[7];          // scalar quantization
 
     /* generatable tables and related variables */
     int                 gain_size_factor;
@@ -165,55 +165,58 @@ static float rootpow2tab[127];
 /*************** init functions ***************/
 
 /* table generator */
-static av_cold void init_pow2table(void){
+static av_cold void init_pow2table(void)
+{
     int i;
-    for (i=-63 ; i<64 ; i++){
-            pow2tab[63+i]=     pow(2, i);
-        rootpow2tab[63+i]=sqrt(pow(2, i));
+    for (i = -63; i < 64; i++) {
+        pow2tab[63 + i] = pow(2, i);
+        rootpow2tab[63 + i] = sqrt(pow(2, i));
     }
 }
 
 /* table generator */
-static av_cold void init_gain_table(COOKContext *q) {
+static av_cold void init_gain_table(COOKContext *q)
+{
     int i;
-    q->gain_size_factor = q->samples_per_channel/8;
-    for (i=0 ; i<23 ; i++) {
-        q->gain_table[i] = pow(pow2tab[i+52] ,
-                               (1.0/(double)q->gain_size_factor));
-    }
+    q->gain_size_factor = q->samples_per_channel / 8;
+    for (i = 0; i < 23; i++)
+        q->gain_table[i] = pow(pow2tab[i + 52],
+                               (1.0 / (double) q->gain_size_factor));
 }
 
 
-static av_cold int init_cook_vlc_tables(COOKContext *q) {
+static av_cold int init_cook_vlc_tables(COOKContext *q)
+{
     int i, result;
 
     result = 0;
-    for (i=0 ; i<13 ; i++) {
-        result |= init_vlc (&q->envelope_quant_index[i], 9, 24,
-            envelope_quant_index_huffbits[i], 1, 1,
-            envelope_quant_index_huffcodes[i], 2, 2, 0);
+    for (i = 0; i < 13; i++) {
+        result |= init_vlc(&q->envelope_quant_index[i], 9, 24,
+                           envelope_quant_index_huffbits[i], 1, 1,
+                           envelope_quant_index_huffcodes[i], 2, 2, 0);
     }
-    av_log(q->avctx,AV_LOG_DEBUG,"sqvh VLC init\n");
-    for (i=0 ; i<7 ; i++) {
-        result |= init_vlc (&q->sqvh[i], vhvlcsize_tab[i], vhsize_tab[i],
-            cvh_huffbits[i], 1, 1,
-            cvh_huffcodes[i], 2, 2, 0);
+    av_log(q->avctx, AV_LOG_DEBUG, "sqvh VLC init\n");
+    for (i = 0; i < 7; i++) {
+        result |= init_vlc(&q->sqvh[i], vhvlcsize_tab[i], vhsize_tab[i],
+                           cvh_huffbits[i], 1, 1,
+                           cvh_huffcodes[i], 2, 2, 0);
     }
 
-    for(i=0;i<q->num_subpackets;i++){
-        if (q->subpacket[i].joint_stereo==1){
-            result |= init_vlc (&q->subpacket[i].ccpl, 6, (1<<q->subpacket[i].js_vlc_bits)-1,
-                ccpl_huffbits[q->subpacket[i].js_vlc_bits-2], 1, 1,
-                ccpl_huffcodes[q->subpacket[i].js_vlc_bits-2], 2, 2, 0);
-            av_log(q->avctx,AV_LOG_DEBUG,"subpacket %i Joint-stereo VLC used.\n",i);
+    for (i = 0; i < q->num_subpackets; i++) {
+        if (q->subpacket[i].joint_stereo == 1) {
+            result |= init_vlc(&q->subpacket[i].ccpl, 6, (1 << q->subpacket[i].js_vlc_bits) - 1,
+                               ccpl_huffbits[q->subpacket[i].js_vlc_bits - 2], 1, 1,
+                               ccpl_huffcodes[q->subpacket[i].js_vlc_bits - 2], 2, 2, 0);
+            av_log(q->avctx, AV_LOG_DEBUG, "subpacket %i Joint-stereo VLC used.\n", i);
         }
     }
 
-    av_log(q->avctx,AV_LOG_DEBUG,"VLC tables initialized.\n");
+    av_log(q->avctx, AV_LOG_DEBUG, "VLC tables initialized.\n");
     return result;
 }
 
-static av_cold int init_cook_mlt(COOKContext *q) {
+static av_cold int init_cook_mlt(COOKContext *q)
+{
     int j, ret;
     int mlt_size = q->samples_per_channel;
 
@@ -222,35 +225,36 @@ static av_cold int init_cook_mlt(COOKContext *q) {
 
     /* Initialize the MLT window: simple sine window. */
     ff_sine_window_init(q->mlt_window, mlt_size);
-    for(j=0 ; j<mlt_size ; j++)
+    for (j = 0; j < mlt_size; j++)
         q->mlt_window[j] *= sqrt(2.0 / q->samples_per_channel);
 
     /* Initialize the MDCT. */
-    if ((ret = ff_mdct_init(&q->mdct_ctx, av_log2(mlt_size)+1, 1, 1.0/32768.0))) {
+    if ((ret = ff_mdct_init(&q->mdct_ctx, av_log2(mlt_size) + 1, 1, 1.0 / 32768.0))) {
         av_free(q->mlt_window);
         return ret;
     }
-    av_log(q->avctx,AV_LOG_DEBUG,"MDCT initialized, order = %d.\n",
-           av_log2(mlt_size)+1);
+    av_log(q->avctx, AV_LOG_DEBUG, "MDCT initialized, order = %d.\n",
+           av_log2(mlt_size) + 1);
 
     return 0;
 }
 
-static const float *maybe_reformat_buffer32 (COOKContext *q, const float *ptr, int n)
+static const float *maybe_reformat_buffer32(COOKContext *q, const float *ptr, int n)
 {
     if (1)
         return ptr;
 }
 
-static av_cold void init_cplscales_table (COOKContext *q) {
+static av_cold void init_cplscales_table(COOKContext *q)
+{
     int i;
-    for (i=0;i<5;i++)
-        q->cplscales[i] = maybe_reformat_buffer32 (q, cplscales[i], (1<<(i+2))-1);
+    for (i = 0; i < 5; i++)
+        q->cplscales[i] = maybe_reformat_buffer32(q, cplscales[i], (1 << (i + 2)) - 1);
 }
 
 /*************** init functions end ***********/
 
-#define DECODE_BYTES_PAD1(bytes) (3 - ((bytes)+3) % 4)
+#define DECODE_BYTES_PAD1(bytes) (3 - ((bytes) + 3) % 4)
 #define DECODE_BYTES_PAD2(bytes) ((bytes) % 4 + DECODE_BYTES_PAD1(2 * (bytes)))
 
 /**
@@ -273,27 +277,27 @@ static av_cold void init_cplscales_table (COOKContext *q) {
  * @param out       pointer to byte array of outdata
  * @param bytes     number of bytes
  */
-
-static inline int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
+static inline int decode_bytes(const uint8_t *inbuffer, uint8_t *out, int bytes)
+{
     static const uint32_t tab[4] = {
         AV_BE2NE32C(0x37c511f2), AV_BE2NE32C(0xf237c511),
         AV_BE2NE32C(0x11f237c5), AV_BE2NE32C(0xc511f237),
     };
     int i, off;
     uint32_t c;
-    const uint32_t* buf;
-    uint32_t* obuf = (uint32_t*) out;
+    const uint32_t *buf;
+    uint32_t *obuf = (uint32_t *) out;
     /* FIXME: 64 bit platforms would be able to do 64 bits at a time.
      * I'm too lazy though, should be something like
-     * for(i=0 ; i<bitamount/64 ; i++)
-     *     (int64_t)out[i] = 0x37c511f237c511f2^av_be2ne64(int64_t)in[i]);
+     * for (i = 0; i < bitamount / 64; i++)
+     *     (int64_t) out[i] = 0x37c511f237c511f2 ^ av_be2ne64(int64_t) in[i]);
      * Buffer alignment needs to be checked. */
 
-    off = (intptr_t)inbuffer & 3;
-    buf = (const uint32_t*) (inbuffer - off);
+    off = (intptr_t) inbuffer & 3;
+    buf = (const uint32_t *) (inbuffer - off);
     c = tab[off];
     bytes += 3 + off;
-    for (i = 0; i < bytes/4; i++)
+    for (i = 0; i < bytes / 4; i++)
         obuf[i] = c ^ buf[i];
 
     return off;
@@ -302,12 +306,11 @@ static inline int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes)
 /**
  * Cook uninit
  */
-
 static av_cold int cook_decode_close(AVCodecContext *avctx)
 {
     int i;
     COOKContext *q = avctx->priv_data;
-    av_log(avctx,AV_LOG_DEBUG, "Deallocating memory.\n");
+    av_log(avctx, AV_LOG_DEBUG, "Deallocating memory.\n");
 
     /* Free allocated memory buffers. */
     av_free(q->mlt_window);
@@ -317,17 +320,14 @@ static av_cold int cook_decode_close(AVCodecContext *avctx)
     ff_mdct_end(&q->mdct_ctx);
 
     /* Free the VLC tables. */
-    for (i=0 ; i<13 ; i++) {
+    for (i = 0; i < 13; i++)
         free_vlc(&q->envelope_quant_index[i]);
-    }
-    for (i=0 ; i<7 ; i++) {
+    for (i = 0; i < 7; i++)
         free_vlc(&q->sqvh[i]);
-    }
-    for (i=0 ; i<q->num_subpackets ; i++) {
+    for (i = 0; i < q->num_subpackets; i++)
         free_vlc(&q->subpacket[i].ccpl);
-    }
 
-    av_log(avctx,AV_LOG_DEBUG,"Memory deallocated.\n");
+    av_log(avctx, AV_LOG_DEBUG, "Memory deallocated.\n");
 
     return 0;
 }
@@ -338,22 +338,26 @@ static av_cold int cook_decode_close(AVCodecContext *avctx)
  * @param gb          pointer to the GetBitContext
  * @param gaininfo    array[9] of gain indexes
  */
-
 static void decode_gain_info(GetBitContext *gb, int *gaininfo)
 {
     int i, n;
 
-    while (get_bits1(gb)) {}
-    n = get_bits_count(gb) - 1;     //amount of elements*2 to update
+    while (get_bits1(gb)) {
+        /* NOTHING */
+    }
+
+    n = get_bits_count(gb) - 1;     // amount of elements*2 to update
 
     i = 0;
     while (n--) {
         int index = get_bits(gb, 3);
         int gain = get_bits1(gb) ? get_bits(gb, 4) - 7 : -1;
 
-        while (i <= index) gaininfo[i++] = gain;
+        while (i <= index)
+            gaininfo[i++] = gain;
     }
-    while (i <= 8) gaininfo[i++] = 0;
+    while (i <= 8)
+        gaininfo[i++] = 0;
 }
 
 /**
@@ -362,25 +366,28 @@ static void decode_gain_info(GetBitContext *gb, int *gaininfo)
  * @param q                 pointer to the COOKContext
  * @param quant_index_table pointer to the array
  */
+static void decode_envelope(COOKContext *q, COOKSubpacket *p,
+                            int *quant_index_table)
+{
+    int i, j, vlc_index;
 
-static void decode_envelope(COOKContext *q, COOKSubpacket *p, int* quant_index_table) {
-    int i,j, vlc_index;
-
-    quant_index_table[0]= get_bits(&q->gb,6) - 6;       //This is used later in categorize
+    quant_index_table[0] = get_bits(&q->gb, 6) - 6; // This is used later in categorize
 
-    for (i=1 ; i < p->total_subbands ; i++){
-        vlc_index=i;
+    for (i = 1; i < p->total_subbands; i++) {
+        vlc_index = i;
         if (i >= p->js_subband_start * 2) {
-            vlc_index-=p->js_subband_start;
+            vlc_index -= p->js_subband_start;
         } else {
-            vlc_index/=2;
-            if(vlc_index < 1) vlc_index = 1;
+            vlc_index /= 2;
+            if (vlc_index < 1)
+                vlc_index = 1;
         }
-        if (vlc_index>13) vlc_index = 13;           //the VLC tables >13 are identical to No. 13
+        if (vlc_index > 13)
+            vlc_index = 13; // the VLC tables >13 are identical to No. 13
 
-        j = get_vlc2(&q->gb, q->envelope_quant_index[vlc_index-1].table,
-                     q->envelope_quant_index[vlc_index-1].bits,2);
-        quant_index_table[i] = quant_index_table[i-1] + j - 12;    //differential encoding
+        j = get_vlc2(&q->gb, q->envelope_quant_index[vlc_index - 1].table,
+                     q->envelope_quant_index[vlc_index - 1].bits, 2);
+        quant_index_table[i] = quant_index_table[i - 1] + j - 12; // differential encoding
     }
 }
 
@@ -392,22 +399,22 @@ static void decode_envelope(COOKContext *q, COOKSubpacket *p, int* quant_index_t
  * @param category              pointer to the category array
  * @param category_index        pointer to the category_index array
  */
-
-static void categorize(COOKContext *q, COOKSubpacket *p, int* quant_index_table,
-                       int* category, int* category_index){
+static void categorize(COOKContext *q, COOKSubpacket *p, int *quant_index_table,
+                       int *category, int *category_index)
+{
     int exp_idx, bias, tmpbias1, tmpbias2, bits_left, num_bits, index, v, i, j;
     int exp_index2[102];
     int exp_index1[102];
 
-    int tmp_categorize_array[128*2];
-    int tmp_categorize_array1_idx=p->numvector_size;
-    int tmp_categorize_array2_idx=p->numvector_size;
+    int tmp_categorize_array[128 * 2];
+    int tmp_categorize_array1_idx = p->numvector_size;
+    int tmp_categorize_array2_idx = p->numvector_size;
 
-    bits_left =  p->bits_per_subpacket - get_bits_count(&q->gb);
+    bits_left = p->bits_per_subpacket - get_bits_count(&q->gb);
 
-    if(bits_left > q->samples_per_channel) {
+    if (bits_left > q->samples_per_channel) {
         bits_left = q->samples_per_channel +
-                    ((bits_left - q->samples_per_channel)*5)/8;
+                    ((bits_left - q->samples_per_channel) * 5) / 8;
         //av_log(q->avctx, AV_LOG_ERROR, "bits_left = %d\n",bits_left);
     }
 
@@ -415,25 +422,24 @@ static void categorize(COOKContext *q, COOKSubpacket *p, int* quant_index_table,
     memset(&exp_index2,           0, sizeof(exp_index2));
     memset(&tmp_categorize_array, 0, sizeof(tmp_categorize_array));
 
-    bias=-32;
+    bias = -32;
 
     /* Estimate bias. */
-    for (i=32 ; i>0 ; i=i/2){
+    for (i = 32; i > 0; i = i / 2) {
         num_bits = 0;
-        index = 0;
-        for (j=p->total_subbands ; j>0 ; j--){
+        index    = 0;
+        for (j = p->total_subbands; j > 0; j--) {
             exp_idx = av_clip((i - quant_index_table[index] + bias) / 2, 0, 7);
             index++;
-            num_bits+=expbits_tab[exp_idx];
-        }
-        if(num_bits >= bits_left - 32){
-            bias+=i;
+            num_bits += expbits_tab[exp_idx];
         }
+        if (num_bits >= bits_left - 32)
+            bias += i;
     }
 
     /* Calculate total number of bits. */
-    num_bits=0;
-    for (i=0 ; i<p->total_subbands ; i++) {
+    num_bits = 0;
+    for (i = 0; i < p->total_subbands; i++) {
         exp_idx = av_clip((bias - quant_index_table[i]) / 2, 0, 7);
         num_bits += expbits_tab[exp_idx];
         exp_index1[i] = exp_idx;
@@ -441,50 +447,51 @@ static void categorize(COOKContext *q, COOKSubpacket *p, int* quant_index_table,
     }
     tmpbias1 = tmpbias2 = num_bits;
 
-    for (j = 1 ; j < p->numvector_size ; j++) {
-        if (tmpbias1 + tmpbias2 > 2*bits_left) {  /* ---> */
+    for (j = 1; j < p->numvector_size; j++) {
+        if (tmpbias1 + tmpbias2 > 2 * bits_left) {  /* ---> */
             int max = -999999;
-            index=-1;
-            for (i=0 ; i<p->total_subbands ; i++){
+            index = -1;
+            for (i = 0; i < p->total_subbands; i++) {
                 if (exp_index1[i] < 7) {
-                    v = (-2*exp_index1[i]) - quant_index_table[i] + bias;
-                    if ( v >= max) {
-                        max = v;
+                    v = (-2 * exp_index1[i]) - quant_index_table[i] + bias;
+                    if (v >= max) {
+                        max   = v;
                         index = i;
                     }
                 }
             }
-            if(index==-1)break;
+            if (index == -1)
+                break;
             tmp_categorize_array[tmp_categorize_array1_idx++] = index;
             tmpbias1 -= expbits_tab[exp_index1[index]] -
-                        expbits_tab[exp_index1[index]+1];
+                        expbits_tab[exp_index1[index] + 1];
             ++exp_index1[index];
         } else {  /* <--- */
             int min = 999999;
-            index=-1;
-            for (i=0 ; i<p->total_subbands ; i++){
-                if(exp_index2[i] > 0){
-                    v = (-2*exp_index2[i])-quant_index_table[i]+bias;
-                    if ( v < min) {
-                        min = v;
+            index = -1;
+            for (i = 0; i < p->total_subbands; i++) {
+                if (exp_index2[i] > 0) {
+                    v = (-2 * exp_index2[i]) - quant_index_table[i] + bias;
+                    if (v < min) {
+                        min   = v;
                         index = i;
                     }
                 }
             }
-            if(index == -1)break;
+            if (index == -1)
+                break;
             tmp_categorize_array[--tmp_categorize_array2_idx] = index;
             tmpbias2 -= expbits_tab[exp_index2[index]] -
-                        expbits_tab[exp_index2[index]-1];
+                        expbits_tab[exp_index2[index] - 1];
             --exp_index2[index];
         }
     }
 
-    for(i=0 ; i<p->total_subbands ; i++)
+    for (i = 0; i < p->total_subbands; i++)
         category[i] = exp_index2[i];
 
-    for(i=0 ; i<p->numvector_size-1 ; i++)
+    for (i = 0; i < p->numvector_size - 1; i++)
         category_index[i] = tmp_categorize_array[tmp_categorize_array2_idx++];
-
 }
 
 
@@ -495,13 +502,12 @@ static void categorize(COOKContext *q, COOKSubpacket *p, int* quant_index_table,
  * @param category              pointer to the category array
  * @param category_index        pointer to the category_index array
  */
-
-static inline void expand_category(COOKContext *q, int* category,
-                                   int* category_index){
+static inline void expand_category(COOKContext *q, int *category,
+                                   int *category_index)
+{
     int i;
-    for(i=0 ; i<q->num_vectors ; i++){
+    for (i = 0; i < q->num_vectors; i++)
         ++category[category_index[i]];
-    }
 }
 
 /**
@@ -514,23 +520,25 @@ static inline void expand_category(COOKContext *q, int* category,
  * @param subband_coef_sign     signs of coefficients
  * @param mlt_p                 pointer into the mlt buffer
  */
-
 static void scalar_dequant_float(COOKContext *q, int index, int quant_index,
-                           int* subband_coef_index, int* subband_coef_sign,
-                           float* mlt_p){
+                                 int *subband_coef_index, int *subband_coef_sign,
+                                 float *mlt_p)
+{
     int i;
     float f1;
 
-    for(i=0 ; i<SUBBAND_SIZE ; i++) {
+    for (i = 0; i < SUBBAND_SIZE; i++) {
         if (subband_coef_index[i]) {
             f1 = quant_centroid_tab[index][subband_coef_index[i]];
-            if (subband_coef_sign[i]) f1 = -f1;
+            if (subband_coef_sign[i])
+                f1 = -f1;
         } else {
             /* noise coding if subband_coef_index[i] == 0 */
             f1 = dither_tab[index];
-            if (av_lfg_get(&q->random_state) < 0x80000000) f1 = -f1;
+            if (av_lfg_get(&q->random_state) < 0x80000000)
+                f1 = -f1;
         }
-        mlt_p[i] = f1 * rootpow2tab[quant_index+63];
+        mlt_p[i] = f1 * rootpow2tab[quant_index + 63];
     }
 }
 /**
@@ -541,35 +549,35 @@ static void scalar_dequant_float(COOKContext *q, int index, int quant_index,
  * @param subband_coef_index    array of indexes to quant_centroid_tab
  * @param subband_coef_sign     signs of coefficients
  */
-
-static int unpack_SQVH(COOKContext *q, COOKSubpacket *p, int category, int* subband_coef_index,
-                       int* subband_coef_sign) {
-    int i,j;
-    int vlc, vd ,tmp, result;
+static int unpack_SQVH(COOKContext *q, COOKSubpacket *p, int category,
+                       int *subband_coef_index, int *subband_coef_sign)
+{
+    int i, j;
+    int vlc, vd, tmp, result;
 
     vd = vd_tab[category];
     result = 0;
-    for(i=0 ; i<vpr_tab[category] ; i++){
+    for (i = 0; i < vpr_tab[category]; i++) {
         vlc = get_vlc2(&q->gb, q->sqvh[category].table, q->sqvh[category].bits, 3);
-        if (p->bits_per_subpacket < get_bits_count(&q->gb)){
+        if (p->bits_per_subpacket < get_bits_count(&q->gb)) {
             vlc = 0;
             result = 1;
         }
-        for(j=vd-1 ; j>=0 ; j--){
-            tmp = (vlc * invradix_tab[category])/0x100000;
-            subband_coef_index[vd*i+j] = vlc - tmp * (kmax_tab[category]+1);
+        for (j = vd - 1; j >= 0; j--) {
+            tmp = (vlc * invradix_tab[category]) / 0x100000;
+            subband_coef_index[vd * i + j] = vlc - tmp * (kmax_tab[category] + 1);
             vlc = tmp;
         }
-        for(j=0 ; j<vd ; j++){
-            if (subband_coef_index[i*vd + j]) {
-                if(get_bits_count(&q->gb) < p->bits_per_subpacket){
-                    subband_coef_sign[i*vd+j] = get_bits1(&q->gb);
+        for (j = 0; j < vd; j++) {
+            if (subband_coef_index[i * vd + j]) {
+                if (get_bits_count(&q->gb) < p->bits_per_subpacket) {
+                    subband_coef_sign[i * vd + j] = get_bits1(&q->gb);
                 } else {
-                    result=1;
-                    subband_coef_sign[i*vd+j]=0;
+                    result = 1;
+                    subband_coef_sign[i * vd + j] = 0;
                 }
             } else {
-                subband_coef_sign[i*vd+j]=0;
+                subband_coef_sign[i * vd + j] = 0;
             }
         }
     }
@@ -585,10 +593,9 @@ static int unpack_SQVH(COOKContext *q, COOKSubpacket *p, int category, int* subb
  * @param quant_index_table pointer to the array
  * @param mlt_buffer        pointer to mlt coefficients
  */
-
-
-static void decode_vectors(COOKContext* q, COOKSubpacket* p, int* category,
-                           int *quant_index_table, float* mlt_buffer){
+static void decode_vectors(COOKContext *q, COOKSubpacket *p, int *category,
+                           int *quant_index_table, float *mlt_buffer)
+{
     /* A zero in this table means that the subband coefficient is
        random noise coded. */
     int subband_coef_index[SUBBAND_SIZE];
@@ -596,28 +603,29 @@ static void decode_vectors(COOKContext* q, COOKSubpacket* p, int* category,
        positive multiplicator. */
     int subband_coef_sign[SUBBAND_SIZE];
     int band, j;
-    int index=0;
+    int index = 0;
 
-    for(band=0 ; band<p->total_subbands ; band++){
+    for (band = 0; band < p->total_subbands; band++) {
         index = category[band];
-        if(category[band] < 7){
-            if(unpack_SQVH(q, p, category[band], subband_coef_index, subband_coef_sign)){
-                index=7;
-                for(j=0 ; j<p->total_subbands ; j++) category[band+j]=7;
+        if (category[band] < 7) {
+            if (unpack_SQVH(q, p, category[band], subband_coef_index, subband_coef_sign)) {
+                index = 7;
+                for (j = 0; j < p->total_subbands; j++)
+                    category[band + j] = 7;
             }
         }
-        if(index>=7) {
+        if (index >= 7) {
             memset(subband_coef_index, 0, sizeof(subband_coef_index));
-            memset(subband_coef_sign, 0, sizeof(subband_coef_sign));
+            memset(subband_coef_sign,  0, sizeof(subband_coef_sign));
         }
         q->scalar_dequant(q, index, quant_index_table[band],
                           subband_coef_index, subband_coef_sign,
                           &mlt_buffer[band * SUBBAND_SIZE]);
     }
 
-    if(p->total_subbands*SUBBAND_SIZE >= q->samples_per_channel){
+    /* FIXME: should this be removed, or moved into loop above? */
+    if (p->total_subbands * SUBBAND_SIZE >= q->samples_per_channel)
         return;
-    } /* FIXME: should this be removed, or moved into loop above? */
 }
 
 
@@ -627,9 +635,8 @@ static void decode_vectors(COOKContext* q, COOKSubpacket* p, int* category,
  * @param q                 pointer to the COOKContext
  * @param mlt_buffer        pointer to mlt coefficients
  */
-
-static void mono_decode(COOKContext *q, COOKSubpacket *p, float* mlt_buffer) {
-
+static void mono_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer)
+{
     int category_index[128];
     int quant_index_table[102];
     int category[128];
@@ -638,7 +645,7 @@ static void mono_decode(COOKContext *q, COOKSubpacket *p, float* mlt_buffer) {
     memset(&category_index, 0, sizeof(category_index));
 
     decode_envelope(q, p, quant_index_table);
-    q->num_vectors = get_bits(&q->gb,p->log2_numvector_size);
+    q->num_vectors = get_bits(&q->gb, p->log2_numvector_size);
     categorize(q, p, quant_index_table, category, category_index);
     expand_category(q, category, category_index);
     decode_vectors(q, p, category, quant_index_table, mlt_buffer);
@@ -653,22 +660,21 @@ static void mono_decode(COOKContext *q, COOKSubpacket *p, float* mlt_buffer) {
  * @param gain_index        index for the block multiplier
  * @param gain_index_next   index for the next block multiplier
  */
-
-static void interpolate_float(COOKContext *q, float* buffer,
-                        int gain_index, int gain_index_next){
+static void interpolate_float(COOKContext *q, float *buffer,
+                              int gain_index, int gain_index_next)
+{
     int i;
     float fc1, fc2;
-    fc1 = pow2tab[gain_index+63];
-
-    if(gain_index == gain_index_next){              //static gain
-        for(i=0 ; i<q->gain_size_factor ; i++){
-            buffer[i]*=fc1;
-        }
-    } else {                                        //smooth gain
-        fc2 = q->gain_table[11 + (gain_index_next-gain_index)];
-        for(i=0 ; i<q->gain_size_factor ; i++){
-            buffer[i]*=fc1;
-            fc1*=fc2;
+    fc1 = pow2tab[gain_index + 63];
+
+    if (gain_index == gain_index_next) {             // static gain
+        for (i = 0; i < q->gain_size_factor; i++)
+            buffer[i] *= fc1;
+    } else {                                        // smooth gain
+        fc2 = q->gain_table[11 + (gain_index_next - gain_index)];
+        for (i = 0; i < q->gain_size_factor; i++) {
+            buffer[i] *= fc1;
+            fc1       *= fc2;
         }
     }
 }
@@ -681,9 +687,8 @@ static void interpolate_float(COOKContext *q, float* buffer,
  * @param gains_ptr         current and previous gains
  * @param previous_buffer   pointer to the previous buffer to be used for overlapping
  */
-
-static void imlt_window_float (COOKContext *q, float *inbuffer,
-                               cook_gains *gains_ptr, float *previous_buffer)
+static void imlt_window_float(COOKContext *q, float *inbuffer,
+                              cook_gains *gains_ptr, float *previous_buffer)
 {
     const float fc = pow2tab[gains_ptr->previous[0] + 63];
     int i;
@@ -694,10 +699,9 @@ static void imlt_window_float (COOKContext *q, float *inbuffer,
      */
 
     /* Apply window and overlap */
-    for(i = 0; i < q->samples_per_channel; i++){
+    for (i = 0; i < q->samples_per_channel; i++)
         inbuffer[i] = inbuffer[i] * fc * q->mlt_window[i] -
-          previous_buffer[i] * q->mlt_window[q->samples_per_channel - 1 - i];
-    }
+                      previous_buffer[i] * q->mlt_window[q->samples_per_channel - 1 - i];
 }
 
 /**
@@ -711,9 +715,8 @@ static void imlt_window_float (COOKContext *q, float *inbuffer,
  * @param gains_ptr         current and previous gains
  * @param previous_buffer   pointer to the previous buffer to be used for overlapping
  */
-
 static void imlt_gain(COOKContext *q, float *inbuffer,
-                      cook_gains *gains_ptr, float* previous_buffer)
+                      cook_gains *gains_ptr, float *previous_buffer)
 {
     float *buffer0 = q->mono_mdct_output;
     float *buffer1 = q->mono_mdct_output + q->samples_per_channel;
@@ -722,14 +725,13 @@ static void imlt_gain(COOKContext *q, float *inbuffer,
     /* Inverse modified discrete cosine transform */
     q->mdct_ctx.imdct_calc(&q->mdct_ctx, q->mono_mdct_output, inbuffer);
 
-    q->imlt_window (q, buffer1, gains_ptr, previous_buffer);
+    q->imlt_window(q, buffer1, gains_ptr, previous_buffer);
 
     /* Apply gain profile */
-    for (i = 0; i < 8; i++) {
+    for (i = 0; i < 8; i++)
         if (gains_ptr->now[i] || gains_ptr->now[i + 1])
             q->interpolate(q, &buffer1[q->gain_size_factor * i],
                            gains_ptr->now[i], gains_ptr->now[i + 1]);
-    }
 
     /* Save away the current to be previous block. */
     memcpy(previous_buffer, buffer0,
@@ -749,19 +751,18 @@ static void decouple_info(COOKContext *q, COOKSubpacket *p, int *decouple_tab)
     int i;
     int vlc    = get_bits1(&q->gb);
     int start  = cplband[p->js_subband_start];
-    int end    = cplband[p->subbands-1];
+    int end    = cplband[p->subbands - 1];
     int length = end - start + 1;
 
     if (start > end)
         return;
 
-    if (vlc) {
+    if (vlc)
         for (i = 0; i < length; i++)
             decouple_tab[start + i] = get_vlc2(&q->gb, p->ccpl.table, p->ccpl.bits, 2);
-    } else {
+    else
         for (i = 0; i < length; i++)
             decouple_tab[start + i] = get_bits(&q->gb, p->js_vlc_bits);
-    }
 }
 
 /*
@@ -775,18 +776,18 @@ static void decouple_info(COOKContext *q, COOKSubpacket *p, int *decouple_tab)
  * @param mlt_buffer1       pointer to left channel mlt coefficients
  * @param mlt_buffer2       pointer to right channel mlt coefficients
  */
-static void decouple_float (COOKContext *q,
-                            COOKSubpacket *p,
-                            int subband,
-                            float f1, float f2,
-                            float *decode_buffer,
-                            float *mlt_buffer1, float *mlt_buffer2)
+static void decouple_float(COOKContext *q,
+                           COOKSubpacket *p,
+                           int subband,
+                           float f1, float f2,
+                           float *decode_buffer,
+                           float *mlt_buffer1, float *mlt_buffer2)
 {
     int j, tmp_idx;
-    for (j=0 ; j<SUBBAND_SIZE ; j++) {
-        tmp_idx = ((p->js_subband_start + subband)*SUBBAND_SIZE)+j;
-        mlt_buffer1[SUBBAND_SIZE*subband + j] = f1 * decode_buffer[tmp_idx];
-        mlt_buffer2[SUBBAND_SIZE*subband + j] = f2 * decode_buffer[tmp_idx];
+    for (j = 0; j < SUBBAND_SIZE; j++) {
+        tmp_idx = ((p->js_subband_start + subband) * SUBBAND_SIZE) + j;
+        mlt_buffer1[SUBBAND_SIZE * subband + j] = f1 * decode_buffer[tmp_idx];
+        mlt_buffer2[SUBBAND_SIZE * subband + j] = f2 * decode_buffer[tmp_idx];
     }
 }
 
@@ -797,15 +798,15 @@ static void decouple_float (COOKContext *q,
  * @param mlt_buffer1       pointer to left channel mlt coefficients
  * @param mlt_buffer2       pointer to right channel mlt coefficients
  */
-
-static void joint_decode(COOKContext *q, COOKSubpacket *p, float* mlt_buffer1,
-                         float* mlt_buffer2) {
-    int i,j;
+static void joint_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer1,
+                         float *mlt_buffer2)
+{
+    int i, j;
     int decouple_tab[SUBBAND_SIZE];
     float *decode_buffer = q->decode_buffer_0;
     int idx, cpl_tmp;
-    float f1,f2;
-    const float* cplscale;
+    float f1, f2;
+    const float *cplscale;
 
     memset(decouple_tab, 0, sizeof(decouple_tab));
     memset(decode_buffer, 0, sizeof(q->decode_buffer_0));
@@ -817,23 +818,23 @@ static void joint_decode(COOKContext *q, COOKSubpacket *p, float* mlt_buffer1,
     mono_decode(q, p, decode_buffer);
 
     /* The two channels are stored interleaved in decode_buffer. */
-    for (i=0 ; i<p->js_subband_start ; i++) {
-        for (j=0 ; j<SUBBAND_SIZE ; j++) {
-            mlt_buffer1[i*20+j] = decode_buffer[i*40+j];
-            mlt_buffer2[i*20+j] = decode_buffer[i*40+20+j];
+    for (i = 0; i < p->js_subband_start; i++) {
+        for (j = 0; j < SUBBAND_SIZE; j++) {
+            mlt_buffer1[i * 20 + j] = decode_buffer[i * 40 + j];
+            mlt_buffer2[i * 20 + j] = decode_buffer[i * 40 + 20 + j];
         }
     }
 
     /* When we reach js_subband_start (the higher frequencies)
        the coefficients are stored in a coupling scheme. */
     idx = (1 << p->js_vlc_bits) - 1;
-    for (i=p->js_subband_start ; i<p->subbands ; i++) {
+    for (i = p->js_subband_start; i < p->subbands; i++) {
         cpl_tmp = cplband[i];
-        idx -=decouple_tab[cpl_tmp];
-        cplscale = q->cplscales[p->js_vlc_bits-2];  //choose decoupler table
+        idx -= decouple_tab[cpl_tmp];
+        cplscale = q->cplscales[p->js_vlc_bits - 2];  // choose decoupler table
         f1 = cplscale[decouple_tab[cpl_tmp]];
-        f2 = cplscale[idx-1];
-        q->decouple (q, p, i, f1, f2, decode_buffer, mlt_buffer1, mlt_buffer2);
+        f2 = cplscale[idx - 1];
+        q->decouple(q, p, i, f1, f2, decode_buffer, mlt_buffer1, mlt_buffer2);
         idx = (1 << p->js_vlc_bits) - 1;
     }
 }
@@ -846,15 +847,14 @@ static void joint_decode(COOKContext *q, COOKSubpacket *p, float* mlt_buffer1,
  * @param inbuffer          pointer to raw stream data
  * @param gains_ptr         array of current/prev gain pointers
  */
-
-static inline void
-decode_bytes_and_gain(COOKContext *q, COOKSubpacket *p, const uint8_t *inbuffer,
-                      cook_gains *gains_ptr)
+static inline void decode_bytes_and_gain(COOKContext *q, COOKSubpacket *p,
+                                         const uint8_t *inbuffer,
+                                         cook_gains *gains_ptr)
 {
     int offset;
 
     offset = decode_bytes(inbuffer, q->decoded_bytes_buffer,
-                          p->bits_per_subpacket/8);
+                          p->bits_per_subpacket / 8);
     init_get_bits(&q->gb, q->decoded_bytes_buffer + offset,
                   p->bits_per_subpacket);
     decode_gain_info(&q->gb, gains_ptr->now);
@@ -863,7 +863,7 @@ decode_bytes_and_gain(COOKContext *q, COOKSubpacket *p, const uint8_t *inbuffer,
     FFSWAP(int *, gains_ptr->now, gains_ptr->previous);
 }
 
- /**
+/**
  * Saturate the output signal and interleave.
  *
  * @param q                 pointer to the COOKContext
@@ -891,11 +891,9 @@ static void saturate_output_float(COOKContext *q, int chan, float *out)
  * @param out               pointer to the output buffer
  * @param chan              0: left or single channel, 1: right channel
  */
-
-static inline void
-mlt_compensate_output(COOKContext *q, float *decode_buffer,
-                      cook_gains *gains_ptr, float *previous_buffer,
-                      float *out, int chan)
+static inline void mlt_compensate_output(COOKContext *q, float *decode_buffer,
+                                         cook_gains *gains_ptr, float *previous_buffer,
+                                         float *out, int chan)
 {
     imlt_gain(q, decode_buffer, gains_ptr, previous_buffer);
     if (out)
@@ -916,11 +914,10 @@ static void decode_subpacket(COOKContext *q, COOKSubpacket *p,
 {
     int sub_packet_size = p->size;
     /* packet dump */
-//    for (i=0 ; i<sub_packet_size ; i++) {
-//        av_log(q->avctx, AV_LOG_ERROR, "%02x", inbuffer[i]);
-//    }
-//    av_log(q->avctx, AV_LOG_ERROR, "\n");
-    memset(q->decode_buffer_1,0,sizeof(q->decode_buffer_1));
+    // for (i = 0; i < sub_packet_size ; i++)
+    //     av_log(q->avctx, AV_LOG_ERROR, "%02x", inbuffer[i]);
+    // av_log(q->avctx, AV_LOG_ERROR, "\n");
+    memset(q->decode_buffer_1, 0, sizeof(q->decode_buffer_1));
     decode_bytes_and_gain(q, p, inbuffer, &p->gains1);
 
     if (p->joint_stereo) {
@@ -929,7 +926,7 @@ static void decode_subpacket(COOKContext *q, COOKSubpacket *p,
         mono_decode(q, p, q->decode_buffer_1);
 
         if (p->num_channels == 2) {
-            decode_bytes_and_gain(q, p, inbuffer + sub_packet_size/2, &p->gains2);
+            decode_bytes_and_gain(q, p, inbuffer + sub_packet_size / 2, &p->gains2);
             mono_decode(q, p, q->decode_buffer_2);
         }
     }
@@ -937,16 +934,13 @@ static void decode_subpacket(COOKContext *q, COOKSubpacket *p,
     mlt_compensate_output(q, q->decode_buffer_1, &p->gains1,
                           p->mono_previous_buffer1, outbuffer, p->ch_idx);
 
-    if (p->num_channels == 2) {
-        if (p->joint_stereo) {
+    if (p->num_channels == 2)
+        if (p->joint_stereo)
             mlt_compensate_output(q, q->decode_buffer_2, &p->gains1,
                                   p->mono_previous_buffer2, outbuffer, p->ch_idx + 1);
-         } else {
+        else
             mlt_compensate_output(q, q->decode_buffer_2, &p->gains2,
                                   p->mono_previous_buffer2, outbuffer, p->ch_idx + 1);
-         }
-     }
-
 }
 
 
@@ -955,7 +949,6 @@ static void decode_subpacket(COOKContext *q, COOKSubpacket *p,
  *
  * @param avctx     pointer to the AVCodecContext
  */
-
 static int cook_decode_frame(AVCodecContext *avctx, void *data,
                              int *got_frame_ptr, AVPacket *avpkt)
 {
@@ -977,30 +970,37 @@ static int cook_decode_frame(AVCodecContext *avctx, void *data,
             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
             return ret;
         }
-        samples = (float *)q->frame.data[0];
+        samples = (float *) q->frame.data[0];
     }
 
     /* estimate subpacket sizes */
     q->subpacket[0].size = avctx->block_align;
 
-    for(i=1;i<q->num_subpackets;i++){
+    for (i = 1; i < q->num_subpackets; i++) {
         q->subpacket[i].size = 2 * buf[avctx->block_align - q->num_subpackets + i];
         q->subpacket[0].size -= q->subpacket[i].size + 1;
         if (q->subpacket[0].size < 0) {
-            av_log(avctx,AV_LOG_DEBUG,"frame subpacket size total > avctx->block_align!\n");
+            av_log(avctx, AV_LOG_DEBUG,
+                   "frame subpacket size total > avctx->block_align!\n");
             return AVERROR_INVALIDDATA;
         }
     }
 
     /* decode supbackets */
-    for(i=0;i<q->num_subpackets;i++){
-        q->subpacket[i].bits_per_subpacket = (q->subpacket[i].size*8)>>q->subpacket[i].bits_per_subpdiv;
+    for (i = 0; i < q->num_subpackets; i++) {
+        q->subpacket[i].bits_per_subpacket = (q->subpacket[i].size * 8) >>
+                                              q->subpacket[i].bits_per_subpdiv;
         q->subpacket[i].ch_idx = chidx;
-        av_log(avctx,AV_LOG_DEBUG,"subpacket[%i] size %i js %i %i block_align %i\n",i,q->subpacket[i].size,q->subpacket[i].joint_stereo,offset,avctx->block_align);
+        av_log(avctx, AV_LOG_DEBUG,
+               "subpacket[%i] size %i js %i %i block_align %i\n",
+               i, q->subpacket[i].size, q->subpacket[i].joint_stereo, offset,
+               avctx->block_align);
+
         decode_subpacket(q, &q->subpacket[i], buf + offset, samples);
         offset += q->subpacket[i].size;
         chidx += q->subpacket[i].num_channels;
-        av_log(avctx,AV_LOG_DEBUG,"subpacket[%i] %i %i\n",i,q->subpacket[i].size * 8,get_bits_count(&q->gb));
+        av_log(avctx, AV_LOG_DEBUG, "subpacket[%i] %i %i\n",
+               i, q->subpacket[i].size * 8, get_bits_count(&q->gb));
     }
 
     /* Discard the first two frames: no valid audio. */
@@ -1010,8 +1010,8 @@ static int cook_decode_frame(AVCodecContext *avctx, void *data,
         return avctx->block_align;
     }
 
-    *got_frame_ptr   = 1;
-    *(AVFrame *)data = q->frame;
+    *got_frame_ptr    = 1;
+    *(AVFrame *) data = q->frame;
 
     return avctx->block_align;
 }
@@ -1020,34 +1020,34 @@ static int cook_decode_frame(AVCodecContext *avctx, void *data,
 static void dump_cook_context(COOKContext *q)
 {
     //int i=0;
-#define PRINT(a,b) av_log(q->avctx,AV_LOG_ERROR," %s = %d\n", a, b);
-    av_log(q->avctx,AV_LOG_ERROR,"COOKextradata\n");
-    av_log(q->avctx,AV_LOG_ERROR,"cookversion=%x\n",q->subpacket[0].cookversion);
+#define PRINT(a, b) av_log(q->avctx, AV_LOG_ERROR, " %s = %d\n", a, b);
+    av_log(q->avctx, AV_LOG_ERROR, "COOKextradata\n");
+    av_log(q->avctx, AV_LOG_ERROR, "cookversion=%x\n", q->subpacket[0].cookversion);
     if (q->subpacket[0].cookversion > STEREO) {
-        PRINT("js_subband_start",q->subpacket[0].js_subband_start);
-        PRINT("js_vlc_bits",q->subpacket[0].js_vlc_bits);
+        PRINT("js_subband_start", q->subpacket[0].js_subband_start);
+        PRINT("js_vlc_bits", q->subpacket[0].js_vlc_bits);
     }
-    av_log(q->avctx,AV_LOG_ERROR,"COOKContext\n");
-    PRINT("nb_channels",q->nb_channels);
-    PRINT("bit_rate",q->bit_rate);
-    PRINT("sample_rate",q->sample_rate);
-    PRINT("samples_per_channel",q->subpacket[0].samples_per_channel);
-    PRINT("samples_per_frame",q->subpacket[0].samples_per_frame);
-    PRINT("subbands",q->subpacket[0].subbands);
-    PRINT("js_subband_start",q->subpacket[0].js_subband_start);
-    PRINT("log2_numvector_size",q->subpacket[0].log2_numvector_size);
-    PRINT("numvector_size",q->subpacket[0].numvector_size);
-    PRINT("total_subbands",q->subpacket[0].total_subbands);
+    av_log(q->avctx, AV_LOG_ERROR, "COOKContext\n");
+    PRINT("nb_channels", q->nb_channels);
+    PRINT("bit_rate", q->bit_rate);
+    PRINT("sample_rate", q->sample_rate);
+    PRINT("samples_per_channel", q->subpacket[0].samples_per_channel);
+    PRINT("samples_per_frame", q->subpacket[0].samples_per_frame);
+    PRINT("subbands", q->subpacket[0].subbands);
+    PRINT("js_subband_start", q->subpacket[0].js_subband_start);
+    PRINT("log2_numvector_size", q->subpacket[0].log2_numvector_size);
+    PRINT("numvector_size", q->subpacket[0].numvector_size);
+    PRINT("total_subbands", q->subpacket[0].total_subbands);
 }
 #endif
 
-static av_cold int cook_count_channels(unsigned int mask){
+static av_cold int cook_count_channels(unsigned int mask)
+{
     int i;
     int channels = 0;
-    for(i = 0;i<32;i++){
-        if(mask & (1<<i))
+    for (i = 0; i < 32; i++)
+        if (mask & (1 << i))
             ++channels;
-    }
     return channels;
 }
 
@@ -1056,7 +1056,6 @@ static av_cold int cook_count_channels(unsigned int mask){
  *
  * @param avctx     pointer to the AVCodecContext
  */
-
 static av_cold int cook_decode_init(AVCodecContext *avctx)
 {
     COOKContext *q = avctx->priv_data;
@@ -1070,10 +1069,10 @@ static av_cold int cook_decode_init(AVCodecContext *avctx)
 
     /* Take care of the codec specific extradata. */
     if (extradata_size <= 0) {
-        av_log(avctx,AV_LOG_ERROR,"Necessary extradata missing!\n");
+        av_log(avctx, AV_LOG_ERROR, "Necessary extradata missing!\n");
         return AVERROR_INVALIDDATA;
     }
-    av_log(avctx,AV_LOG_DEBUG,"codecdata_length=%d\n",avctx->extradata_size);
+    av_log(avctx, AV_LOG_DEBUG, "codecdata_length=%d\n", avctx->extradata_size);
 
     /* Take data from the AVCodecContext (RM container). */
     q->sample_rate = avctx->sample_rate;
@@ -1083,17 +1082,17 @@ static av_cold int cook_decode_init(AVCodecContext *avctx)
     /* Initialize RNG. */
     av_lfg_init(&q->random_state, 0);
 
-    while(edata_ptr < edata_ptr_end){
+    while (edata_ptr < edata_ptr_end) {
         /* 8 for mono, 16 for stereo, ? for multichannel
            Swap to right endianness so we don't need to care later on. */
-        if (extradata_size >= 8){
+        if (extradata_size >= 8) {
             q->subpacket[s].cookversion = bytestream_get_be32(&edata_ptr);
-            q->subpacket[s].samples_per_frame =  bytestream_get_be16(&edata_ptr);
+            q->subpacket[s].samples_per_frame = bytestream_get_be16(&edata_ptr);
             q->subpacket[s].subbands = bytestream_get_be16(&edata_ptr);
             extradata_size -= 8;
         }
         if (extradata_size >= 8) {
-            bytestream_get_be32(&edata_ptr);    //Unknown unused
+            bytestream_get_be32(&edata_ptr);    // Unknown unused
             q->subpacket[s].js_subband_start = bytestream_get_be16(&edata_ptr);
             q->subpacket[s].js_vlc_bits = bytestream_get_be16(&edata_ptr);
             extradata_size -= 8;
@@ -1110,69 +1109,72 @@ static av_cold int cook_decode_init(AVCodecContext *avctx)
 
         /* Initialize version-dependent variables */
 
-        av_log(avctx,AV_LOG_DEBUG,"subpacket[%i].cookversion=%x\n",s,q->subpacket[s].cookversion);
+        av_log(avctx, AV_LOG_DEBUG, "subpacket[%i].cookversion=%x\n", s,
+               q->subpacket[s].cookversion);
         q->subpacket[s].joint_stereo = 0;
         switch (q->subpacket[s].cookversion) {
-            case MONO:
-                if (q->nb_channels != 1) {
-                    av_log_ask_for_sample(avctx, "Container channels != 1.\n");
-                    return AVERROR_PATCHWELCOME;
-                }
-                av_log(avctx,AV_LOG_DEBUG,"MONO\n");
-                break;
-            case STEREO:
-                if (q->nb_channels != 1) {
-                    q->subpacket[s].bits_per_subpdiv = 1;
-                    q->subpacket[s].num_channels = 2;
-                }
-                av_log(avctx,AV_LOG_DEBUG,"STEREO\n");
-                break;
-            case JOINT_STEREO:
-                if (q->nb_channels != 2) {
-                    av_log_ask_for_sample(avctx, "Container channels != 2.\n");
-                    return AVERROR_PATCHWELCOME;
-                }
-                av_log(avctx,AV_LOG_DEBUG,"JOINT_STEREO\n");
-                if (avctx->extradata_size >= 16){
-                    q->subpacket[s].total_subbands = q->subpacket[s].subbands + q->subpacket[s].js_subband_start;
-                    q->subpacket[s].joint_stereo = 1;
-                    q->subpacket[s].num_channels = 2;
-                }
+        case MONO:
+            if (q->nb_channels != 1) {
+                av_log_ask_for_sample(avctx, "Container channels != 1.\n");
+                return AVERROR_PATCHWELCOME;
+            }
+            av_log(avctx, AV_LOG_DEBUG, "MONO\n");
+            break;
+        case STEREO:
+            if (q->nb_channels != 1) {
+                q->subpacket[s].bits_per_subpdiv = 1;
+                q->subpacket[s].num_channels = 2;
+            }
+            av_log(avctx, AV_LOG_DEBUG, "STEREO\n");
+            break;
+        case JOINT_STEREO:
+            if (q->nb_channels != 2) {
+                av_log_ask_for_sample(avctx, "Container channels != 2.\n");
+                return AVERROR_PATCHWELCOME;
+            }
+            av_log(avctx, AV_LOG_DEBUG, "JOINT_STEREO\n");
+            if (avctx->extradata_size >= 16) {
+                q->subpacket[s].total_subbands = q->subpacket[s].subbands +
+                                                 q->subpacket[s].js_subband_start;
+                q->subpacket[s].joint_stereo = 1;
+                q->subpacket[s].num_channels = 2;
+            }
+            if (q->subpacket[s].samples_per_channel > 256) {
+                q->subpacket[s].log2_numvector_size = 6;
+            }
+            if (q->subpacket[s].samples_per_channel > 512) {
+                q->subpacket[s].log2_numvector_size = 7;
+            }
+            break;
+        case MC_COOK:
+            av_log(avctx, AV_LOG_DEBUG, "MULTI_CHANNEL\n");
+            if (extradata_size >= 4)
+                channel_mask |= q->subpacket[s].channel_mask = bytestream_get_be32(&edata_ptr);
+
+            if (cook_count_channels(q->subpacket[s].channel_mask) > 1) {
+                q->subpacket[s].total_subbands = q->subpacket[s].subbands +
+                                                 q->subpacket[s].js_subband_start;
+                q->subpacket[s].joint_stereo = 1;
+                q->subpacket[s].num_channels = 2;
+                q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame >> 1;
+
                 if (q->subpacket[s].samples_per_channel > 256) {
-                    q->subpacket[s].log2_numvector_size  = 6;
+                    q->subpacket[s].log2_numvector_size = 6;
                 }
                 if (q->subpacket[s].samples_per_channel > 512) {
-                    q->subpacket[s].log2_numvector_size  = 7;
+                    q->subpacket[s].log2_numvector_size = 7;
                 }
-                break;
-            case MC_COOK:
-                av_log(avctx,AV_LOG_DEBUG,"MULTI_CHANNEL\n");
-                if(extradata_size >= 4)
-                    channel_mask |= q->subpacket[s].channel_mask = bytestream_get_be32(&edata_ptr);
-
-                if(cook_count_channels(q->subpacket[s].channel_mask) > 1){
-                    q->subpacket[s].total_subbands = q->subpacket[s].subbands + q->subpacket[s].js_subband_start;
-                    q->subpacket[s].joint_stereo = 1;
-                    q->subpacket[s].num_channels = 2;
-                    q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame >> 1;
-
-                    if (q->subpacket[s].samples_per_channel > 256) {
-                        q->subpacket[s].log2_numvector_size  = 6;
-                    }
-                    if (q->subpacket[s].samples_per_channel > 512) {
-                        q->subpacket[s].log2_numvector_size  = 7;
-                    }
-                }else
-                    q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame;
+            } else
+                q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame;
 
-                break;
-            default:
-                av_log_ask_for_sample(avctx, "Unknown Cook version.\n");
-                return AVERROR_PATCHWELCOME;
+            break;
+        default:
+            av_log_ask_for_sample(avctx, "Unknown Cook version.\n");
+            return AVERROR_PATCHWELCOME;
         }
 
-        if(s > 1 && q->subpacket[s].samples_per_channel != q->samples_per_channel) {
-            av_log(avctx,AV_LOG_ERROR,"different number of samples per channel!\n");
+        if (s > 1 && q->subpacket[s].samples_per_channel != q->samples_per_channel) {
+            av_log(avctx, AV_LOG_ERROR, "different number of samples per channel!\n");
             return AVERROR_INVALIDDATA;
         } else
             q->samples_per_channel = q->subpacket[0].samples_per_channel;
@@ -1187,9 +1189,10 @@ static av_cold int cook_decode_init(AVCodecContext *avctx)
             return AVERROR_PATCHWELCOME;
         }
 
-        if ((q->subpacket[s].js_vlc_bits > 6) || (q->subpacket[s].js_vlc_bits < 2*q->subpacket[s].joint_stereo)) {
-            av_log(avctx,AV_LOG_ERROR,"js_vlc_bits = %d, only >= %d and <= 6 allowed!\n",
-                   q->subpacket[s].js_vlc_bits, 2*q->subpacket[s].joint_stereo);
+        if ((q->subpacket[s].js_vlc_bits > 6) ||
+            (q->subpacket[s].js_vlc_bits < 2 * q->subpacket[s].joint_stereo)) {
+            av_log(avctx, AV_LOG_ERROR, "js_vlc_bits = %d, only >= %d and <= 6 allowed!\n",
+                   q->subpacket[s].js_vlc_bits, 2 * q->subpacket[s].joint_stereo);
             return AVERROR_INVALIDDATA;
         }
 
@@ -1218,16 +1221,16 @@ static av_cold int cook_decode_init(AVCodecContext *avctx)
         return ret;
 
 
-    if(avctx->block_align >= UINT_MAX/2)
+    if (avctx->block_align >= UINT_MAX / 2)
         return AVERROR(EINVAL);
 
     /* Pad the databuffer with:
        DECODE_BYTES_PAD1 or DECODE_BYTES_PAD2 for decode_bytes(),
        FF_INPUT_BUFFER_PADDING_SIZE, for the bitstreamreader. */
-        q->decoded_bytes_buffer =
-          av_mallocz(avctx->block_align
-                     + DECODE_BYTES_PAD1(avctx->block_align)
-                     + FF_INPUT_BUFFER_PADDING_SIZE);
+    q->decoded_bytes_buffer =
+        av_mallocz(avctx->block_align
+                   + DECODE_BYTES_PAD1(avctx->block_align)
+                   + FF_INPUT_BUFFER_PADDING_SIZE);
     if (q->decoded_bytes_buffer == NULL)
         return AVERROR(ENOMEM);
 
@@ -1245,7 +1248,8 @@ static av_cold int cook_decode_init(AVCodecContext *avctx)
     }
 
     /* Try to catch some obviously faulty streams, othervise it might be exploitable */
-    if ((q->samples_per_channel == 256) || (q->samples_per_channel == 512) || (q->samples_per_channel == 1024)) {
+    if ((q->samples_per_channel == 256) || (q->samples_per_channel == 512)
+                || (q->samples_per_channel == 1024)) {
     } else {
         av_log_ask_for_sample(avctx,
                               "unknown amount of samples_per_channel = %d\n",
@@ -1257,7 +1261,7 @@ static av_cold int cook_decode_init(AVCodecContext *avctx)
     if (channel_mask)
         avctx->channel_layout = channel_mask;
     else
-        avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
+        avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
 
     avcodec_get_frame_defaults(&q->frame);
     avctx->coded_frame = &q->frame;
@@ -1268,16 +1272,14 @@ static av_cold int cook_decode_init(AVCodecContext *avctx)
     return 0;
 }
 
-
-AVCodec ff_cook_decoder =
-{
-    .name = "cook",
-    .type = AVMEDIA_TYPE_AUDIO,
-    .id = CODEC_ID_COOK,
+AVCodec ff_cook_decoder = {
+    .name           = "cook",
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = CODEC_ID_COOK,
     .priv_data_size = sizeof(COOKContext),
-    .init = cook_decode_init,
-    .close = cook_decode_close,
-    .decode = cook_decode_frame,
-    .capabilities = CODEC_CAP_DR1,
-    .long_name = NULL_IF_CONFIG_SMALL("COOK"),
+    .init           = cook_decode_init,
+    .close          = cook_decode_close,
+    .decode         = cook_decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
+    .long_name      = NULL_IF_CONFIG_SMALL("COOK"),
 };
diff --git a/libavcodec/dca.c b/libavcodec/dca.c
index e3f87b9..3735b5a 100644
--- a/libavcodec/dca.c
+++ b/libavcodec/dca.c
@@ -48,13 +48,13 @@
 
 //#define TRACE
 
-#define DCA_PRIM_CHANNELS_MAX (7)
-#define DCA_SUBBANDS (32)
-#define DCA_ABITS_MAX (32)      /* Should be 28 */
-#define DCA_SUBSUBFRAMES_MAX (4)
-#define DCA_SUBFRAMES_MAX (16)
-#define DCA_BLOCKS_MAX (16)
-#define DCA_LFE_MAX (3)
+#define DCA_PRIM_CHANNELS_MAX  (7)
+#define DCA_SUBBANDS          (32)
+#define DCA_ABITS_MAX         (32)      /* Should be 28 */
+#define DCA_SUBSUBFRAMES_MAX   (4)
+#define DCA_SUBFRAMES_MAX     (16)
+#define DCA_BLOCKS_MAX        (16)
+#define DCA_LFE_MAX            (3)
 
 enum DCAMode {
     DCA_MONO = 0,
@@ -127,28 +127,45 @@ static const int dca_ext_audio_descr_mask[] = {
  * OV -> center back
  * All 2 channel configurations -> AV_CH_LAYOUT_STEREO
  */
-
 static const uint64_t dca_core_channel_layout[] = {
-    AV_CH_FRONT_CENTER,                                                      ///< 1, A
-    AV_CH_LAYOUT_STEREO,                                                     ///< 2, A + B (dual mono)
-    AV_CH_LAYOUT_STEREO,                                                     ///< 2, L + R (stereo)
-    AV_CH_LAYOUT_STEREO,                                                     ///< 2, (L+R) + (L-R) (sum-difference)
-    AV_CH_LAYOUT_STEREO,                                                     ///< 2, LT +RT (left and right total)
-    AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER,                                  ///< 3, C+L+R
-    AV_CH_LAYOUT_STEREO|AV_CH_BACK_CENTER,                                   ///< 3, L+R+S
-    AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER|AV_CH_BACK_CENTER,                ///< 4, C + L + R+ S
-    AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT,                    ///< 4, L + R +SL+ SR
-    AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT, ///< 5, C + L + R+ SL+SR
-    AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER,                    ///< 6, CL + CR + L + R + SL + SR
-    AV_CH_LAYOUT_STEREO|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT|AV_CH_FRONT_CENTER|AV_CH_BACK_CENTER,                                      ///< 6, C + L + R+ LR + RR + OV
-    AV_CH_FRONT_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_BACK_CENTER|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT,   ///< 6, CF+ CR+LF+ RF+LR + RR
-    AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER|AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT, ///< 7, CL + C + CR + L + R + SL + SR
-    AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER|AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT, ///< 8, CL + CR + L + R + SL1 + SL2+ SR1 + SR2
-    AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER|AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_BACK_CENTER|AV_CH_SIDE_RIGHT, ///< 8, CL + C+ CR + L + R + SL + S+ SR
+    AV_CH_FRONT_CENTER,                                                     ///< 1, A
+    AV_CH_LAYOUT_STEREO,                                                    ///< 2, A + B (dual mono)
+    AV_CH_LAYOUT_STEREO,                                                    ///< 2, L + R (stereo)
+    AV_CH_LAYOUT_STEREO,                                                    ///< 2, (L + R) + (L - R) (sum-difference)
+    AV_CH_LAYOUT_STEREO,                                                    ///< 2, LT + RT (left and right total)
+    AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER,                               ///< 3, C + L + R
+    AV_CH_LAYOUT_STEREO | AV_CH_BACK_CENTER,                                ///< 3, L + R + S
+    AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_BACK_CENTER,           ///< 4, C + L + R + S
+    AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,               ///< 4, L + R + SL + SR
+
+    AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER | AV_CH_SIDE_LEFT |
+    AV_CH_SIDE_RIGHT,                                                       ///< 5, C + L + R + SL + SR
+
+    AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
+    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER,               ///< 6, CL + CR + L + R + SL + SR
+
+    AV_CH_LAYOUT_STEREO | AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT |
+    AV_CH_FRONT_CENTER  | AV_CH_BACK_CENTER,                                ///< 6, C + L + R + LR + RR + OV
+
+    AV_CH_FRONT_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
+    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_BACK_CENTER   |
+    AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT,                                     ///< 6, CF + CR + LF + RF + LR + RR
+
+    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER   |
+    AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
+    AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,                                     ///< 7, CL + C + CR + L + R + SL + SR
+
+    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER |
+    AV_CH_LAYOUT_STEREO | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT |
+    AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT,                                     ///< 8, CL + CR + L + R + SL1 + SL2 + SR1 + SR2
+
+    AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_CENTER   |
+    AV_CH_FRONT_RIGHT_OF_CENTER | AV_CH_LAYOUT_STEREO |
+    AV_CH_SIDE_LEFT | AV_CH_BACK_CENTER | AV_CH_SIDE_RIGHT,                 ///< 8, CL + C + CR + L + R + SL + S + SR
 };
 
 static const int8_t dca_lfe_index[] = {
-    1,2,2,2,2,3,2,3,2,3,2,3,1,3,2,3
+    1, 2, 2, 2, 2, 3, 2, 3, 2, 3, 2, 3, 1, 3, 2, 3
 };
 
 static const int8_t dca_channel_reorder_lfe[][9] = {
@@ -227,19 +244,19 @@ static const int8_t dca_channel_reorder_nolfe_xch[][9] = {
     { 3,  2,  4,  0,  1,  5,  8,  7,  6},
 };
 
-#define DCA_DOLBY 101           /* FIXME */
+#define DCA_DOLBY                  101           /* FIXME */
 
-#define DCA_CHANNEL_BITS 6
-#define DCA_CHANNEL_MASK 0x3F
+#define DCA_CHANNEL_BITS             6
+#define DCA_CHANNEL_MASK          0x3F
 
-#define DCA_LFE 0x80
+#define DCA_LFE                   0x80
 
-#define HEADER_SIZE 14
+#define HEADER_SIZE                 14
 
-#define DCA_MAX_FRAME_SIZE 16384
-#define DCA_MAX_EXSS_HEADER_SIZE 4096
+#define DCA_MAX_FRAME_SIZE       16384
+#define DCA_MAX_EXSS_HEADER_SIZE  4096
 
-#define DCA_BUFFER_PADDING_SIZE 1024
+#define DCA_BUFFER_PADDING_SIZE   1024
 
 /** Bit allocation */
 typedef struct {
@@ -254,9 +271,11 @@ static BitAlloc dca_tmode;             ///< transition mode VLCs
 static BitAlloc dca_scalefactor;       ///< scalefactor VLCs
 static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
 
-static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba, int idx)
+static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba,
+                                         int idx)
 {
-    return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) + ba->offset;
+    return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) +
+           ba->offset;
 }
 
 typedef struct {
@@ -307,8 +326,8 @@ typedef struct {
     float scalefactor_adj[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX];   ///< scale factor adjustment
 
     /* Primary audio coding side information */
-    int subsubframes[DCA_SUBFRAMES_MAX];           ///< number of subsubframes
-    int partial_samples[DCA_SUBFRAMES_MAX];        ///< partial subsubframe samples count
+    int subsubframes[DCA_SUBFRAMES_MAX];                         ///< number of subsubframes
+    int partial_samples[DCA_SUBFRAMES_MAX];                      ///< partial subsubframe samples count
     int prediction_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< prediction mode (ADPCM used or not)
     int prediction_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];      ///< prediction VQ coefs
     int bitalloc[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];           ///< bit allocation index
@@ -335,13 +354,13 @@ typedef struct {
     float scale_bias;           ///< output scale
 
     DECLARE_ALIGNED(32, float, subband_samples)[DCA_BLOCKS_MAX][DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
-    DECLARE_ALIGNED(32, float, samples)[(DCA_PRIM_CHANNELS_MAX+1)*256];
-    const float *samples_chanptr[DCA_PRIM_CHANNELS_MAX+1];
+    DECLARE_ALIGNED(32, float, samples)[(DCA_PRIM_CHANNELS_MAX + 1) * 256];
+    const float *samples_chanptr[DCA_PRIM_CHANNELS_MAX + 1];
 
     uint8_t dca_buffer[DCA_MAX_FRAME_SIZE + DCA_MAX_EXSS_HEADER_SIZE + DCA_BUFFER_PADDING_SIZE];
     int dca_buffer_size;        ///< how much data is in the dca_buffer
 
-    const int8_t* channel_order_tab;                             ///< channel reordering table, lfe and non lfe
+    const int8_t *channel_order_tab;  ///< channel reordering table, lfe and non lfe
     GetBitContext gb;
     /* Current position in DCA frame */
     int current_subframe;
@@ -416,13 +435,15 @@ static av_cold void dca_init_vlcs(void)
     }
 
     for (i = 0; i < 10; i++)
-        for (j = 0; j < 7; j++){
-            if (!bitalloc_codes[i][j]) break;
-            dca_smpl_bitalloc[i+1].offset = bitalloc_offsets[i];
-            dca_smpl_bitalloc[i+1].wrap = 1 + (j > 4);
-            dca_smpl_bitalloc[i+1].vlc[j].table = &dca_table[dca_vlc_offs[c]];
-            dca_smpl_bitalloc[i+1].vlc[j].table_allocated = dca_vlc_offs[c + 1] - dca_vlc_offs[c];
-            init_vlc(&dca_smpl_bitalloc[i+1].vlc[j], bitalloc_maxbits[i][j],
+        for (j = 0; j < 7; j++) {
+            if (!bitalloc_codes[i][j])
+                break;
+            dca_smpl_bitalloc[i + 1].offset                 = bitalloc_offsets[i];
+            dca_smpl_bitalloc[i + 1].wrap                   = 1 + (j > 4);
+            dca_smpl_bitalloc[i + 1].vlc[j].table           = &dca_table[dca_vlc_offs[c]];
+            dca_smpl_bitalloc[i + 1].vlc[j].table_allocated = dca_vlc_offs[c + 1] - dca_vlc_offs[c];
+
+            init_vlc(&dca_smpl_bitalloc[i + 1].vlc[j], bitalloc_maxbits[i][j],
                      bitalloc_sizes[i],
                      bitalloc_bits[i][j], 1, 1,
                      bitalloc_codes[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
@@ -433,19 +454,19 @@ static av_cold void dca_init_vlcs(void)
 
 static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
 {
-    while(len--)
+    while (len--)
         *dst++ = get_bits(gb, bits);
 }
 
-static int dca_parse_audio_coding_header(DCAContext * s, int base_channel)
+static int dca_parse_audio_coding_header(DCAContext *s, int base_channel)
 {
     int i, j;
     static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
     static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
-    static const int thr[11] = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
+    static const int thr[11]    = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
 
-    s->total_channels    = get_bits(&s->gb, 3) + 1 + base_channel;
-    s->prim_channels     = s->total_channels;
+    s->total_channels = get_bits(&s->gb, 3) + 1 + base_channel;
+    s->prim_channels  = s->total_channels;
 
     if (s->prim_channels > DCA_PRIM_CHANNELS_MAX)
         s->prim_channels = DCA_PRIM_CHANNELS_MAX;
@@ -488,23 +509,28 @@ static int dca_parse_audio_coding_header(DCAContext * s, int base_channel)
         get_bits(&s->gb, 16);
     }
 
-    s->current_subframe = 0;
+    s->current_subframe    = 0;
     s->current_subsubframe = 0;
 
 #ifdef TRACE
     av_log(s->avctx, AV_LOG_DEBUG, "subframes: %i\n", s->subframes);
     av_log(s->avctx, AV_LOG_DEBUG, "prim channels: %i\n", s->prim_channels);
-    for (i = base_channel; i < s->prim_channels; i++){
-        av_log(s->avctx, AV_LOG_DEBUG, "subband activity: %i\n", s->subband_activity[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "vq start subband: %i\n", s->vq_start_subband[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "joint intensity: %i\n", s->joint_intensity[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "transient mode codebook: %i\n", s->transient_huffman[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "scale factor codebook: %i\n", s->scalefactor_huffman[i]);
-        av_log(s->avctx, AV_LOG_DEBUG, "bit allocation quantizer: %i\n", s->bitalloc_huffman[i]);
+    for (i = base_channel; i < s->prim_channels; i++) {
+        av_log(s->avctx, AV_LOG_DEBUG, "subband activity: %i\n",
+               s->subband_activity[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "vq start subband: %i\n",
+               s->vq_start_subband[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "joint intensity: %i\n",
+               s->joint_intensity[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "transient mode codebook: %i\n",
+               s->transient_huffman[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "scale factor codebook: %i\n",
+               s->scalefactor_huffman[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "bit allocation quantizer: %i\n",
+               s->bitalloc_huffman[i]);
         av_log(s->avctx, AV_LOG_DEBUG, "quant index huff:");
         for (j = 0; j < 11; j++)
-            av_log(s->avctx, AV_LOG_DEBUG, " %i",
-                   s->quant_index_huffman[i][j]);
+            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->quant_index_huffman[i][j]);
         av_log(s->avctx, AV_LOG_DEBUG, "\n");
         av_log(s->avctx, AV_LOG_DEBUG, "scalefac adj:");
         for (j = 0; j < 11; j++)
@@ -513,10 +539,10 @@ static int dca_parse_audio_coding_header(DCAContext * s, int base_channel)
     }
 #endif
 
-  return 0;
+    return 0;
 }
 
-static int dca_parse_frame_header(DCAContext * s)
+static int dca_parse_frame_header(DCAContext *s)
 {
     init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
 
@@ -565,7 +591,8 @@ static int dca_parse_frame_header(DCAContext * s)
 
     /* FIXME: channels mixing levels */
     s->output = s->amode;
-    if (s->lfe) s->output |= DCA_LFE;
+    if (s->lfe)
+        s->output |= DCA_LFE;
 
 #ifdef TRACE
     av_log(s->avctx, AV_LOG_DEBUG, "frame type: %i\n", s->frame_type);
@@ -614,15 +641,15 @@ static int dca_parse_frame_header(DCAContext * s)
 
 static inline int get_scale(GetBitContext *gb, int level, int value)
 {
-   if (level < 5) {
-       /* huffman encoded */
-       value += get_bitalloc(gb, &dca_scalefactor, level);
-   } else if (level < 8)
-       value = get_bits(gb, level + 1);
-   return value;
+    if (level < 5) {
+        /* huffman encoded */
+        value += get_bitalloc(gb, &dca_scalefactor, level);
+    } else if (level < 8)
+        value = get_bits(gb, level + 1);
+    return value;
 }
 
-static int dca_subframe_header(DCAContext * s, int base_channel, int block_index)
+static int dca_subframe_header(DCAContext *s, int base_channel, int block_index)
 {
     /* Primary audio coding side information */
     int j, k;
@@ -631,7 +658,7 @@ static int dca_subframe_header(DCAContext * s, int base_channel, int block_index
         return AVERROR_INVALIDDATA;
 
     if (!base_channel) {
-        s->subsubframes[s->current_subframe] = get_bits(&s->gb, 2) + 1;
+        s->subsubframes[s->current_subframe]    = get_bits(&s->gb, 2) + 1;
         s->partial_samples[s->current_subframe] = get_bits(&s->gb, 3);
     }
 
@@ -667,8 +694,8 @@ static int dca_subframe_header(DCAContext * s, int base_channel, int block_index
             }
 
             if (s->bitalloc[j][k] > 26) {
-//                 av_log(s->avctx,AV_LOG_DEBUG,"bitalloc index [%i][%i] too big (%i)\n",
-//                          j, k, s->bitalloc[j][k]);
+                // av_log(s->avctx, AV_LOG_DEBUG, "bitalloc index [%i][%i] too big (%i)\n",
+                //        j, k, s->bitalloc[j][k]);
                 return AVERROR_INVALIDDATA;
             }
         }
@@ -693,7 +720,8 @@ static int dca_subframe_header(DCAContext * s, int base_channel, int block_index
         const uint32_t *scale_table;
         int scale_sum;
 
-        memset(s->scale_factor[j], 0, s->subband_activity[j] * sizeof(s->scale_factor[0][0][0]) * 2);
+        memset(s->scale_factor[j], 0,
+               s->subband_activity[j] * sizeof(s->scale_factor[0][0][0]) * 2);
 
         if (s->scalefactor_huffman[j] == 6)
             scale_table = scale_factor_quant7;
@@ -811,9 +839,11 @@ static int dca_subframe_header(DCAContext * s, int base_channel, int block_index
     }
 
 #ifdef TRACE
-    av_log(s->avctx, AV_LOG_DEBUG, "subsubframes: %i\n", s->subsubframes[s->current_subframe]);
+    av_log(s->avctx, AV_LOG_DEBUG, "subsubframes: %i\n",
+           s->subsubframes[s->current_subframe]);
     av_log(s->avctx, AV_LOG_DEBUG, "partial samples: %i\n",
            s->partial_samples[s->current_subframe]);
+
     for (j = base_channel; j < s->prim_channels; j++) {
         av_log(s->avctx, AV_LOG_DEBUG, "prediction mode:");
         for (k = 0; k < s->subband_activity[j]; k++)
@@ -822,12 +852,12 @@ static int dca_subframe_header(DCAContext * s, int base_channel, int block_index
     }
     for (j = base_channel; j < s->prim_channels; j++) {
         for (k = 0; k < s->subband_activity[j]; k++)
-                av_log(s->avctx, AV_LOG_DEBUG,
-                       "prediction coefs: %f, %f, %f, %f\n",
-                       (float) adpcm_vb[s->prediction_vq[j][k]][0] / 8192,
-                       (float) adpcm_vb[s->prediction_vq[j][k]][1] / 8192,
-                       (float) adpcm_vb[s->prediction_vq[j][k]][2] / 8192,
-                       (float) adpcm_vb[s->prediction_vq[j][k]][3] / 8192);
+            av_log(s->avctx, AV_LOG_DEBUG,
+                   "prediction coefs: %f, %f, %f, %f\n",
+                   (float) adpcm_vb[s->prediction_vq[j][k]][0] / 8192,
+                   (float) adpcm_vb[s->prediction_vq[j][k]][1] / 8192,
+                   (float) adpcm_vb[s->prediction_vq[j][k]][2] / 8192,
+                   (float) adpcm_vb[s->prediction_vq[j][k]][3] / 8192);
     }
     for (j = base_channel; j < s->prim_channels; j++) {
         av_log(s->avctx, AV_LOG_DEBUG, "bitalloc index: ");
@@ -863,8 +893,10 @@ static int dca_subframe_header(DCAContext * s, int base_channel, int block_index
     if (!base_channel && s->prim_channels > 2 && s->downmix) {
         av_log(s->avctx, AV_LOG_DEBUG, "Downmix coeffs:\n");
         for (j = 0; j < s->prim_channels; j++) {
-            av_log(s->avctx, AV_LOG_DEBUG, "Channel 0,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][0]]);
-            av_log(s->avctx, AV_LOG_DEBUG, "Channel 1,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][1]]);
+            av_log(s->avctx, AV_LOG_DEBUG, "Channel 0, %d = %f\n", j,
+                   dca_downmix_coeffs[s->downmix_coef[j][0]]);
+            av_log(s->avctx, AV_LOG_DEBUG, "Channel 1, %d = %f\n", j,
+                   dca_downmix_coeffs[s->downmix_coef[j][1]]);
         }
         av_log(s->avctx, AV_LOG_DEBUG, "\n");
     }
@@ -885,7 +917,7 @@ static int dca_subframe_header(DCAContext * s, int base_channel, int block_index
     return 0;
 }
 
-static void qmf_32_subbands(DCAContext * s, int chans,
+static void qmf_32_subbands(DCAContext *s, int chans,
                             float samples_in[32][8], float *samples_out,
                             float scale)
 {
@@ -895,7 +927,7 @@ static void qmf_32_subbands(DCAContext * s, int chans,
     int sb_act = s->subband_activity[chans];
     int subindex;
 
-    scale *= sqrt(1/8.0);
+    scale *= sqrt(1 / 8.0);
 
     /* Select filter */
     if (!s->multirate_inter)    /* Non-perfect reconstruction */
@@ -909,18 +941,18 @@ static void qmf_32_subbands(DCAContext * s, int chans,
     /* Reconstructed channel sample index */
     for (subindex = 0; subindex < 8; subindex++) {
         /* Load in one sample from each subband and clear inactive subbands */
-        for (i = 0; i < sb_act; i++){
+        for (i = 0; i < sb_act; i++) {
             unsigned sign = (i - 1) & 2;
-            uint32_t v = AV_RN32A(&samples_in[i][subindex]) ^ sign << 30;
+            uint32_t v    = AV_RN32A(&samples_in[i][subindex]) ^ sign << 30;
             AV_WN32A(&s->raXin[i], v);
         }
 
         s->synth.synth_filter_float(&s->imdct,
-                              s->subband_fir_hist[chans], &s->hist_index[chans],
-                              s->subband_fir_noidea[chans], prCoeff,
-                              samples_out, s->raXin, scale);
-        samples_out+= 32;
-
+                                    s->subband_fir_hist[chans],
+                                    &s->hist_index[chans],
+                                    s->subband_fir_noidea[chans], prCoeff,
+                                    samples_out, s->raXin, scale);
+        samples_out += 32;
     }
 }
 
@@ -950,45 +982,44 @@ static void lfe_interpolation_fir(DCAContext *s, int decimation_select,
     }
     /* Interpolation */
     for (deciindex = 0; deciindex < num_deci_sample; deciindex++) {
-        s->dcadsp.lfe_fir(samples_out, samples_in, prCoeff, decifactor,
-                          scale);
+        s->dcadsp.lfe_fir(samples_out, samples_in, prCoeff, decifactor, scale);
         samples_in++;
         samples_out += 2 * decifactor;
     }
 }
 
 /* downmixing routines */
-#define MIX_REAR1(samples, si1, rs, coef) \
-     samples[i]     += samples[si1] * coef[rs][0];  \
-     samples[i+256] += samples[si1] * coef[rs][1];
-
-#define MIX_REAR2(samples, si1, si2, rs, coef) \
-     samples[i]     += samples[si1] * coef[rs][0] + samples[si2] * coef[rs+1][0]; \
-     samples[i+256] += samples[si1] * coef[rs][1] + samples[si2] * coef[rs+1][1];
-
-#define MIX_FRONT3(samples, coef) \
-    t = samples[i+c]; \
-    u = samples[i+l]; \
-    v = samples[i+r]; \
+#define MIX_REAR1(samples, si1, rs, coef)           \
+    samples[i]     += samples[si1] * coef[rs][0];   \
+    samples[i+256] += samples[si1] * coef[rs][1];
+
+#define MIX_REAR2(samples, si1, si2, rs, coef)                                     \
+    samples[i]     += samples[si1] * coef[rs][0] + samples[si2] * coef[rs + 1][0]; \
+    samples[i+256] += samples[si1] * coef[rs][1] + samples[si2] * coef[rs + 1][1];
+
+#define MIX_FRONT3(samples, coef)                                      \
+    t = samples[i + c];                                                \
+    u = samples[i + l];                                                \
+    v = samples[i + r];                                                \
     samples[i]     = t * coef[0][0] + u * coef[1][0] + v * coef[2][0]; \
     samples[i+256] = t * coef[0][1] + u * coef[1][1] + v * coef[2][1];
 
-#define DOWNMIX_TO_STEREO(op1, op2) \
-    for (i = 0; i < 256; i++){ \
-        op1 \
-        op2 \
+#define DOWNMIX_TO_STEREO(op1, op2)             \
+    for (i = 0; i < 256; i++) {                 \
+        op1                                     \
+        op2                                     \
     }
 
 static void dca_downmix(float *samples, int srcfmt,
                         int downmix_coef[DCA_PRIM_CHANNELS_MAX][2],
                         const int8_t *channel_mapping)
 {
-    int c,l,r,sl,sr,s;
+    int c, l, r, sl, sr, s;
     int i;
     float t, u, v;
     float coef[DCA_PRIM_CHANNELS_MAX][2];
 
-    for (i=0; i<DCA_PRIM_CHANNELS_MAX; i++) {
+    for (i = 0; i < DCA_PRIM_CHANNELS_MAX; i++) {
         coef[i][0] = dca_downmix_coeffs[downmix_coef[i][0]];
         coef[i][1] = dca_downmix_coeffs[downmix_coef[i][1]];
     }
@@ -1007,11 +1038,11 @@ static void dca_downmix(float *samples, int srcfmt,
         c = channel_mapping[0] * 256;
         l = channel_mapping[1] * 256;
         r = channel_mapping[2] * 256;
-        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),);
+        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), );
         break;
     case DCA_2F1R:
         s = channel_mapping[2] * 256;
-        DOWNMIX_TO_STEREO(MIX_REAR1(samples, i + s, 2, coef),);
+        DOWNMIX_TO_STEREO(MIX_REAR1(samples, i + s, 2, coef), );
         break;
     case DCA_3F1R:
         c = channel_mapping[0] * 256;
@@ -1024,12 +1055,12 @@ static void dca_downmix(float *samples, int srcfmt,
     case DCA_2F2R:
         sl = channel_mapping[2] * 256;
         sr = channel_mapping[3] * 256;
-        DOWNMIX_TO_STEREO(MIX_REAR2(samples, i + sl, i + sr, 2, coef),);
+        DOWNMIX_TO_STEREO(MIX_REAR2(samples, i + sl, i + sr, 2, coef), );
         break;
     case DCA_3F2R:
-        c =  channel_mapping[0] * 256;
-        l =  channel_mapping[1] * 256;
-        r =  channel_mapping[2] * 256;
+        c  = channel_mapping[0] * 256;
+        l  = channel_mapping[1] * 256;
+        r  = channel_mapping[2] * 256;
         sl = channel_mapping[3] * 256;
         sr = channel_mapping[4] * 256;
         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
@@ -1049,7 +1080,7 @@ static int decode_blockcode(int code, int levels, int *values)
 
     for (i = 0; i < 4; i++) {
         int div = FASTDIV(code, levels);
-        values[i] = code - offset - div*levels;
+        values[i] = code - offset - div * levels;
         code = div;
     }
 
@@ -1063,8 +1094,8 @@ static int decode_blockcodes(int code1, int code2, int levels, int *values)
 }
 #endif
 
-static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
-static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
+static const uint8_t abits_sizes[7]  = { 7, 10, 12, 13, 15, 17, 19 };
+static const uint8_t abits_levels[7] = { 3,  5,  7,  9, 13, 17, 25 };
 
 #ifndef int8x8_fmul_int32
 static inline void int8x8_fmul_int32(float *dst, const int8_t *src, int scale)
@@ -1076,7 +1107,7 @@ static inline void int8x8_fmul_int32(float *dst, const int8_t *src, int scale)
 }
 #endif
 
-static int dca_subsubframe(DCAContext * s, int base_channel, int block_index)
+static int dca_subsubframe(DCAContext *s, int base_channel, int block_index)
 {
     int k, l;
     int subsubframe = s->current_subsubframe;
@@ -1119,20 +1150,21 @@ static int dca_subsubframe(DCAContext * s, int base_channel, int block_index)
             /*
              * Extract bits from the bit stream
              */
-            if (!abits){
+            if (!abits) {
                 memset(subband_samples[k][l], 0, 8 * sizeof(subband_samples[0][0][0]));
             } else {
                 /* Deal with transients */
                 int sfi = s->transition_mode[k][l] && subsubframe >= s->transition_mode[k][l];
-                float rscale = quant_step_size * s->scale_factor[k][l][sfi] * s->scalefactor_adj[k][sel];
+                float rscale = quant_step_size * s->scale_factor[k][l][sfi] *
+                               s->scalefactor_adj[k][sel];
 
-                if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table){
-                    if (abits <= 7){
+                if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table) {
+                    if (abits <= 7) {
                         /* Block code */
                         int block_code1, block_code2, size, levels, err;
 
-                        size = abits_sizes[abits-1];
-                        levels = abits_levels[abits-1];
+                        size   = abits_sizes[abits - 1];
+                        levels = abits_levels[abits - 1];
 
                         block_code1 = get_bits(&s->gb, size);
                         block_code2 = get_bits(&s->gb, size);
@@ -1143,19 +1175,20 @@ static int dca_subsubframe(DCAContext * s, int base_channel, int block_index)
                                    "ERROR: block code look-up failed\n");
                             return AVERROR_INVALIDDATA;
                         }
-                    }else{
+                    } else {
                         /* no coding */
                         for (m = 0; m < 8; m++)
                             block[m] = get_sbits(&s->gb, abits - 3);
                     }
-                }else{
+                } else {
                     /* Huffman coded */
                     for (m = 0; m < 8; m++)
-                        block[m] = get_bitalloc(&s->gb, &dca_smpl_bitalloc[abits], sel);
+                        block[m] = get_bitalloc(&s->gb,
+                                                &dca_smpl_bitalloc[abits], sel);
                 }
 
                 s->fmt_conv.int32_to_float_fmul_scalar(subband_samples[k][l],
-                                                  block, rscale, 8);
+                                                       block, rscale, 8);
             }
 
             /*
@@ -1172,8 +1205,7 @@ static int dca_subsubframe(DCAContext * s, int base_channel, int block_index)
                         else if (s->predictor_history)
                             subband_samples[k][l][m] +=
                                 (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
-                                 s->subband_samples_hist[k][l][m - n +
-                                                               4] / 8192);
+                                 s->subband_samples_hist[k][l][m - n + 4] / 8192);
                 }
             }
         }
@@ -1187,7 +1219,8 @@ static int dca_subsubframe(DCAContext * s, int base_channel, int block_index)
             int hfvq = s->high_freq_vq[k][l];
 
             if (!s->debug_flag & 0x01) {
-                av_log(s->avctx, AV_LOG_DEBUG, "Stream with high frequencies VQ coding\n");
+                av_log(s->avctx, AV_LOG_DEBUG,
+                       "Stream with high frequencies VQ coding\n");
                 s->debug_flag |= 0x01;
             }
 
@@ -1211,23 +1244,25 @@ static int dca_subsubframe(DCAContext * s, int base_channel, int block_index)
     /* Backup predictor history for adpcm */
     for (k = base_channel; k < s->prim_channels; k++)
         for (l = 0; l < s->vq_start_subband[k]; l++)
-            memcpy(s->subband_samples_hist[k][l], &subband_samples[k][l][4],
-                        4 * sizeof(subband_samples[0][0][0]));
+            memcpy(s->subband_samples_hist[k][l],
+                   &subband_samples[k][l][4],
+                   4 * sizeof(subband_samples[0][0][0]));
 
     return 0;
 }
 
-static int dca_filter_channels(DCAContext * s, int block_index)
+static int dca_filter_channels(DCAContext *s, int block_index)
 {
     float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
     int k;
 
     /* 32 subbands QMF */
     for (k = 0; k < s->prim_channels; k++) {
-/*        static float pcm_to_double[8] =
-            {32768.0, 32768.0, 524288.0, 524288.0, 0, 8388608.0, 8388608.0};*/
-         qmf_32_subbands(s, k, subband_samples[k], &s->samples[256 * s->channel_order_tab[k]],
-                         M_SQRT1_2*s->scale_bias /*pcm_to_double[s->source_pcm_res] */ );
+/*        static float pcm_to_double[8] = { 32768.0, 32768.0, 524288.0, 524288.0,
+                                            0, 8388608.0, 8388608.0 };*/
+        qmf_32_subbands(s, k, subband_samples[k],
+                        &s->samples[256 * s->channel_order_tab[k]],
+                        M_SQRT1_2 * s->scale_bias /* pcm_to_double[s->source_pcm_res] */);
     }
 
     /* Down mixing */
@@ -1240,7 +1275,7 @@ static int dca_filter_channels(DCAContext * s, int block_index)
         lfe_interpolation_fir(s, s->lfe, 2 * s->lfe,
                               s->lfe_data + 2 * s->lfe * (block_index + 4),
                               &s->samples[256 * dca_lfe_index[s->amode]],
-                              (1.0/256.0)*s->scale_bias);
+                              (1.0 / 256.0) * s->scale_bias);
         /* Outputs 20bits pcm samples */
     }
 
@@ -1248,7 +1283,7 @@ static int dca_filter_channels(DCAContext * s, int block_index)
 }
 
 
-static int dca_subframe_footer(DCAContext * s, int base_channel)
+static int dca_subframe_footer(DCAContext *s, int base_channel)
 {
     int aux_data_count = 0, i;
 
@@ -1280,7 +1315,7 @@ static int dca_subframe_footer(DCAContext * s, int base_channel)
  * @param s     pointer to the DCAContext
  */
 
-static int dca_decode_block(DCAContext * s, int base_channel, int block_index)
+static int dca_decode_block(DCAContext *s, int base_channel, int block_index)
 {
     int ret;
 
@@ -1328,8 +1363,8 @@ static int dca_decode_block(DCAContext * s, int base_channel, int block_index)
 /**
  * Convert bitstream to one representation based on sync marker
  */
-static int dca_convert_bitstream(const uint8_t * src, int src_size, uint8_t * dst,
-                          int max_size)
+static int dca_convert_bitstream(const uint8_t *src, int src_size, uint8_t *dst,
+                                 int max_size)
 {
     uint32_t mrk;
     int i, tmp;
@@ -1337,7 +1372,7 @@ static int dca_convert_bitstream(const uint8_t * src, int src_size, uint8_t * ds
     uint16_t *sdst = (uint16_t *) dst;
     PutBitContext pb;
 
-    if ((unsigned)src_size > (unsigned)max_size) {
+    if ((unsigned) src_size > (unsigned) max_size) {
 //        av_log(NULL, AV_LOG_ERROR, "Input frame size larger than DCA_MAX_FRAME_SIZE!\n");
 //        return -1;
         src_size = max_size;
@@ -1372,18 +1407,16 @@ static int dca_convert_bitstream(const uint8_t * src, int src_size, uint8_t * ds
 static int dca_exss_mask2count(int mask)
 {
     /* count bits that mean speaker pairs twice */
-    return av_popcount(mask)
-        + av_popcount(mask & (
-            DCA_EXSS_CENTER_LEFT_RIGHT
-          | DCA_EXSS_FRONT_LEFT_RIGHT
-          | DCA_EXSS_FRONT_HIGH_LEFT_RIGHT
-          | DCA_EXSS_WIDE_LEFT_RIGHT
-          | DCA_EXSS_SIDE_LEFT_RIGHT
-          | DCA_EXSS_SIDE_HIGH_LEFT_RIGHT
-          | DCA_EXSS_SIDE_REAR_LEFT_RIGHT
-          | DCA_EXSS_REAR_LEFT_RIGHT
-          | DCA_EXSS_REAR_HIGH_LEFT_RIGHT
-          ));
+    return av_popcount(mask) +
+           av_popcount(mask & (DCA_EXSS_CENTER_LEFT_RIGHT      |
+                               DCA_EXSS_FRONT_LEFT_RIGHT       |
+                               DCA_EXSS_FRONT_HIGH_LEFT_RIGHT  |
+                               DCA_EXSS_WIDE_LEFT_RIGHT        |
+                               DCA_EXSS_SIDE_LEFT_RIGHT        |
+                               DCA_EXSS_SIDE_HIGH_LEFT_RIGHT   |
+                               DCA_EXSS_SIDE_REAR_LEFT_RIGHT   |
+                               DCA_EXSS_REAR_LEFT_RIGHT        |
+                               DCA_EXSS_REAR_HIGH_LEFT_RIGHT));
 }
 
 /**
@@ -1409,7 +1442,7 @@ static int dca_exss_parse_asset_header(DCAContext *s)
     int header_size;
     int channels;
     int embedded_stereo = 0;
-    int embedded_6ch = 0;
+    int embedded_6ch    = 0;
     int drc_code_present;
     int extensions_mask;
     int i, j;
@@ -1544,7 +1577,8 @@ static int dca_exss_parse_asset_header(DCAContext *s)
     if (!(extensions_mask & DCA_EXT_CORE))
         av_log(s->avctx, AV_LOG_WARNING, "DTS core detection mismatch.\n");
     if ((extensions_mask & DCA_CORE_EXTS) != s->core_ext_mask)
-        av_log(s->avctx, AV_LOG_WARNING, "DTS extensions detection mismatch (%d, %d)\n",
+        av_log(s->avctx, AV_LOG_WARNING,
+               "DTS extensions detection mismatch (%d, %d)\n",
                extensions_mask & DCA_CORE_EXTS, s->core_ext_mask);
 
     return 0;
@@ -1569,7 +1603,7 @@ static void dca_exss_parse_header(DCAContext *s)
     ss_index = get_bits(&s->gb, 2);
 
     blownup = get_bits1(&s->gb);
-    skip_bits(&s->gb, 8 + 4 * blownup); // header_size
+    skip_bits(&s->gb,  8 + 4 * blownup); // header_size
     skip_bits(&s->gb, 16 + 4 * blownup); // hd_size
 
     s->static_fields = get_bits1(&s->gb);
@@ -1610,18 +1644,18 @@ static void dca_exss_parse_header(DCAContext *s)
             int mix_out_mask_size;
 
             skip_bits(&s->gb, 2); // adjustment level
-            mix_out_mask_size = (get_bits(&s->gb, 2) + 1) << 2;
-            s->num_mix_configs = get_bits(&s->gb, 2) + 1;
+            mix_out_mask_size  = (get_bits(&s->gb, 2) + 1) << 2;
+            s->num_mix_configs =  get_bits(&s->gb, 2) + 1;
 
             for (i = 0; i < s->num_mix_configs; i++) {
-                int mix_out_mask = get_bits(&s->gb, mix_out_mask_size);
+                int mix_out_mask        = get_bits(&s->gb, mix_out_mask_size);
                 s->mix_config_num_ch[i] = dca_exss_mask2count(mix_out_mask);
             }
         }
     }
 
     for (i = 0; i < num_assets; i++)
-        skip_bits_long(&s->gb, 16 + 4 * blownup); // asset size
+        skip_bits_long(&s->gb, 16 + 4 * blownup);  // asset size
 
     for (i = 0; i < num_assets; i++) {
         if (dca_exss_parse_asset_header(s))
@@ -1668,8 +1702,8 @@ static int dca_decode_frame(AVCodecContext *avctx, void *data,
     }
     //set AVCodec values with parsed data
     avctx->sample_rate = s->sample_rate;
-    avctx->bit_rate = s->bit_rate;
-    avctx->frame_size = s->sample_blocks * 32;
+    avctx->bit_rate    = s->bit_rate;
+    avctx->frame_size  = s->sample_blocks * 32;
 
     s->profile = FF_PROFILE_DTS;
 
@@ -1701,72 +1735,71 @@ static int dca_decode_frame(AVCodecContext *avctx, void *data,
         /* extensions start at 32-bit boundaries into bitstream */
         skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
 
-    while(core_ss_end - get_bits_count(&s->gb) >= 32) {
-        uint32_t bits = get_bits_long(&s->gb, 32);
+        while (core_ss_end - get_bits_count(&s->gb) >= 32) {
+            uint32_t bits = get_bits_long(&s->gb, 32);
 
-        switch(bits) {
-        case 0x5a5a5a5a: {
-            int ext_amode, xch_fsize;
+            switch (bits) {
+            case 0x5a5a5a5a: {
+                int ext_amode, xch_fsize;
 
-            s->xch_base_channel = s->prim_channels;
+                s->xch_base_channel = s->prim_channels;
 
-            /* validate sync word using XCHFSIZE field */
-            xch_fsize = show_bits(&s->gb, 10);
-            if((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&
-               (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))
-                continue;
-
-            /* skip length-to-end-of-frame field for the moment */
-            skip_bits(&s->gb, 10);
-
-            s->core_ext_mask |= DCA_EXT_XCH;
+                /* validate sync word using XCHFSIZE field */
+                xch_fsize = show_bits(&s->gb, 10);
+                if ((s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize) &&
+                    (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + xch_fsize + 1))
+                    continue;
 
-            /* extension amode should == 1, number of channels in extension */
-            /* AFAIK XCh is not used for more channels */
-            if ((ext_amode = get_bits(&s->gb, 4)) != 1) {
-                av_log(avctx, AV_LOG_ERROR, "XCh extension amode %d not"
-                       " supported!\n",ext_amode);
-                continue;
-            }
+                /* skip length-to-end-of-frame field for the moment */
+                skip_bits(&s->gb, 10);
 
-            /* much like core primary audio coding header */
-            dca_parse_audio_coding_header(s, s->xch_base_channel);
+                s->core_ext_mask |= DCA_EXT_XCH;
 
-            for (i = 0; i < (s->sample_blocks / 8); i++) {
-                if ((ret = dca_decode_block(s, s->xch_base_channel, i))) {
-                    av_log(avctx, AV_LOG_ERROR, "error decoding XCh extension\n");
+                /* extension amode(number of channels in extension) should be 1 */
+                /* AFAIK XCh is not used for more channels */
+                if ((ext_amode = get_bits(&s->gb, 4)) != 1) {
+                    av_log(avctx, AV_LOG_ERROR, "XCh extension amode %d not"
+                           " supported!\n", ext_amode);
                     continue;
                 }
+
+                /* much like core primary audio coding header */
+                dca_parse_audio_coding_header(s, s->xch_base_channel);
+
+                for (i = 0; i < (s->sample_blocks / 8); i++)
+                    if ((ret = dca_decode_block(s, s->xch_base_channel, i))) {
+                        av_log(avctx, AV_LOG_ERROR, "error decoding XCh extension\n");
+                        continue;
+                    }
+
+                s->xch_present = 1;
+                break;
             }
+            case 0x47004a03:
+                /* XXCh: extended channels */
+                /* usually found either in core or HD part in DTS-HD HRA streams,
+                 * but not in DTS-ES which contains XCh extensions instead */
+                s->core_ext_mask |= DCA_EXT_XXCH;
+                break;
+
+            case 0x1d95f262: {
+                int fsize96 = show_bits(&s->gb, 12) + 1;
+                if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)
+                    continue;
 
-            s->xch_present = 1;
-            break;
-        }
-        case 0x47004a03:
-            /* XXCh: extended channels */
-            /* usually found either in core or HD part in DTS-HD HRA streams,
-             * but not in DTS-ES which contains XCh extensions instead */
-            s->core_ext_mask |= DCA_EXT_XXCH;
-            break;
-
-        case 0x1d95f262: {
-            int fsize96 = show_bits(&s->gb, 12) + 1;
-            if (s->frame_size != (get_bits_count(&s->gb) >> 3) - 4 + fsize96)
-                continue;
-
-            av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n", get_bits_count(&s->gb));
-            skip_bits(&s->gb, 12);
-            av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);
-            av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));
-
-            s->core_ext_mask |= DCA_EXT_X96;
-            break;
-        }
-        }
+                av_log(avctx, AV_LOG_DEBUG, "X96 extension found at %d bits\n",
+                       get_bits_count(&s->gb));
+                skip_bits(&s->gb, 12);
+                av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", fsize96);
+                av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));
 
-        skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
-    }
+                s->core_ext_mask |= DCA_EXT_X96;
+                break;
+            }
+            }
 
+            skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);
+        }
     } else {
         /* no supported extensions, skip the rest of the core substream */
         skip_bits_long(&s->gb, core_ss_end - get_bits_count(&s->gb));
@@ -1778,15 +1811,15 @@ static int dca_decode_frame(AVCodecContext *avctx, void *data,
         s->profile = FF_PROFILE_DTS_ES;
 
     /* check for ExSS (HD part) */
-    if (s->dca_buffer_size - s->frame_size > 32
-        && get_bits_long(&s->gb, 32) == DCA_HD_MARKER)
+    if (s->dca_buffer_size - s->frame_size > 32 &&
+        get_bits_long(&s->gb, 32) == DCA_HD_MARKER)
         dca_exss_parse_header(s);
 
     avctx->profile = s->profile;
 
     channels = s->prim_channels + !!s->lfe;
 
-    if (s->amode<16) {
+    if (s->amode < 16) {
         avctx->channel_layout = dca_core_channel_layout[s->amode];
 
         if (s->xch_present && (!avctx->request_channels ||
@@ -1818,7 +1851,7 @@ static int dca_decode_frame(AVCodecContext *avctx, void *data,
             avctx->channel_layout = AV_CH_LAYOUT_STEREO;
         }
     } else {
-        av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n",s->amode);
+        av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n", s->amode);
         return AVERROR_INVALIDDATA;
     }
 
@@ -1844,8 +1877,8 @@ static int dca_decode_frame(AVCodecContext *avctx, void *data,
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
-    samples_flt = (float   *)s->frame.data[0];
-    samples_s16 = (int16_t *)s->frame.data[0];
+    samples_flt = (float *)   s->frame.data[0];
+    samples_s16 = (int16_t *) s->frame.data[0];
 
     /* filter to get final output */
     for (i = 0; i < (s->sample_blocks / 8); i++) {
@@ -1853,10 +1886,10 @@ static int dca_decode_frame(AVCodecContext *avctx, void *data,
 
         /* If this was marked as a DTS-ES stream we need to subtract back- */
         /* channel from SL & SR to remove matrixed back-channel signal */
-        if((s->source_pcm_res & 1) && s->xch_present) {
-            float* back_chan = s->samples + s->channel_order_tab[s->xch_base_channel] * 256;
-            float* lt_chan   = s->samples + s->channel_order_tab[s->xch_base_channel - 2] * 256;
-            float* rt_chan   = s->samples + s->channel_order_tab[s->xch_base_channel - 1] * 256;
+        if ((s->source_pcm_res & 1) && s->xch_present) {
+            float *back_chan = s->samples + s->channel_order_tab[s->xch_base_channel]     * 256;
+            float *lt_chan   = s->samples + s->channel_order_tab[s->xch_base_channel - 2] * 256;
+            float *rt_chan   = s->samples + s->channel_order_tab[s->xch_base_channel - 1] * 256;
             s->dsp.vector_fmac_scalar(lt_chan, back_chan, -M_SQRT1_2, 256);
             s->dsp.vector_fmac_scalar(rt_chan, back_chan, -M_SQRT1_2, 256);
         }
@@ -1875,12 +1908,11 @@ static int dca_decode_frame(AVCodecContext *avctx, void *data,
 
     /* update lfe history */
     lfe_samples = 2 * s->lfe * (s->sample_blocks / 8);
-    for (i = 0; i < 2 * s->lfe * 4; i++) {
+    for (i = 0; i < 2 * s->lfe * 4; i++)
         s->lfe_data[i] = s->lfe_data[i + lfe_samples];
-    }
 
-    *got_frame_ptr   = 1;
-    *(AVFrame *)data = s->frame;
+    *got_frame_ptr    = 1;
+    *(AVFrame *) data = s->frame;
 
     return buf_size;
 }
@@ -1893,7 +1925,7 @@ static int dca_decode_frame(AVCodecContext *avctx, void *data,
  * @param avctx     pointer to the AVCodecContext
  */
 
-static av_cold int dca_decode_init(AVCodecContext * avctx)
+static av_cold int dca_decode_init(AVCodecContext *avctx)
 {
     DCAContext *s = avctx->priv_data;
     int i;
@@ -1907,15 +1939,15 @@ static av_cold int dca_decode_init(AVCodecContext * avctx)
     ff_dcadsp_init(&s->dcadsp);
     ff_fmt_convert_init(&s->fmt_conv, avctx);
 
-    for (i = 0; i < DCA_PRIM_CHANNELS_MAX+1; i++)
+    for (i = 0; i < DCA_PRIM_CHANNELS_MAX + 1; i++)
         s->samples_chanptr[i] = s->samples + i * 256;
 
     if (avctx->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
         avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
-        s->scale_bias = 1.0 / 32768.0;
+        s->scale_bias     = 1.0 / 32768.0;
     } else {
         avctx->sample_fmt = AV_SAMPLE_FMT_S16;
-        s->scale_bias = 1.0;
+        s->scale_bias     = 1.0;
     }
 
     /* allow downmixing to stereo */
@@ -1930,7 +1962,7 @@ static av_cold int dca_decode_init(AVCodecContext * avctx)
     return 0;
 }
 
-static av_cold int dca_decode_end(AVCodecContext * avctx)
+static av_cold int dca_decode_end(AVCodecContext *avctx)
 {
     DCAContext *s = avctx->priv_data;
     ff_mdct_end(&s->imdct);
@@ -1947,17 +1979,17 @@ static const AVProfile profiles[] = {
 };
 
 AVCodec ff_dca_decoder = {
-    .name = "dca",
-    .type = AVMEDIA_TYPE_AUDIO,
-    .id = CODEC_ID_DTS,
-    .priv_data_size = sizeof(DCAContext),
-    .init = dca_decode_init,
-    .decode = dca_decode_frame,
-    .close = dca_decode_end,
-    .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
-    .capabilities = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
-    .sample_fmts = (const enum AVSampleFormat[]) {
-        AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
-    },
-    .profiles = NULL_IF_CONFIG_SMALL(profiles),
+    .name            = "dca",
+    .type            = AVMEDIA_TYPE_AUDIO,
+    .id              = CODEC_ID_DTS,
+    .priv_data_size  = sizeof(DCAContext),
+    .init            = dca_decode_init,
+    .decode          = dca_decode_frame,
+    .close           = dca_decode_end,
+    .long_name       = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
+    .capabilities    = CODEC_CAP_CHANNEL_CONF | CODEC_CAP_DR1,
+    .sample_fmts     = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLT,
+                                                       AV_SAMPLE_FMT_S16,
+                                                       AV_SAMPLE_FMT_NONE },
+    .profiles        = NULL_IF_CONFIG_SMALL(profiles),
 };
diff --git a/libavcodec/dct.c b/libavcodec/dct.c
index 5c63af3..e65671e 100644
--- a/libavcodec/dct.c
+++ b/libavcodec/dct.c
@@ -28,15 +28,16 @@
  */
 
 #include <math.h>
+
 #include "libavutil/mathematics.h"
 #include "dct.h"
 #include "dct32.h"
 
-/* sin((M_PI * x / (2*n)) */
-#define SIN(s,n,x) (s->costab[(n) - (x)])
+/* sin((M_PI * x / (2 * n)) */
+#define SIN(s, n, x) (s->costab[(n) - (x)])
 
-/* cos((M_PI * x / (2*n)) */
-#define COS(s,n,x) (s->costab[x])
+/* cos((M_PI * x / (2 * n)) */
+#define COS(s, n, x) (s->costab[x])
 
 static void ff_dst_calc_I_c(DCTContext *ctx, FFTSample *data)
 {
@@ -44,28 +45,28 @@ static void ff_dst_calc_I_c(DCTContext *ctx, FFTSample *data)
     int i;
 
     data[0] = 0;
-    for(i = 1; i < n/2; i++) {
-        float tmp1 = data[i    ];
-        float tmp2 = data[n - i];
-        float s = SIN(ctx, n, 2*i);
-
-        s *= tmp1 + tmp2;
-        tmp1 = (tmp1 - tmp2) * 0.5f;
-        data[i    ] = s + tmp1;
-        data[n - i] = s - tmp1;
+    for (i = 1; i < n / 2; i++) {
+        float tmp1   = data[i    ];
+        float tmp2   = data[n - i];
+        float s      = SIN(ctx, n, 2 * i);
+
+        s           *= tmp1 + tmp2;
+        tmp1         = (tmp1 - tmp2) * 0.5f;
+        data[i]      = s + tmp1;
+        data[n - i]  = s - tmp1;
     }
 
-    data[n/2] *= 2;
+    data[n / 2] *= 2;
     ctx->rdft.rdft_calc(&ctx->rdft, data);
 
     data[0] *= 0.5f;
 
-    for(i = 1; i < n-2; i += 2) {
-        data[i + 1] += data[i - 1];
-        data[i    ] = -data[i + 2];
+    for (i = 1; i < n - 2; i += 2) {
+        data[i + 1] +=  data[i - 1];
+        data[i]      = -data[i + 2];
     }
 
-    data[n-1] = 0;
+    data[n - 1] = 0;
 }
 
 static void ff_dct_calc_I_c(DCTContext *ctx, FFTSample *data)
@@ -74,19 +75,19 @@ static void ff_dct_calc_I_c(DCTContext *ctx, FFTSample *data)
     int i;
     float next = -0.5f * (data[0] - data[n]);
 
-    for(i = 0; i < n/2; i++) {
-        float tmp1 = data[i    ];
+    for (i = 0; i < n / 2; i++) {
+        float tmp1 = data[i];
         float tmp2 = data[n - i];
-        float s = SIN(ctx, n, 2*i);
-        float c = COS(ctx, n, 2*i);
+        float s    = SIN(ctx, n, 2 * i);
+        float c    = COS(ctx, n, 2 * i);
 
         c *= tmp1 - tmp2;
         s *= tmp1 - tmp2;
 
         next += c;
 
-        tmp1 = (tmp1 + tmp2) * 0.5f;
-        data[i    ] = tmp1 - s;
+        tmp1        = (tmp1 + tmp2) * 0.5f;
+        data[i]     = tmp1 - s;
         data[n - i] = tmp1 + s;
     }
 
@@ -94,7 +95,7 @@ static void ff_dct_calc_I_c(DCTContext *ctx, FFTSample *data)
     data[n] = data[1];
     data[1] = next;
 
-    for(i = 3; i <= n; i += 2)
+    for (i = 3; i <= n; i += 2)
         data[i] = data[i - 2] - data[i];
 }
 
@@ -103,16 +104,16 @@ static void ff_dct_calc_III_c(DCTContext *ctx, FFTSample *data)
     int n = 1 << ctx->nbits;
     int i;
 
-    float next = data[n - 1];
+    float next  = data[n - 1];
     float inv_n = 1.0f / n;
 
     for (i = n - 2; i >= 2; i -= 2) {
-        float val1 = data[i    ];
+        float val1 = data[i];
         float val2 = data[i - 1] - data[i + 1];
-        float c = COS(ctx, n, i);
-        float s = SIN(ctx, n, i);
+        float c    = COS(ctx, n, i);
+        float s    = SIN(ctx, n, i);
 
-        data[i    ] = c * val1 + s * val2;
+        data[i]     = c * val1 + s * val2;
         data[i + 1] = s * val1 - c * val2;
     }
 
@@ -121,13 +122,13 @@ static void ff_dct_calc_III_c(DCTContext *ctx, FFTSample *data)
     ctx->rdft.rdft_calc(&ctx->rdft, data);
 
     for (i = 0; i < n / 2; i++) {
-        float tmp1 = data[i        ] * inv_n;
+        float tmp1 = data[i]         * inv_n;
         float tmp2 = data[n - i - 1] * inv_n;
-        float csc = ctx->csc2[i] * (tmp1 - tmp2);
+        float csc  = ctx->csc2[i] * (tmp1 - tmp2);
 
-        tmp1 += tmp2;
-        data[i        ] = tmp1 + csc;
-        data[n - i - 1] = tmp1 - csc;
+        tmp1            += tmp2;
+        data[i]          = tmp1 + csc;
+        data[n - i - 1]  = tmp1 - csc;
     }
 }
 
@@ -137,34 +138,33 @@ static void ff_dct_calc_II_c(DCTContext *ctx, FFTSample *data)
     int i;
     float next;
 
-    for (i=0; i < n/2; i++) {
-        float tmp1 = data[i        ];
+    for (i = 0; i < n / 2; i++) {
+        float tmp1 = data[i];
         float tmp2 = data[n - i - 1];
-        float s = SIN(ctx, n, 2*i + 1);
+        float s    = SIN(ctx, n, 2 * i + 1);
 
-        s *= tmp1 - tmp2;
-        tmp1 = (tmp1 + tmp2) * 0.5f;
+        s    *= tmp1 - tmp2;
+        tmp1  = (tmp1 + tmp2) * 0.5f;
 
-        data[i    ] = tmp1 + s;
+        data[i]     = tmp1 + s;
         data[n-i-1] = tmp1 - s;
     }
 
     ctx->rdft.rdft_calc(&ctx->rdft, data);
 
-    next = data[1] * 0.5;
+    next     = data[1] * 0.5;
     data[1] *= -1;
 
     for (i = n - 2; i >= 0; i -= 2) {
         float inr = data[i    ];
         float ini = data[i + 1];
-        float c = COS(ctx, n, i);
-        float s = SIN(ctx, n, i);
+        float c   = COS(ctx, n, i);
+        float s   = SIN(ctx, n, i);
 
-        data[i  ] = c * inr + s * ini;
+        data[i]     = c * inr + s * ini;
+        data[i + 1] = next;
 
-        data[i+1] = next;
-
-        next +=     s * inr - c * ini;
+        next += s * inr - c * ini;
     }
 }
 
@@ -180,36 +180,36 @@ av_cold int ff_dct_init(DCTContext *s, int nbits, enum DCTTransformType inverse)
 
     memset(s, 0, sizeof(*s));
 
-    s->nbits    = nbits;
-    s->inverse  = inverse;
+    s->nbits   = nbits;
+    s->inverse = inverse;
 
     if (inverse == DCT_II && nbits == 5) {
         s->dct_calc = dct32_func;
     } else {
-        ff_init_ff_cos_tabs(nbits+2);
-
-        s->costab = ff_cos_tabs[nbits+2];
+        ff_init_ff_cos_tabs(nbits + 2);
 
-        s->csc2 = av_malloc(n/2 * sizeof(FFTSample));
+        s->costab = ff_cos_tabs[nbits + 2];
+        s->csc2   = av_malloc(n / 2 * sizeof(FFTSample));
 
         if (ff_rdft_init(&s->rdft, nbits, inverse == DCT_III) < 0) {
             av_free(s->csc2);
             return -1;
         }
 
-        for (i = 0; i < n/2; i++)
-            s->csc2[i] = 0.5 / sin((M_PI / (2*n) * (2*i + 1)));
+        for (i = 0; i < n / 2; i++)
+            s->csc2[i] = 0.5 / sin((M_PI / (2 * n) * (2 * i + 1)));
 
-        switch(inverse) {
-        case DCT_I  : s->dct_calc = ff_dct_calc_I_c; break;
-        case DCT_II : s->dct_calc = ff_dct_calc_II_c ; break;
+        switch (inverse) {
+        case DCT_I  : s->dct_calc = ff_dct_calc_I_c;   break;
+        case DCT_II : s->dct_calc = ff_dct_calc_II_c;  break;
         case DCT_III: s->dct_calc = ff_dct_calc_III_c; break;
-        case DST_I  : s->dct_calc = ff_dst_calc_I_c; break;
+        case DST_I  : s->dct_calc = ff_dst_calc_I_c;   break;
         }
     }
 
     s->dct32 = ff_dct32_float;
-    if (HAVE_MMX)     ff_dct_init_mmx(s);
+    if (HAVE_MMX)
+        ff_dct_init_mmx(s);
 
     return 0;
 }
diff --git a/libavcodec/dnxhdenc.c b/libavcodec/dnxhdenc.c
index d1ab597..2b7089b 100644
--- a/libavcodec/dnxhdenc.c
+++ b/libavcodec/dnxhdenc.c
@@ -580,9 +580,9 @@ static int dnxhd_encode_thread(AVCodecContext *avctx, void *arg, int jobnr, int
 
         for (i = 0; i < 8; i++) {
             DCTELEM *block = ctx->blocks[i];
-            int last_index, overflow;
-            int n = dnxhd_switch_matrix(ctx, i);
-            last_index = ctx->m.dct_quantize(&ctx->m, block, i, qscale, &overflow);
+            int overflow, n = dnxhd_switch_matrix(ctx, i);
+            int last_index = ctx->m.dct_quantize(&ctx->m, block, i,
+                                                 qscale, &overflow);
             //START_TIMER;
             dnxhd_encode_block(ctx, block, last_index, n);
             //STOP_TIMER("encode_block");
diff --git a/libavcodec/dpcm.c b/libavcodec/dpcm.c
index 935f67c..1b0f6b0 100644
--- a/libavcodec/dpcm.c
+++ b/libavcodec/dpcm.c
@@ -288,7 +288,7 @@ static int dpcm_decode_frame(AVCodecContext *avctx, void *data,
     }
     case CODEC_ID_SOL_DPCM:
         if (avctx->codec_tag != 3) {
-            uint8_t *output_samples_u8 = data;
+            uint8_t *output_samples_u8 = s->frame.data[0];
             while (buf < buf_end) {
                 uint8_t n = *buf++;
 
diff --git a/libavcodec/dv.c b/libavcodec/dv.c
index 76825f5..74cbffb 100644
--- a/libavcodec/dv.c
+++ b/libavcodec/dv.c
@@ -757,7 +757,7 @@ static av_always_inline int dv_guess_dct_mode(DVVideoContext *s, uint8_t *data,
         if (ps > 0) {
             int is = s->ildct_cmp(NULL, data           , NULL, linesize<<1, 4) +
                      s->ildct_cmp(NULL, data + linesize, NULL, linesize<<1, 4);
-            return (ps > is);
+            return ps > is;
         }
     }
 
diff --git a/libavcodec/error_resilience.c b/libavcodec/error_resilience.c
index fe28f46..855ae77 100644
--- a/libavcodec/error_resilience.c
+++ b/libavcodec/error_resilience.c
@@ -50,7 +50,11 @@ static void decode_mb(MpegEncContext *s, int ref){
         h->mb_xy= s->mb_x + s->mb_y*s->mb_stride;
         memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
         assert(ref>=0);
-        if(ref >= h->ref_count[0]) //FIXME it is posible albeit uncommon that slice references differ between slices, we take the easy approuch and ignore it for now. If this turns out to have any relevance in practice then correct remapping should be added
+        /* FIXME: It is posible albeit uncommon that slice references
+         * differ between slices. We take the easy approach and ignore
+         * it for now. If this turns out to have any relevance in
+         * practice then correct remapping should be added. */
+        if (ref >= h->ref_count[0])
             ref=0;
         fill_rectangle(&s->current_picture.f.ref_index[0][4*h->mb_xy], 2, 2, 2, ref, 1);
         fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
@@ -105,8 +109,8 @@ static void put_dc(MpegEncContext *s, uint8_t *dest_y, uint8_t *dest_cb, uint8_t
     for(y=0; y<8; y++){
         int x;
         for(x=0; x<8; x++){
-            dest_cb[x + y*(s->uvlinesize)]= dcu/8;
-            dest_cr[x + y*(s->uvlinesize)]= dcv/8;
+            dest_cb[x + y * s->uvlinesize] = dcu / 8;
+            dest_cr[x + y * s->uvlinesize] = dcv / 8;
         }
     }
 }
@@ -662,7 +666,7 @@ static int is_intra_more_likely(MpegEncContext *s){
     if(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration && s->pict_type == AV_PICTURE_TYPE_I)
         return 1;
 
-    skip_amount= FFMAX(undamaged_count/50, 1); //check only upto 50 MBs
+    skip_amount = FFMAX(undamaged_count / 50, 1); // check only up to 50 MBs
     is_intra_likely=0;
 
     j=0;
@@ -1088,8 +1092,8 @@ void ff_er_frame_end(MpegEncContext *s){
             for(y=0; y<8; y++){
                 int x;
                 for(x=0; x<8; x++){
-                    dcu+=dest_cb[x + y*(s->uvlinesize)];
-                    dcv+=dest_cr[x + y*(s->uvlinesize)];
+                    dcu += dest_cb[x + y * s->uvlinesize];
+                    dcv += dest_cr[x + y * s->uvlinesize];
                 }
             }
             s->dc_val[1][mb_x + mb_y*s->mb_stride]= (dcu+4)>>3;
diff --git a/libavcodec/flicvideo.c b/libavcodec/flicvideo.c
index 8e8a813..b7bbfb4 100644
--- a/libavcodec/flicvideo.c
+++ b/libavcodec/flicvideo.c
@@ -41,6 +41,8 @@
 
 #include "libavutil/intreadwrite.h"
 #include "avcodec.h"
+#include "bytestream.h"
+#include "mathops.h"
 
 #define FLI_256_COLOR 4
 #define FLI_DELTA     7
@@ -132,7 +134,7 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
 {
     FlicDecodeContext *s = avctx->priv_data;
 
-    int stream_ptr = 0;
+    GetByteContext g2;
     int stream_ptr_after_color_chunk;
     int pixel_ptr;
     int palette_ptr;
@@ -163,6 +165,8 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
     unsigned char *pixels;
     unsigned int pixel_limit;
 
+    bytestream2_init(&g2, buf, buf_size);
+
     s->frame.reference = 1;
     s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
     if (avctx->reget_buffer(avctx, &s->frame) < 0) {
@@ -172,25 +176,22 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
 
     pixels = s->frame.data[0];
     pixel_limit = s->avctx->height * s->frame.linesize[0];
-
-    frame_size = AV_RL32(&buf[stream_ptr]);
-    stream_ptr += 6;  /* skip the magic number */
-    num_chunks = AV_RL16(&buf[stream_ptr]);
-    stream_ptr += 10;  /* skip padding */
+    frame_size = bytestream2_get_le32(&g2);
+    bytestream2_skip(&g2, 2); /* skip the magic number */
+    num_chunks = bytestream2_get_le16(&g2);
+    bytestream2_skip(&g2, 8);  /* skip padding */
 
     frame_size -= 16;
 
     /* iterate through the chunks */
     while ((frame_size > 0) && (num_chunks > 0)) {
-        chunk_size = AV_RL32(&buf[stream_ptr]);
-        stream_ptr += 4;
-        chunk_type = AV_RL16(&buf[stream_ptr]);
-        stream_ptr += 2;
+        chunk_size = bytestream2_get_le32(&g2);
+        chunk_type = bytestream2_get_le16(&g2);
 
         switch (chunk_type) {
         case FLI_256_COLOR:
         case FLI_COLOR:
-            stream_ptr_after_color_chunk = stream_ptr + chunk_size - 6;
+            stream_ptr_after_color_chunk = bytestream2_tell(&g2) + chunk_size - 6;
 
             /* check special case: If this file is from the Magic Carpet
              * game and uses 6-bit colors even though it reports 256-color
@@ -201,15 +202,14 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
             else
                 color_shift = 2;
             /* set up the palette */
-            color_packets = AV_RL16(&buf[stream_ptr]);
-            stream_ptr += 2;
+            color_packets = bytestream2_get_le16(&g2);
             palette_ptr = 0;
             for (i = 0; i < color_packets; i++) {
                 /* first byte is how many colors to skip */
-                palette_ptr += buf[stream_ptr++];
+                palette_ptr += bytestream2_get_byte(&g2);
 
                 /* next byte indicates how many entries to change */
-                color_changes = buf[stream_ptr++];
+                color_changes = bytestream2_get_byte(&g2);
 
                 /* if there are 0 color changes, there are actually 256 */
                 if (color_changes == 0)
@@ -222,9 +222,9 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
                     if ((unsigned)palette_ptr >= 256)
                         palette_ptr = 0;
 
-                    r = buf[stream_ptr++] << color_shift;
-                    g = buf[stream_ptr++] << color_shift;
-                    b = buf[stream_ptr++] << color_shift;
+                    r = bytestream2_get_byte(&g2) << color_shift;
+                    g = bytestream2_get_byte(&g2) << color_shift;
+                    b = bytestream2_get_byte(&g2) << color_shift;
                     entry = (r << 16) | (g << 8) | b;
                     if (s->palette[palette_ptr] != entry)
                         s->new_palette = 1;
@@ -233,20 +233,19 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
             }
 
             /* color chunks sometimes have weird 16-bit alignment issues;
-             * therefore, take the hardline approach and set the stream_ptr
+             * therefore, take the hardline approach and skip
              * to the value calculated w.r.t. the size specified by the color
              * chunk header */
-            stream_ptr = stream_ptr_after_color_chunk;
+            if (stream_ptr_after_color_chunk - bytestream2_tell(&g2) > 0)
+                bytestream2_skip(&g2, stream_ptr_after_color_chunk - bytestream2_tell(&g2));
 
             break;
 
         case FLI_DELTA:
             y_ptr = 0;
-            compressed_lines = AV_RL16(&buf[stream_ptr]);
-            stream_ptr += 2;
+            compressed_lines = bytestream2_get_le16(&g2);
             while (compressed_lines > 0) {
-                line_packets = AV_RL16(&buf[stream_ptr]);
-                stream_ptr += 2;
+                line_packets = bytestream2_get_le16(&g2);
                 if ((line_packets & 0xC000) == 0xC000) {
                     // line skip opcode
                     line_packets = -line_packets;
@@ -265,14 +264,14 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
                     pixel_countdown = s->avctx->width;
                     for (i = 0; i < line_packets; i++) {
                         /* account for the skip bytes */
-                        pixel_skip = buf[stream_ptr++];
+                        pixel_skip = bytestream2_get_byte(&g2);
                         pixel_ptr += pixel_skip;
                         pixel_countdown -= pixel_skip;
-                        byte_run = (signed char)(buf[stream_ptr++]);
+                        byte_run = sign_extend(bytestream2_get_byte(&g2), 8);
                         if (byte_run < 0) {
                             byte_run = -byte_run;
-                            palette_idx1 = buf[stream_ptr++];
-                            palette_idx2 = buf[stream_ptr++];
+                            palette_idx1 = bytestream2_get_byte(&g2);
+                            palette_idx2 = bytestream2_get_byte(&g2);
                             CHECK_PIXEL_PTR(byte_run * 2);
                             for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {
                                 pixels[pixel_ptr++] = palette_idx1;
@@ -281,8 +280,7 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
                         } else {
                             CHECK_PIXEL_PTR(byte_run * 2);
                             for (j = 0; j < byte_run * 2; j++, pixel_countdown--) {
-                                palette_idx1 = buf[stream_ptr++];
-                                pixels[pixel_ptr++] = palette_idx1;
+                                pixels[pixel_ptr++] = bytestream2_get_byte(&g2);
                             }
                         }
                     }
@@ -294,34 +292,31 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
 
         case FLI_LC:
             /* line compressed */
-            starting_line = AV_RL16(&buf[stream_ptr]);
-            stream_ptr += 2;
+            starting_line = bytestream2_get_le16(&g2);
             y_ptr = 0;
             y_ptr += starting_line * s->frame.linesize[0];
 
-            compressed_lines = AV_RL16(&buf[stream_ptr]);
-            stream_ptr += 2;
+            compressed_lines = bytestream2_get_le16(&g2);
             while (compressed_lines > 0) {
                 pixel_ptr = y_ptr;
                 CHECK_PIXEL_PTR(0);
                 pixel_countdown = s->avctx->width;
-                line_packets = buf[stream_ptr++];
+                line_packets = bytestream2_get_byte(&g2);
                 if (line_packets > 0) {
                     for (i = 0; i < line_packets; i++) {
                         /* account for the skip bytes */
-                        pixel_skip = buf[stream_ptr++];
+                        pixel_skip = bytestream2_get_byte(&g2);
                         pixel_ptr += pixel_skip;
                         pixel_countdown -= pixel_skip;
-                        byte_run = (signed char)(buf[stream_ptr++]);
+                        byte_run = sign_extend(bytestream2_get_byte(&g2),8);
                         if (byte_run > 0) {
                             CHECK_PIXEL_PTR(byte_run);
                             for (j = 0; j < byte_run; j++, pixel_countdown--) {
-                                palette_idx1 = buf[stream_ptr++];
-                                pixels[pixel_ptr++] = palette_idx1;
+                                pixels[pixel_ptr++] = bytestream2_get_byte(&g2);
                             }
                         } else if (byte_run < 0) {
                             byte_run = -byte_run;
-                            palette_idx1 = buf[stream_ptr++];
+                            palette_idx1 = bytestream2_get_byte(&g2);
                             CHECK_PIXEL_PTR(byte_run);
                             for (j = 0; j < byte_run; j++, pixel_countdown--) {
                                 pixels[pixel_ptr++] = palette_idx1;
@@ -349,12 +344,12 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
                 pixel_ptr = y_ptr;
                 /* disregard the line packets; instead, iterate through all
                  * pixels on a row */
-                stream_ptr++;
+                 bytestream2_skip(&g2, 1);
                 pixel_countdown = s->avctx->width;
                 while (pixel_countdown > 0) {
-                    byte_run = (signed char)(buf[stream_ptr++]);
+                    byte_run = sign_extend(bytestream2_get_byte(&g2), 8);
                     if (byte_run > 0) {
-                        palette_idx1 = buf[stream_ptr++];
+                        palette_idx1 = bytestream2_get_byte(&g2);
                         CHECK_PIXEL_PTR(byte_run);
                         for (j = 0; j < byte_run; j++) {
                             pixels[pixel_ptr++] = palette_idx1;
@@ -367,8 +362,7 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
                         byte_run = -byte_run;
                         CHECK_PIXEL_PTR(byte_run);
                         for (j = 0; j < byte_run; j++) {
-                            palette_idx1 = buf[stream_ptr++];
-                            pixels[pixel_ptr++] = palette_idx1;
+                            pixels[pixel_ptr++] = bytestream2_get_byte(&g2);
                             pixel_countdown--;
                             if (pixel_countdown < 0)
                                 av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n",
@@ -386,20 +380,19 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
             if (chunk_size - 6 > s->avctx->width * s->avctx->height) {
                 av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \
                        "bigger than image, skipping chunk\n", chunk_size - 6);
-                stream_ptr += chunk_size - 6;
+                bytestream2_skip(&g2, chunk_size - 6);
             } else {
                 for (y_ptr = 0; y_ptr < s->frame.linesize[0] * s->avctx->height;
                      y_ptr += s->frame.linesize[0]) {
-                    memcpy(&pixels[y_ptr], &buf[stream_ptr],
-                        s->avctx->width);
-                    stream_ptr += s->avctx->width;
+                    bytestream2_get_buffer(&g2, &pixels[y_ptr],
+                                           s->avctx->width);
                 }
             }
             break;
 
         case FLI_MINI:
             /* some sort of a thumbnail? disregard this chunk... */
-            stream_ptr += chunk_size - 6;
+            bytestream2_skip(&g2, chunk_size - 6);
             break;
 
         default:
@@ -413,9 +406,11 @@ static int flic_decode_frame_8BPP(AVCodecContext *avctx,
 
     /* by the end of the chunk, the stream ptr should equal the frame
      * size (minus 1, possibly); if it doesn't, issue a warning */
-    if ((stream_ptr != buf_size) && (stream_ptr != buf_size - 1))
+    if ((bytestream2_get_bytes_left(&g2) != 0) &&
+        (bytestream2_get_bytes_left(&g2) != 1))
         av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \
-               "and final chunk ptr = %d\n", buf_size, stream_ptr);
+               "and final chunk ptr = %d\n", buf_size,
+               buf_size - bytestream2_get_bytes_left(&g2));
 
     /* make the palette available on the way out */
     memcpy(s->frame.data[1], s->palette, AVPALETTE_SIZE);
@@ -438,7 +433,7 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
     /* Format is the pixel format, the packets are processed the same. */
     FlicDecodeContext *s = avctx->priv_data;
 
-    int stream_ptr = 0;
+    GetByteContext g2;
     int pixel_ptr;
     unsigned char palette_idx1;
 
@@ -461,6 +456,8 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
     int pixel;
     unsigned int pixel_limit;
 
+    bytestream2_init(&g2, buf, buf_size);
+
     s->frame.reference = 1;
     s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
     if (avctx->reget_buffer(avctx, &s->frame) < 0) {
@@ -471,19 +468,17 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
     pixels = s->frame.data[0];
     pixel_limit = s->avctx->height * s->frame.linesize[0];
 
-    frame_size = AV_RL32(&buf[stream_ptr]);
-    stream_ptr += 6;  /* skip the magic number */
-    num_chunks = AV_RL16(&buf[stream_ptr]);
-    stream_ptr += 10;  /* skip padding */
+    frame_size = bytestream2_get_le32(&g2);
+    bytestream2_skip(&g2, 2);  /* skip the magic number */
+    num_chunks = bytestream2_get_le16(&g2);
+    bytestream2_skip(&g2, 8);  /* skip padding */
 
     frame_size -= 16;
 
     /* iterate through the chunks */
     while ((frame_size > 0) && (num_chunks > 0)) {
-        chunk_size = AV_RL32(&buf[stream_ptr]);
-        stream_ptr += 4;
-        chunk_type = AV_RL16(&buf[stream_ptr]);
-        stream_ptr += 2;
+        chunk_size = bytestream2_get_le32(&g2);
+        chunk_type = bytestream2_get_le16(&g2);
 
         switch (chunk_type) {
         case FLI_256_COLOR:
@@ -492,17 +487,15 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
              * include one of these chunks in their first frame.
              * Why I do not know, it seems rather extraneous. */
 /*            av_log(avctx, AV_LOG_ERROR, "Unexpected Palette chunk %d in non-paletised FLC\n",chunk_type);*/
-            stream_ptr = stream_ptr + chunk_size - 6;
+            bytestream2_skip(&g2, chunk_size - 6);
             break;
 
         case FLI_DELTA:
         case FLI_DTA_LC:
             y_ptr = 0;
-            compressed_lines = AV_RL16(&buf[stream_ptr]);
-            stream_ptr += 2;
+            compressed_lines = bytestream2_get_le16(&g2);
             while (compressed_lines > 0) {
-                line_packets = AV_RL16(&buf[stream_ptr]);
-                stream_ptr += 2;
+                line_packets = bytestream2_get_le16(&g2);
                 if (line_packets < 0) {
                     line_packets = -line_packets;
                     y_ptr += line_packets * s->frame.linesize[0];
@@ -513,14 +506,13 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                     pixel_countdown = s->avctx->width;
                     for (i = 0; i < line_packets; i++) {
                         /* account for the skip bytes */
-                        pixel_skip = buf[stream_ptr++];
+                        pixel_skip = bytestream2_get_byte(&g2);
                         pixel_ptr += (pixel_skip*2); /* Pixel is 2 bytes wide */
                         pixel_countdown -= pixel_skip;
-                        byte_run = (signed char)(buf[stream_ptr++]);
+                        byte_run = sign_extend(bytestream2_get_byte(&g2), 8);
                         if (byte_run < 0) {
                             byte_run = -byte_run;
-                            pixel    = AV_RL16(&buf[stream_ptr]);
-                            stream_ptr += 2;
+                            pixel    = bytestream2_get_le16(&g2);
                             CHECK_PIXEL_PTR(2 * byte_run);
                             for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {
                                 *((signed short*)(&pixels[pixel_ptr])) = pixel;
@@ -529,8 +521,7 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                         } else {
                             CHECK_PIXEL_PTR(2 * byte_run);
                             for (j = 0; j < byte_run; j++, pixel_countdown--) {
-                                *((signed short*)(&pixels[pixel_ptr])) = AV_RL16(&buf[stream_ptr]);
-                                stream_ptr += 2;
+                                *((signed short*)(&pixels[pixel_ptr])) = bytestream2_get_le16(&g2);
                                 pixel_ptr += 2;
                             }
                         }
@@ -543,7 +534,7 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
 
         case FLI_LC:
             av_log(avctx, AV_LOG_ERROR, "Unexpected FLI_LC chunk in non-paletised FLC\n");
-            stream_ptr = stream_ptr + chunk_size - 6;
+            bytestream2_skip(&g2, chunk_size - 6);
             break;
 
         case FLI_BLACK:
@@ -558,13 +549,13 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                 pixel_ptr = y_ptr;
                 /* disregard the line packets; instead, iterate through all
                  * pixels on a row */
-                stream_ptr++;
+                bytestream2_skip(&g2, 1);
                 pixel_countdown = (s->avctx->width * 2);
 
                 while (pixel_countdown > 0) {
-                    byte_run = (signed char)(buf[stream_ptr++]);
+                    byte_run = sign_extend(bytestream2_get_byte(&g2), 8);
                     if (byte_run > 0) {
-                        palette_idx1 = buf[stream_ptr++];
+                        palette_idx1 = bytestream2_get_byte(&g2);
                         CHECK_PIXEL_PTR(byte_run);
                         for (j = 0; j < byte_run; j++) {
                             pixels[pixel_ptr++] = palette_idx1;
@@ -577,7 +568,7 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                         byte_run = -byte_run;
                         CHECK_PIXEL_PTR(byte_run);
                         for (j = 0; j < byte_run; j++) {
-                            palette_idx1 = buf[stream_ptr++];
+                            palette_idx1 = bytestream2_get_byte(&g2);
                             pixels[pixel_ptr++] = palette_idx1;
                             pixel_countdown--;
                             if (pixel_countdown < 0)
@@ -610,14 +601,13 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                 pixel_ptr = y_ptr;
                 /* disregard the line packets; instead, iterate through all
                  * pixels on a row */
-                stream_ptr++;
+                bytestream2_skip(&g2, 1);
                 pixel_countdown = s->avctx->width; /* Width is in pixels, not bytes */
 
                 while (pixel_countdown > 0) {
-                    byte_run = (signed char)(buf[stream_ptr++]);
+                    byte_run = sign_extend(bytestream2_get_byte(&g2), 8);
                     if (byte_run > 0) {
-                        pixel    = AV_RL16(&buf[stream_ptr]);
-                        stream_ptr += 2;
+                        pixel    = bytestream2_get_le16(&g2);
                         CHECK_PIXEL_PTR(2 * byte_run);
                         for (j = 0; j < byte_run; j++) {
                             *((signed short*)(&pixels[pixel_ptr])) = pixel;
@@ -631,8 +621,7 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                         byte_run = -byte_run;
                         CHECK_PIXEL_PTR(2 * byte_run);
                         for (j = 0; j < byte_run; j++) {
-                            *((signed short*)(&pixels[pixel_ptr])) = AV_RL16(&buf[stream_ptr]);
-                            stream_ptr += 2;
+                            *((signed short*)(&pixels[pixel_ptr])) = bytestream2_get_le16(&g2);
                             pixel_ptr  += 2;
                             pixel_countdown--;
                             if (pixel_countdown < 0)
@@ -652,7 +641,7 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
             if (chunk_size - 6 > (unsigned int)(s->avctx->width * s->avctx->height)*2) {
                 av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \
                        "bigger than image, skipping chunk\n", chunk_size - 6);
-                stream_ptr += chunk_size - 6;
+                bytestream2_skip(&g2, chunk_size - 6);
             } else {
 
                 for (y_ptr = 0; y_ptr < s->frame.linesize[0] * s->avctx->height;
@@ -661,18 +650,17 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
                     pixel_countdown = s->avctx->width;
                     pixel_ptr = 0;
                     while (pixel_countdown > 0) {
-                      *((signed short*)(&pixels[y_ptr + pixel_ptr])) = AV_RL16(&buf[stream_ptr+pixel_ptr]);
+                      *((signed short*)(&pixels[y_ptr + pixel_ptr])) = bytestream2_get_le16(&g2);
                       pixel_ptr += 2;
                       pixel_countdown--;
                     }
-                    stream_ptr += s->avctx->width*2;
                 }
             }
             break;
 
         case FLI_MINI:
             /* some sort of a thumbnail? disregard this chunk... */
-            stream_ptr += chunk_size - 6;
+            bytestream2_skip(&g2, chunk_size - 6);
             break;
 
         default:
@@ -686,9 +674,9 @@ static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,
 
     /* by the end of the chunk, the stream ptr should equal the frame
      * size (minus 1, possibly); if it doesn't, issue a warning */
-    if ((stream_ptr != buf_size) && (stream_ptr != buf_size - 1))
+    if ((bytestream2_get_bytes_left(&g2) != 0) && (bytestream2_get_bytes_left(&g2) != 1))
         av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \
-               "and final chunk ptr = %d\n", buf_size, stream_ptr);
+               "and final chunk ptr = %d\n", buf_size, bytestream2_tell(&g2));
 
 
     *data_size=sizeof(AVFrame);
diff --git a/libavcodec/g722enc.c b/libavcodec/g722enc.c
index 1eed784..1cb0070 100644
--- a/libavcodec/g722enc.c
+++ b/libavcodec/g722enc.c
@@ -32,6 +32,15 @@
 
 #define FREEZE_INTERVAL 128
 
+/* This is an arbitrary value. Allowing insanely large values leads to strange
+   problems, so we limit it to a reasonable value */
+#define MAX_FRAME_SIZE 32768
+
+/* We clip the value of avctx->trellis to prevent data type overflows and
+   undefined behavior. Using larger values is insanely slow anyway. */
+#define MIN_TRELLIS 0
+#define MAX_TRELLIS 16
+
 static av_cold int g722_encode_init(AVCodecContext * avctx)
 {
     G722Context *c = avctx->priv_data;
@@ -56,6 +65,40 @@ static av_cold int g722_encode_init(AVCodecContext * avctx)
         }
     }
 
+    if (avctx->frame_size) {
+        /* validate frame size */
+        if (avctx->frame_size & 1 || avctx->frame_size > MAX_FRAME_SIZE) {
+            int new_frame_size;
+
+            if (avctx->frame_size == 1)
+                new_frame_size = 2;
+            else if (avctx->frame_size > MAX_FRAME_SIZE)
+                new_frame_size = MAX_FRAME_SIZE;
+            else
+                new_frame_size = avctx->frame_size - 1;
+
+            av_log(avctx, AV_LOG_WARNING, "Requested frame size is not "
+                   "allowed. Using %d instead of %d\n", new_frame_size,
+                   avctx->frame_size);
+            avctx->frame_size = new_frame_size;
+        }
+    } else {
+        /* This is arbitrary. We use 320 because it's 20ms @ 16kHz, which is
+           a common packet size for VoIP applications */
+        avctx->frame_size = 320;
+    }
+
+    if (avctx->trellis) {
+        /* validate trellis */
+        if (avctx->trellis < MIN_TRELLIS || avctx->trellis > MAX_TRELLIS) {
+            int new_trellis = av_clip(avctx->trellis, MIN_TRELLIS, MAX_TRELLIS);
+            av_log(avctx, AV_LOG_WARNING, "Requested trellis value is not "
+                   "allowed. Using %d instead of %d\n", new_trellis,
+                   avctx->trellis);
+            avctx->trellis = new_trellis;
+        }
+    }
+
     return 0;
 }
 
@@ -117,13 +160,12 @@ static inline int encode_low(const struct G722Band* state, int xlow)
     return (diff < 0 ? (i < 2 ? 63 : 33) : 61) - i;
 }
 
-static int g722_encode_trellis(AVCodecContext *avctx,
-                               uint8_t *dst, int buf_size, void *data)
+static void g722_encode_trellis(G722Context *c, int trellis,
+                                uint8_t *dst, int nb_samples,
+                                const int16_t *samples)
 {
-    G722Context *c = avctx->priv_data;
-    const int16_t *samples = data;
     int i, j, k;
-    int frontier = 1 << avctx->trellis;
+    int frontier = 1 << trellis;
     struct TrellisNode **nodes[2];
     struct TrellisNode **nodes_next[2];
     int pathn[2] = {0, 0}, froze = -1;
@@ -139,7 +181,7 @@ static int g722_encode_trellis(AVCodecContext *avctx,
         nodes[i][0]->state = c->band[i];
     }
 
-    for (i = 0; i < buf_size; i++) {
+    for (i = 0; i < nb_samples >> 1; i++) {
         int xlow, xhigh;
         struct TrellisNode *next[2];
         int heap_pos[2] = {0, 0};
@@ -271,8 +313,28 @@ static int g722_encode_trellis(AVCodecContext *avctx,
     }
     c->band[0] = nodes[0][0]->state;
     c->band[1] = nodes[1][0]->state;
+}
+
+static av_always_inline void encode_byte(G722Context *c, uint8_t *dst,
+                                         const int16_t *samples)
+{
+    int xlow, xhigh, ilow, ihigh;
+    filter_samples(c, samples, &xlow, &xhigh);
+    ihigh = encode_high(&c->band[1], xhigh);
+    ilow  = encode_low (&c->band[0], xlow);
+    ff_g722_update_high_predictor(&c->band[1], c->band[1].scale_factor *
+                                ff_g722_high_inv_quant[ihigh] >> 10, ihigh);
+    ff_g722_update_low_predictor(&c->band[0], ilow >> 2);
+    *dst = ihigh << 6 | ilow;
+}
 
-    return i;
+static void g722_encode_no_trellis(G722Context *c,
+                                   uint8_t *dst, int nb_samples,
+                                   const int16_t *samples)
+{
+    int i;
+    for (i = 0; i < nb_samples; i += 2)
+        encode_byte(c, dst++, &samples[i]);
 }
 
 static int g722_encode_frame(AVCodecContext *avctx,
@@ -280,22 +342,22 @@ static int g722_encode_frame(AVCodecContext *avctx,
 {
     G722Context *c = avctx->priv_data;
     const int16_t *samples = data;
-    int i;
+    int nb_samples;
 
-    if (avctx->trellis)
-        return g722_encode_trellis(avctx, dst, buf_size, data);
+    nb_samples = avctx->frame_size - (avctx->frame_size & 1);
 
-    for (i = 0; i < buf_size; i++) {
-        int xlow, xhigh, ihigh, ilow;
-        filter_samples(c, &samples[2*i], &xlow, &xhigh);
-        ihigh = encode_high(&c->band[1], xhigh);
-        ilow  = encode_low(&c->band[0], xlow);
-        ff_g722_update_high_predictor(&c->band[1], c->band[1].scale_factor *
-                                      ff_g722_high_inv_quant[ihigh] >> 10, ihigh);
-        ff_g722_update_low_predictor(&c->band[0], ilow >> 2);
-        *dst++ = ihigh << 6 | ilow;
+    if (avctx->trellis)
+        g722_encode_trellis(c, avctx->trellis, dst, nb_samples, samples);
+    else
+        g722_encode_no_trellis(c, dst, nb_samples, samples);
+
+    /* handle last frame with odd frame_size */
+    if (nb_samples < avctx->frame_size) {
+        int16_t last_samples[2] = { samples[nb_samples], samples[nb_samples] };
+        encode_byte(c, &dst[nb_samples >> 1], last_samples);
     }
-    return i;
+
+    return (avctx->frame_size + 1) >> 1;
 }
 
 AVCodec ff_adpcm_g722_encoder = {
@@ -306,6 +368,7 @@ AVCodec ff_adpcm_g722_encoder = {
     .init           = g722_encode_init,
     .close          = g722_encode_close,
     .encode         = g722_encode_frame,
+    .capabilities   = CODEC_CAP_SMALL_LAST_FRAME,
     .long_name      = NULL_IF_CONFIG_SMALL("G.722 ADPCM"),
     .sample_fmts    = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
 };
diff --git a/libavcodec/h264.c b/libavcodec/h264.c
index 2bde0fe..cee16e7 100644
--- a/libavcodec/h264.c
+++ b/libavcodec/h264.c
@@ -1280,7 +1280,6 @@ int ff_h264_frame_start(H264Context *h){
     MpegEncContext * const s = &h->s;
     int i;
     const int pixel_shift = h->pixel_shift;
-    int thread_count = (s->avctx->active_thread_type & FF_THREAD_SLICE) ? s->avctx->thread_count : 1;
 
     if(MPV_frame_start(s, s->avctx) < 0)
         return -1;
@@ -1309,7 +1308,7 @@ int ff_h264_frame_start(H264Context *h){
 
     /* can't be in alloc_tables because linesize isn't known there.
      * FIXME: redo bipred weight to not require extra buffer? */
-    for(i = 0; i < thread_count; i++)
+    for(i = 0; i < s->slice_context_count; i++)
         if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
             h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
 
@@ -1818,7 +1817,7 @@ static av_always_inline void hl_decode_mb_predict_luma(H264Context *h, int mb_ty
                                     idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
                                 else
                                     idct_add   (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
-                            }else
+                            } else if (CONFIG_SVQ3_DECODER)
                                 ff_svq3_add_idct_c(ptr, h->mb + i*16+p*256, linesize, qscale, 0);
                         }
                     }
@@ -1838,7 +1837,7 @@ static av_always_inline void hl_decode_mb_predict_luma(H264Context *h, int mb_ty
                         dctcoef_set(h->mb+(p*256 << pixel_shift), pixel_shift, dc_mapping[i], dctcoef_get(h->mb_luma_dc[p], pixel_shift, i));
                 }
             }
-        }else
+        } else if (CONFIG_SVQ3_DECODER)
             ff_svq3_luma_dc_dequant_idct_c(h->mb+p*256, h->mb_luma_dc[p], qscale);
     }
 }
@@ -1882,7 +1881,7 @@ static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
                     }
                 }
             }
-        }else{
+        } else if (CONFIG_SVQ3_DECODER) {
             for(i=0; i<16; i++){
                 if(h->non_zero_count_cache[ scan8[i+p*16] ] || h->mb[i*16+p*256]){ //FIXME benchmark weird rule, & below
                     uint8_t * const ptr= dest_y + block_offset[i];
@@ -2081,7 +2080,7 @@ static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple, i
                     h->h264dsp.h264_idct_add8(dest, block_offset,
                                               h->mb, uvlinesize,
                                               h->non_zero_count_cache);
-                }else{
+                } else if (CONFIG_SVQ3_DECODER) {
                     h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16*1, h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
                     h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16*2, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
                     for(j=1; j<3; j++){
@@ -2826,7 +2825,7 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
                 return -1;
             }
         } else {
-            for(i = 1; i < s->avctx->thread_count; i++) {
+            for(i = 1; i < s->slice_context_count; i++) {
                 H264Context *c;
                 c = h->thread_context[i] = av_malloc(sizeof(H264Context));
                 memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
@@ -2839,7 +2838,7 @@ static int decode_slice_header(H264Context *h, H264Context *h0){
                 clone_tables(c, h, i);
             }
 
-            for(i = 0; i < s->avctx->thread_count; i++)
+            for(i = 0; i < s->slice_context_count; i++)
                 if (context_init(h->thread_context[i]) < 0) {
                     av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
                     return -1;
@@ -3742,7 +3741,7 @@ static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
     int nals_needed=0; ///< number of NALs that need decoding before the next frame thread starts
     int nal_index;
 
-    h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
+    h->max_contexts = s->slice_context_count;
     if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
         h->current_slice = 0;
         if (!s->first_field)
@@ -4009,7 +4008,7 @@ static int decode_frame(AVCodecContext *avctx,
     H264Context *h = avctx->priv_data;
     MpegEncContext *s = &h->s;
     AVFrame *pict = data;
-    int buf_index;
+    int buf_index = 0;
 
     s->flags= avctx->flags;
     s->flags2= avctx->flags2;
@@ -4039,7 +4038,7 @@ static int decode_frame(AVCodecContext *avctx,
             *pict= *(AVFrame*)out;
         }
 
-        return 0;
+        return buf_index;
     }
 
     buf_index=decode_nal_units(h, buf, buf_size);
@@ -4110,10 +4109,10 @@ int main(void){
     uint8_t temp[SIZE];
     PutBitContext pb;
     GetBitContext gb;
-//    int int_temp[10000];
     DSPContext dsp;
     AVCodecContext avctx;
 
+    avctx.av_class = avcodec_get_class();
     dsputil_init(&dsp, &avctx);
 
     init_put_bits(&pb, temp, SIZE);
@@ -4127,9 +4126,7 @@ int main(void){
 
     init_get_bits(&gb, temp, 8*SIZE);
     for(i=0; i<COUNT; i++){
-        int j, s;
-
-        s= show_bits(&gb, 24);
+        int j, s = show_bits(&gb, 24);
 
         START_TIMER
         j= get_ue_golomb(&gb);
@@ -4152,9 +4149,7 @@ int main(void){
 
     init_get_bits(&gb, temp, 8*SIZE);
     for(i=0; i<COUNT; i++){
-        int j, s;
-
-        s= show_bits(&gb, 24);
+        int j, s = show_bits(&gb, 24);
 
         START_TIMER
         j= get_se_golomb(&gb);
diff --git a/libavcodec/h264_parser.c b/libavcodec/h264_parser.c
index 826c17a..bcaa04a 100644
--- a/libavcodec/h264_parser.c
+++ b/libavcodec/h264_parser.c
@@ -330,6 +330,7 @@ static int init(AVCodecParserContext *s)
 {
     H264Context *h = s->priv_data;
     h->thread_context[0] = h;
+    h->s.slice_context_count = 1;
     return 0;
 }
 
diff --git a/libavcodec/imgconvert.c b/libavcodec/imgconvert.c
index eb398f7..eab051b 100644
--- a/libavcodec/imgconvert.c
+++ b/libavcodec/imgconvert.c
@@ -1000,7 +1000,7 @@ static void deinterlace_bottom_field_inplace(uint8_t *src1, int src_wrap,
     uint8_t *src_m1, *src_0, *src_p1, *src_p2;
     int y;
     uint8_t *buf;
-    buf = (uint8_t*)av_malloc(width);
+    buf = av_malloc(width);
 
     src_m1 = src1;
     memcpy(buf,src_m1,width);
diff --git a/libavcodec/indeo3.c b/libavcodec/indeo3.c
index 46efbd8..d2b01f4 100644
--- a/libavcodec/indeo3.c
+++ b/libavcodec/indeo3.c
@@ -89,6 +89,7 @@ typedef struct Indeo3DecodeContext {
     const uint8_t   *next_cell_data;
     const uint8_t   *last_byte;
     const int8_t    *mc_vectors;
+    unsigned        num_vectors;    ///< number of motion vectors in mc_vectors
 
     int16_t         width, height;
     uint32_t        frame_num;      ///< current frame number (zero-based)
@@ -764,10 +765,16 @@ static int parse_bintree(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
             break;
         case INTER_DATA:
             if (!curr_cell.tree) { /* MC tree INTER code */
+                unsigned mv_idx;
                 /* get motion vector index and setup the pointer to the mv set */
                 if (!ctx->need_resync)
                     ctx->next_cell_data = &ctx->gb.buffer[(get_bits_count(&ctx->gb) + 7) >> 3];
-                curr_cell.mv_ptr = &ctx->mc_vectors[*(ctx->next_cell_data++) << 1];
+                mv_idx = *(ctx->next_cell_data++) << 1;
+                if (mv_idx >= ctx->num_vectors) {
+                    av_log(avctx, AV_LOG_ERROR, "motion vector index out of range\n");
+                    return AVERROR_INVALIDDATA;
+                }
+                curr_cell.mv_ptr = &ctx->mc_vectors[mv_idx];
                 curr_cell.tree   = 1; /* enter the VQ tree */
                 UPDATE_BITPOS(8);
             } else { /* VQ tree DATA code */
@@ -797,15 +804,22 @@ static int decode_plane(Indeo3DecodeContext *ctx, AVCodecContext *avctx,
                         int32_t strip_width)
 {
     Cell            curr_cell;
-    int             num_vectors;
+    unsigned        num_vectors;
 
     /* each plane data starts with mc_vector_count field, */
     /* an optional array of motion vectors followed by the vq data */
     num_vectors = bytestream_get_le32(&data);
-    ctx->mc_vectors  = num_vectors ? data : 0;
-
+    if (num_vectors > 256) {
+        av_log(ctx->avctx, AV_LOG_ERROR,
+               "Read invalid number of motion vectors %d\n", num_vectors);
+        return AVERROR_INVALIDDATA;
+    }
     if (num_vectors * 2 >= data_size)
         return AVERROR_INVALIDDATA;
+
+    ctx->num_vectors = num_vectors;
+    ctx->mc_vectors  = num_vectors ? data : 0;
+
     /* init the bitreader */
     init_get_bits(&ctx->gb, &data[num_vectors * 2], (data_size - num_vectors * 2) << 3);
     ctx->skip_bits   = 0;
diff --git a/libavcodec/indeo4.c b/libavcodec/indeo4.c
index e816330..dd8e5b1 100644
--- a/libavcodec/indeo4.c
+++ b/libavcodec/indeo4.c
@@ -148,7 +148,7 @@ static int decode_plane_subdivision(GetBitContext *gb)
 
 static inline int scale_tile_size(int def_size, int size_factor)
 {
-    return (size_factor == 15 ? def_size : (size_factor + 1) << 5);
+    return size_factor == 15 ? def_size : (size_factor + 1) << 5;
 }
 
 /**
diff --git a/libavcodec/indeo5.c b/libavcodec/indeo5.c
index 8b72b1f..019fa2b 100644
--- a/libavcodec/indeo5.c
+++ b/libavcodec/indeo5.c
@@ -757,7 +757,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
 
     switch_buffers(ctx);
 
-    //START_TIMER;
+    //{ START_TIMER;
 
     if (ctx->frame_type != FRAMETYPE_NULL) {
         for (p = 0; p < 3; p++) {
@@ -772,7 +772,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
         }
     }
 
-    //STOP_TIMER("decode_planes");
+    //STOP_TIMER("decode_planes"); }
 
     if (ctx->frame.data[0])
         avctx->release_buffer(avctx, &ctx->frame);
diff --git a/libavcodec/interplayvideo.c b/libavcodec/interplayvideo.c
index db98bec..724f5f1 100644
--- a/libavcodec/interplayvideo.c
+++ b/libavcodec/interplayvideo.c
@@ -1019,9 +1019,6 @@ static av_cold int ipvideo_decode_init(AVCodecContext *avctx)
 
     dsputil_init(&s->dsp, avctx);
 
-    /* decoding map contains 4 bits of information per 8x8 block */
-    s->decoding_map_size = avctx->width * avctx->height / (8 * 8 * 2);
-
     s->current_frame.data[0] = s->last_frame.data[0] =
     s->second_last_frame.data[0] = NULL;
 
@@ -1036,6 +1033,9 @@ static int ipvideo_decode_frame(AVCodecContext *avctx,
     int buf_size = avpkt->size;
     IpvideoContext *s = avctx->priv_data;
 
+    /* decoding map contains 4 bits of information per 8x8 block */
+    s->decoding_map_size = avctx->width * avctx->height / (8 * 8 * 2);
+
     /* compressed buffer needs to be large enough to at least hold an entire
      * decoding map */
     if (buf_size < s->decoding_map_size)
@@ -1096,6 +1096,6 @@ AVCodec ff_interplay_video_decoder = {
     .init           = ipvideo_decode_init,
     .close          = ipvideo_decode_end,
     .decode         = ipvideo_decode_frame,
-    .capabilities   = CODEC_CAP_DR1,
+    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_PARAM_CHANGE,
     .long_name = NULL_IF_CONFIG_SMALL("Interplay MVE video"),
 };
diff --git a/libavcodec/ivi_common.c b/libavcodec/ivi_common.c
index 9cec0a8..eedcd28 100644
--- a/libavcodec/ivi_common.c
+++ b/libavcodec/ivi_common.c
@@ -611,6 +611,9 @@ void ff_ivi_output_plane(IVIPlaneDesc *plane, uint8_t *dst, int dst_pitch)
     const int16_t   *src  = plane->bands[0].buf;
     uint32_t        pitch = plane->bands[0].pitch;
 
+    if (!src)
+        return;
+
     for (y = 0; y < plane->height; y++) {
         for (x = 0; x < plane->width; x++)
             dst[x] = av_clip_uint8(src[x] + 128);
diff --git a/libavcodec/ivi_common.h b/libavcodec/ivi_common.h
index dcda13a..4b2ae06 100644
--- a/libavcodec/ivi_common.h
+++ b/libavcodec/ivi_common.h
@@ -195,10 +195,10 @@ typedef struct {
 /** compare some properties of two pictures */
 static inline int ivi_pic_config_cmp(IVIPicConfig *str1, IVIPicConfig *str2)
 {
-    return (str1->pic_width    != str2->pic_width    || str1->pic_height    != str2->pic_height    ||
-            str1->chroma_width != str2->chroma_width || str1->chroma_height != str2->chroma_height ||
-            str1->tile_width   != str2->tile_width   || str1->tile_height   != str2->tile_height   ||
-            str1->luma_bands   != str2->luma_bands   || str1->chroma_bands  != str2->chroma_bands);
+    return str1->pic_width    != str2->pic_width    || str1->pic_height    != str2->pic_height    ||
+           str1->chroma_width != str2->chroma_width || str1->chroma_height != str2->chroma_height ||
+           str1->tile_width   != str2->tile_width   || str1->tile_height   != str2->tile_height   ||
+           str1->luma_bands   != str2->luma_bands   || str1->chroma_bands  != str2->chroma_bands;
 }
 
 /** calculate number of tiles in a stride */
diff --git a/libavcodec/kmvc.c b/libavcodec/kmvc.c
index 6c55863..2b54b84 100644
--- a/libavcodec/kmvc.c
+++ b/libavcodec/kmvc.c
@@ -46,6 +46,7 @@ typedef struct KmvcContext {
     uint32_t pal[256];
     uint8_t *cur, *prev;
     uint8_t *frm0, *frm1;
+    GetByteContext g;
 } KmvcContext;
 
 typedef struct BitBuf {
@@ -55,23 +56,19 @@ typedef struct BitBuf {
 
 #define BLK(data, x, y)  data[(x) + (y) * 320]
 
-#define kmvc_init_getbits(bb, src)  bb.bits = 7; bb.bitbuf = *src++;
+#define kmvc_init_getbits(bb, g)  bb.bits = 7; bb.bitbuf = bytestream2_get_byte(g);
 
-#define kmvc_getbit(bb, src, src_end, res) {\
+#define kmvc_getbit(bb, g, res) {\
     res = 0; \
     if (bb.bitbuf & (1 << bb.bits)) res = 1; \
     bb.bits--; \
     if(bb.bits == -1) { \
-        if (src >= src_end) { \
-            av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n"); \
-            return AVERROR_INVALIDDATA; \
-        } \
-        bb.bitbuf = *src++; \
+        bb.bitbuf = bytestream2_get_byte(g); \
         bb.bits = 7; \
     } \
 }
 
-static int kmvc_decode_intra_8x8(KmvcContext * ctx, const uint8_t * src, int src_size, int w, int h)
+static int kmvc_decode_intra_8x8(KmvcContext * ctx, int w, int h)
 {
     BitBuf bb;
     int res, val;
@@ -79,42 +76,33 @@ static int kmvc_decode_intra_8x8(KmvcContext * ctx, const uint8_t * src, int src
     int bx, by;
     int l0x, l1x, l0y, l1y;
     int mx, my;
-    const uint8_t *src_end = src + src_size;
 
-    kmvc_init_getbits(bb, src);
+    kmvc_init_getbits(bb, &ctx->g);
 
     for (by = 0; by < h; by += 8)
         for (bx = 0; bx < w; bx += 8) {
-            kmvc_getbit(bb, src, src_end, res);
+            if (!bytestream2_get_bytes_left(&ctx->g)) {
+                av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
+                return AVERROR_INVALIDDATA;
+            }
+            kmvc_getbit(bb, &ctx->g, res);
             if (!res) {         // fill whole 8x8 block
-                if (src >= src_end) {
-                    av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
-                    return AVERROR_INVALIDDATA;
-                }
-                val = *src++;
+                val = bytestream2_get_byte(&ctx->g);
                 for (i = 0; i < 64; i++)
                     BLK(ctx->cur, bx + (i & 0x7), by + (i >> 3)) = val;
             } else {            // handle four 4x4 subblocks
                 for (i = 0; i < 4; i++) {
                     l0x = bx + (i & 1) * 4;
                     l0y = by + (i & 2) * 2;
-                    kmvc_getbit(bb, src, src_end, res);
+                    kmvc_getbit(bb, &ctx->g, res);
                     if (!res) {
-                        kmvc_getbit(bb, src, src_end, res);
+                        kmvc_getbit(bb, &ctx->g, res);
                         if (!res) {     // fill whole 4x4 block
-                            if (src >= src_end) {
-                                av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
-                                return AVERROR_INVALIDDATA;
-                            }
-                            val = *src++;
+                            val = bytestream2_get_byte(&ctx->g);
                             for (j = 0; j < 16; j++)
                                 BLK(ctx->cur, l0x + (j & 3), l0y + (j >> 2)) = val;
                         } else {        // copy block from already decoded place
-                            if (src >= src_end) {
-                                av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
-                                return AVERROR_INVALIDDATA;
-                            }
-                            val = *src++;
+                            val = bytestream2_get_byte(&ctx->g);
                             mx = val & 0xF;
                             my = val >> 4;
                             for (j = 0; j < 16; j++)
@@ -125,25 +113,17 @@ static int kmvc_decode_intra_8x8(KmvcContext * ctx, const uint8_t * src, int src
                         for (j = 0; j < 4; j++) {
                             l1x = l0x + (j & 1) * 2;
                             l1y = l0y + (j & 2);
-                            kmvc_getbit(bb, src, src_end, res);
+                            kmvc_getbit(bb, &ctx->g, res);
                             if (!res) {
-                                kmvc_getbit(bb, src, src_end, res);
+                                kmvc_getbit(bb, &ctx->g, res);
                                 if (!res) {     // fill whole 2x2 block
-                                    if (src >= src_end) {
-                                        av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
-                                        return AVERROR_INVALIDDATA;
-                                    }
-                                    val = *src++;
+                                    val = bytestream2_get_byte(&ctx->g);
                                     BLK(ctx->cur, l1x, l1y) = val;
                                     BLK(ctx->cur, l1x + 1, l1y) = val;
                                     BLK(ctx->cur, l1x, l1y + 1) = val;
                                     BLK(ctx->cur, l1x + 1, l1y + 1) = val;
                                 } else {        // copy block from already decoded place
-                                    if (src >= src_end) {
-                                        av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
-                                        return AVERROR_INVALIDDATA;
-                                    }
-                                    val = *src++;
+                                    val = bytestream2_get_byte(&ctx->g);
                                     mx = val & 0xF;
                                     my = val >> 4;
                                     BLK(ctx->cur, l1x, l1y) = BLK(ctx->cur, l1x - mx, l1y - my);
@@ -155,10 +135,10 @@ static int kmvc_decode_intra_8x8(KmvcContext * ctx, const uint8_t * src, int src
                                         BLK(ctx->cur, l1x + 1 - mx, l1y + 1 - my);
                                 }
                             } else {    // read values for block
-                                BLK(ctx->cur, l1x, l1y) = *src++;
-                                BLK(ctx->cur, l1x + 1, l1y) = *src++;
-                                BLK(ctx->cur, l1x, l1y + 1) = *src++;
-                                BLK(ctx->cur, l1x + 1, l1y + 1) = *src++;
+                                BLK(ctx->cur, l1x, l1y) = bytestream2_get_byte(&ctx->g);
+                                BLK(ctx->cur, l1x + 1, l1y) = bytestream2_get_byte(&ctx->g);
+                                BLK(ctx->cur, l1x, l1y + 1) = bytestream2_get_byte(&ctx->g);
+                                BLK(ctx->cur, l1x + 1, l1y + 1) = bytestream2_get_byte(&ctx->g);
                             }
                         }
                     }
@@ -169,7 +149,7 @@ static int kmvc_decode_intra_8x8(KmvcContext * ctx, const uint8_t * src, int src
     return 0;
 }
 
-static int kmvc_decode_inter_8x8(KmvcContext * ctx, const uint8_t * src, int src_size, int w, int h)
+static int kmvc_decode_inter_8x8(KmvcContext * ctx, int w, int h)
 {
     BitBuf bb;
     int res, val;
@@ -177,21 +157,20 @@ static int kmvc_decode_inter_8x8(KmvcContext * ctx, const uint8_t * src, int src
     int bx, by;
     int l0x, l1x, l0y, l1y;
     int mx, my;
-    const uint8_t *src_end = src + src_size;
 
-    kmvc_init_getbits(bb, src);
+    kmvc_init_getbits(bb, &ctx->g);
 
     for (by = 0; by < h; by += 8)
         for (bx = 0; bx < w; bx += 8) {
-            kmvc_getbit(bb, src, src_end, res);
+            kmvc_getbit(bb, &ctx->g, res);
             if (!res) {
-                kmvc_getbit(bb, src, src_end, res);
+                kmvc_getbit(bb, &ctx->g, res);
                 if (!res) {     // fill whole 8x8 block
-                    if (src >= src_end) {
+                    if (!bytestream2_get_bytes_left(&ctx->g)) {
                         av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
                         return AVERROR_INVALIDDATA;
                     }
-                    val = *src++;
+                    val = bytestream2_get_byte(&ctx->g);
                     for (i = 0; i < 64; i++)
                         BLK(ctx->cur, bx + (i & 0x7), by + (i >> 3)) = val;
                 } else {        // copy block from previous frame
@@ -200,26 +179,22 @@ static int kmvc_decode_inter_8x8(KmvcContext * ctx, const uint8_t * src, int src
                             BLK(ctx->prev, bx + (i & 0x7), by + (i >> 3));
                 }
             } else {            // handle four 4x4 subblocks
+                if (!bytestream2_get_bytes_left(&ctx->g)) {
+                    av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
+                    return AVERROR_INVALIDDATA;
+                }
                 for (i = 0; i < 4; i++) {
                     l0x = bx + (i & 1) * 4;
                     l0y = by + (i & 2) * 2;
-                    kmvc_getbit(bb, src, src_end, res);
+                    kmvc_getbit(bb, &ctx->g, res);
                     if (!res) {
-                        kmvc_getbit(bb, src, src_end, res);
+                        kmvc_getbit(bb, &ctx->g, res);
                         if (!res) {     // fill whole 4x4 block
-                            if (src >= src_end) {
-                                av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
-                                return AVERROR_INVALIDDATA;
-                            }
-                            val = *src++;
+                            val = bytestream2_get_byte(&ctx->g);
                             for (j = 0; j < 16; j++)
                                 BLK(ctx->cur, l0x + (j & 3), l0y + (j >> 2)) = val;
                         } else {        // copy block
-                            if (src >= src_end) {
-                                av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
-                                return AVERROR_INVALIDDATA;
-                            }
-                            val = *src++;
+                            val = bytestream2_get_byte(&ctx->g);
                             mx = (val & 0xF) - 8;
                             my = (val >> 4) - 8;
                             for (j = 0; j < 16; j++)
@@ -230,25 +205,17 @@ static int kmvc_decode_inter_8x8(KmvcContext * ctx, const uint8_t * src, int src
                         for (j = 0; j < 4; j++) {
                             l1x = l0x + (j & 1) * 2;
                             l1y = l0y + (j & 2);
-                            kmvc_getbit(bb, src, src_end, res);
+                            kmvc_getbit(bb, &ctx->g, res);
                             if (!res) {
-                                kmvc_getbit(bb, src, src_end, res);
+                                kmvc_getbit(bb, &ctx->g, res);
                                 if (!res) {     // fill whole 2x2 block
-                                    if (src >= src_end) {
-                                        av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
-                                        return AVERROR_INVALIDDATA;
-                                    }
-                                    val = *src++;
+                                    val = bytestream2_get_byte(&ctx->g);
                                     BLK(ctx->cur, l1x, l1y) = val;
                                     BLK(ctx->cur, l1x + 1, l1y) = val;
                                     BLK(ctx->cur, l1x, l1y + 1) = val;
                                     BLK(ctx->cur, l1x + 1, l1y + 1) = val;
                                 } else {        // copy block
-                                    if (src >= src_end) {
-                                        av_log(ctx->avctx, AV_LOG_ERROR, "Data overrun\n");
-                                        return AVERROR_INVALIDDATA;
-                                    }
-                                    val = *src++;
+                                    val = bytestream2_get_byte(&ctx->g);
                                     mx = (val & 0xF) - 8;
                                     my = (val >> 4) - 8;
                                     BLK(ctx->cur, l1x, l1y) = BLK(ctx->prev, l1x + mx, l1y + my);
@@ -260,10 +227,10 @@ static int kmvc_decode_inter_8x8(KmvcContext * ctx, const uint8_t * src, int src
                                         BLK(ctx->prev, l1x + 1 + mx, l1y + 1 + my);
                                 }
                             } else {    // read values for block
-                                BLK(ctx->cur, l1x, l1y) = *src++;
-                                BLK(ctx->cur, l1x + 1, l1y) = *src++;
-                                BLK(ctx->cur, l1x, l1y + 1) = *src++;
-                                BLK(ctx->cur, l1x + 1, l1y + 1) = *src++;
+                                BLK(ctx->cur, l1x, l1y) = bytestream2_get_byte(&ctx->g);
+                                BLK(ctx->cur, l1x + 1, l1y) = bytestream2_get_byte(&ctx->g);
+                                BLK(ctx->cur, l1x, l1y + 1) = bytestream2_get_byte(&ctx->g);
+                                BLK(ctx->cur, l1x + 1, l1y + 1) = bytestream2_get_byte(&ctx->g);
                             }
                         }
                     }
@@ -276,8 +243,6 @@ static int kmvc_decode_inter_8x8(KmvcContext * ctx, const uint8_t * src, int src
 
 static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPacket *avpkt)
 {
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
     KmvcContext *const ctx = avctx->priv_data;
     uint8_t *out, *src;
     int i;
@@ -285,6 +250,7 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPa
     int blocksize;
     const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);
 
+    bytestream2_init(&ctx->g, avpkt->data, avpkt->size);
     if (ctx->pic.data[0])
         avctx->release_buffer(avctx, &ctx->pic);
 
@@ -295,16 +261,16 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPa
         return -1;
     }
 
-    header = *buf++;
+    header = bytestream2_get_byte(&ctx->g);
 
     /* blocksize 127 is really palette change event */
-    if (buf[0] == 127) {
-        buf += 3;
+    if (bytestream2_peek_byte(&ctx->g) == 127) {
+        bytestream2_skip(&ctx->g, 3);
         for (i = 0; i < 127; i++) {
-            ctx->pal[i + (header & 0x81)] = AV_RB24(buf);
-            buf += 4;
+            ctx->pal[i + (header & 0x81)] = bytestream2_get_be24(&ctx->g);
+            bytestream2_skip(&ctx->g, 1);
         }
-        buf -= 127 * 4 + 3;
+        bytestream2_seek(&ctx->g, -127 * 4 - 3, SEEK_CUR);
     }
 
     if (header & KMVC_KEYFRAME) {
@@ -319,7 +285,7 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPa
         ctx->pic.palette_has_changed = 1;
         // palette starts from index 1 and has 127 entries
         for (i = 1; i <= ctx->palsize; i++) {
-            ctx->pal[i] = bytestream_get_be24(&buf);
+            ctx->pal[i] = bytestream2_get_be24(&ctx->g);
         }
     }
 
@@ -336,7 +302,7 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPa
     /* make the palette available on the way out */
     memcpy(ctx->pic.data[1], ctx->pal, 1024);
 
-    blocksize = *buf++;
+    blocksize = bytestream2_get_byte(&ctx->g);
 
     if (blocksize != 8 && blocksize != 127) {
         av_log(avctx, AV_LOG_ERROR, "Block size = %i\n", blocksize);
@@ -349,10 +315,10 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPa
         memcpy(ctx->cur, ctx->prev, 320 * 200);
         break;
     case 3:
-        kmvc_decode_intra_8x8(ctx, buf, buf_size, avctx->width, avctx->height);
+        kmvc_decode_intra_8x8(ctx, avctx->width, avctx->height);
         break;
     case 4:
-        kmvc_decode_inter_8x8(ctx, buf, buf_size, avctx->width, avctx->height);
+        kmvc_decode_inter_8x8(ctx, avctx->width, avctx->height);
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Unknown compression method %i\n", header & KMVC_METHOD);
@@ -380,7 +346,7 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *data_size, AVPa
     *(AVFrame *) data = ctx->pic;
 
     /* always report that the buffer was completely consumed */
-    return buf_size;
+    return avpkt->size;
 }
 
 
diff --git a/libavcodec/libdiracenc.c b/libavcodec/libdiracenc.c
index 33dba22..156ba57 100644
--- a/libavcodec/libdiracenc.c
+++ b/libavcodec/libdiracenc.c
@@ -136,7 +136,7 @@ static av_cold int libdirac_encode_init(AVCodecContext *avccontext)
     preset = GetDiracVideoFormatPreset(avccontext);
 
     /* initialize the encoder context */
-    dirac_encoder_context_init(&(p_dirac_params->enc_ctx), preset);
+    dirac_encoder_context_init(&p_dirac_params->enc_ctx, preset);
 
     p_dirac_params->enc_ctx.src_params.chroma = GetDiracChromaFormat(avccontext->pix_fmt);
 
@@ -199,7 +199,7 @@ static av_cold int libdirac_encode_init(AVCodecContext *avccontext)
          * irrespective of the type of source material */
         p_dirac_params->enc_ctx.enc_params.picture_coding_mode = 1;
 
-    p_dirac_params->p_encoder = dirac_encoder_init(&(p_dirac_params->enc_ctx),
+    p_dirac_params->p_encoder = dirac_encoder_init(&p_dirac_params->enc_ctx,
                                                    verbose);
 
     if (!p_dirac_params->p_encoder) {
@@ -221,7 +221,7 @@ static void DiracFreeFrame(void *data)
 {
     DiracSchroEncodedFrame *enc_frame = data;
 
-    av_freep(&(enc_frame->p_encbuf));
+    av_freep(&enc_frame->p_encbuf);
     av_free(enc_frame);
 }
 
diff --git a/libavcodec/libschroedingerenc.c b/libavcodec/libschroedingerenc.c
index dec9c2a..2aadd3a 100644
--- a/libavcodec/libschroedingerenc.c
+++ b/libavcodec/libschroedingerenc.c
@@ -258,7 +258,7 @@ static void SchroedingerFreeFrame(void *data)
 {
     DiracSchroEncodedFrame *enc_frame = data;
 
-    av_freep(&(enc_frame->p_encbuf));
+    av_freep(&enc_frame->p_encbuf);
     av_free(enc_frame);
 }
 
diff --git a/libavcodec/libspeexenc.c b/libavcodec/libspeexenc.c
index 18f973f..290718c 100644
--- a/libavcodec/libspeexenc.c
+++ b/libavcodec/libspeexenc.c
@@ -83,7 +83,8 @@ typedef struct {
     int abr;                    ///< flag to enable ABR
     int pkt_frame_count;        ///< frame count for the current packet
     int lookahead;              ///< encoder delay
-    int sample_count;           ///< total sample count (used for pts)
+    int64_t next_pts;           ///< next pts, in sample_rate time base
+    int pkt_sample_count;       ///< sample count in the current packet
 } LibSpeexEncContext;
 
 static av_cold void print_enc_params(AVCodecContext *avctx,
@@ -201,7 +202,7 @@ static av_cold int encode_init(AVCodecContext *avctx)
 
     /* set encoding delay */
     speex_encoder_ctl(s->enc_state, SPEEX_GET_LOOKAHEAD, &s->lookahead);
-    s->sample_count = -s->lookahead;
+    s->next_pts = -s->lookahead;
 
     /* create header packet bytes from header struct */
     /* note: libspeex allocates the memory for header_data, which is freed
@@ -235,7 +236,6 @@ static int encode_frame(AVCodecContext *avctx, uint8_t *frame, int buf_size,
 {
     LibSpeexEncContext *s = avctx->priv_data;
     int16_t *samples      = data;
-    int sample_count      = s->sample_count;
 
     if (data) {
         /* encode Speex frame */
@@ -243,7 +243,7 @@ static int encode_frame(AVCodecContext *avctx, uint8_t *frame, int buf_size,
             speex_encode_stereo_int(samples, s->header.frame_size, &s->bits);
         speex_encode_int(s->enc_state, samples, &s->bits);
         s->pkt_frame_count++;
-        s->sample_count += avctx->frame_size;
+        s->pkt_sample_count += avctx->frame_size;
     } else {
         /* handle end-of-stream */
         if (!s->pkt_frame_count)
@@ -259,8 +259,10 @@ static int encode_frame(AVCodecContext *avctx, uint8_t *frame, int buf_size,
     if (s->pkt_frame_count == s->frames_per_packet) {
         s->pkt_frame_count = 0;
         avctx->coded_frame->pts =
-            av_rescale_q(sample_count, (AVRational){ 1, avctx->sample_rate },
+            av_rescale_q(s->next_pts, (AVRational){ 1, avctx->sample_rate },
                          avctx->time_base);
+        s->next_pts += s->pkt_sample_count;
+        s->pkt_sample_count = 0;
         if (buf_size > speex_bits_nbytes(&s->bits)) {
             int ret = speex_bits_write(&s->bits, frame, buf_size);
             speex_bits_reset(&s->bits);
diff --git a/libavcodec/libvorbis.c b/libavcodec/libvorbis.c
index 28e313a..25e6006 100644
--- a/libavcodec/libvorbis.c
+++ b/libavcodec/libvorbis.c
@@ -105,7 +105,7 @@ static av_cold int oggvorbis_init_encoder(vorbis_info *vi, AVCodecContext *avcco
 /* How many bytes are needed for a buffer of length 'l' */
 static int xiph_len(int l)
 {
-    return (1 + l / 255 + l);
+    return 1 + l / 255 + l;
 }
 
 static av_cold int oggvorbis_encode_init(AVCodecContext *avccontext)
diff --git a/libavcodec/libvpxdec.c b/libavcodec/libvpxdec.c
index 5acd0f9..917a502 100644
--- a/libavcodec/libvpxdec.c
+++ b/libavcodec/libvpxdec.c
@@ -119,5 +119,6 @@ AVCodec ff_libvpx_decoder = {
     .init           = vp8_init,
     .close          = vp8_free,
     .decode         = vp8_decode,
-    .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
+    .capabilities   = CODEC_CAP_AUTO_THREADS,
+    .long_name      = NULL_IF_CONFIG_SMALL("libvpx VP8"),
 };
diff --git a/libavcodec/libvpxenc.c b/libavcodec/libvpxenc.c
index fce3de0..64ff2c1 100644
--- a/libavcodec/libvpxenc.c
+++ b/libavcodec/libvpxenc.c
@@ -572,7 +572,7 @@ AVCodec ff_libvpx_encoder = {
     .init           = vp8_init,
     .encode         = vp8_encode,
     .close          = vp8_free,
-    .capabilities   = CODEC_CAP_DELAY,
+    .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
     .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
     .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
     .priv_class = &class,
diff --git a/libavcodec/libx264.c b/libavcodec/libx264.c
index c525808..9b34795 100644
--- a/libavcodec/libx264.c
+++ b/libavcodec/libx264.c
@@ -592,7 +592,7 @@ AVCodec ff_libx264_encoder = {
     .init           = X264_init,
     .encode         = X264_frame,
     .close          = X264_close,
-    .capabilities   = CODEC_CAP_DELAY,
+    .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
     .long_name      = NULL_IF_CONFIG_SMALL("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
     .priv_class     = &class,
     .defaults       = x264_defaults,
diff --git a/libavcodec/libxavs.c b/libavcodec/libxavs.c
index 823f5fb..1a16bd9 100644
--- a/libavcodec/libxavs.c
+++ b/libavcodec/libxavs.c
@@ -414,7 +414,7 @@ AVCodec ff_libxavs_encoder = {
     .init           = XAVS_init,
     .encode         = XAVS_frame,
     .close          = XAVS_close,
-    .capabilities   = CODEC_CAP_DELAY,
+    .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
     .pix_fmts       = (const enum PixelFormat[]) { PIX_FMT_YUV420P, PIX_FMT_NONE },
     .long_name      = NULL_IF_CONFIG_SMALL("libxavs - the Chinese Audio Video Standard Encoder"),
     .priv_class     = &class,
diff --git a/libavcodec/libxvidff.c b/libavcodec/libxvidff.c
index d0f4ed3..a11e4ac 100644
--- a/libavcodec/libxvidff.c
+++ b/libavcodec/libxvidff.c
@@ -270,7 +270,7 @@ static av_cold int xvid_encode_init(AVCodecContext *avctx)  {
         rc2pass2.version = XVID_VERSION;
         rc2pass2.bitrate = avctx->bit_rate;
 
-        fd = ff_tempfile("xvidff.", &(x->twopassfile));
+        fd = ff_tempfile("xvidff.", &x->twopassfile);
         if( fd == -1 ) {
             av_log(avctx, AV_LOG_ERROR,
                 "Xvid: Cannot write 2-pass pipe\n");
@@ -414,7 +414,7 @@ static int xvid_encode_frame(AVCodecContext *avctx,
     char *tmp;
     struct xvid_context *x = avctx->priv_data;
     AVFrame *picture = data;
-    AVFrame *p = &(x->encoded_picture);
+    AVFrame *p = &x->encoded_picture;
 
     xvid_enc_frame_t xvid_enc_frame;
     xvid_enc_stats_t xvid_enc_stats;
@@ -575,7 +575,7 @@ int xvid_strip_vol_header(AVCodecContext *avctx,
         }
         /* Less dangerous now, memmove properly copies the two
            chunks of overlapping data */
-        memmove(frame, &(frame[vo_len]), frame_len - vo_len);
+        memmove(frame, &frame[vo_len], frame_len - vo_len);
         return frame_len - vo_len;
     } else
         return frame_len;
diff --git a/libavcodec/mjpegdec.c b/libavcodec/mjpegdec.c
index 058b08f..2ae502d 100644
--- a/libavcodec/mjpegdec.c
+++ b/libavcodec/mjpegdec.c
@@ -30,7 +30,7 @@
  * MJPEG decoder.
  */
 
-//#define DEBUG
+// #define DEBUG
 #include <assert.h>
 
 #include "libavutil/imgutils.h"
@@ -42,8 +42,9 @@
 #include "jpeglsdec.h"
 
 
-static int build_vlc(VLC *vlc, const uint8_t *bits_table, const uint8_t *val_table,
-                      int nb_codes, int use_static, int is_ac)
+static int build_vlc(VLC *vlc, const uint8_t *bits_table,
+                     const uint8_t *val_table, int nb_codes,
+                     int use_static, int is_ac)
 {
     uint8_t huff_size[256];
     uint16_t huff_code[256];
@@ -55,15 +56,18 @@ static int build_vlc(VLC *vlc, const uint8_t *bits_table, const uint8_t *val_tab
     memset(huff_size, 0, sizeof(huff_size));
     ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
 
-    for(i=0; i<256; i++)
-        huff_sym[i]= i + 16*is_ac;
+    for (i = 0; i < 256; i++)
+        huff_sym[i] = i + 16 * is_ac;
 
-    if(is_ac) huff_sym[0]= 16*256;
+    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 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) {
+static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)
+{
     build_vlc(&s->vlcs[0][0], ff_mjpeg_bits_dc_luminance,
               ff_mjpeg_val_dc, 12, 0, 0);
     build_vlc(&s->vlcs[0][1], ff_mjpeg_bits_dc_chrominance,
@@ -88,11 +92,11 @@ av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
     s->avctx = avctx;
     dsputil_init(&s->dsp, avctx);
     ff_init_scantable(s->dsp.idct_permutation, &s->scantable, ff_zigzag_direct);
-    s->buffer_size = 0;
-    s->buffer = NULL;
-    s->start_code = -1;
+    s->buffer_size   = 0;
+    s->buffer        = NULL;
+    s->start_code    = -1;
     s->first_picture = 1;
-    s->org_height = avctx->coded_height;
+    s->org_height    = avctx->coded_height;
     avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
 
     build_basic_mjpeg_vlc(s);
@@ -101,17 +105,17 @@ av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
     if (avctx->flags & CODEC_FLAG_EXTERN_HUFF)
         s->extern_huff = 1;
 #endif
-    if (s->extern_huff)
-    {
+    if (s->extern_huff) {
         av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");
-        init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size*8);
+        init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
         if (ff_mjpeg_decode_dht(s)) {
-            av_log(avctx, AV_LOG_ERROR, "mjpeg: error using external huffman table\n");
+            av_log(avctx, AV_LOG_ERROR,
+                   "mjpeg: error using external huffman table\n");
             return AVERROR_INVALIDDATA;
         }
     }
     if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
-        s->interlace_polarity = 1; /* bottom field first */
+        s->interlace_polarity = 1;           /* bottom field first */
         av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");
     }
     if (avctx->codec->id == CODEC_ID_AMV)
@@ -130,8 +134,7 @@ int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
 
     while (len >= 65) {
         /* only 8 bit precision handled */
-        if (get_bits(&s->gb, 4) != 0)
-        {
+        if (get_bits(&s->gb, 4) != 0) {
             av_log(s->avctx, AV_LOG_ERROR, "dqt: 16bit precision\n");
             return -1;
         }
@@ -140,19 +143,18 @@ int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
             return -1;
         av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
         /* read quant table */
-        for(i=0;i<64;i++) {
+        for (i = 0; i < 64; i++) {
             j = s->scantable.permutated[i];
             s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
         }
 
-        //XXX FIXME finetune, and perhaps add dc too
-        s->qscale[index]= FFMAX(
-            s->quant_matrixes[index][s->scantable.permutated[1]],
-            s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
-        av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n", index, s->qscale[index]);
+        // XXX FIXME finetune, and perhaps add dc too
+        s->qscale[index] = FFMAX(s->quant_matrixes[index][s->scantable.permutated[1]],
+                                 s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
+        av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
+               index, s->qscale[index]);
         len -= 65;
     }
-
     return 0;
 }
 
@@ -175,7 +177,7 @@ int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
         if (index >= 4)
             return -1;
         n = 0;
-        for(i=1;i<=16;i++) {
+        for (i = 1; i <= 16; i++) {
             bits_table[i] = get_bits(&s->gb, 8);
             n += bits_table[i];
         }
@@ -184,7 +186,7 @@ int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
             return -1;
 
         code_max = 0;
-        for(i=0;i<n;i++) {
+        for (i = 0; i < n; i++) {
             v = get_bits(&s->gb, 8);
             if (v > code_max)
                 code_max = v;
@@ -196,15 +198,15 @@ int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
         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, code_max + 1, 0, class > 0) < 0){
+        if (build_vlc(&s->vlcs[class][index], bits_table, val_table,
+                      code_max + 1, 0, class > 0) < 0)
             return -1;
-        }
 
-        if(class>0){
+        if (class > 0) {
             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;
-            }
+            if (build_vlc(&s->vlcs[2][index], bits_table, val_table,
+                          code_max + 1, 0, 0) < 0)
+                return -1;
         }
     }
     return 0;
@@ -215,44 +217,47 @@ int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
     int len, nb_components, i, width, height, pix_fmt_id;
 
     /* XXX: verify len field validity */
-    len = get_bits(&s->gb, 16);
-    s->bits= get_bits(&s->gb, 8);
+    len     = get_bits(&s->gb, 16);
+    s->bits = get_bits(&s->gb, 8);
 
-    if(s->pegasus_rct) s->bits=9;
-    if(s->bits==9 && !s->pegasus_rct) s->rct=1;    //FIXME ugly
+    if (s->pegasus_rct)
+        s->bits = 9;
+    if (s->bits == 9 && !s->pegasus_rct)
+        s->rct  = 1;    // FIXME ugly
 
-    if (s->bits != 8 && !s->lossless){
+    if (s->bits != 8 && !s->lossless) {
         av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
         return -1;
     }
 
     height = get_bits(&s->gb, 16);
-    width = get_bits(&s->gb, 16);
+    width  = get_bits(&s->gb, 16);
 
-    //HACK for odd_height.mov
-    if(s->interlaced && s->width == width && s->height == height + 1)
+    // HACK for odd_height.mov
+    if (s->interlaced && s->width == width && s->height == height + 1)
         height= s->height;
 
     av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
-    if(av_image_check_size(width, height, 0, s->avctx))
+    if (av_image_check_size(width, height, 0, s->avctx))
         return -1;
 
     nb_components = get_bits(&s->gb, 8);
     if (nb_components <= 0 ||
         nb_components > MAX_COMPONENTS)
         return -1;
-    if (s->ls && !(s->bits <= 8 || nb_components == 1)){
-        av_log(s->avctx, AV_LOG_ERROR, "only <= 8 bits/component or 16-bit gray accepted for JPEG-LS\n");
+    if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
+        av_log(s->avctx, AV_LOG_ERROR,
+               "only <= 8 bits/component or 16-bit gray accepted for JPEG-LS\n");
         return -1;
     }
     s->nb_components = nb_components;
-    s->h_max = 1;
-    s->v_max = 1;
-    for(i=0;i<nb_components;i++) {
+    s->h_max         = 1;
+    s->v_max         = 1;
+    for (i = 0; i < nb_components; i++) {
         /* component id */
         s->component_id[i] = get_bits(&s->gb, 8) - 1;
-        s->h_count[i] = get_bits(&s->gb, 4);
-        s->v_count[i] = get_bits(&s->gb, 4);
+        s->h_count[i]      = get_bits(&s->gb, 4);
+        s->v_count[i]      = get_bits(&s->gb, 4);
         /* compute hmax and vmax (only used in interleaved case) */
         if (s->h_count[i] > s->h_max)
             s->h_max = s->h_count[i];
@@ -261,45 +266,47 @@ int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
         s->quant_index[i] = get_bits(&s->gb, 8);
         if (s->quant_index[i] >= 4)
             return -1;
-        av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n", i, s->h_count[i],
-               s->v_count[i], s->component_id[i], s->quant_index[i]);
+        av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
+               i, s->h_count[i], s->v_count[i],
+               s->component_id[i], s->quant_index[i]);
     }
 
-    if(s->ls && (s->h_max > 1 || s->v_max > 1)) {
-        av_log(s->avctx, AV_LOG_ERROR, "Subsampling in JPEG-LS is not supported.\n");
+    if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
+        av_log(s->avctx, AV_LOG_ERROR,
+               "Subsampling in JPEG-LS is not supported.\n");
         return -1;
     }
 
-    if(s->v_max==1 && s->h_max==1 && s->lossless==1) s->rgb=1;
+    if (s->v_max == 1 && s->h_max == 1 && s->lossless == 1)
+        s->rgb = 1;
 
     /* if different size, realloc/alloc picture */
     /* XXX: also check h_count and v_count */
     if (width != s->width || height != s->height) {
         av_freep(&s->qscale_table);
 
-        s->width = width;
-        s->height = height;
+        s->width      = width;
+        s->height     = height;
         s->interlaced = 0;
 
         /* test interlaced mode */
-        if (s->first_picture &&
+        if (s->first_picture   &&
             s->org_height != 0 &&
             s->height < ((s->org_height * 3) / 4)) {
-            s->interlaced = 1;
-            s->bottom_field = s->interlace_polarity;
+            s->interlaced                    = 1;
+            s->bottom_field                  = s->interlace_polarity;
             s->picture_ptr->interlaced_frame = 1;
-            s->picture_ptr->top_field_first = !s->interlace_polarity;
+            s->picture_ptr->top_field_first  = !s->interlace_polarity;
             height *= 2;
         }
 
         avcodec_set_dimensions(s->avctx, width, height);
 
-        s->qscale_table= av_mallocz((s->width+15)/16);
-
+        s->qscale_table  = av_mallocz((s->width + 15) / 16);
         s->first_picture = 0;
     }
 
-    if(s->interlaced && (s->bottom_field == !s->interlace_polarity))
+    if (s->interlaced && (s->bottom_field == !s->interlace_polarity))
         return 0;
 
     /* XXX: not complete test ! */
@@ -308,19 +315,20 @@ int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
                  (s->h_count[2] << 12) | (s->v_count[2] <<  8) |
                  (s->h_count[3] <<  4) |  s->v_count[3];
     av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
-    //NOTE we do not allocate pictures large enough for the possible padding of h/v_count being 4
-    if(!(pix_fmt_id & 0xD0D0D0D0))
-        pix_fmt_id-= (pix_fmt_id & 0xF0F0F0F0)>>1;
-    if(!(pix_fmt_id & 0x0D0D0D0D))
-        pix_fmt_id-= (pix_fmt_id & 0x0F0F0F0F)>>1;
-
-    switch(pix_fmt_id){
+    /* NOTE we do not allocate pictures large enough for the possible
+     * padding of h/v_count being 4 */
+    if (!(pix_fmt_id & 0xD0D0D0D0))
+        pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
+    if (!(pix_fmt_id & 0x0D0D0D0D))
+        pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
+
+    switch (pix_fmt_id) {
     case 0x11111100:
-        if(s->rgb){
+        if (s->rgb)
             s->avctx->pix_fmt = PIX_FMT_BGRA;
-        }else
+        else
             s->avctx->pix_fmt = s->cs_itu601 ? PIX_FMT_YUV444P : PIX_FMT_YUVJ444P;
-        assert(s->nb_components==3);
+        assert(s->nb_components == 3);
         break;
     case 0x11000000:
         s->avctx->pix_fmt = PIX_FMT_GRAY8;
@@ -338,47 +346,46 @@ int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
         av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
         return -1;
     }
-    if(s->ls){
-        if(s->nb_components > 1)
+    if (s->ls) {
+        if (s->nb_components > 1)
             s->avctx->pix_fmt = PIX_FMT_RGB24;
-        else if(s->bits <= 8)
+        else if (s->bits <= 8)
             s->avctx->pix_fmt = PIX_FMT_GRAY8;
         else
             s->avctx->pix_fmt = PIX_FMT_GRAY16;
     }
 
-    if(s->picture_ptr->data[0])
+    if (s->picture_ptr->data[0])
         s->avctx->release_buffer(s->avctx, s->picture_ptr);
 
-    if(s->avctx->get_buffer(s->avctx, s->picture_ptr) < 0){
+    if (s->avctx->get_buffer(s->avctx, s->picture_ptr) < 0) {
         av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return -1;
     }
-    s->picture_ptr->pict_type= AV_PICTURE_TYPE_I;
-    s->picture_ptr->key_frame= 1;
-    s->got_picture = 1;
+    s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
+    s->picture_ptr->key_frame = 1;
+    s->got_picture            = 1;
 
-    for(i=0; i<3; i++){
-        s->linesize[i]= s->picture_ptr->linesize[i] << s->interlaced;
-    }
+    for (i = 0; i < 3; i++)
+        s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
 
-//    printf("%d %d %d %d %d %d\n", s->width, s->height, s->linesize[0], s->linesize[1], s->interlaced, s->avctx->height);
+//    printf("%d %d %d %d %d %d\n",
+//           s->width, s->height, s->linesize[0], s->linesize[1],
+//           s->interlaced, s->avctx->height);
 
-    if (len != (8+(3*nb_components)))
-    {
+    if (len != (8 + (3 * nb_components)))
         av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
-    }
 
     /* totally blank picture as progressive JPEG will only add details to it */
-    if(s->progressive){
-        int bw = (width  + s->h_max*8-1) / (s->h_max*8);
-        int bh = (height + s->v_max*8-1) / (s->v_max*8);
-        for(i=0; i<s->nb_components; i++) {
+    if (s->progressive) {
+        int bw = (width  + s->h_max * 8 - 1) / (s->h_max * 8);
+        int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
+        for (i = 0; i < s->nb_components; i++) {
             int size = bw * bh * s->h_count[i] * s->v_count[i];
             av_freep(&s->blocks[i]);
             av_freep(&s->last_nnz[i]);
-            s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
-            s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
+            s->blocks[i]       = av_malloc(size * sizeof(**s->blocks));
+            s->last_nnz[i]     = av_mallocz(size * sizeof(**s->last_nnz));
             s->block_stride[i] = bw * s->h_count[i];
         }
         memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
@@ -390,22 +397,22 @@ static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
 {
     int code;
     code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
-    if (code < 0)
-    {
-        av_log(s->avctx, AV_LOG_WARNING, "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n", 0, dc_index,
-               &s->vlcs[0][dc_index]);
+    if (code < 0) {
+        av_log(s->avctx, AV_LOG_WARNING,
+               "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
+               0, dc_index, &s->vlcs[0][dc_index]);
         return 0xffff;
     }
 
-    if(code)
+    if (code)
         return get_xbits(&s->gb, code);
     else
         return 0;
 }
 
 /* decode block and dequantize */
-static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
-                        int component, int dc_index, int ac_index, int16_t *quant_matrix)
+static int decode_block(MJpegDecodeContext *s, DCTELEM *block, int component,
+                        int dc_index, int ac_index, int16_t *quant_matrix)
 {
     int code, i, j, level, val;
 
@@ -427,14 +434,14 @@ static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
 
         i += ((unsigned)code) >> 4;
             code &= 0xf;
-        if(code){
-            if(code > MIN_CACHE_BITS - 16){
+        if (code) {
+            if (code > MIN_CACHE_BITS - 16)
                 UPDATE_CACHE(re, &s->gb);
-            }
+
             {
-                int cache=GET_CACHE(re,&s->gb);
-                int sign=(~cache)>>31;
-                level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
+                int cache = GET_CACHE(re, &s->gb);
+                int sign  = (~cache) >> 31;
+                level     = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
             }
 
             LAST_SKIP_BITS(re, &s->gb, code);
@@ -443,17 +450,18 @@ static int decode_block(MJpegDecodeContext *s, DCTELEM *block,
                 av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
                 return -1;
             }
-            j = s->scantable.permutated[i];
+            j        = s->scantable.permutated[i];
             block[j] = level * quant_matrix[j];
         }
-    }while(i<63);
+    } while (i < 63);
     CLOSE_READER(re, &s->gb);}
 
     return 0;
 }
 
-static int decode_dc_progressive(MJpegDecodeContext *s, DCTELEM *block, int component,
-                                 int dc_index, int16_t *quant_matrix, int Al)
+static int decode_dc_progressive(MJpegDecodeContext *s, DCTELEM *block,
+                                 int component, int dc_index,
+                                 int16_t *quant_matrix, int Al)
 {
     int val;
     s->dsp.clear_block(block);
@@ -469,113 +477,121 @@ static int decode_dc_progressive(MJpegDecodeContext *s, DCTELEM *block, int comp
 }
 
 /* decode block and dequantize - progressive JPEG version */
-static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block, uint8_t *last_nnz,
-                                    int ac_index, int16_t *quant_matrix,
+static int decode_block_progressive(MJpegDecodeContext *s, DCTELEM *block,
+                                    uint8_t *last_nnz, int ac_index,
+                                    int16_t *quant_matrix,
                                     int ss, int se, int Al, int *EOBRUN)
 {
     int code, i, j, level, val, run;
 
-    if(*EOBRUN){
+    if (*EOBRUN) {
         (*EOBRUN)--;
         return 0;
     }
-    {OPEN_READER(re, &s->gb);
-    for(i=ss;;i++) {
-        UPDATE_CACHE(re, &s->gb);
-        GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
 
-        run = ((unsigned) code) >> 4;
-        code &= 0xF;
-        if(code) {
-            i += run;
-            if(code > MIN_CACHE_BITS - 16){
-                UPDATE_CACHE(re, &s->gb);
-            }
-            {
-                int cache=GET_CACHE(re,&s->gb);
-                int sign=(~cache)>>31;
-                level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
-            }
+    {
+        OPEN_READER(re, &s->gb);
+        for (i = ss; ; i++) {
+            UPDATE_CACHE(re, &s->gb);
+            GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
 
-            LAST_SKIP_BITS(re, &s->gb, code);
+            run = ((unsigned) code) >> 4;
+            code &= 0xF;
+            if (code) {
+                i += run;
+                if (code > MIN_CACHE_BITS - 16)
+                    UPDATE_CACHE(re, &s->gb);
 
-            if (i >= se) {
-                if(i == se){
-                    j = s->scantable.permutated[se];
-                    block[j] = level * quant_matrix[j] << Al;
-                    break;
+                {
+                    int cache = GET_CACHE(re, &s->gb);
+                    int sign  = (~cache) >> 31;
+                    level     = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
                 }
-                av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
-                return -1;
-            }
-            j = s->scantable.permutated[i];
-            block[j] = level * quant_matrix[j] << Al;
-        }else{
-            if(run == 0xF){// ZRL - skip 15 coefficients
-                i += 15;
+
+                LAST_SKIP_BITS(re, &s->gb, code);
+
                 if (i >= se) {
-                    av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
+                    if (i == se) {
+                        j = s->scantable.permutated[se];
+                        block[j] = level * quant_matrix[j] << Al;
+                        break;
+                    }
+                    av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
                     return -1;
                 }
-            }else{
-                val = (1 << run);
-                if(run){
-                    UPDATE_CACHE(re, &s->gb);
-                    val += NEG_USR32(GET_CACHE(re, &s->gb), run);
-                    LAST_SKIP_BITS(re, &s->gb, run);
+                j = s->scantable.permutated[i];
+                block[j] = level * quant_matrix[j] << Al;
+            } else {
+                if (run == 0xF) {// ZRL - skip 15 coefficients
+                    i += 15;
+                    if (i >= se) {
+                        av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
+                        return -1;
+                    }
+                } else {
+                    val = (1 << run);
+                    if (run) {
+                        UPDATE_CACHE(re, &s->gb);
+                        val += NEG_USR32(GET_CACHE(re, &s->gb), run);
+                        LAST_SKIP_BITS(re, &s->gb, run);
+                    }
+                    *EOBRUN = val - 1;
+                    break;
                 }
-                *EOBRUN = val - 1;
-                break;
             }
         }
+        CLOSE_READER(re, &s->gb);
     }
-    CLOSE_READER(re, &s->gb);}
-    if(i > *last_nnz)
+
+    if (i > *last_nnz)
         *last_nnz = i;
+
     return 0;
 }
 
-#define REFINE_BIT(j) {\
-    UPDATE_CACHE(re, &s->gb);\
-    sign = block[j]>>15;\
-    block[j] += SHOW_UBITS(re, &s->gb, 1) * ((quant_matrix[j]^sign)-sign) << Al;\
-    LAST_SKIP_BITS(re, &s->gb, 1);\
+#define REFINE_BIT(j) {                                             \
+    UPDATE_CACHE(re, &s->gb);                                       \
+    sign = block[j] >> 15;                                          \
+    block[j] += SHOW_UBITS(re, &s->gb, 1) *                         \
+                ((quant_matrix[j] ^ sign) - sign) << Al;            \
+    LAST_SKIP_BITS(re, &s->gb, 1);                                  \
 }
 
-#define ZERO_RUN \
-for(;;i++) {\
-    if(i > last) {\
-        i += run;\
-        if(i > se) {\
-            av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);\
-            return -1;\
-        }\
-        break;\
-    }\
-    j = s->scantable.permutated[i];\
-    if(block[j])\
-        REFINE_BIT(j)\
-    else if(run-- == 0)\
-        break;\
+#define ZERO_RUN                                                    \
+for (; ; i++) {                                                     \
+    if (i > last) {                                                 \
+        i += run;                                                   \
+        if (i > se) {                                               \
+            av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
+            return -1;                                              \
+        }                                                           \
+        break;                                                      \
+    }                                                               \
+    j = s->scantable.permutated[i];                                 \
+    if (block[j])                                                   \
+        REFINE_BIT(j)                                               \
+    else if (run-- == 0)                                            \
+        break;                                                      \
 }
 
 /* decode block and dequantize - progressive JPEG refinement pass */
-static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block, uint8_t *last_nnz,
-                        int ac_index, int16_t *quant_matrix,
-                        int ss, int se, int Al, int *EOBRUN)
+static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block,
+                                   uint8_t *last_nnz,
+                                   int ac_index, int16_t *quant_matrix,
+                                   int ss, int se, int Al, int *EOBRUN)
 {
-    int code, i=ss, j, sign, val, run;
-    int last = FFMIN(se, *last_nnz);
+    int code, i = ss, j, sign, val, run;
+    int last    = FFMIN(se, *last_nnz);
 
     OPEN_READER(re, &s->gb);
-    if(*EOBRUN)
+    if (*EOBRUN) {
         (*EOBRUN)--;
-    else {
-        for(;;i++) {
+    } else {
+        for (; ; i++) {
             UPDATE_CACHE(re, &s->gb);
             GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
 
-            if(code & 0xF) {
+            if (code & 0xF) {
                 run = ((unsigned) code) >> 4;
                 UPDATE_CACHE(re, &s->gb);
                 val = SHOW_UBITS(re, &s->gb, 1);
@@ -583,21 +599,21 @@ static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block, uint8_
                 ZERO_RUN;
                 j = s->scantable.permutated[i];
                 val--;
-                block[j] = ((quant_matrix[j]^val)-val) << Al;
-                if(i == se) {
-                    if(i > *last_nnz)
+                block[j] = ((quant_matrix[j]^val) - val) << Al;
+                if (i == se) {
+                    if (i > *last_nnz)
                         *last_nnz = i;
                     CLOSE_READER(re, &s->gb);
                     return 0;
                 }
-            }else{
+            } else {
                 run = ((unsigned) code) >> 4;
-                if(run == 0xF){
+                if (run == 0xF) {
                     ZERO_RUN;
-                }else{
+                } else {
                     val = run;
                     run = (1 << run);
-                    if(val) {
+                    if (val) {
                         UPDATE_CACHE(re, &s->gb);
                         run += SHOW_UBITS(re, &s->gb, val);
                         LAST_SKIP_BITS(re, &s->gb, val);
@@ -608,13 +624,13 @@ static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block, uint8_
             }
         }
 
-        if(i > *last_nnz)
+        if (i > *last_nnz)
             *last_nnz = i;
     }
 
-    for(;i<=last;i++) {
+    for (; i <= last; i++) {
         j = s->scantable.permutated[i];
-        if(block[j])
+        if (block[j])
             REFINE_BIT(j)
     }
     CLOSE_READER(re, &s->gb);
@@ -624,43 +640,46 @@ static int decode_block_refinement(MJpegDecodeContext *s, DCTELEM *block, uint8_
 #undef REFINE_BIT
 #undef ZERO_RUN
 
-static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor, int point_transform){
+static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor,
+                                 int point_transform)
+{
     int i, mb_x, mb_y;
     uint16_t (*buffer)[4];
     int left[3], top[3], topleft[3];
-    const int linesize= s->linesize[0];
-    const int mask= (1<<s->bits)-1;
+    const int linesize = s->linesize[0];
+    const int mask     = (1 << s->bits) - 1;
 
-    av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size, (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
-    buffer= s->ljpeg_buffer;
+    av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
+                   (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
+    buffer = s->ljpeg_buffer;
 
-    for(i=0; i<3; i++){
-        buffer[0][i]= 1 << (s->bits + point_transform - 1);
-    }
-    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
-        const int modified_predictor= mb_y ? predictor : 1;
+    for (i = 0; i < 3; i++)
+        buffer[0][i] = 1 << (s->bits + point_transform - 1);
+
+    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
+        const int modified_predictor = mb_y ? predictor : 1;
         uint8_t *ptr = s->picture_ptr->data[0] + (linesize * mb_y);
 
         if (s->interlaced && s->bottom_field)
             ptr += linesize >> 1;
 
-        for(i=0; i<3; i++){
-            top[i]= left[i]= topleft[i]= buffer[0][i];
-        }
-        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
+        for (i = 0; i < 3; i++)
+            top[i] = left[i] = topleft[i] = buffer[0][i];
+
+        for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
             if (s->restart_interval && !s->restart_count)
                 s->restart_count = s->restart_interval;
 
-            for(i=0;i<3;i++) {
+            for (i = 0; i < 3; i++) {
                 int pred;
 
-                topleft[i]= top[i];
-                top[i]= buffer[mb_x][i];
+                topleft[i] = top[i];
+                top[i]     = buffer[mb_x][i];
 
                 PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
 
-                left[i]=
-                buffer[mb_x][i]= mask & (pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform));
+                left[i] = buffer[mb_x][i] =
+                    mask & (pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform));
             }
 
             if (s->restart_interval && !--s->restart_count) {
@@ -669,71 +688,74 @@ static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor, int point
             }
         }
 
-        if(s->rct){
-            for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
-                ptr[4*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200)>>2);
-                ptr[4*mb_x+0] = buffer[mb_x][1] + ptr[4*mb_x+1];
-                ptr[4*mb_x+2] = buffer[mb_x][2] + ptr[4*mb_x+1];
+        if (s->rct) {
+            for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
+                ptr[4 * mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
+                ptr[4 * mb_x + 0] = buffer[mb_x][1] + ptr[4 * mb_x + 1];
+                ptr[4 * mb_x + 2] = buffer[mb_x][2] + ptr[4 * mb_x + 1];
             }
-        }else if(s->pegasus_rct){
-            for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
-                ptr[4*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2])>>2);
-                ptr[4*mb_x+0] = buffer[mb_x][1] + ptr[4*mb_x+1];
-                ptr[4*mb_x+2] = buffer[mb_x][2] + ptr[4*mb_x+1];
+        } else if (s->pegasus_rct) {
+            for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
+                ptr[4 * mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
+                ptr[4 * mb_x + 0] = buffer[mb_x][1] + ptr[4 * mb_x + 1];
+                ptr[4 * mb_x + 2] = buffer[mb_x][2] + ptr[4 * mb_x + 1];
             }
-        }else{
-            for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
-                ptr[4*mb_x+0] = buffer[mb_x][2];
-                ptr[4*mb_x+1] = buffer[mb_x][1];
-                ptr[4*mb_x+2] = buffer[mb_x][0];
+        } else {
+            for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
+                ptr[4 * mb_x + 0] = buffer[mb_x][2];
+                ptr[4 * mb_x + 1] = buffer[mb_x][1];
+                ptr[4 * mb_x + 2] = buffer[mb_x][0];
             }
         }
     }
     return 0;
 }
 
-static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point_transform){
+static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
+                                 int point_transform)
+{
     int i, mb_x, mb_y;
-    const int nb_components=3;
+    const int nb_components = 3;
 
-    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
-        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
+    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
+        for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
             if (s->restart_interval && !s->restart_count)
                 s->restart_count = s->restart_interval;
 
-            if(mb_x==0 || mb_y==0 || s->interlaced){
-                for(i=0;i<nb_components;i++) {
+            if (mb_x == 0 || mb_y == 0 || s->interlaced) {
+                for (i = 0; i < nb_components; i++) {
                     uint8_t *ptr;
                     int n, h, v, x, y, c, j, linesize;
-                    n = s->nb_blocks[i];
-                    c = s->comp_index[i];
-                    h = s->h_scount[i];
-                    v = s->v_scount[i];
-                    x = 0;
-                    y = 0;
-                    linesize= s->linesize[c];
-
-                    for(j=0; j<n; j++) {
+                    n        = s->nb_blocks[i];
+                    c        = s->comp_index[i];
+                    h        = s->h_scount[i];
+                    v        = s->v_scount[i];
+                    x        = 0;
+                    y        = 0;
+                    linesize = s->linesize[c];
+
+                    for (j = 0; j < n; j++) {
                         int pred;
-
-                        ptr = s->picture_ptr->data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
-                        if(y==0 && mb_y==0){
-                            if(x==0 && mb_x==0){
-                                pred= 128 << point_transform;
-                            }else{
-                                pred= ptr[-1];
-                            }
-                        }else{
-                            if(x==0 && mb_x==0){
-                                pred= ptr[-linesize];
-                            }else{
-                                PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
-                            }
-                        }
+                        // FIXME optimize this crap
+                        ptr = s->picture_ptr->data[c] +
+                              (linesize * (v * mb_y + y)) +
+                              (h * mb_x + x);
+                        if (y == 0 && mb_y == 0) {
+                            if (x == 0 && mb_x == 0)
+                                pred = 128 << point_transform;
+                            else
+                                pred = ptr[-1];
+                        } else {
+                            if (x == 0 && mb_x == 0)
+                                pred = ptr[-linesize];
+                            else
+                                PREDICT(pred, ptr[-linesize - 1],
+                                        ptr[-linesize], ptr[-1], predictor);
+                       }
 
                         if (s->interlaced && s->bottom_field)
                             ptr += linesize >> 1;
-                        *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
+                        *ptr = pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
 
                         if (++x == h) {
                             x = 0;
@@ -741,24 +763,28 @@ static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor, int point
                         }
                     }
                 }
-            }else{
-                for(i=0;i<nb_components;i++) {
+            } else {
+                for (i = 0; i < nb_components; i++) {
                     uint8_t *ptr;
                     int n, h, v, x, y, c, j, linesize;
-                    n = s->nb_blocks[i];
-                    c = s->comp_index[i];
-                    h = s->h_scount[i];
-                    v = s->v_scount[i];
-                    x = 0;
-                    y = 0;
-                    linesize= s->linesize[c];
-
-                    for(j=0; j<n; j++) {
+                    n        = s->nb_blocks[i];
+                    c        = s->comp_index[i];
+                    h        = s->h_scount[i];
+                    v        = s->v_scount[i];
+                    x        = 0;
+                    y        = 0;
+                    linesize = s->linesize[c];
+
+                    for (j = 0; j < n; j++) {
                         int pred;
 
-                        ptr = s->picture_ptr->data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
-                        PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
-                        *ptr= pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
+                        // FIXME optimize this crap
+                        ptr = s->picture_ptr->data[c] +
+                              (linesize * (v * mb_y + y)) +
+                              (h * mb_x + x);
+                        PREDICT(pred, ptr[-linesize - 1],
+                                ptr[-linesize], ptr[-1], predictor);
+                        *ptr = pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
                         if (++x == h) {
                             x = 0;
                             y++;
@@ -790,49 +816,54 @@ static av_always_inline void mjpeg_copy_block(uint8_t *dst, const uint8_t *src,
     }
 }
 
-static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al,
-                             const uint8_t *mb_bitmask, const AVFrame *reference){
+static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
+                             int Al, const uint8_t *mb_bitmask,
+                             const AVFrame *reference)
+{
     int i, mb_x, mb_y;
-    uint8_t* data[MAX_COMPONENTS];
+    uint8_t *data[MAX_COMPONENTS];
     const uint8_t *reference_data[MAX_COMPONENTS];
     int linesize[MAX_COMPONENTS];
     GetBitContext mb_bitmask_gb;
 
-    if (mb_bitmask) {
-        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);
-    }
+    if (mb_bitmask)
+        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
 
-    if(s->flipped && s->avctx->flags & CODEC_FLAG_EMU_EDGE) {
-        av_log(s->avctx, AV_LOG_ERROR, "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");
+    if (s->flipped && s->avctx->flags & CODEC_FLAG_EMU_EDGE) {
+        av_log(s->avctx, AV_LOG_ERROR,
+               "Can not flip image with CODEC_FLAG_EMU_EDGE set!\n");
         s->flipped = 0;
     }
-    for(i=0; i < nb_components; i++) {
-        int c = s->comp_index[i];
+
+    for (i = 0; i < nb_components; i++) {
+        int c   = s->comp_index[i];
         data[c] = s->picture_ptr->data[c];
         reference_data[c] = reference ? reference->data[c] : NULL;
-        linesize[c]=s->linesize[c];
+        linesize[c] = s->linesize[c];
         s->coefs_finished[c] |= 1;
-        if(s->flipped) {
-            //picture should be flipped upside-down for this codec
-            int offset = (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));
-            data[c] += offset;
+        if (s->flipped) {
+            // picture should be flipped upside-down for this codec
+            int offset = (linesize[c] * (s->v_scount[i] *
+                         (8 * s->mb_height - ((s->height / s->v_max) & 7)) - 1));
+            data[c]           += offset;
             reference_data[c] += offset;
-            linesize[c] *= -1;
+            linesize[c]       *= -1;
         }
     }
 
-    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
-        for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
+    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
+        for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
             const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
 
             if (s->restart_interval && !s->restart_count)
                 s->restart_count = s->restart_interval;
 
-            if(get_bits_count(&s->gb)>s->gb.size_in_bits){
-                av_log(s->avctx, AV_LOG_ERROR, "overread %d\n", get_bits_count(&s->gb) - s->gb.size_in_bits);
+            if (get_bits_count(&s->gb)>s->gb.size_in_bits) {
+                av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
+                       get_bits_count(&s->gb) - s->gb.size_in_bits);
                 return -1;
             }
-            for(i=0;i<nb_components;i++) {
+            for (i = 0; i < nb_components; i++) {
                 uint8_t *ptr;
                 int n, h, v, x, y, c, j;
                 int block_offset;
@@ -842,38 +873,48 @@ static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, i
                 v = s->v_scount[i];
                 x = 0;
                 y = 0;
-                for(j=0;j<n;j++) {
+                for (j = 0; j < n; j++) {
                     block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
                                      (h * mb_x + x) * 8) >> s->avctx->lowres);
 
-                    if(s->interlaced && s->bottom_field)
+                    if (s->interlaced && s->bottom_field)
                         block_offset += linesize[c] >> 1;
                     ptr = data[c] + block_offset;
-                    if(!s->progressive) {
-                        if (copy_mb) {
-                            mjpeg_copy_block(ptr, reference_data[c] + block_offset, linesize[c], s->avctx->lowres);
-                        } else {
-                        s->dsp.clear_block(s->block);
-                        if(decode_block(s, s->block, i,
-                                     s->dc_index[i], s->ac_index[i],
-                                     s->quant_matrixes[ s->quant_index[c] ]) < 0) {
-                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
-                            return -1;
-                        }
-                        s->dsp.idct_put(ptr, linesize[c], s->block);
+                    if (!s->progressive) {
+                        if (copy_mb)
+                            mjpeg_copy_block(ptr, reference_data[c] + block_offset,
+                                             linesize[c], s->avctx->lowres);
+                        else {
+                            s->dsp.clear_block(s->block);
+                            if (decode_block(s, s->block, i,
+                                             s->dc_index[i], s->ac_index[i],
+                                             s->quant_matrixes[s->quant_index[c]]) < 0) {
+                                av_log(s->avctx, AV_LOG_ERROR,
+                                       "error y=%d x=%d\n", mb_y, mb_x);
+                                return -1;
+                            }
+                            s->dsp.idct_put(ptr, linesize[c], s->block);
                         }
                     } else {
-                        int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x);
+                        int block_idx  = s->block_stride[c] * (v * mb_y + y) +
+                                         (h * mb_x + x);
                         DCTELEM *block = s->blocks[c][block_idx];
-                        if(Ah)
-                            block[0] += get_bits1(&s->gb) * s->quant_matrixes[ s->quant_index[c] ][0] << Al;
-                        else if(decode_dc_progressive(s, block, i, s->dc_index[i], s->quant_matrixes[ s->quant_index[c] ], Al) < 0) {
-                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
+                        if (Ah)
+                            block[0] += get_bits1(&s->gb) *
+                                        s->quant_matrixes[s->quant_index[c]][0] << Al;
+                        else if (decode_dc_progressive(s, block, i, s->dc_index[i],
+                                                       s->quant_matrixes[s->quant_index[c]],
+                                                       Al) < 0) {
+                            av_log(s->avctx, AV_LOG_ERROR,
+                                   "error y=%d x=%d\n", mb_y, mb_x);
                             return -1;
                         }
                     }
-//                    av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x);
-//av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n", mb_x, mb_y, x, y, c, s->bottom_field, (v * mb_y + y) * 8, (h * mb_x + x) * 8);
+                    // av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n",
+                    //        mb_y, mb_x);
+                    // av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n",
+                    //        mb_x, mb_y, x, y, c, s->bottom_field,
+                    //        (v * mb_y + y) * 8, (h * mb_x + x) * 8);
                     if (++x == h) {
                         x = 0;
                         y++;
@@ -881,76 +922,87 @@ static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, i
                 }
             }
 
-            if (s->restart_interval && show_bits(&s->gb, 8) == 0xFF){ /* skip RSTn */
-                --s->restart_count;
-                align_get_bits(&s->gb);
-                while(show_bits(&s->gb, 8) == 0xFF)
-                    skip_bits(&s->gb, 8);
-                skip_bits(&s->gb, 8);
-                for (i=0; i<nb_components; i++) /* reset dc */
-                    s->last_dc[i] = 1024;
+            if (s->restart_interval) {
+                s->restart_count--;
+                i = 8 + ((-get_bits_count(&s->gb)) & 7);
+                /* skip RSTn */
+                if (show_bits(&s->gb, i) == (1 << i) - 1) {
+                    int pos = get_bits_count(&s->gb);
+                    align_get_bits(&s->gb);
+                    while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
+                        skip_bits(&s->gb, 8);
+                    if ((get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
+                        for (i = 0; i < nb_components; i++) /* reset dc */
+                            s->last_dc[i] = 1024;
+                    } else
+                        skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
+                }
             }
         }
     }
     return 0;
 }
 
-static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int se, int Ah, int Al,
-                                            const uint8_t *mb_bitmask, const AVFrame *reference){
+static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
+                                            int se, int Ah, int Al,
+                                            const uint8_t *mb_bitmask,
+                                            const AVFrame *reference)
+{
     int mb_x, mb_y;
     int EOBRUN = 0;
     int c = s->comp_index[0];
-    uint8_t* data = s->picture_ptr->data[c];
+    uint8_t *data = s->picture_ptr->data[c];
     const uint8_t *reference_data = reference ? reference->data[c] : NULL;
-    int linesize = s->linesize[c];
+    int linesize  = s->linesize[c];
     int last_scan = 0;
-    int16_t *quant_matrix = s->quant_matrixes[ s->quant_index[c] ];
+    int16_t *quant_matrix = s->quant_matrixes[s->quant_index[c]];
     GetBitContext mb_bitmask_gb;
 
-    if (mb_bitmask) {
-        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width*s->mb_height);
-    }
+    if (mb_bitmask)
+        init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
 
-    if(!Al) {
-        s->coefs_finished[c] |= (1LL<<(se+1))-(1LL<<ss);
+    if (!Al) {
+        s->coefs_finished[c] |= (1LL << (se + 1)) - (1LL << ss);
         last_scan = !~s->coefs_finished[c];
     }
 
-    if(s->interlaced && s->bottom_field) {
-        int offset = linesize >> 1;
-        data += offset;
+    if (s->interlaced && s->bottom_field) {
+        int offset      = linesize >> 1;
+        data           += offset;
         reference_data += offset;
     }
 
-    for(mb_y = 0; mb_y < s->mb_height; mb_y++) {
-        int block_offset = (mb_y*linesize*8 >> s->avctx->lowres);
-        uint8_t *ptr = data + block_offset;
-        int block_idx = mb_y * s->block_stride[c];
+    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
+        int block_offset = (mb_y * linesize * 8 >> s->avctx->lowres);
+        uint8_t *ptr     = data + block_offset;
+        int block_idx    = mb_y * s->block_stride[c];
         DCTELEM (*block)[64] = &s->blocks[c][block_idx];
-        uint8_t *last_nnz = &s->last_nnz[c][block_idx];
-        for(mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
+        uint8_t *last_nnz    = &s->last_nnz[c][block_idx];
+        for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
             const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
 
             if (!copy_mb) {
-            int ret;
-            if(Ah)
-                ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
-                                              quant_matrix, ss, se, Al, &EOBRUN);
-            else
-                ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
-                                               quant_matrix, ss, se, Al, &EOBRUN);
-            if(ret < 0) {
-                av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);
-                return -1;
-            }
+                int ret;
+                if (Ah)
+                    ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
+                                                  quant_matrix, ss, se, Al, &EOBRUN);
+                else
+                    ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
+                                                   quant_matrix, ss, se, Al, &EOBRUN);
+                if (ret < 0) {
+                    av_log(s->avctx, AV_LOG_ERROR,
+                           "error y=%d x=%d\n", mb_y, mb_x);
+                    return -1;
+                }
             }
 
-            if(last_scan) {
+            if (last_scan) {
                 if (copy_mb) {
-                    mjpeg_copy_block(ptr, reference_data + block_offset, linesize, s->avctx->lowres);
+                    mjpeg_copy_block(ptr, reference_data + block_offset,
+                                     linesize, s->avctx->lowres);
                 } else {
-                s->dsp.idct_put(ptr, linesize, *block);
-                ptr += 8 >> s->avctx->lowres;
+                    s->dsp.idct_put(ptr, linesize, *block);
+                    ptr += 8 >> s->avctx->lowres;
                 }
             }
         }
@@ -958,36 +1010,36 @@ static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss, int s
     return 0;
 }
 
-int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
-                        const uint8_t *mb_bitmask, const AVFrame *reference)
+int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
+                        const AVFrame *reference)
 {
     int len, nb_components, i, h, v, predictor, point_transform;
     int index, id;
-    const int block_size= s->lossless ? 1 : 8;
+    const int block_size = s->lossless ? 1 : 8;
     int ilv, prev_shift;
 
     /* XXX: verify len field validity */
     len = get_bits(&s->gb, 16);
     nb_components = get_bits(&s->gb, 8);
-    if (nb_components == 0 || nb_components > MAX_COMPONENTS){
-        av_log(s->avctx, AV_LOG_ERROR, "decode_sos: nb_components (%d) unsupported\n", nb_components);
+    if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
+        av_log(s->avctx, AV_LOG_ERROR,
+               "decode_sos: nb_components (%d) unsupported\n", nb_components);
         return -1;
     }
-    if (len != 6+2*nb_components)
-    {
+    if (len != 6 + 2 * nb_components) {
         av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
         return -1;
     }
-    for(i=0;i<nb_components;i++) {
+    for (i = 0; i < nb_components; i++) {
         id = get_bits(&s->gb, 8) - 1;
         av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
         /* find component index */
-        for(index=0;index<s->nb_components;index++)
+        for (index = 0; index < s->nb_components; index++)
             if (id == s->component_id[index])
                 break;
-        if (index == s->nb_components)
-        {
-            av_log(s->avctx, AV_LOG_ERROR, "decode_sos: index(%d) out of components\n", index);
+        if (index == s->nb_components) {
+            av_log(s->avctx, AV_LOG_ERROR,
+                   "decode_sos: index(%d) out of components\n", index);
             return -1;
         }
         /* Metasoft MJPEG codec has Cb and Cr swapped */
@@ -998,8 +1050,8 @@ int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
         s->comp_index[i] = index;
 
         s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
-        s->h_scount[i] = s->h_count[index];
-        s->v_scount[i] = s->v_count[index];
+        s->h_scount[i]  = s->h_count[index];
+        s->v_scount[i]  = s->v_count[index];
 
         s->dc_index[i] = get_bits(&s->gb, 4);
         s->ac_index[i] = get_bits(&s->gb, 4);
@@ -1007,34 +1059,36 @@ int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
         if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||
             s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
             goto out_of_range;
-        if (!s->vlcs[0][s->dc_index[i]].table || !s->vlcs[1][s->ac_index[i]].table)
+        if (!s->vlcs[0][s->dc_index[i]].table ||
+            !s->vlcs[1][s->ac_index[i]].table)
             goto out_of_range;
     }
 
-    predictor= get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
-    ilv= get_bits(&s->gb, 8);    /* JPEG Se / JPEG-LS ILV */
-    prev_shift = get_bits(&s->gb, 4); /* Ah */
-    point_transform= get_bits(&s->gb, 4); /* Al */
+    predictor = get_bits(&s->gb, 8);       /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
+    ilv = get_bits(&s->gb, 8);             /* JPEG Se / JPEG-LS ILV */
+    prev_shift      = get_bits(&s->gb, 4); /* Ah */
+    point_transform = get_bits(&s->gb, 4); /* Al */
 
-    for(i=0;i<nb_components;i++)
+    for (i = 0; i < nb_components; i++)
         s->last_dc[i] = 1024;
 
     if (nb_components > 1) {
         /* interleaved stream */
         s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);
         s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
-    } else if(!s->ls) { /* skip this for JPEG-LS */
+    } else if (!s->ls) { /* skip this for JPEG-LS */
         h = s->h_max / s->h_scount[0];
         v = s->v_max / s->v_scount[0];
-        s->mb_width  = (s->width  + h * block_size - 1) / (h * block_size);
-        s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
+        s->mb_width     = (s->width  + h * block_size - 1) / (h * block_size);
+        s->mb_height    = (s->height + v * block_size - 1) / (v * block_size);
         s->nb_blocks[0] = 1;
-        s->h_scount[0] = 1;
-        s->v_scount[0] = 1;
+        s->h_scount[0]  = 1;
+        s->v_scount[0]  = 1;
     }
 
-    if(s->avctx->debug & FF_DEBUG_PICT_INFO)
-        av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d %s\n", s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
+    if (s->avctx->debug & FF_DEBUG_PICT_INFO)
+        av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d %s\n",
+               s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
                predictor, point_transform, ilv, s->bits,
                s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
 
@@ -1043,30 +1097,31 @@ int ff_mjpeg_decode_sos(MJpegDecodeContext *s,
     for (i = s->mjpb_skiptosod; i > 0; i--)
         skip_bits(&s->gb, 8);
 
-    if(s->lossless){
-        if(CONFIG_JPEGLS_DECODER && s->ls){
-//            for(){
+    if (s->lossless) {
+        if (CONFIG_JPEGLS_DECODER && s->ls) {
+//            for () {
 //            reset_ls_coding_parameters(s, 0);
 
-            if(ff_jpegls_decode_picture(s, predictor, point_transform, ilv) < 0)
+            if (ff_jpegls_decode_picture(s, predictor, point_transform, ilv) < 0)
                 return -1;
-        }else{
-            if(s->rgb){
-                if(ljpeg_decode_rgb_scan(s, predictor, point_transform) < 0)
+        } else {
+            if (s->rgb) {
+                if (ljpeg_decode_rgb_scan(s, predictor, point_transform) < 0)
                     return -1;
-            }else{
-                if(ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
+            } else {
+                if (ljpeg_decode_yuv_scan(s, predictor, point_transform) < 0)
                     return -1;
             }
         }
-    }else{
-        if(s->progressive && predictor) {
-            if(mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift, point_transform,
-                                                mb_bitmask, reference) < 0)
+    } else {
+        if (s->progressive && predictor) {
+            if (mjpeg_decode_scan_progressive_ac(s, predictor, ilv, prev_shift,
+                                                 point_transform,
+                                                 mb_bitmask, reference) < 0)
                 return -1;
         } else {
-            if(mjpeg_decode_scan(s, nb_components, prev_shift, point_transform,
-                                 mb_bitmask, reference) < 0)
+            if (mjpeg_decode_scan(s, nb_components, prev_shift, point_transform,
+                                  mb_bitmask, reference) < 0)
                 return -1;
         }
     }
@@ -1082,8 +1137,9 @@ static int mjpeg_decode_dri(MJpegDecodeContext *s)
     if (get_bits(&s->gb, 16) != 4)
         return -1;
     s->restart_interval = get_bits(&s->gb, 16);
-    s->restart_count = 0;
-    av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n", s->restart_interval);
+    s->restart_count    = 0;
+    av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
+           s->restart_interval);
 
     return 0;
 }
@@ -1095,22 +1151,20 @@ static int mjpeg_decode_app(MJpegDecodeContext *s)
     len = get_bits(&s->gb, 16);
     if (len < 5)
         return -1;
-    if(8*len + get_bits_count(&s->gb) > s->gb.size_in_bits)
+    if (8 * len + get_bits_count(&s->gb) > s->gb.size_in_bits)
         return -1;
 
-    id = get_bits_long(&s->gb, 32);
-    id = av_be2ne32(id);
+    id   = get_bits_long(&s->gb, 32);
+    id   = av_be2ne32(id);
     len -= 6;
 
-    if(s->avctx->debug & FF_DEBUG_STARTCODE){
+    if (s->avctx->debug & FF_DEBUG_STARTCODE)
         av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
-    }
 
     /* Buggy AVID, it puts EOI only at every 10th frame. */
     /* Also, this fourcc is used by non-avid files too, it holds some
        information, but it's always present in AVID-created files. */
-    if (id == AV_RL32("AVI1"))
-    {
+    if (id == AV_RL32("AVI1")) {
         /* structure:
             4bytes      AVI1
             1bytes      polarity
@@ -1118,12 +1172,14 @@ static int mjpeg_decode_app(MJpegDecodeContext *s)
             4bytes      field_size
             4bytes      field_size_less_padding
         */
-            s->buggy_avid = 1;
-//        if (s->first_picture)
-//            printf("mjpeg: workarounding buggy AVID\n");
+        s->buggy_avid = 1;
+//      if (s->first_picture)
+//          printf("mjpeg: workarounding buggy AVID\n");
         i = get_bits(&s->gb, 8);
-        if     (i==2) s->bottom_field= 1;
-        else if(i==1) s->bottom_field= 0;
+        if (i == 2)
+            s->bottom_field = 1;
+        else if (i == 1)
+            s->bottom_field = 0;
 #if 0
         skip_bits(&s->gb, 8);
         skip_bits(&s->gb, 32);
@@ -1137,63 +1193,61 @@ static int mjpeg_decode_app(MJpegDecodeContext *s)
 
 //    len -= 2;
 
-    if (id == AV_RL32("JFIF"))
-    {
+    if (id == AV_RL32("JFIF")) {
         int t_w, t_h, v1, v2;
         skip_bits(&s->gb, 8); /* the trailing zero-byte */
-        v1= get_bits(&s->gb, 8);
-        v2= get_bits(&s->gb, 8);
+        v1 = get_bits(&s->gb, 8);
+        v2 = get_bits(&s->gb, 8);
         skip_bits(&s->gb, 8);
 
-        s->avctx->sample_aspect_ratio.num= get_bits(&s->gb, 16);
-        s->avctx->sample_aspect_ratio.den= get_bits(&s->gb, 16);
+        s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
+        s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
 
         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
-            av_log(s->avctx, AV_LOG_INFO, "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
-                v1, v2,
-                s->avctx->sample_aspect_ratio.num,
-                s->avctx->sample_aspect_ratio.den
-            );
+            av_log(s->avctx, AV_LOG_INFO,
+                   "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
+                   v1, v2,
+                   s->avctx->sample_aspect_ratio.num,
+                   s->avctx->sample_aspect_ratio.den);
 
         t_w = get_bits(&s->gb, 8);
         t_h = get_bits(&s->gb, 8);
-        if (t_w && t_h)
-        {
+        if (t_w && t_h) {
             /* skip thumbnail */
-            if (len-10-(t_w*t_h*3) > 0)
-                len -= t_w*t_h*3;
+            if (len -10 - (t_w * t_h * 3) > 0)
+                len -= t_w * t_h * 3;
         }
         len -= 10;
         goto out;
     }
 
-    if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e'))
-    {
+    if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
             av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
         skip_bits(&s->gb, 16); /* version */
         skip_bits(&s->gb, 16); /* flags0 */
         skip_bits(&s->gb, 16); /* flags1 */
-        skip_bits(&s->gb, 8);  /* transform */
+        skip_bits(&s->gb,  8); /* transform */
         len -= 7;
         goto out;
     }
 
-    if (id == AV_RL32("LJIF")){
+    if (id == AV_RL32("LJIF")) {
         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
-            av_log(s->avctx, AV_LOG_INFO, "Pegasus lossless jpeg header found\n");
+            av_log(s->avctx, AV_LOG_INFO,
+                   "Pegasus lossless jpeg header found\n");
         skip_bits(&s->gb, 16); /* version ? */
         skip_bits(&s->gb, 16); /* unknwon always 0? */
         skip_bits(&s->gb, 16); /* unknwon always 0? */
         skip_bits(&s->gb, 16); /* unknwon always 0? */
-        switch( get_bits(&s->gb, 8)){
+        switch (get_bits(&s->gb, 8)) {
         case 1:
-            s->rgb= 1;
-            s->pegasus_rct=0;
+            s->rgb         = 1;
+            s->pegasus_rct = 0;
             break;
         case 2:
-            s->rgb= 1;
-            s->pegasus_rct=1;
+            s->rgb         = 1;
+            s->pegasus_rct = 1;
             break;
         default:
             av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
@@ -1203,13 +1257,12 @@ static int mjpeg_decode_app(MJpegDecodeContext *s)
     }
 
     /* Apple MJPEG-A */
-    if ((s->start_code == APP1) && (len > (0x28 - 8)))
-    {
-        id = get_bits_long(&s->gb, 32);
-        id = av_be2ne32(id);
+    if ((s->start_code == APP1) && (len > (0x28 - 8))) {
+        id   = get_bits_long(&s->gb, 32);
+        id   = av_be2ne32(id);
         len -= 4;
-        if (id == AV_RL32("mjpg")) /* Apple MJPEG-A */
-        {
+        /* Apple MJPEG-A */
+        if (id == AV_RL32("mjpg")) {
 #if 0
             skip_bits(&s->gb, 32); /* field size */
             skip_bits(&s->gb, 32); /* pad field size */
@@ -1228,8 +1281,9 @@ static int mjpeg_decode_app(MJpegDecodeContext *s)
 out:
     /* slow but needed for extreme adobe jpegs */
     if (len < 0)
-        av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error, decode_app parser read over the end\n");
-    while(--len > 0)
+        av_log(s->avctx, AV_LOG_ERROR,
+               "mjpeg: error, decode_app parser read over the end\n");
+    while (--len > 0)
         skip_bits(&s->gb, 8);
 
     return 0;
@@ -1238,34 +1292,31 @@ out:
 static int mjpeg_decode_com(MJpegDecodeContext *s)
 {
     int len = get_bits(&s->gb, 16);
-    if (len >= 2 && 8*len - 16 + get_bits_count(&s->gb) <= s->gb.size_in_bits) {
+    if (len >= 2 &&
+        8 * len - 16 + get_bits_count(&s->gb) <= s->gb.size_in_bits) {
         char *cbuf = av_malloc(len - 1);
         if (cbuf) {
             int i;
             for (i = 0; i < len - 2; i++)
                 cbuf[i] = get_bits(&s->gb, 8);
-            if (i > 0 && cbuf[i-1] == '\n')
-                cbuf[i-1] = 0;
+            if (i > 0 && cbuf[i - 1] == '\n')
+                cbuf[i - 1] = 0;
             else
                 cbuf[i] = 0;
 
-            if(s->avctx->debug & FF_DEBUG_PICT_INFO)
+            if (s->avctx->debug & FF_DEBUG_PICT_INFO)
                 av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
 
             /* buggy avid, it puts EOI only at every 10th frame */
-            if (!strcmp(cbuf, "AVID"))
-            {
+            if (!strcmp(cbuf, "AVID")) {
                 s->buggy_avid = 1;
-                //        if (s->first_picture)
-                //            printf("mjpeg: workarounding buggy AVID\n");
-            }
-            else if(!strcmp(cbuf, "CS=ITU601")){
-                s->cs_itu601= 1;
-            }
-            else if((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
-                    (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20))){
+                // if (s->first_picture)
+                // printf("mjpeg: workarounding buggy AVID\n");
+            } else if (!strcmp(cbuf, "CS=ITU601"))
+                s->cs_itu601 = 1;
+            else if ((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
+                     (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
                 s->flipped = 1;
-            }
 
             av_free(cbuf);
         }
@@ -1282,12 +1333,12 @@ static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
     unsigned int v, v2;
     int val;
 #ifdef DEBUG
-    int skipped=0;
+    int skipped = 0;
 #endif
 
     buf_ptr = *pbuf_ptr;
     while (buf_ptr < buf_end) {
-        v = *buf_ptr++;
+        v  = *buf_ptr++;
         v2 = *buf_ptr;
         if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
             val = *buf_ptr++;
@@ -1306,105 +1357,97 @@ found:
 
 int ff_mjpeg_find_marker(MJpegDecodeContext *s,
                          const uint8_t **buf_ptr, const uint8_t *buf_end,
-                         const uint8_t **unescaped_buf_ptr, int *unescaped_buf_size)
+                         const uint8_t **unescaped_buf_ptr,
+                         int *unescaped_buf_size)
 {
     int start_code;
     start_code = find_marker(buf_ptr, buf_end);
 
-                if ((buf_end - *buf_ptr) > s->buffer_size)
-                {
-                    av_free(s->buffer);
-                    s->buffer_size = buf_end - *buf_ptr;
-                    s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
-                    av_log(s->avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",
-                        s->buffer_size);
-                }
-
-                /* unescape buffer of SOS, use special treatment for JPEG-LS */
-                if (start_code == SOS && !s->ls)
-                {
-                    const uint8_t *src = *buf_ptr;
-                    uint8_t *dst = s->buffer;
+    if ((buf_end - *buf_ptr) > s->buffer_size) {
+        av_free(s->buffer);
+        s->buffer_size = buf_end - *buf_ptr;
+        s->buffer      = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);
+        av_log(s->avctx, AV_LOG_DEBUG,
+               "buffer too small, expanding to %d bytes\n", s->buffer_size);
+    }
 
-                    while (src<buf_end)
-                    {
-                        uint8_t x = *(src++);
+    /* unescape buffer of SOS, use special treatment for JPEG-LS */
+    if (start_code == SOS && !s->ls) {
+        const uint8_t *src = *buf_ptr;
+        uint8_t *dst = s->buffer;
 
-                        *(dst++) = x;
-                        if (s->avctx->codec_id != CODEC_ID_THP)
-                        {
-                            if (x == 0xff) {
-                                while (src < buf_end && x == 0xff)
-                                    x = *(src++);
-
-                                if (x >= 0xd0 && x <= 0xd7)
-                                    *(dst++) = x;
-                                else if (x)
-                                    break;
-                            }
-                        }
-                    }
-                    *unescaped_buf_ptr  = s->buffer;
-                    *unescaped_buf_size = dst - s->buffer;
+        while (src < buf_end) {
+            uint8_t x = *(src++);
 
-                    av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
-                           (buf_end - *buf_ptr) - (dst - s->buffer));
-                }
-                else if(start_code == SOS && s->ls){
-                    const uint8_t *src = *buf_ptr;
-                    uint8_t *dst = s->buffer;
-                    int bit_count = 0;
-                    int t = 0, b = 0;
-                    PutBitContext pb;
-
-                    s->cur_scan++;
-
-                    /* find marker */
-                    while (src + t < buf_end){
-                        uint8_t x = src[t++];
-                        if (x == 0xff){
-                            while((src + t < buf_end) && x == 0xff)
-                                x = src[t++];
-                            if (x & 0x80) {
-                                t -= 2;
-                                break;
-                            }
-                        }
-                    }
-                    bit_count = t * 8;
-
-                    init_put_bits(&pb, dst, t);
-
-                    /* unescape bitstream */
-                    while(b < t){
-                        uint8_t x = src[b++];
-                        put_bits(&pb, 8, x);
-                        if(x == 0xFF){
-                            x = src[b++];
-                            put_bits(&pb, 7, x);
-                            bit_count--;
-                        }
-                    }
-                    flush_put_bits(&pb);
+            *(dst++) = x;
+            if (s->avctx->codec_id != CODEC_ID_THP) {
+                if (x == 0xff) {
+                    while (src < buf_end && x == 0xff)
+                        x = *(src++);
 
-                    *unescaped_buf_ptr  = dst;
-                    *unescaped_buf_size = (bit_count + 7) >> 3;
+                    if (x >= 0xd0 && x <= 0xd7)
+                        *(dst++) = x;
+                    else if (x)
+                        break;
                 }
-                else
-                {
-                    *unescaped_buf_ptr  = *buf_ptr;
-                    *unescaped_buf_size = buf_end - *buf_ptr;
+            }
+        }
+        *unescaped_buf_ptr  = s->buffer;
+        *unescaped_buf_size = dst - s->buffer;
+
+        av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
+               (buf_end - *buf_ptr) - (dst - s->buffer));
+    } else if (start_code == SOS && s->ls) {
+        const uint8_t *src = *buf_ptr;
+        uint8_t *dst  = s->buffer;
+        int bit_count = 0;
+        int t = 0, b = 0;
+        PutBitContext pb;
+
+        s->cur_scan++;
+
+        /* find marker */
+        while (src + t < buf_end) {
+            uint8_t x = src[t++];
+            if (x == 0xff) {
+                while ((src + t < buf_end) && x == 0xff)
+                    x = src[t++];
+                if (x & 0x80) {
+                    t -= 2;
+                    break;
                 }
+            }
+        }
+        bit_count = t * 8;
+        init_put_bits(&pb, dst, t);
+
+        /* unescape bitstream */
+        while (b < t) {
+            uint8_t x = src[b++];
+            put_bits(&pb, 8, x);
+            if (x == 0xFF) {
+                x = src[b++];
+                put_bits(&pb, 7, x);
+                bit_count--;
+            }
+        }
+        flush_put_bits(&pb);
+
+        *unescaped_buf_ptr  = dst;
+        *unescaped_buf_size = (bit_count + 7) >> 3;
+    } else {
+        *unescaped_buf_ptr  = *buf_ptr;
+        *unescaped_buf_size = buf_end - *buf_ptr;
+    }
 
     return start_code;
 }
 
-int ff_mjpeg_decode_frame(AVCodecContext *avctx,
-                              void *data, int *data_size,
-                              AVPacket *avpkt)
+int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
+                          AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
+    int buf_size       = avpkt->size;
     MJpegDecodeContext *s = avctx->priv_data;
     const uint8_t *buf_end, *buf_ptr;
     const uint8_t *unescaped_buf_ptr;
@@ -1418,149 +1461,155 @@ int ff_mjpeg_decode_frame(AVCodecContext *avctx,
     while (buf_ptr < buf_end) {
         /* find start next marker */
         start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
-                                          &unescaped_buf_ptr, &unescaped_buf_size);
-        {
-            /* EOF */
-            if (start_code < 0) {
-                goto the_end;
-            } else {
-                av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n", start_code, buf_end - buf_ptr);
-
-                init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size*8);
-
-                s->start_code = start_code;
-                if(s->avctx->debug & FF_DEBUG_STARTCODE){
-                    av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
-                }
-
-                /* process markers */
-                if (start_code >= 0xd0 && start_code <= 0xd7) {
-                    av_log(avctx, AV_LOG_DEBUG, "restart marker: %d\n", start_code&0x0f);
-                    /* APP fields */
-                } else if (start_code >= APP0 && start_code <= APP15) {
-                    mjpeg_decode_app(s);
-                    /* Comment */
-                } else if (start_code == COM){
-                    mjpeg_decode_com(s);
+                                          &unescaped_buf_ptr,
+                                          &unescaped_buf_size);
+        /* EOF */
+        if (start_code < 0) {
+            goto the_end;
+        } else {
+            av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
+                   start_code, buf_end - buf_ptr);
+
+            init_get_bits(&s->gb, unescaped_buf_ptr, unescaped_buf_size * 8);
+
+            s->start_code = start_code;
+            if (s->avctx->debug & FF_DEBUG_STARTCODE)
+                av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
+
+            /* process markers */
+            if (start_code >= 0xd0 && start_code <= 0xd7)
+                av_log(avctx, AV_LOG_DEBUG,
+                       "restart marker: %d\n", start_code & 0x0f);
+                /* APP fields */
+            else if (start_code >= APP0 && start_code <= APP15)
+                mjpeg_decode_app(s);
+                /* Comment */
+            else if (start_code == COM)
+                mjpeg_decode_com(s);
+
+            switch (start_code) {
+            case SOI:
+                s->restart_interval = 0;
+                s->restart_count    = 0;
+                /* nothing to do on SOI */
+                break;
+            case DQT:
+                ff_mjpeg_decode_dqt(s);
+                break;
+            case DHT:
+                if (ff_mjpeg_decode_dht(s) < 0) {
+                    av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
+                    return -1;
                 }
-
-                switch(start_code) {
-                case SOI:
-                    s->restart_interval = 0;
-
-                    s->restart_count = 0;
-                    /* nothing to do on SOI */
-                    break;
-                case DQT:
-                    ff_mjpeg_decode_dqt(s);
-                    break;
-                case DHT:
-                    if(ff_mjpeg_decode_dht(s) < 0){
-                        av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
-                        return -1;
-                    }
-                    break;
-                case SOF0:
-                case SOF1:
-                    s->lossless=0;
-                    s->ls=0;
-                    s->progressive=0;
-                    if (ff_mjpeg_decode_sof(s) < 0)
-                        return -1;
-                    break;
-                case SOF2:
-                    s->lossless=0;
-                    s->ls=0;
-                    s->progressive=1;
-                    if (ff_mjpeg_decode_sof(s) < 0)
-                        return -1;
-                    break;
-                case SOF3:
-                    s->lossless=1;
-                    s->ls=0;
-                    s->progressive=0;
-                    if (ff_mjpeg_decode_sof(s) < 0)
-                        return -1;
-                    break;
-                case SOF48:
-                    s->lossless=1;
-                    s->ls=1;
-                    s->progressive=0;
-                    if (ff_mjpeg_decode_sof(s) < 0)
-                        return -1;
-                    break;
-                case LSE:
-                    if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)
-                        return -1;
+                break;
+            case SOF0:
+            case SOF1:
+                s->lossless    = 0;
+                s->ls          = 0;
+                s->progressive = 0;
+                if (ff_mjpeg_decode_sof(s) < 0)
+                    return -1;
+                break;
+            case SOF2:
+                s->lossless    = 0;
+                s->ls          = 0;
+                s->progressive = 1;
+                if (ff_mjpeg_decode_sof(s) < 0)
+                    return -1;
+                break;
+            case SOF3:
+                s->lossless    = 1;
+                s->ls          = 0;
+                s->progressive = 0;
+                if (ff_mjpeg_decode_sof(s) < 0)
+                    return -1;
+                break;
+            case SOF48:
+                s->lossless    = 1;
+                s->ls          = 1;
+                s->progressive = 0;
+                if (ff_mjpeg_decode_sof(s) < 0)
+                    return -1;
+                break;
+            case LSE:
+                if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)
+                    return -1;
+                break;
+            case EOI:
+                s->cur_scan = 0;
+                if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
                     break;
-                case EOI:
-                    s->cur_scan = 0;
-                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
-                        break;
 eoi_parser:
-                    if (!s->got_picture) {
-                        av_log(avctx, AV_LOG_WARNING, "Found EOI before any SOF, ignoring\n");
-                        break;
+                if (!s->got_picture) {
+                    av_log(avctx, AV_LOG_WARNING,
+                           "Found EOI before any SOF, ignoring\n");
+                    break;
                     }
-                    if (s->interlaced) {
-                        s->bottom_field ^= 1;
-                        /* if not bottom field, do not output image yet */
-                        if (s->bottom_field == !s->interlace_polarity)
-                            goto not_the_end;
+                if (s->interlaced) {
+                    s->bottom_field ^= 1;
+                    /* if not bottom field, do not output image yet */
+                    if (s->bottom_field == !s->interlace_polarity)
+                        goto not_the_end;
                     }
-                    *picture = *s->picture_ptr;
+                    *picture   = *s->picture_ptr;
                     *data_size = sizeof(AVFrame);
 
-                    if(!s->lossless){
-                        picture->quality= FFMAX3(s->qscale[0], s->qscale[1], s->qscale[2]);
-                        picture->qstride= 0;
-                        picture->qscale_table= s->qscale_table;
-                        memset(picture->qscale_table, picture->quality, (s->width+15)/16);
-                        if(avctx->debug & FF_DEBUG_QP)
-                            av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);
-                        picture->quality*= FF_QP2LAMBDA;
+                    if (!s->lossless) {
+                        picture->quality      = FFMAX3(s->qscale[0],
+                                                       s->qscale[1],
+                                                       s->qscale[2]);
+                        picture->qstride      = 0;
+                        picture->qscale_table = s->qscale_table;
+                        memset(picture->qscale_table, picture->quality,
+                               (s->width + 15) / 16);
+                        if (avctx->debug & FF_DEBUG_QP)
+                            av_log(avctx, AV_LOG_DEBUG,
+                                   "QP: %d\n", picture->quality);
+                        picture->quality *= FF_QP2LAMBDA;
                     }
 
-                    goto the_end;
-                case SOS:
-                    if (!s->got_picture) {
-                        av_log(avctx, AV_LOG_WARNING, "Can not process SOS before SOF, skipping\n");
-                        break;
-                    }
-                    if (ff_mjpeg_decode_sos(s, NULL, NULL) < 0 &&
-                        (avctx->err_recognition & AV_EF_EXPLODE))
-                      return AVERROR_INVALIDDATA;
-                    /* buggy avid puts EOI every 10-20th frame */
-                    /* if restart period is over process EOI */
-                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
-                        goto eoi_parser;
-                    break;
-                case DRI:
-                    mjpeg_decode_dri(s);
-                    break;
-                case SOF5:
-                case SOF6:
-                case SOF7:
-                case SOF9:
-                case SOF10:
-                case SOF11:
-                case SOF13:
-                case SOF14:
-                case SOF15:
-                case JPG:
-                    av_log(avctx, AV_LOG_ERROR, "mjpeg: unsupported coding type (%x)\n", start_code);
+                goto the_end;
+            case SOS:
+                if (!s->got_picture) {
+                    av_log(avctx, AV_LOG_WARNING,
+                           "Can not process SOS before SOF, skipping\n");
                     break;
-//                default:
-//                    printf("mjpeg: unsupported marker (%x)\n", start_code);
-//                    break;
-                }
+                    }
+                if (ff_mjpeg_decode_sos(s, NULL, NULL) < 0 &&
+                    (avctx->err_recognition & AV_EF_EXPLODE))
+                    return AVERROR_INVALIDDATA;
+                /* buggy avid puts EOI every 10-20th frame */
+                /* if restart period is over process EOI */
+                if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
+                    goto eoi_parser;
+                break;
+            case DRI:
+                mjpeg_decode_dri(s);
+                break;
+            case SOF5:
+            case SOF6:
+            case SOF7:
+            case SOF9:
+            case SOF10:
+            case SOF11:
+            case SOF13:
+            case SOF14:
+            case SOF15:
+            case JPG:
+                av_log(avctx, AV_LOG_ERROR,
+                       "mjpeg: unsupported coding type (%x)\n", start_code);
+                break;
+//              default:
+//              printf("mjpeg: unsupported marker (%x)\n", start_code);
+//              break;
+            }
 
 not_the_end:
-                /* eof process start code */
-                buf_ptr += (get_bits_count(&s->gb)+7)/8;
-                av_log(avctx, AV_LOG_DEBUG, "marker parser used %d bytes (%d bits)\n",
-                       (get_bits_count(&s->gb)+7)/8, get_bits_count(&s->gb));
-            }
+            /* eof process start code */
+            buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
+            av_log(avctx, AV_LOG_DEBUG,
+                   "marker parser used %d bytes (%d bits)\n",
+                   (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
         }
     }
     if (s->got_picture) {
@@ -1570,8 +1619,9 @@ not_the_end:
     av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
     return -1;
 the_end:
-    av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n", buf_end - buf_ptr);
-//    return buf_end - buf_ptr;
+    av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n",
+           buf_end - buf_ptr);
+//  return buf_end - buf_ptr;
     return buf_ptr - buf;
 }
 
@@ -1586,13 +1636,13 @@ av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
     av_free(s->buffer);
     av_free(s->qscale_table);
     av_freep(&s->ljpeg_buffer);
-    s->ljpeg_buffer_size=0;
+    s->ljpeg_buffer_size = 0;
 
-    for(i=0;i<3;i++) {
-        for(j=0;j<4;j++)
+    for (i = 0; i < 3; i++) {
+        for (j = 0; j < 4; j++)
             free_vlc(&s->vlcs[i][j]);
     }
-    for(i=0; i<MAX_COMPONENTS; i++) {
+    for (i = 0; i < MAX_COMPONENTS; i++) {
         av_freep(&s->blocks[i]);
         av_freep(&s->last_nnz[i]);
     }
@@ -1602,7 +1652,8 @@ av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
 static const AVOption options[] = {
-    { "extern_huff",        "Use external huffman table.",  OFFSET(extern_huff), AV_OPT_TYPE_INT, { 0 }, 0, 1, VD },
+    { "extern_huff", "Use external huffman table.",
+      OFFSET(extern_huff), AV_OPT_TYPE_INT, { 0 }, 0, 1, VD },
     { NULL },
 };
 
@@ -1622,8 +1673,8 @@ AVCodec ff_mjpeg_decoder = {
     .close          = ff_mjpeg_decode_end,
     .decode         = ff_mjpeg_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
-    .max_lowres = 3,
-    .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
+    .max_lowres     = 3,
+    .long_name      = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
     .priv_class     = &mjpegdec_class,
 };
 
@@ -1636,6 +1687,6 @@ AVCodec ff_thp_decoder = {
     .close          = ff_mjpeg_decode_end,
     .decode         = ff_mjpeg_decode_frame,
     .capabilities   = CODEC_CAP_DR1,
-    .max_lowres = 3,
-    .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
+    .max_lowres     = 3,
+    .long_name      = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
 };
diff --git a/libavcodec/mpeg12.c b/libavcodec/mpeg12.c
index 48860cf..34857d6 100644
--- a/libavcodec/mpeg12.c
+++ b/libavcodec/mpeg12.c
@@ -1235,7 +1235,7 @@ static int mpeg_decode_postinit(AVCodecContext *avctx)
 
         /* low_delay may be forced, in this case we will have B-frames
          * that behave like P-frames. */
-        avctx->has_b_frames = !(s->low_delay);
+        avctx->has_b_frames = !s->low_delay;
 
         assert((avctx->sub_id == 1) == (avctx->codec_id == CODEC_ID_MPEG1VIDEO));
         if (avctx->codec_id == CODEC_ID_MPEG1VIDEO) {
@@ -2428,7 +2428,9 @@ static int decode_chunks(AVCodecContext *avctx,
                 }
 
                 if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE)) {
-                    int threshold= (s2->mb_height * s->slice_count + avctx->thread_count / 2) / avctx->thread_count;
+                    int threshold = (s2->mb_height * s->slice_count +
+                                     s2->slice_context_count / 2) /
+                                    s2->slice_context_count;
                     if (threshold <= mb_y) {
                         MpegEncContext *thread_context = s2->thread_context[s->slice_count];
 
diff --git a/libavcodec/mpeg4video_parser.c b/libavcodec/mpeg4video_parser.c
index 162bc1d..89bbf34 100644
--- a/libavcodec/mpeg4video_parser.c
+++ b/libavcodec/mpeg4video_parser.c
@@ -99,6 +99,7 @@ static av_cold int mpeg4video_parse_init(AVCodecParserContext *s)
     if (!pc->enc)
         return -1;
     pc->first_picture = 1;
+    pc->enc->slice_context_count = 1;
     return 0;
 }
 
diff --git a/libavcodec/mpegaudiodec.c b/libavcodec/mpegaudiodec.c
index 0c8f9c7..6a06afa 100644
--- a/libavcodec/mpegaudiodec.c
+++ b/libavcodec/mpegaudiodec.c
@@ -58,7 +58,7 @@ typedef struct GranuleDef {
     int preflag;
     int short_start, long_end; /* long/short band indexes */
     uint8_t scale_factors[40];
-    INTFLOAT sb_hybrid[SBLIMIT * 18]; /* 576 samples */
+    DECLARE_ALIGNED(16, INTFLOAT, sb_hybrid)[SBLIMIT * 18]; /* 576 samples */
 } GranuleDef;
 
 typedef struct MPADecodeContext {
@@ -130,7 +130,6 @@ static uint16_t band_index_long[9][23];
 static INTFLOAT is_table[2][16];
 static INTFLOAT is_table_lsf[2][2][16];
 static INTFLOAT csa_table[8][4];
-static INTFLOAT mdct_win[8][36];
 
 static int16_t division_tab3[1<<6 ];
 static int16_t division_tab5[1<<8 ];
@@ -417,43 +416,6 @@ static av_cold void decode_init_static(void)
         csa_table[i][3] = ca - cs;
 #endif
     }
-
-    /* compute mdct windows */
-    for (i = 0; i < 36; i++) {
-        for (j = 0; j < 4; j++) {
-            double d;
-
-            if (j == 2 && i % 3 != 1)
-                continue;
-
-            d = sin(M_PI * (i + 0.5) / 36.0);
-            if (j == 1) {
-                if      (i >= 30) d = 0;
-                else if (i >= 24) d = sin(M_PI * (i - 18 + 0.5) / 12.0);
-                else if (i >= 18) d = 1;
-            } else if (j == 3) {
-                if      (i <   6) d = 0;
-                else if (i <  12) d = sin(M_PI * (i -  6 + 0.5) / 12.0);
-                else if (i <  18) d = 1;
-            }
-            //merge last stage of imdct into the window coefficients
-            d *= 0.5 / cos(M_PI * (2 * i + 19) / 72);
-
-            if (j == 2)
-                mdct_win[j][i/3] = FIXHR((d / (1<<5)));
-            else
-                mdct_win[j][i  ] = FIXHR((d / (1<<5)));
-        }
-    }
-
-    /* NOTE: we do frequency inversion adter the MDCT by changing
-        the sign of the right window coefs */
-    for (j = 0; j < 4; j++) {
-        for (i = 0; i < 36; i += 2) {
-            mdct_win[j + 4][i    ] =  mdct_win[j][i    ];
-            mdct_win[j + 4][i + 1] = -mdct_win[j][i + 1];
-        }
-    }
 }
 
 static av_cold int decode_init(AVCodecContext * avctx)
@@ -483,32 +445,9 @@ static av_cold int decode_init(AVCodecContext * avctx)
 }
 
 #define C3 FIXHR(0.86602540378443864676/2)
-
-/* 0.5 / cos(pi*(2*i+1)/36) */
-static const INTFLOAT icos36[9] = {
-    FIXR(0.50190991877167369479),
-    FIXR(0.51763809020504152469), //0
-    FIXR(0.55168895948124587824),
-    FIXR(0.61038729438072803416),
-    FIXR(0.70710678118654752439), //1
-    FIXR(0.87172339781054900991),
-    FIXR(1.18310079157624925896),
-    FIXR(1.93185165257813657349), //2
-    FIXR(5.73685662283492756461),
-};
-
-/* 0.5 / cos(pi*(2*i+1)/36) */
-static const INTFLOAT icos36h[9] = {
-    FIXHR(0.50190991877167369479/2),
-    FIXHR(0.51763809020504152469/2), //0
-    FIXHR(0.55168895948124587824/2),
-    FIXHR(0.61038729438072803416/2),
-    FIXHR(0.70710678118654752439/2), //1
-    FIXHR(0.87172339781054900991/2),
-    FIXHR(1.18310079157624925896/4),
-    FIXHR(1.93185165257813657349/4), //2
-//    FIXHR(5.73685662283492756461),
-};
+#define C4 FIXHR(0.70710678118654752439/2) //0.5 / cos(pi*(9)/36)
+#define C5 FIXHR(0.51763809020504152469/2) //0.5 / cos(pi*(5)/36)
+#define C6 FIXHR(1.93185165257813657349/4) //0.5 / cos(pi*(15)/36)
 
 /* 12 points IMDCT. We compute it "by hand" by factorizing obvious
    cases. */
@@ -529,7 +468,7 @@ static void imdct12(INTFLOAT *out, INTFLOAT *in)
     in3  = MULH3(in3, C3, 4);
 
     t1   = in0 - in4;
-    t2   = MULH3(in1 - in5, icos36h[4], 2);
+    t2   = MULH3(in1 - in5, C4, 2);
 
     out[ 7] =
     out[10] = t1 + t2;
@@ -539,112 +478,20 @@ static void imdct12(INTFLOAT *out, INTFLOAT *in)
     in0    += SHR(in4, 1);
     in4     = in0 + in2;
     in5    += 2*in1;
-    in1     = MULH3(in5 + in3, icos36h[1], 1);
+    in1     = MULH3(in5 + in3, C5, 1);
     out[ 8] =
     out[ 9] = in4 + in1;
     out[ 2] =
     out[ 3] = in4 - in1;
 
     in0    -= in2;
-    in5     = MULH3(in5 - in3, icos36h[7], 2);
+    in5     = MULH3(in5 - in3, C6, 2);
     out[ 0] =
     out[ 5] = in0 - in5;
     out[ 6] =
     out[11] = in0 + in5;
 }
 
-/* cos(pi*i/18) */
-#define C1 FIXHR(0.98480775301220805936/2)
-#define C2 FIXHR(0.93969262078590838405/2)
-#define C3 FIXHR(0.86602540378443864676/2)
-#define C4 FIXHR(0.76604444311897803520/2)
-#define C5 FIXHR(0.64278760968653932632/2)
-#define C6 FIXHR(0.5/2)
-#define C7 FIXHR(0.34202014332566873304/2)
-#define C8 FIXHR(0.17364817766693034885/2)
-
-
-/* using Lee like decomposition followed by hand coded 9 points DCT */
-static void imdct36(INTFLOAT *out, INTFLOAT *buf, INTFLOAT *in, INTFLOAT *win)
-{
-    int i, j;
-    INTFLOAT t0, t1, t2, t3, s0, s1, s2, s3;
-    INTFLOAT tmp[18], *tmp1, *in1;
-
-    for (i = 17; i >= 1; i--)
-        in[i] += in[i-1];
-    for (i = 17; i >= 3; i -= 2)
-        in[i] += in[i-2];
-
-    for (j = 0; j < 2; j++) {
-        tmp1 = tmp + j;
-        in1 = in + j;
-
-        t2 = in1[2*4] + in1[2*8] - in1[2*2];
-
-        t3 = in1[2*0] + SHR(in1[2*6],1);
-        t1 = in1[2*0] - in1[2*6];
-        tmp1[ 6] = t1 - SHR(t2,1);
-        tmp1[16] = t1 + t2;
-
-        t0 = MULH3(in1[2*2] + in1[2*4] ,    C2, 2);
-        t1 = MULH3(in1[2*4] - in1[2*8] , -2*C8, 1);
-        t2 = MULH3(in1[2*2] + in1[2*8] ,   -C4, 2);
-
-        tmp1[10] = t3 - t0 - t2;
-        tmp1[ 2] = t3 + t0 + t1;
-        tmp1[14] = t3 + t2 - t1;
-
-        tmp1[ 4] = MULH3(in1[2*5] + in1[2*7] - in1[2*1], -C3, 2);
-        t2 = MULH3(in1[2*1] + in1[2*5],    C1, 2);
-        t3 = MULH3(in1[2*5] - in1[2*7], -2*C7, 1);
-        t0 = MULH3(in1[2*3], C3, 2);
-
-        t1 = MULH3(in1[2*1] + in1[2*7],   -C5, 2);
-
-        tmp1[ 0] = t2 + t3 + t0;
-        tmp1[12] = t2 + t1 - t0;
-        tmp1[ 8] = t3 - t1 - t0;
-    }
-
-    i = 0;
-    for (j = 0; j < 4; j++) {
-        t0 = tmp[i];
-        t1 = tmp[i + 2];
-        s0 = t1 + t0;
-        s2 = t1 - t0;
-
-        t2 = tmp[i + 1];
-        t3 = tmp[i + 3];
-        s1 = MULH3(t3 + t2, icos36h[    j], 2);
-        s3 = MULLx(t3 - t2, icos36 [8 - j], FRAC_BITS);
-
-        t0 = s0 + s1;
-        t1 = s0 - s1;
-        out[(9 + j) * SBLIMIT] = MULH3(t1, win[     9 + j], 1) + buf[9 + j];
-        out[(8 - j) * SBLIMIT] = MULH3(t1, win[     8 - j], 1) + buf[8 - j];
-        buf[ 9 + j           ] = MULH3(t0, win[18 + 9 + j], 1);
-        buf[ 8 - j           ] = MULH3(t0, win[18 + 8 - j], 1);
-
-        t0 = s2 + s3;
-        t1 = s2 - s3;
-        out[(9 + 8 - j) * SBLIMIT] = MULH3(t1, win[     9 + 8 - j], 1) + buf[9 + 8 - j];
-        out[         j  * SBLIMIT] = MULH3(t1, win[             j], 1) + buf[        j];
-        buf[ 9 + 8 - j           ] = MULH3(t0, win[18 + 9 + 8 - j], 1);
-        buf[         j           ] = MULH3(t0, win[18         + j], 1);
-        i += 4;
-    }
-
-    s0 = tmp[16];
-    s1 = MULH3(tmp[17], icos36h[4], 2);
-    t0 = s0 + s1;
-    t1 = s0 - s1;
-    out[(9 + 4) * SBLIMIT] = MULH3(t1, win[     9 + 4], 1) + buf[9 + 4];
-    out[(8 - 4) * SBLIMIT] = MULH3(t1, win[     8 - 4], 1) + buf[8 - 4];
-    buf[ 9 + 4           ] = MULH3(t0, win[18 + 9 + 4], 1);
-    buf[ 8 - 4           ] = MULH3(t0, win[18 + 8 - 4], 1);
-}
-
 /* return the number of decoded frames */
 static int mp_decode_layer1(MPADecodeContext *s)
 {
@@ -1366,7 +1213,7 @@ static void compute_antialias(MPADecodeContext *s, GranuleDef *g)
 static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
                           INTFLOAT *sb_samples, INTFLOAT *mdct_buf)
 {
-    INTFLOAT *win, *win1, *out_ptr, *ptr, *buf, *ptr1;
+    INTFLOAT *win, *out_ptr, *ptr, *buf, *ptr1;
     INTFLOAT out2[12];
     int i, j, mdct_long_end, sblimit;
 
@@ -1392,63 +1239,53 @@ static void compute_imdct(MPADecodeContext *s, GranuleDef *g,
         mdct_long_end = sblimit;
     }
 
-    buf = mdct_buf;
-    ptr = g->sb_hybrid;
-    for (j = 0; j < mdct_long_end; j++) {
-        /* apply window & overlap with previous buffer */
-        out_ptr = sb_samples + j;
-        /* select window */
-        if (g->switch_point && j < 2)
-            win1 = mdct_win[0];
-        else
-            win1 = mdct_win[g->block_type];
-        /* select frequency inversion */
-        win = win1 + ((4 * 36) & -(j & 1));
-        imdct36(out_ptr, buf, ptr, win);
-        out_ptr += 18 * SBLIMIT;
-        ptr     += 18;
-        buf     += 18;
-    }
+    s->mpadsp.RENAME(imdct36_blocks)(sb_samples, mdct_buf, g->sb_hybrid,
+                                     mdct_long_end, g->switch_point,
+                                     g->block_type);
+
+    buf = mdct_buf + 4*18*(mdct_long_end >> 2) + (mdct_long_end & 3);
+    ptr = g->sb_hybrid + 18 * mdct_long_end;
+
     for (j = mdct_long_end; j < sblimit; j++) {
         /* select frequency inversion */
-        win     = mdct_win[2] + ((4 * 36) & -(j & 1));
+        win     = RENAME(ff_mdct_win)[2 + (4  & -(j & 1))];
         out_ptr = sb_samples + j;
 
         for (i = 0; i < 6; i++) {
-            *out_ptr = buf[i];
+            *out_ptr = buf[4*i];
             out_ptr += SBLIMIT;
         }
         imdct12(out2, ptr + 0);
         for (i = 0; i < 6; i++) {
-            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*1];
-            buf[i + 6*2] = MULH3(out2[i + 6], win[i + 6], 1);
+            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*1)];
+            buf[4*(i + 6*2)] = MULH3(out2[i + 6], win[i + 6], 1);
             out_ptr += SBLIMIT;
         }
         imdct12(out2, ptr + 1);
         for (i = 0; i < 6; i++) {
-            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*2];
-            buf[i + 6*0] = MULH3(out2[i + 6], win[i + 6], 1);
+            *out_ptr     = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*2)];
+            buf[4*(i + 6*0)] = MULH3(out2[i + 6], win[i + 6], 1);
             out_ptr += SBLIMIT;
         }
         imdct12(out2, ptr + 2);
         for (i = 0; i < 6; i++) {
-            buf[i + 6*0] = MULH3(out2[i    ], win[i    ], 1) + buf[i + 6*0];
-            buf[i + 6*1] = MULH3(out2[i + 6], win[i + 6], 1);
-            buf[i + 6*2] = 0;
+            buf[4*(i + 6*0)] = MULH3(out2[i    ], win[i    ], 1) + buf[4*(i + 6*0)];
+            buf[4*(i + 6*1)] = MULH3(out2[i + 6], win[i + 6], 1);
+            buf[4*(i + 6*2)] = 0;
         }
         ptr += 18;
-        buf += 18;
+        buf += (j&3) != 3 ? 1 : (4*18-3);
     }
     /* zero bands */
     for (j = sblimit; j < SBLIMIT; j++) {
         /* overlap */
         out_ptr = sb_samples + j;
         for (i = 0; i < 18; i++) {
-            *out_ptr = buf[i];
-            buf[i]   = 0;
+            *out_ptr = buf[4*i];
+            buf[4*i]   = 0;
             out_ptr += SBLIMIT;
         }
-        buf += 18;
+        buf += (j&3) != 3 ? 1 : (4*18-3);
     }
 }
 
@@ -1539,6 +1376,7 @@ static int mp_decode_layer3(MPADecodeContext *s)
     }
 
     if (!s->adu_mode) {
+        int skip;
         const uint8_t *ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);
         assert((get_bits_count(&s->gb) & 7) == 0);
         /* now we get bits from the main_data_begin offset */
@@ -1548,28 +1386,32 @@ static int mp_decode_layer3(MPADecodeContext *s)
         memcpy(s->last_buf + s->last_buf_size, ptr, EXTRABYTES);
         s->in_gb = s->gb;
         init_get_bits(&s->gb, s->last_buf, s->last_buf_size*8);
-#if CONFIG_SAFE_BITSTREAM_READER
+#if !UNCHECKED_BITSTREAM_READER
         s->gb.size_in_bits_plus8 += EXTRABYTES * 8;
 #endif
-        skip_bits_long(&s->gb, 8*(s->last_buf_size - main_data_begin));
+        s->last_buf_size <<= 3;
+        for (gr = 0; gr < nb_granules && (s->last_buf_size >> 3) < main_data_begin; gr++) {
+            for (ch = 0; ch < s->nb_channels; ch++) {
+                g = &s->granules[ch][gr];
+                s->last_buf_size += g->part2_3_length;
+                memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
+            }
+        }
+        skip = s->last_buf_size - 8 * main_data_begin;
+        if (skip >= s->gb.size_in_bits && s->in_gb.buffer) {
+            skip_bits_long(&s->in_gb, skip - s->gb.size_in_bits);
+            s->gb           = s->in_gb;
+            s->in_gb.buffer = NULL;
+        } else {
+            skip_bits_long(&s->gb, skip);
+        }
+    } else {
+        gr = 0;
     }
 
-    for (gr = 0; gr < nb_granules; gr++) {
+    for (; gr < nb_granules; gr++) {
         for (ch = 0; ch < s->nb_channels; ch++) {
             g = &s->granules[ch][gr];
-            if (get_bits_count(&s->gb) < 0) {
-                av_log(s->avctx, AV_LOG_DEBUG, "mdb:%d, lastbuf:%d skipping granule %d\n",
-                       main_data_begin, s->last_buf_size, gr);
-                skip_bits_long(&s->gb, g->part2_3_length);
-                memset(g->sb_hybrid, 0, sizeof(g->sb_hybrid));
-                if (get_bits_count(&s->gb) >= s->gb.size_in_bits && s->in_gb.buffer) {
-                    skip_bits_long(&s->in_gb, get_bits_count(&s->gb) - s->gb.size_in_bits);
-                    s->gb           = s->in_gb;
-                    s->in_gb.buffer = NULL;
-                }
-                continue;
-            }
-
             bits_pos = get_bits_count(&s->gb);
 
             if (!s->lsf) {
diff --git a/libavcodec/mpegaudiodsp.c b/libavcodec/mpegaudiodsp.c
index 438b097..431724a 100644
--- a/libavcodec/mpegaudiodsp.c
+++ b/libavcodec/mpegaudiodsp.c
@@ -28,6 +28,8 @@ void ff_mpadsp_init(MPADSPContext *s)
     DCTContext dct;
 
     ff_dct_init(&dct, 5, DCT_II);
+    ff_init_mpadsp_tabs_float();
+    ff_init_mpadsp_tabs_fixed();
 
     s->apply_window_float = ff_mpadsp_apply_window_float;
     s->apply_window_fixed = ff_mpadsp_apply_window_fixed;
@@ -35,6 +37,9 @@ void ff_mpadsp_init(MPADSPContext *s)
     s->dct32_float = dct.dct32;
     s->dct32_fixed = ff_dct32_fixed;
 
+    s->imdct36_blocks_float = ff_imdct36_blocks_float;
+    s->imdct36_blocks_fixed = ff_imdct36_blocks_fixed;
+
     if (ARCH_ARM)     ff_mpadsp_init_arm(s);
     if (HAVE_MMX)     ff_mpadsp_init_mmx(s);
     if (HAVE_ALTIVEC) ff_mpadsp_init_altivec(s);
diff --git a/libavcodec/mpegaudiodsp.h b/libavcodec/mpegaudiodsp.h
index 8a18db8..c24ea41 100644
--- a/libavcodec/mpegaudiodsp.h
+++ b/libavcodec/mpegaudiodsp.h
@@ -20,6 +20,7 @@
 #define AVCODEC_MPEGAUDIODSP_H
 
 #include <stdint.h>
+#include "libavutil/common.h"
 
 typedef struct MPADSPContext {
     void (*apply_window_float)(float *synth_buf, float *window,
@@ -28,6 +29,10 @@ typedef struct MPADSPContext {
                                int *dither_state, int16_t *samples, int incr);
     void (*dct32_float)(float *dst, const float *src);
     void (*dct32_fixed)(int *dst, const int *src);
+    void (*imdct36_blocks_float)(float *out, float *buf, float *in,
+                                 int count, int switch_point, int block_type);
+    void (*imdct36_blocks_fixed)(int *out, int *buf, int *in,
+                                 int count, int switch_point, int block_type);
 } MPADSPContext;
 
 void ff_mpadsp_init(MPADSPContext *s);
@@ -61,4 +66,19 @@ void ff_mpadsp_apply_window_fixed(int32_t *synth_buf, int32_t *window,
                                   int *dither_state, int16_t *samples,
                                   int incr);
 
+void ff_imdct36_blocks_float(float *out, float *buf, float *in,
+                             int count, int switch_point, int block_type);
+
+void ff_imdct36_blocks_fixed(int *out, int *buf, int *in,
+                             int count, int switch_point, int block_type);
+
+void ff_init_mpadsp_tabs_float(void);
+void ff_init_mpadsp_tabs_fixed(void);
+
+/** For SSE implementation, MDCT_BUF_SIZE/2 should be 128-bit aligned */
+#define MDCT_BUF_SIZE FFALIGN(36, 2*4)
+
+extern int ff_mdct_win_fixed[8][MDCT_BUF_SIZE];
+extern float ff_mdct_win_float[8][MDCT_BUF_SIZE];
+
 #endif /* AVCODEC_MPEGAUDIODSP_H */
diff --git a/libavcodec/mpegaudiodsp_template.c b/libavcodec/mpegaudiodsp_template.c
index 5561c46..d616f8a 100644
--- a/libavcodec/mpegaudiodsp_template.c
+++ b/libavcodec/mpegaudiodsp_template.c
@@ -39,7 +39,12 @@ static inline float round_sample(float *sum)
 
 #define MACS(rt, ra, rb) rt+=(ra)*(rb)
 #define MULS(ra, rb) ((ra)*(rb))
+#define MULH3(x, y, s) ((s)*(y)*(x))
 #define MLSS(rt, ra, rb) rt-=(ra)*(rb)
+#define MULLx(x, y, s) ((y)*(x))
+#define FIXHR(x)        ((float)(x))
+#define FIXR(x)        ((float)(x))
+#define SHR(a,b)       ((a)*(1.0f/(1<<(b))))
 
 #else
 
@@ -57,8 +62,19 @@ static inline int round_sample(int64_t *sum)
 #   define MULS(ra, rb) MUL64(ra, rb)
 #   define MACS(rt, ra, rb) MAC64(rt, ra, rb)
 #   define MLSS(rt, ra, rb) MLS64(rt, ra, rb)
+#   define MULH3(x, y, s) MULH((s)*(x), y)
+#   define MULLx(x, y, s) MULL(x,y,s)
+#   define SHR(a,b)       ((a)>>(b))
+#   define FIXR(a)        ((int)((a) * FRAC_ONE + 0.5))
+#   define FIXHR(a)       ((int)((a) * (1LL<<32) + 0.5))
 #endif
 
+/** Window for MDCT. Actually only the elements in [0,17] and
+    [MDCT_BUF_SIZE/2, MDCT_BUF_SIZE/2 + 17] are actually used. The rest
+    is just to preserve alignment for SIMD implementations.
+*/
+DECLARE_ALIGNED(16, INTFLOAT, RENAME(ff_mdct_win))[8][MDCT_BUF_SIZE];
+
 DECLARE_ALIGNED(16, MPA_INT, RENAME(ff_mpa_synth_window))[512+256];
 
 #define SUM8(op, sum, w, p)               \
@@ -194,6 +210,7 @@ void av_cold RENAME(ff_mpa_synth_init)(MPA_INT *window)
             window[512 - i] = v;
     }
 
+
     // Needed for avoiding shuffles in ASM implementations
     for(i=0; i < 8; i++)
         for(j=0; j < 16; j++)
@@ -203,3 +220,181 @@ void av_cold RENAME(ff_mpa_synth_init)(MPA_INT *window)
         for(j=0; j < 16; j++)
             window[512+128+16*i+j] = window[64*i+48-j];
 }
+
+void RENAME(ff_init_mpadsp_tabs)(void)
+{
+    int i, j;
+    /* compute mdct windows */
+    for (i = 0; i < 36; i++) {
+        for (j = 0; j < 4; j++) {
+            double d;
+
+            if (j == 2 && i % 3 != 1)
+                continue;
+
+            d = sin(M_PI * (i + 0.5) / 36.0);
+            if (j == 1) {
+                if      (i >= 30) d = 0;
+                else if (i >= 24) d = sin(M_PI * (i - 18 + 0.5) / 12.0);
+                else if (i >= 18) d = 1;
+            } else if (j == 3) {
+                if      (i <   6) d = 0;
+                else if (i <  12) d = sin(M_PI * (i -  6 + 0.5) / 12.0);
+                else if (i <  18) d = 1;
+            }
+            //merge last stage of imdct into the window coefficients
+            d *= 0.5 / cos(M_PI * (2 * i + 19) / 72);
+
+            if (j == 2)
+                RENAME(ff_mdct_win)[j][i/3] = FIXHR((d / (1<<5)));
+            else {
+                int idx = i < 18 ? i : i + (MDCT_BUF_SIZE/2 - 18);
+                RENAME(ff_mdct_win)[j][idx] = FIXHR((d / (1<<5)));
+            }
+        }
+    }
+
+    /* NOTE: we do frequency inversion adter the MDCT by changing
+        the sign of the right window coefs */
+    for (j = 0; j < 4; j++) {
+        for (i = 0; i < MDCT_BUF_SIZE; i += 2) {
+            RENAME(ff_mdct_win)[j + 4][i    ] =  RENAME(ff_mdct_win)[j][i    ];
+            RENAME(ff_mdct_win)[j + 4][i + 1] = -RENAME(ff_mdct_win)[j][i + 1];
+        }
+    }
+}
+/* cos(pi*i/18) */
+#define C1 FIXHR(0.98480775301220805936/2)
+#define C2 FIXHR(0.93969262078590838405/2)
+#define C3 FIXHR(0.86602540378443864676/2)
+#define C4 FIXHR(0.76604444311897803520/2)
+#define C5 FIXHR(0.64278760968653932632/2)
+#define C6 FIXHR(0.5/2)
+#define C7 FIXHR(0.34202014332566873304/2)
+#define C8 FIXHR(0.17364817766693034885/2)
+
+/* 0.5 / cos(pi*(2*i+1)/36) */
+static const INTFLOAT icos36[9] = {
+    FIXR(0.50190991877167369479),
+    FIXR(0.51763809020504152469), //0
+    FIXR(0.55168895948124587824),
+    FIXR(0.61038729438072803416),
+    FIXR(0.70710678118654752439), //1
+    FIXR(0.87172339781054900991),
+    FIXR(1.18310079157624925896),
+    FIXR(1.93185165257813657349), //2
+    FIXR(5.73685662283492756461),
+};
+
+/* 0.5 / cos(pi*(2*i+1)/36) */
+static const INTFLOAT icos36h[9] = {
+    FIXHR(0.50190991877167369479/2),
+    FIXHR(0.51763809020504152469/2), //0
+    FIXHR(0.55168895948124587824/2),
+    FIXHR(0.61038729438072803416/2),
+    FIXHR(0.70710678118654752439/2), //1
+    FIXHR(0.87172339781054900991/2),
+    FIXHR(1.18310079157624925896/4),
+    FIXHR(1.93185165257813657349/4), //2
+//    FIXHR(5.73685662283492756461),
+};
+
+/* using Lee like decomposition followed by hand coded 9 points DCT */
+static void imdct36(INTFLOAT *out, INTFLOAT *buf, INTFLOAT *in, INTFLOAT *win)
+{
+    int i, j;
+    INTFLOAT t0, t1, t2, t3, s0, s1, s2, s3;
+    INTFLOAT tmp[18], *tmp1, *in1;
+
+    for (i = 17; i >= 1; i--)
+        in[i] += in[i-1];
+    for (i = 17; i >= 3; i -= 2)
+        in[i] += in[i-2];
+
+    for (j = 0; j < 2; j++) {
+        tmp1 = tmp + j;
+        in1 = in + j;
+
+        t2 = in1[2*4] + in1[2*8] - in1[2*2];
+
+        t3 = in1[2*0] + SHR(in1[2*6],1);
+        t1 = in1[2*0] - in1[2*6];
+        tmp1[ 6] = t1 - SHR(t2,1);
+        tmp1[16] = t1 + t2;
+
+        t0 = MULH3(in1[2*2] + in1[2*4] ,    C2, 2);
+        t1 = MULH3(in1[2*4] - in1[2*8] , -2*C8, 1);
+        t2 = MULH3(in1[2*2] + in1[2*8] ,   -C4, 2);
+
+        tmp1[10] = t3 - t0 - t2;
+        tmp1[ 2] = t3 + t0 + t1;
+        tmp1[14] = t3 + t2 - t1;
+
+        tmp1[ 4] = MULH3(in1[2*5] + in1[2*7] - in1[2*1], -C3, 2);
+        t2 = MULH3(in1[2*1] + in1[2*5],    C1, 2);
+        t3 = MULH3(in1[2*5] - in1[2*7], -2*C7, 1);
+        t0 = MULH3(in1[2*3], C3, 2);
+
+        t1 = MULH3(in1[2*1] + in1[2*7],   -C5, 2);
+
+        tmp1[ 0] = t2 + t3 + t0;
+        tmp1[12] = t2 + t1 - t0;
+        tmp1[ 8] = t3 - t1 - t0;
+    }
+
+    i = 0;
+    for (j = 0; j < 4; j++) {
+        t0 = tmp[i];
+        t1 = tmp[i + 2];
+        s0 = t1 + t0;
+        s2 = t1 - t0;
+
+        t2 = tmp[i + 1];
+        t3 = tmp[i + 3];
+        s1 = MULH3(t3 + t2, icos36h[    j], 2);
+        s3 = MULLx(t3 - t2, icos36 [8 - j], FRAC_BITS);
+
+        t0 = s0 + s1;
+        t1 = s0 - s1;
+        out[(9 + j) * SBLIMIT] = MULH3(t1, win[     9 + j], 1) + buf[4*(9 + j)];
+        out[(8 - j) * SBLIMIT] = MULH3(t1, win[     8 - j], 1) + buf[4*(8 - j)];
+        buf[4 * ( 9 + j     )] = MULH3(t0, win[MDCT_BUF_SIZE/2 + 9 + j], 1);
+        buf[4 * ( 8 - j     )] = MULH3(t0, win[MDCT_BUF_SIZE/2 + 8 - j], 1);
+
+        t0 = s2 + s3;
+        t1 = s2 - s3;
+        out[(9 + 8 - j) * SBLIMIT] = MULH3(t1, win[     9 + 8 - j], 1) + buf[4*(9 + 8 - j)];
+        out[         j  * SBLIMIT] = MULH3(t1, win[             j], 1) + buf[4*(        j)];
+        buf[4 * ( 9 + 8 - j     )] = MULH3(t0, win[MDCT_BUF_SIZE/2 + 9 + 8 - j], 1);
+        buf[4 * (         j     )] = MULH3(t0, win[MDCT_BUF_SIZE/2         + j], 1);
+        i += 4;
+    }
+
+    s0 = tmp[16];
+    s1 = MULH3(tmp[17], icos36h[4], 2);
+    t0 = s0 + s1;
+    t1 = s0 - s1;
+    out[(9 + 4) * SBLIMIT] = MULH3(t1, win[     9 + 4], 1) + buf[4*(9 + 4)];
+    out[(8 - 4) * SBLIMIT] = MULH3(t1, win[     8 - 4], 1) + buf[4*(8 - 4)];
+    buf[4 * ( 9 + 4     )] = MULH3(t0, win[MDCT_BUF_SIZE/2 + 9 + 4], 1);
+    buf[4 * ( 8 - 4     )] = MULH3(t0, win[MDCT_BUF_SIZE/2 + 8 - 4], 1);
+}
+
+void RENAME(ff_imdct36_blocks)(INTFLOAT *out, INTFLOAT *buf, INTFLOAT *in,
+                               int count, int switch_point, int block_type)
+{
+    int j;
+    for (j=0 ; j < count; j++) {
+        /* apply window & overlap with previous buffer */
+
+        /* select window */
+        int win_idx = (switch_point && j < 2) ? 0 : block_type;
+        INTFLOAT *win = RENAME(ff_mdct_win)[win_idx + (4 & -(j & 1))];
+
+        imdct36(out, buf, in, win);
+
+        in  += 18;
+        buf += ((j&3) != 3 ? 1 : (72-3));
+        out++;
+    }
+}
diff --git a/libavcodec/mpegvideo.c b/libavcodec/mpegvideo.c
index 214b64e..f711d36 100644
--- a/libavcodec/mpegvideo.c
+++ b/libavcodec/mpegvideo.c
@@ -637,6 +637,8 @@ void MPV_common_defaults(MpegEncContext *s)
 
     s->picture_range_start   = 0;
     s->picture_range_end     = MAX_PICTURE_COUNT;
+
+    s->slice_context_count   = 1;
 }
 
 /**
@@ -655,11 +657,13 @@ void MPV_decode_defaults(MpegEncContext *s)
  */
 av_cold int MPV_common_init(MpegEncContext *s)
 {
-    int y_size, c_size, yc_size, i, mb_array_size, mv_table_size, x, y,
-        threads = (s->encoding ||
-                   (HAVE_THREADS &&
-                    s->avctx->active_thread_type & FF_THREAD_SLICE)) ?
-                  s->avctx->thread_count : 1;
+    int y_size, c_size, yc_size, i, mb_array_size, mv_table_size, x, y;
+    int nb_slices = (HAVE_THREADS &&
+                     s->avctx->active_thread_type & FF_THREAD_SLICE) ?
+                    s->avctx->thread_count : 1;
+
+    if (s->encoding && s->avctx->slices)
+        nb_slices = s->avctx->slices;
 
     if (s->codec_id == CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)
         s->mb_height = (s->height + 31) / 32 * 2;
@@ -672,14 +676,15 @@ av_cold int MPV_common_init(MpegEncContext *s)
         return -1;
     }
 
-    if ((s->encoding || (s->avctx->active_thread_type & FF_THREAD_SLICE)) &&
-        (s->avctx->thread_count > MAX_THREADS ||
-         (s->avctx->thread_count > s->mb_height && s->mb_height))) {
-        int max_threads = FFMIN(MAX_THREADS, s->mb_height);
-        av_log(s->avctx, AV_LOG_WARNING,
-               "too many threads (%d), reducing to %d\n",
-               s->avctx->thread_count, max_threads);
-        threads = max_threads;
+    if (nb_slices > MAX_THREADS || (nb_slices > s->mb_height && s->mb_height)) {
+        int max_slices;
+        if (s->mb_height)
+            max_slices = FFMIN(MAX_THREADS, s->mb_height);
+        else
+            max_slices = MAX_THREADS;
+        av_log(s->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
+               " reducing to %d\n", nb_slices, max_slices);
+        nb_slices = max_slices;
     }
 
     if ((s->width || s->height) &&
@@ -700,8 +705,8 @@ av_cold int MPV_common_init(MpegEncContext *s)
         mv_table_size = (s->mb_height + 2) * s->mb_stride + 1;
 
         /* set chroma shifts */
-        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt,&(s->chroma_x_shift),
-                                      &(s->chroma_y_shift) );
+        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &s->chroma_x_shift,
+                                      &s->chroma_y_shift);
 
         /* set default edge pos, will be overriden
          * in decode_header if needed */
@@ -885,22 +890,19 @@ av_cold int MPV_common_init(MpegEncContext *s)
     s->thread_context[0]   = s;
 
     if (s->width && s->height) {
-        if (s->encoding || (HAVE_THREADS &&
-                            s->avctx->active_thread_type&FF_THREAD_SLICE)) {
-            for (i = 1; i < threads; i++) {
+        if (nb_slices > 1) {
+            for (i = 1; i < nb_slices; i++) {
                 s->thread_context[i] = av_malloc(sizeof(MpegEncContext));
                 memcpy(s->thread_context[i], s, sizeof(MpegEncContext));
             }
 
-            for (i = 0; i < threads; i++) {
+            for (i = 0; i < nb_slices; i++) {
                 if (init_duplicate_context(s->thread_context[i], s) < 0)
                     goto fail;
                     s->thread_context[i]->start_mb_y =
-                        (s->mb_height * (i) + s->avctx->thread_count / 2) /
-                        s->avctx->thread_count;
+                        (s->mb_height * (i) + nb_slices / 2) / nb_slices;
                     s->thread_context[i]->end_mb_y   =
-                        (s->mb_height * (i + 1) + s->avctx->thread_count / 2) /
-                        s->avctx->thread_count;
+                        (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;
             }
         } else {
             if (init_duplicate_context(s, s) < 0)
@@ -908,6 +910,7 @@ av_cold int MPV_common_init(MpegEncContext *s)
             s->start_mb_y = 0;
             s->end_mb_y   = s->mb_height;
         }
+        s->slice_context_count = nb_slices;
     }
 
     return 0;
@@ -921,14 +924,14 @@ void MPV_common_end(MpegEncContext *s)
 {
     int i, j, k;
 
-    if (s->encoding || (HAVE_THREADS &&
-        s->avctx->active_thread_type & FF_THREAD_SLICE)) {
-        for (i = 0; i < s->avctx->thread_count; i++) {
+    if (s->slice_context_count > 1) {
+        for (i = 0; i < s->slice_context_count; i++) {
             free_duplicate_context(s->thread_context[i]);
         }
-        for (i = 1; i < s->avctx->thread_count; i++) {
+        for (i = 1; i < s->slice_context_count; i++) {
             av_freep(&s->thread_context[i]);
         }
+        s->slice_context_count = 1;
     } else free_duplicate_context(s);
 
     av_freep(&s->parse_context.buffer);
@@ -1167,25 +1170,26 @@ int MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
            s->codec_id == CODEC_ID_SVQ3);
 
     /* mark & release old frames */
-    if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&
-        s->last_picture_ptr != s->next_picture_ptr &&
-        s->last_picture_ptr->f.data[0]) {
-        if (s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3) {
+    if (s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3) {
+        if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&
+            s->last_picture_ptr != s->next_picture_ptr &&
+            s->last_picture_ptr->f.data[0]) {
             if (s->last_picture_ptr->owner2 == s)
                 free_frame_buffer(s, s->last_picture_ptr);
+        }
 
-            /* release forgotten pictures */
-            /* if (mpeg124/h263) */
-            if (!s->encoding) {
-                for (i = 0; i < s->picture_count; i++) {
-                    if (s->picture[i].owner2 == s && s->picture[i].f.data[0] &&
-                        &s->picture[i] != s->next_picture_ptr &&
-                        s->picture[i].f.reference) {
-                        if (!(avctx->active_thread_type & FF_THREAD_FRAME))
-                            av_log(avctx, AV_LOG_ERROR,
-                                   "releasing zombie picture\n");
-                        free_frame_buffer(s, &s->picture[i]);
-                    }
+        /* release forgotten pictures */
+        /* if (mpeg124/h263) */
+        if (!s->encoding) {
+            for (i = 0; i < s->picture_count; i++) {
+                if (s->picture[i].owner2 == s && s->picture[i].f.data[0] &&
+                    &s->picture[i] != s->last_picture_ptr &&
+                    &s->picture[i] != s->next_picture_ptr &&
+                    s->picture[i].f.reference) {
+                    if (!(avctx->active_thread_type & FF_THREAD_FRAME))
+                        av_log(avctx, AV_LOG_ERROR,
+                               "releasing zombie picture\n");
+                    free_frame_buffer(s, &s->picture[i]);
                 }
             }
         }
@@ -1292,6 +1296,14 @@ int MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
     if (s->next_picture_ptr)
         ff_copy_picture(&s->next_picture, s->next_picture_ptr);
 
+    if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_FRAME) &&
+        (s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3)) {
+        if (s->next_picture_ptr)
+            s->next_picture_ptr->owner2 = s;
+        if (s->last_picture_ptr)
+            s->last_picture_ptr->owner2 = s;
+    }
+
     assert(s->pict_type == AV_PICTURE_TYPE_I || (s->last_picture_ptr &&
                                                  s->last_picture_ptr->f.data[0]));
 
@@ -2336,7 +2348,7 @@ void MPV_decode_mb_internal(MpegEncContext *s, DCTELEM block[12][64],
         }
 
         dct_linesize = linesize << s->interlaced_dct;
-        dct_offset =(s->interlaced_dct)? linesize : linesize*block_size;
+        dct_offset   = s->interlaced_dct ? linesize : linesize * block_size;
 
         if(readable){
             dest_y=  s->dest[0];
@@ -2432,7 +2444,7 @@ void MPV_decode_mb_internal(MpegEncContext *s, DCTELEM block[12][64],
                     }else{
                         //chroma422
                         dct_linesize = uvlinesize << s->interlaced_dct;
-                        dct_offset =(s->interlaced_dct)? uvlinesize : uvlinesize*8;
+                        dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize * 8;
 
                         add_dct(s, block[4], 4, dest_cb, dct_linesize);
                         add_dct(s, block[5], 5, dest_cr, dct_linesize);
@@ -2484,7 +2496,7 @@ void MPV_decode_mb_internal(MpegEncContext *s, DCTELEM block[12][64],
                     }else{
 
                         dct_linesize = uvlinesize << s->interlaced_dct;
-                        dct_offset =(s->interlaced_dct)? uvlinesize : uvlinesize*8;
+                        dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize * 8;
 
                         s->dsp.idct_put(dest_cb,              dct_linesize, block[4]);
                         s->dsp.idct_put(dest_cr,              dct_linesize, block[5]);
diff --git a/libavcodec/mpegvideo.h b/libavcodec/mpegvideo.h
index 6483893..3473e6d 100644
--- a/libavcodec/mpegvideo.h
+++ b/libavcodec/mpegvideo.h
@@ -268,6 +268,7 @@ typedef struct MpegEncContext {
     int start_mb_y;            ///< start mb_y of this thread (so current thread should process start_mb_y <= row < end_mb_y)
     int end_mb_y;              ///< end   mb_y of this thread (so current thread should process start_mb_y <= row < end_mb_y)
     struct MpegEncContext *thread_context[MAX_THREADS];
+    int slice_context_count;   ///< number of used thread_contexts
 
     /**
      * copy of the previous picture structure.
diff --git a/libavcodec/mpegvideo_enc.c b/libavcodec/mpegvideo_enc.c
index af303d8..84a5cda 100644
--- a/libavcodec/mpegvideo_enc.c
+++ b/libavcodec/mpegvideo_enc.c
@@ -1428,7 +1428,8 @@ int MPV_encode_picture(AVCodecContext *avctx,
 {
     MpegEncContext *s = avctx->priv_data;
     AVFrame *pic_arg  = data;
-    int i, stuffing_count, context_count = avctx->thread_count;
+    int i, stuffing_count;
+    int context_count = s->slice_context_count;
 
     for (i = 0; i < context_count; i++) {
         int start_y = s->thread_context[i]->start_mb_y;
@@ -3059,7 +3060,7 @@ static int encode_picture(MpegEncContext *s, int picture_number)
 {
     int i;
     int bits;
-    int context_count = s->avctx->thread_count;
+    int context_count = s->slice_context_count;
 
     s->picture_number = picture_number;
 
diff --git a/libavcodec/options.c b/libavcodec/options.c
index 4ac9313..a99aed7 100644
--- a/libavcodec/options.c
+++ b/libavcodec/options.c
@@ -370,7 +370,7 @@ static const AVOption options[]={
 {"float", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_AA_FLOAT }, INT_MIN, INT_MAX, V|D, "aa"},
 #endif
 {"qns", "quantizer noise shaping", OFFSET(quantizer_noise_shaping), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
-{"threads", NULL, OFFSET(thread_count), AV_OPT_TYPE_INT, {.dbl = 1 }, 0, INT_MAX, V|E|D, "threads"},
+{"threads", NULL, OFFSET(thread_count), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, V|E|D, "threads"},
 {"auto", "detect a good number of threads", 0, AV_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, V|E|D, "threads"},
 {"me_threshold", "motion estimaton threshold", OFFSET(me_threshold), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
 {"mb_threshold", "macroblock threshold", OFFSET(mb_threshold), AV_OPT_TYPE_INT, {.dbl = DEFAULT }, INT_MIN, INT_MAX, V|E},
@@ -506,7 +506,7 @@ static const AVOption options[]={
 {"cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = AV_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, A|E, "lpc_type"},
 {"lpc_passes", "deprecated, use flac-specific options", OFFSET(lpc_passes), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, A|E},
 #endif
-{"slices", "number of slices, used in parallelized decoding", OFFSET(slices), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, V|E},
+{"slices", "number of slices, used in parallelized encoding", OFFSET(slices), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, V|E},
 {"thread_type", "select multithreading type", OFFSET(thread_type), AV_OPT_TYPE_FLAGS, {.dbl = FF_THREAD_SLICE|FF_THREAD_FRAME }, 0, INT_MAX, V|E|D, "thread_type"},
 {"slice", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_THREAD_SLICE }, INT_MIN, INT_MAX, V|E|D, "thread_type"},
 {"frame", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_THREAD_FRAME }, INT_MIN, INT_MAX, V|E|D, "thread_type"},
diff --git a/libavcodec/ppc/mpegvideo_altivec.c b/libavcodec/ppc/mpegvideo_altivec.c
index 2d3bf89..a033cd7 100644
--- a/libavcodec/ppc/mpegvideo_altivec.c
+++ b/libavcodec/ppc/mpegvideo_altivec.c
@@ -268,10 +268,10 @@ static int dct_quantize_altivec(MpegEncContext* s,
             vec_ste(baseVector, 0, &oldBaseValue);
 
             qmat = (vector signed int*)s->q_intra_matrix[qscale];
-            biasAddr = &(s->intra_quant_bias);
+            biasAddr = &s->intra_quant_bias;
         } else {
             qmat = (vector signed int*)s->q_inter_matrix[qscale];
-            biasAddr = &(s->inter_quant_bias);
+            biasAddr = &s->inter_quant_bias;
         }
 
         // Load the bias vector (We add 0.5 to the bias so that we're
@@ -361,8 +361,8 @@ static int dct_quantize_altivec(MpegEncContext* s,
             vector signed int max_q_int, min_q_int;
             vector signed short max_q, min_q;
 
-            LOAD4(max_q_int, &(s->max_qcoeff));
-            LOAD4(min_q_int, &(s->min_qcoeff));
+            LOAD4(max_q_int, &s->max_qcoeff);
+            LOAD4(min_q_int, &s->min_qcoeff);
 
             max_q = vec_pack(max_q_int, max_q_int);
             min_q = vec_pack(min_q_int, min_q_int);
diff --git a/libavcodec/pthread.c b/libavcodec/pthread.c
index 4356b32..0688d9d 100644
--- a/libavcodec/pthread.c
+++ b/libavcodec/pthread.c
@@ -34,15 +34,20 @@
 #if HAVE_SCHED_GETAFFINITY
 #define _GNU_SOURCE
 #include <sched.h>
-#elif HAVE_GETSYSTEMINFO
+#endif
+#if HAVE_GETPROCESSAFFINITYMASK
 #include <windows.h>
-#elif HAVE_SYSCTL
+#endif
+#if HAVE_SYSCTL
 #if HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
 #include <sys/types.h>
 #include <sys/sysctl.h>
 #endif
+#if HAVE_SYSCONF
+#include <unistd.h>
+#endif
 
 #include "avcodec.h"
 #include "internal.h"
@@ -164,10 +169,11 @@ static int get_logical_cpus(AVCodecContext *avctx)
     if (!ret) {
         nb_cpus = CPU_COUNT(&cpuset);
     }
-#elif HAVE_GETSYSTEMINFO
-    SYSTEM_INFO sysinfo;
-    GetSystemInfo(&sysinfo);
-    nb_cpus = sysinfo.dwNumberOfProcessors;
+#elif HAVE_GETPROCESSAFFINITYMASK
+    DWORD_PTR proc_aff, sys_aff;
+    ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
+    if (ret)
+        nb_cpus = av_popcount64(proc_aff);
 #elif HAVE_SYSCTL && defined(HW_NCPU)
     int mib[2] = { CTL_HW, HW_NCPU };
     size_t len = sizeof(nb_cpus);
@@ -175,9 +181,13 @@ static int get_logical_cpus(AVCodecContext *avctx)
     ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
     if (ret == -1)
         nb_cpus = 0;
+#elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
+    nb_cpus = sysconf(_SC_NPROC_ONLN);
+#elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
+    nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
 #endif
     av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
-    return FFMIN(nb_cpus, MAX_AUTO_THREADS);
+    return nb_cpus;
 }
 
 
@@ -287,9 +297,11 @@ static int thread_init(AVCodecContext *avctx)
 
     if (!thread_count) {
         int nb_cpus = get_logical_cpus(avctx);
-        // use number of cores + 1 as thread count if there is motre than one
+        // use number of cores + 1 as thread count if there is more than one
         if (nb_cpus > 1)
-            thread_count = avctx->thread_count = nb_cpus + 1;
+            thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
+        else
+            thread_count = avctx->thread_count = 1;
     }
 
     if (thread_count <= 1) {
@@ -758,9 +770,11 @@ static int frame_thread_init(AVCodecContext *avctx)
 
     if (!thread_count) {
         int nb_cpus = get_logical_cpus(avctx);
-        // use number of cores + 1 as thread count if there is motre than one
+        // use number of cores + 1 as thread count if there is more than one
         if (nb_cpus > 1)
-            thread_count = avctx->thread_count = nb_cpus + 1;
+            thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
+        else
+            thread_count = avctx->thread_count = 1;
     }
 
     if (thread_count <= 1) {
@@ -815,7 +829,7 @@ static int frame_thread_init(AVCodecContext *avctx)
                 err = AVERROR(ENOMEM);
                 goto error;
             }
-            *(copy->internal) = *(src->internal);
+            *copy->internal = *src->internal;
             copy->internal->is_copy = 1;
 
             if (codec->init_thread_copy)
@@ -973,6 +987,9 @@ static void validate_thread_parameters(AVCodecContext *avctx)
     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
                avctx->thread_type & FF_THREAD_SLICE) {
         avctx->active_thread_type = FF_THREAD_SLICE;
+    } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
+        avctx->thread_count       = 1;
+        avctx->active_thread_type = 0;
     }
 }
 
diff --git a/libavcodec/ra144enc.c b/libavcodec/ra144enc.c
index ee38bd5..c970a26 100644
--- a/libavcodec/ra144enc.c
+++ b/libavcodec/ra144enc.c
@@ -214,7 +214,7 @@ static int adaptive_cb_search(const int16_t *adapt_cb, float *work,
     ff_celp_lp_synthesis_filterf(work, coefs, exc, BLOCKSIZE, LPC_ORDER);
     for (i = 0; i < BLOCKSIZE; i++)
         data[i] -= best_gain * work[i];
-    return (best_vect - BLOCKSIZE / 2 + 1);
+    return best_vect - BLOCKSIZE / 2 + 1;
 }
 
 
diff --git a/libavcodec/rawdec.c b/libavcodec/rawdec.c
index 9989a36..427d109 100644
--- a/libavcodec/rawdec.c
+++ b/libavcodec/rawdec.c
@@ -59,6 +59,7 @@ static const PixelFormatTag pix_fmt_bps_mov[] = {
     { PIX_FMT_RGB555BE, 16 },
     { PIX_FMT_RGB24,    24 },
     { PIX_FMT_ARGB,     32 },
+    { PIX_FMT_MONOWHITE,33 },
     { PIX_FMT_NONE, 0 },
 };
 
@@ -122,6 +123,7 @@ static int raw_decode(AVCodecContext *avctx,
     AVFrame * frame = (AVFrame *) data;
     AVPicture * picture = (AVPicture *) data;
 
+    frame->pict_type        = avctx->coded_frame->pict_type;
     frame->interlaced_frame = avctx->coded_frame->interlaced_frame;
     frame->top_field_first = avctx->coded_frame->top_field_first;
     frame->reordered_opaque = avctx->reordered_opaque;
diff --git a/libavcodec/rv30.c b/libavcodec/rv30.c
index 26708db..4828e98 100644
--- a/libavcodec/rv30.c
+++ b/libavcodec/rv30.c
@@ -275,8 +275,10 @@ AVCodec ff_rv30_decoder = {
     .init           = rv30_decode_init,
     .close          = ff_rv34_decode_end,
     .decode         = ff_rv34_decode_frame,
-    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
+    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
     .flush          = ff_mpeg_flush,
     .long_name      = NULL_IF_CONFIG_SMALL("RealVideo 3.0"),
     .pix_fmts       = ff_pixfmt_list_420,
+    .init_thread_copy      = ONLY_IF_THREADS_ENABLED(ff_rv34_decode_init_thread_copy),
+    .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_rv34_decode_update_thread_context),
 };
diff --git a/libavcodec/rv34.c b/libavcodec/rv34.c
index 1a126be..ec826fd 100644
--- a/libavcodec/rv34.c
+++ b/libavcodec/rv34.c
@@ -24,12 +24,16 @@
  * RV30/40 decoder common data
  */
 
+#include "libavutil/internal.h"
+
 #include "avcodec.h"
 #include "dsputil.h"
 #include "mpegvideo.h"
 #include "golomb.h"
+#include "internal.h"
 #include "mathops.h"
 #include "rectangle.h"
+#include "thread.h"
 
 #include "rv34vlc.h"
 #include "rv34data.h"
@@ -212,7 +216,7 @@ static int rv34_decode_cbp(GetBitContext *gb, RV34VLC *vlc, int table)
 /**
  * Get one coefficient value from the bistream and store it.
  */
-static inline void decode_coeff(DCTELEM *dst, int coef, int esc, GetBitContext *gb, VLC* vlc)
+static inline void decode_coeff(DCTELEM *dst, int coef, int esc, GetBitContext *gb, VLC* vlc, int q)
 {
     if(coef){
         if(coef == esc){
@@ -225,14 +229,34 @@ static inline void decode_coeff(DCTELEM *dst, int coef, int esc, GetBitContext *
         }
         if(get_bits1(gb))
             coef = -coef;
-        *dst = coef;
+        *dst = (coef*q + 8) >> 4;
     }
 }
 
 /**
  * Decode 2x2 subblock of coefficients.
  */
-static inline void decode_subblock(DCTELEM *dst, int code, const int is_block2, GetBitContext *gb, VLC *vlc)
+static inline void decode_subblock(DCTELEM *dst, int code, const int is_block2, GetBitContext *gb, VLC *vlc, int q)
+{
+    int coeffs[4];
+
+    coeffs[0] = modulo_three_table[code][0];
+    coeffs[1] = modulo_three_table[code][1];
+    coeffs[2] = modulo_three_table[code][2];
+    coeffs[3] = modulo_three_table[code][3];
+    decode_coeff(dst  , coeffs[0], 3, gb, vlc, q);
+    if(is_block2){
+        decode_coeff(dst+8, coeffs[1], 2, gb, vlc, q);
+        decode_coeff(dst+1, coeffs[2], 2, gb, vlc, q);
+    }else{
+        decode_coeff(dst+1, coeffs[1], 2, gb, vlc, q);
+        decode_coeff(dst+8, coeffs[2], 2, gb, vlc, q);
+    }
+    decode_coeff(dst+9, coeffs[3], 2, gb, vlc, q);
+}
+
+static inline void decode_subblock3(DCTELEM *dst, int code, const int is_block2, GetBitContext *gb, VLC *vlc,
+                                    int q_dc, int q_ac1, int q_ac2)
 {
     int coeffs[4];
 
@@ -240,15 +264,15 @@ static inline void decode_subblock(DCTELEM *dst, int code, const int is_block2,
     coeffs[1] = modulo_three_table[code][1];
     coeffs[2] = modulo_three_table[code][2];
     coeffs[3] = modulo_three_table[code][3];
-    decode_coeff(dst  , coeffs[0], 3, gb, vlc);
+    decode_coeff(dst  , coeffs[0], 3, gb, vlc, q_dc);
     if(is_block2){
-        decode_coeff(dst+8, coeffs[1], 2, gb, vlc);
-        decode_coeff(dst+1, coeffs[2], 2, gb, vlc);
+        decode_coeff(dst+8, coeffs[1], 2, gb, vlc, q_ac1);
+        decode_coeff(dst+1, coeffs[2], 2, gb, vlc, q_ac1);
     }else{
-        decode_coeff(dst+1, coeffs[1], 2, gb, vlc);
-        decode_coeff(dst+8, coeffs[2], 2, gb, vlc);
+        decode_coeff(dst+1, coeffs[1], 2, gb, vlc, q_ac1);
+        decode_coeff(dst+8, coeffs[2], 2, gb, vlc, q_ac1);
     }
-    decode_coeff(dst+9, coeffs[3], 2, gb, vlc);
+    decode_coeff(dst+9, coeffs[3], 2, gb, vlc, q_ac2);
 }
 
 /**
@@ -262,7 +286,7 @@ static inline void decode_subblock(DCTELEM *dst, int code, const int is_block2,
  *  o--o
  */
 
-static inline void rv34_decode_block(DCTELEM *dst, GetBitContext *gb, RV34VLC *rvlc, int fc, int sc)
+static inline void rv34_decode_block(DCTELEM *dst, GetBitContext *gb, RV34VLC *rvlc, int fc, int sc, int q_dc, int q_ac1, int q_ac2)
 {
     int code, pattern;
 
@@ -271,40 +295,24 @@ static inline void rv34_decode_block(DCTELEM *dst, GetBitContext *gb, RV34VLC *r
     pattern = code & 0x7;
 
     code >>= 3;
-    decode_subblock(dst, code, 0, gb, &rvlc->coefficient);
+    decode_subblock3(dst, code, 0, gb, &rvlc->coefficient, q_dc, q_ac1, q_ac2);
 
     if(pattern & 4){
         code = get_vlc2(gb, rvlc->second_pattern[sc].table, 9, 2);
-        decode_subblock(dst + 2, code, 0, gb, &rvlc->coefficient);
+        decode_subblock(dst + 2, code, 0, gb, &rvlc->coefficient, q_ac2);
     }
     if(pattern & 2){ // Looks like coefficients 1 and 2 are swapped for this block
         code = get_vlc2(gb, rvlc->second_pattern[sc].table, 9, 2);
-        decode_subblock(dst + 8*2, code, 1, gb, &rvlc->coefficient);
+        decode_subblock(dst + 8*2, code, 1, gb, &rvlc->coefficient, q_ac2);
     }
     if(pattern & 1){
         code = get_vlc2(gb, rvlc->third_pattern[sc].table, 9, 2);
-        decode_subblock(dst + 8*2+2, code, 0, gb, &rvlc->coefficient);
+        decode_subblock(dst + 8*2+2, code, 0, gb, &rvlc->coefficient, q_ac2);
     }
 
 }
 
 /**
- * Dequantize 4x4 block of DC values for 16x16 macroblock.
- * @todo optimize
- */
-static inline void rv34_dequant4x4_16x16(DCTELEM *block, int Qdc, int Q)
-{
-    int i;
-
-    for(i = 0; i < 3; i++)
-         block[rv34_dezigzag[i]] = (block[rv34_dezigzag[i]] * Qdc + 8) >> 4;
-    for(; i < 16; i++)
-         block[rv34_dezigzag[i]] = (block[rv34_dezigzag[i]] * Q + 8) >> 4;
-}
-/** @} */ //block functions
-
-
-/**
  * @name RV30/40 bitstream parsing
  * @{
  */
@@ -665,6 +673,14 @@ static inline void rv34_mc(RV34DecContext *r, const int block_type,
         if(uvmx == 6 && uvmy == 6)
             uvmx = uvmy = 4;
     }
+
+    if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME)) {
+        /* wait for the referenced mb row to be finished */
+        int mb_row = FFMIN(s->mb_height - 1, s->mb_y + ((yoff + my + 21) >> 4));
+        AVFrame *f = dir ? &s->next_picture_ptr->f : &s->last_picture_ptr->f;
+        ff_thread_await_progress(f, mb_row, 0);
+    }
+
     dxy = ly*4 + lx;
     srcY = dir ? s->next_picture_ptr->f.data[0] : s->last_picture_ptr->f.data[0];
     srcU = dir ? s->next_picture_ptr->f.data[1] : s->last_picture_ptr->f.data[1];
@@ -676,8 +692,9 @@ static inline void rv34_mc(RV34DecContext *r, const int block_type,
     srcY += src_y * s->linesize + src_x;
     srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
     srcV += uvsrc_y * s->uvlinesize + uvsrc_x;
-    if(   (unsigned)(src_x - !!lx*2) > s->h_edge_pos - !!lx*2 - (width <<3) - 4
-       || (unsigned)(src_y - !!ly*2) > s->v_edge_pos - !!ly*2 - (height<<3) - 4){
+    if(s->h_edge_pos - (width << 3) < 6 || s->v_edge_pos - (height << 3) < 6 ||
+       (unsigned)(src_x - !!lx*2) > s->h_edge_pos - !!lx*2 - (width <<3) - 4 ||
+       (unsigned)(src_y - !!ly*2) > s->v_edge_pos - !!ly*2 - (height<<3) - 4) {
         uint8_t *uvbuf = s->edge_emu_buffer + 22 * s->linesize;
 
         srcY -= 2 + 2*s->linesize;
@@ -819,6 +836,10 @@ static int rv34_decode_mv(RV34DecContext *r, int block_type)
         }
     case RV34_MB_B_DIRECT:
         //surprisingly, it uses motion scheme from next reference frame
+        /* wait for the current mb row to be finished */
+        if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
+            ff_thread_await_progress(&s->next_picture_ptr->f, s->mb_y - 1, 0);
+
         next_bt = s->next_picture_ptr->f.mb_type[s->mb_x + s->mb_y * s->mb_stride];
         if(IS_INTRA(next_bt) || IS_SKIP(next_bt)){
             ZERO8x2(s->current_picture_ptr->f.motion_val[0][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);
@@ -1097,6 +1118,7 @@ static int rv34_decode_macroblock(RV34DecContext *r, int8_t *intra_types)
     MpegEncContext *s = &r->s;
     GetBitContext *gb = &s->gb;
     int cbp, cbp2;
+    int q_dc, q_ac;
     int i, blknum, blkoff;
     LOCAL_ALIGNED_16(DCTELEM, block16, [64]);
     int luma_dc_quant;
@@ -1133,31 +1155,34 @@ static int rv34_decode_macroblock(RV34DecContext *r, int8_t *intra_types)
 
     luma_dc_quant = r->block_type == RV34_MB_P_MIX16x16 ? r->luma_dc_quant_p[s->qscale] : r->luma_dc_quant_i[s->qscale];
     if(r->is16){
+        q_dc = rv34_qscale_tab[luma_dc_quant];
+        q_ac = rv34_qscale_tab[s->qscale];
         memset(block16, 0, 64 * sizeof(*block16));
-        rv34_decode_block(block16, gb, r->cur_vlcs, 3, 0);
-        rv34_dequant4x4_16x16(block16, rv34_qscale_tab[luma_dc_quant],rv34_qscale_tab[s->qscale]);
+        rv34_decode_block(block16, gb, r->cur_vlcs, 3, 0, q_dc, q_dc, q_ac);
         r->rdsp.rv34_inv_transform_tab[1](block16);
     }
 
+    q_ac = rv34_qscale_tab[s->qscale];
     for(i = 0; i < 16; i++, cbp >>= 1){
         if(!r->is16 && !(cbp & 1)) continue;
         blknum = ((i & 2) >> 1) + ((i & 8) >> 2);
         blkoff = ((i & 1) << 2) + ((i & 4) << 3);
         if(cbp & 1)
-            rv34_decode_block(s->block[blknum] + blkoff, gb, r->cur_vlcs, r->luma_vlc, 0);
-        r->rdsp.rv34_dequant4x4(s->block[blknum] + blkoff, rv34_qscale_tab[s->qscale],rv34_qscale_tab[s->qscale]);
+            rv34_decode_block(s->block[blknum] + blkoff, gb,
+                              r->cur_vlcs, r->luma_vlc, 0, q_ac, q_ac, q_ac);
         if(r->is16) //FIXME: optimize
             s->block[blknum][blkoff] = block16[(i & 3) | ((i & 0xC) << 1)];
         r->rdsp.rv34_inv_transform_tab[0](s->block[blknum] + blkoff);
     }
     if(r->block_type == RV34_MB_P_MIX16x16)
         r->cur_vlcs = choose_vlc_set(r->si.quant, r->si.vlc_set, 1);
+    q_dc = rv34_qscale_tab[rv34_chroma_quant[1][s->qscale]];
+    q_ac = rv34_qscale_tab[rv34_chroma_quant[0][s->qscale]];
     for(; i < 24; i++, cbp >>= 1){
         if(!(cbp & 1)) continue;
         blknum = ((i & 4) >> 2) + 4;
         blkoff = ((i & 1) << 2) + ((i & 2) << 4);
-        rv34_decode_block(s->block[blknum] + blkoff, gb, r->cur_vlcs, r->chroma_vlc, 1);
-        r->rdsp.rv34_dequant4x4(s->block[blknum] + blkoff, rv34_qscale_tab[rv34_chroma_quant[1][s->qscale]],rv34_qscale_tab[rv34_chroma_quant[0][s->qscale]]);
+        rv34_decode_block(s->block[blknum] + blkoff, gb, r->cur_vlcs, r->chroma_vlc, 1, q_dc, q_ac, q_ac);
         r->rdsp.rv34_inv_transform_tab[0](s->block[blknum] + blkoff);
     }
     if (IS_INTRA(s->current_picture_ptr->f.mb_type[mb_pos]))
@@ -1177,7 +1202,7 @@ static int check_slice_end(RV34DecContext *r, MpegEncContext *s)
         return 1;
     if(r->s.mb_skip_run > 1)
         return 0;
-    bits = r->bits - get_bits_count(&s->gb);
+    bits = get_bits_left(&s->gb);
     if(bits < 0 || (bits < 8 && !show_bits(&s->gb, bits)))
         return 1;
     return 0;
@@ -1246,6 +1271,7 @@ static int rv34_decode_slice(RV34DecContext *r, int end, const uint8_t* buf, int
             }
         }
         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;
 
@@ -1257,7 +1283,6 @@ static int rv34_decode_slice(RV34DecContext *r, int end, const uint8_t* buf, int
 
     r->si.end = end;
     s->qscale = r->si.quant;
-    r->bits = buf_size*8;
     s->mb_num_left = r->si.end - r->si.start;
     r->s.mb_skip_run = 0;
 
@@ -1291,6 +1316,11 @@ static int rv34_decode_slice(RV34DecContext *r, int end, const uint8_t* buf, int
 
             if(r->loop_filter && s->mb_y >= 2)
                 r->loop_filter(r, s->mb_y - 2);
+
+            if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
+                ff_thread_report_progress(&s->current_picture_ptr->f,
+                                          s->mb_y - 2, 0);
+
         }
         if(s->mb_x == s->resync_mb_x)
             s->first_slice_line=0;
@@ -1356,6 +1386,71 @@ av_cold int ff_rv34_decode_init(AVCodecContext *avctx)
     return 0;
 }
 
+int ff_rv34_decode_init_thread_copy(AVCodecContext *avctx)
+{
+    RV34DecContext *r = avctx->priv_data;
+
+    r->s.avctx = avctx;
+
+    if (avctx->internal->is_copy) {
+        r->cbp_chroma       = av_malloc(r->s.mb_stride * r->s.mb_height *
+                                        sizeof(*r->cbp_chroma));
+        r->cbp_luma         = av_malloc(r->s.mb_stride * r->s.mb_height *
+                                        sizeof(*r->cbp_luma));
+        r->deblock_coefs    = av_malloc(r->s.mb_stride * r->s.mb_height *
+                                        sizeof(*r->deblock_coefs));
+        r->intra_types_hist = av_malloc(r->intra_types_stride * 4 * 2 *
+                                        sizeof(*r->intra_types_hist));
+        r->mb_type          = av_malloc(r->s.mb_stride * r->s.mb_height *
+                                        sizeof(*r->mb_type));
+
+        if (!(r->cbp_chroma       && r->cbp_luma && r->deblock_coefs &&
+              r->intra_types_hist && r->mb_type)) {
+            av_freep(&r->cbp_chroma);
+            av_freep(&r->cbp_luma);
+            av_freep(&r->deblock_coefs);
+            av_freep(&r->intra_types_hist);
+            av_freep(&r->mb_type);
+            r->intra_types = NULL;
+            return AVERROR(ENOMEM);
+        }
+
+        r->intra_types      = r->intra_types_hist + r->intra_types_stride * 4;
+        r->tmp_b_block_base = NULL;
+
+        memset(r->mb_type, 0,  r->s.mb_stride * r->s.mb_height *
+               sizeof(*r->mb_type));
+
+        MPV_common_init(&r->s);
+    }
+    return 0;
+}
+
+int ff_rv34_decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
+{
+    RV34DecContext *r = dst->priv_data, *r1 = src->priv_data;
+    MpegEncContext * const s = &r->s, * const s1 = &r1->s;
+    int err;
+
+    if (dst == src || !s1->context_initialized)
+        return 0;
+
+    if ((err = ff_mpeg_update_thread_context(dst, src)))
+        return err;
+
+    r->cur_pts  = r1->cur_pts;
+    r->last_pts = r1->last_pts;
+    r->next_pts = r1->next_pts;
+
+    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;
+}
+
 static int get_slice_offset(AVCodecContext *avctx, const uint8_t *buf, int n)
 {
     if(avctx->slice_count) return avctx->slice_offset[n];
@@ -1457,6 +1552,9 @@ int ff_rv34_decode_frame(AVCodecContext *avctx,
     if(last && s->current_picture_ptr){
         if(r->loop_filter)
             r->loop_filter(r, s->mb_height - 1);
+        if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
+            ff_thread_report_progress(&s->current_picture_ptr->f,
+                                      s->mb_height - 1, 0);
         ff_er_frame_end(s);
         MPV_frame_end(s);
         if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
diff --git a/libavcodec/rv34.h b/libavcodec/rv34.h
index 12607fb..d86b009 100644
--- a/libavcodec/rv34.h
+++ b/libavcodec/rv34.h
@@ -92,7 +92,6 @@ typedef struct RV34DecContext{
     const uint8_t *luma_dc_quant_p;///< luma subblock DC quantizer for interframes
 
     RV34VLC *cur_vlcs;       ///< VLC set used for current frame decoding
-    int bits;                ///< slice size in bits
     H264PredContext h;       ///< functions for 4x4 and 16x16 intra block prediction
     SliceInfo si;            ///< current slice information
 
@@ -134,5 +133,7 @@ int ff_rv34_get_start_offset(GetBitContext *gb, int blocks);
 int ff_rv34_decode_init(AVCodecContext *avctx);
 int ff_rv34_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt);
 int ff_rv34_decode_end(AVCodecContext *avctx);
+int ff_rv34_decode_init_thread_copy(AVCodecContext *avctx);
+int ff_rv34_decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src);
 
 #endif /* AVCODEC_RV34_H */
diff --git a/libavcodec/rv34data.h b/libavcodec/rv34data.h
index f8f941d..fa41a88 100644
--- a/libavcodec/rv34data.h
+++ b/libavcodec/rv34data.h
@@ -101,16 +101,6 @@ static const uint16_t rv34_qscale_tab[32] = {
 };
 
 /**
- * 4x4 dezigzag pattern
- */
-static const uint8_t rv34_dezigzag[16] = {
-  0,  1,  8, 16,
-  9,  2,  3, 10,
- 17, 24, 25, 18,
- 11, 19, 26, 27
-};
-
-/**
  * tables used to translate a quantizer value into a VLC set for decoding
  * The first table is used for intraframes.
  */
diff --git a/libavcodec/rv34dsp.c b/libavcodec/rv34dsp.c
index 974bf9e..1f4cea8 100644
--- a/libavcodec/rv34dsp.c
+++ b/libavcodec/rv34dsp.c
@@ -100,26 +100,10 @@ static void rv34_inv_transform_noround_c(DCTELEM *block){
 /** @} */ // transform
 
 
-/**
- * Dequantize ordinary 4x4 block.
- */
-void ff_rv34_dequant4x4_neon(DCTELEM *block, int Qdc, int Q);
-static void rv34_dequant4x4_c(DCTELEM *block, int Qdc, int Q)
-{
-    int i, j;
-
-    block[0] = (block[0] * Qdc + 8) >> 4;
-    for (i = 0; i < 4; i++)
-        for (j = !i; j < 4; j++)
-            block[j + i*8] = (block[j + i*8] * Q + 8) >> 4;
-}
-
 av_cold void ff_rv34dsp_init(RV34DSPContext *c, DSPContext* dsp) {
     c->rv34_inv_transform_tab[0] = rv34_inv_transform_c;
     c->rv34_inv_transform_tab[1] = rv34_inv_transform_noround_c;
 
-    c->rv34_dequant4x4 = rv34_dequant4x4_c;
-
     if (HAVE_NEON)
         ff_rv34dsp_init_neon(c, dsp);
 }
diff --git a/libavcodec/rv34dsp.h b/libavcodec/rv34dsp.h
index 01352ea..f2bc20e 100644
--- a/libavcodec/rv34dsp.h
+++ b/libavcodec/rv34dsp.h
@@ -56,7 +56,6 @@ typedef struct RV34DSPContext {
     h264_chroma_mc_func avg_chroma_pixels_tab[3];
     rv40_weight_func rv40_weight_pixels_tab[2];
     rv34_inv_transform_func rv34_inv_transform_tab[2];
-    void (*rv34_dequant4x4)(DCTELEM *block, int Qdc, int Q);
     rv40_weak_loop_filter_func rv40_weak_loop_filter[2];
     rv40_strong_loop_filter_func rv40_strong_loop_filter[2];
     rv40_loop_filter_strength_func rv40_loop_filter_strength[2];
diff --git a/libavcodec/rv40.c b/libavcodec/rv40.c
index bde63e1..c55a07a 100644
--- a/libavcodec/rv40.c
+++ b/libavcodec/rv40.c
@@ -563,8 +563,10 @@ AVCodec ff_rv40_decoder = {
     .init           = rv40_decode_init,
     .close          = ff_rv34_decode_end,
     .decode         = ff_rv34_decode_frame,
-    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
+    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS,
     .flush          = ff_mpeg_flush,
     .long_name      = NULL_IF_CONFIG_SMALL("RealVideo 4.0"),
     .pix_fmts       = ff_pixfmt_list_420,
+    .init_thread_copy      = ONLY_IF_THREADS_ENABLED(ff_rv34_decode_init_thread_copy),
+    .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_rv34_decode_update_thread_context),
 };
diff --git a/libavcodec/snow.c b/libavcodec/snow.c
index 447289a..905e02a 100644
--- a/libavcodec/snow.c
+++ b/libavcodec/snow.c
@@ -516,9 +516,9 @@ static void halfpel_interpol(SnowContext *s, uint8_t *halfpel[4][4], AVFrame *fr
         int ls= frame->linesize[p];
         uint8_t *src= frame->data[p];
 
-        halfpel[1][p]= (uint8_t*)av_malloc(ls * (h+2*EDGE_WIDTH)) + EDGE_WIDTH*(1+ls);
-        halfpel[2][p]= (uint8_t*)av_malloc(ls * (h+2*EDGE_WIDTH)) + EDGE_WIDTH*(1+ls);
-        halfpel[3][p]= (uint8_t*)av_malloc(ls * (h+2*EDGE_WIDTH)) + EDGE_WIDTH*(1+ls);
+        halfpel[1][p] = (uint8_t*) av_malloc(ls * (h + 2 * EDGE_WIDTH)) + EDGE_WIDTH * (1 + ls);
+        halfpel[2][p] = (uint8_t*) av_malloc(ls * (h + 2 * EDGE_WIDTH)) + EDGE_WIDTH * (1 + ls);
+        halfpel[3][p] = (uint8_t*) av_malloc(ls * (h + 2 * EDGE_WIDTH)) + EDGE_WIDTH * (1 + ls);
 
         halfpel[0][p]= src;
         for(y=0; y<h; y++){
diff --git a/libavcodec/truemotion2.c b/libavcodec/truemotion2.c
index 8d72bb6..4045342 100644
--- a/libavcodec/truemotion2.c
+++ b/libavcodec/truemotion2.c
@@ -272,6 +272,8 @@ static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id, i
             len = AV_RB32(buf); buf += 4; cur += 4;
         }
         if(len > 0) {
+            if (skip <= cur)
+                return -1;
             init_get_bits(&ctx->gb, buf, (skip - cur) * 8);
             if(tm2_read_deltas(ctx, stream_id) == -1)
                 return -1;
@@ -286,6 +288,8 @@ static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id, i
     buf += 4; cur += 4;
     buf += 4; cur += 4; /* unused by decoder */
 
+    if (skip <= cur)
+        return -1;
     init_get_bits(&ctx->gb, buf, (skip - cur) * 8);
     if(tm2_build_huff_table(ctx, &codes) == -1)
         return -1;
@@ -303,6 +307,8 @@ static int tm2_read_stream(TM2Context *ctx, const uint8_t *buf, int stream_id, i
     ctx->tok_lens[stream_id] = toks;
     len = AV_RB32(buf); buf += 4; cur += 4;
     if(len > 0) {
+        if (skip <= cur)
+            return -1;
         init_get_bits(&ctx->gb, buf, (skip - cur) * 8);
         for(i = 0; i < toks; i++) {
             if (get_bits_left(&ctx->gb) <= 0) {
diff --git a/libavcodec/tscc.c b/libavcodec/tscc.c
index 90d203d..ccf1048 100644
--- a/libavcodec/tscc.c
+++ b/libavcodec/tscc.c
@@ -88,7 +88,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
         return -1;
     }
 
-    zret = inflateReset(&(c->zstream));
+    zret = inflateReset(&c->zstream);
     if (zret != Z_OK) {
         av_log(avctx, AV_LOG_ERROR, "Inflate reset error: %d\n", zret);
         return -1;
@@ -97,7 +97,7 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
     c->zstream.avail_in = len;
     c->zstream.next_out = c->decomp_buf;
     c->zstream.avail_out = c->decomp_size;
-    zret = inflate(&(c->zstream), Z_FINISH);
+    zret = inflate(&c->zstream, Z_FINISH);
     // Z_DATA_ERROR means empty picture
     if ((zret != Z_OK) && (zret != Z_STREAM_END) && (zret != Z_DATA_ERROR)) {
         av_log(avctx, AV_LOG_ERROR, "Inflate error: %d\n", zret);
@@ -143,7 +143,7 @@ static av_cold int decode_init(AVCodecContext *avctx)
     c->height = avctx->height;
 
     // Needed if zlib unused or init aborted before inflateInit
-    memset(&(c->zstream), 0, sizeof(z_stream));
+    memset(&c->zstream, 0, sizeof(z_stream));
     switch(avctx->bits_per_coded_sample){
     case  8: avctx->pix_fmt = PIX_FMT_PAL8; break;
     case 16: avctx->pix_fmt = PIX_FMT_RGB555; break;
@@ -169,7 +169,7 @@ static av_cold int decode_init(AVCodecContext *avctx)
     c->zstream.zalloc = Z_NULL;
     c->zstream.zfree = Z_NULL;
     c->zstream.opaque = Z_NULL;
-    zret = inflateInit(&(c->zstream));
+    zret = inflateInit(&c->zstream);
     if (zret != Z_OK) {
         av_log(avctx, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
         return 1;
@@ -193,7 +193,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
 
     if (c->pic.data[0])
         avctx->release_buffer(avctx, &c->pic);
-    inflateEnd(&(c->zstream));
+    inflateEnd(&c->zstream);
 
     return 0;
 }
diff --git a/libavcodec/tta.c b/libavcodec/tta.c
index 7ec5435..bc83bfd 100644
--- a/libavcodec/tta.c
+++ b/libavcodec/tta.c
@@ -314,7 +314,7 @@ static int tta_decode_frame(AVCodecContext *avctx, void *data,
 
     // decode directly to output buffer for 24-bit sample format
     if (s->bps == 3)
-        s->decode_buffer = data;
+        s->decode_buffer = s->frame.data[0];
 
     // init per channel states
     for (i = 0; i < s->channels; i++) {
diff --git a/libavcodec/ulti.c b/libavcodec/ulti.c
index 52092b5..62bab3c 100644
--- a/libavcodec/ulti.c
+++ b/libavcodec/ulti.c
@@ -38,16 +38,9 @@ typedef struct UltimotionDecodeContext {
     int width, height, blocks;
     AVFrame frame;
     const uint8_t *ulti_codebook;
+    GetByteContext gb;
 } UltimotionDecodeContext;
 
-#define CHECK_OVERREAD_SIZE(size) \
-    do { \
-        if (buf_end - buf < (size)) { \
-            av_log(avctx, AV_LOG_ERROR, "Insufficient data\n"); \
-            return AVERROR_INVALIDDATA; \
-        } \
-    } while(0)
-
 static av_cold int ulti_decode_init(AVCodecContext *avctx)
 {
     UltimotionDecodeContext *s = avctx->priv_data;
@@ -231,7 +224,6 @@ static int ulti_decode_frame(AVCodecContext *avctx,
     int i;
     int skip;
     int tmp;
-    const uint8_t *buf_end = buf + buf_size;
 
     s->frame.reference = 1;
     s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
@@ -240,18 +232,20 @@ static int ulti_decode_frame(AVCodecContext *avctx,
         return -1;
     }
 
+    bytestream2_init(&s->gb, buf, buf_size);
+
     while(!done) {
         int idx;
         if(blocks >= s->blocks || y >= s->height)
             break;//all blocks decoded
 
-        CHECK_OVERREAD_SIZE(1);
-        idx = *buf++;
+        if (bytestream2_get_bytes_left(&s->gb) < 1)
+            goto err;
+        idx = bytestream2_get_byteu(&s->gb);
         if((idx & 0xF8) == 0x70) {
             switch(idx) {
             case 0x70: //change modifier
-                CHECK_OVERREAD_SIZE(1);
-                modifier = *buf++;
+                modifier = bytestream2_get_byte(&s->gb);
                 if(modifier>1)
                     av_log(avctx, AV_LOG_INFO, "warning: modifier must be 0 or 1, got %i\n", modifier);
                 break;
@@ -265,8 +259,7 @@ static int ulti_decode_frame(AVCodecContext *avctx,
                 done = 1;
                 break;
             case 0x74: //skip some blocks
-                CHECK_OVERREAD_SIZE(1);
-                skip = *buf++;
+                skip = bytestream2_get_byte(&s->gb);
                 if ((blocks + skip) >= s->blocks)
                     break;
                 blocks += skip;
@@ -293,8 +286,7 @@ static int ulti_decode_frame(AVCodecContext *avctx,
             } else {
                 cf = 0;
                 if (idx) {
-                    CHECK_OVERREAD_SIZE(1);
-                    chroma = *buf++;
+                    chroma = bytestream2_get_byte(&s->gb);
                 }
             }
             for (i = 0; i < 4; i++) { // for every subblock
@@ -302,15 +294,13 @@ static int ulti_decode_frame(AVCodecContext *avctx,
                 if(!code) //skip subblock
                     continue;
                 if(cf) {
-                    CHECK_OVERREAD_SIZE(1);
-                    chroma = *buf++;
+                    chroma = bytestream2_get_byte(&s->gb);
                 }
                 tx = x + block_coords[i * 2];
                 ty = y + block_coords[(i * 2) + 1];
                 switch(code) {
                 case 1:
-                    CHECK_OVERREAD_SIZE(1);
-                    tmp = *buf++;
+                    tmp = bytestream2_get_byte(&s->gb);
 
                     angle = angle_by_index[(tmp >> 6) & 0x3];
 
@@ -330,8 +320,7 @@ static int ulti_decode_frame(AVCodecContext *avctx,
 
                 case 2:
                     if (modifier) { // unpack four luma samples
-                        CHECK_OVERREAD_SIZE(3);
-                        tmp = bytestream_get_be24(&buf);
+                        tmp = bytestream2_get_be24(&s->gb);
 
                         Y[0] = (tmp >> 18) & 0x3F;
                         Y[1] = (tmp >> 12) & 0x3F;
@@ -339,8 +328,7 @@ static int ulti_decode_frame(AVCodecContext *avctx,
                         Y[3] = tmp & 0x3F;
                         angle = 16;
                     } else { // retrieve luma samples from codebook
-                        CHECK_OVERREAD_SIZE(2);
-                        tmp = bytestream_get_be16(&buf);
+                        tmp = bytestream2_get_be16(&s->gb);
 
                         angle = (tmp >> 12) & 0xF;
                         tmp &= 0xFFF;
@@ -356,27 +344,27 @@ static int ulti_decode_frame(AVCodecContext *avctx,
                     if (modifier) { // all 16 luma samples
                         uint8_t Luma[16];
 
-                        CHECK_OVERREAD_SIZE(12);
-
-                        tmp = bytestream_get_be24(&buf);
+                        if (bytestream2_get_bytes_left(&s->gb) < 12)
+                            goto err;
+                        tmp = bytestream2_get_be24u(&s->gb);
                         Luma[0] = (tmp >> 18) & 0x3F;
                         Luma[1] = (tmp >> 12) & 0x3F;
                         Luma[2] = (tmp >> 6) & 0x3F;
                         Luma[3] = tmp & 0x3F;
 
-                        tmp = bytestream_get_be24(&buf);
+                        tmp = bytestream2_get_be24u(&s->gb);
                         Luma[4] = (tmp >> 18) & 0x3F;
                         Luma[5] = (tmp >> 12) & 0x3F;
                         Luma[6] = (tmp >> 6) & 0x3F;
                         Luma[7] = tmp & 0x3F;
 
-                        tmp = bytestream_get_be24(&buf);
+                        tmp = bytestream2_get_be24u(&s->gb);
                         Luma[8] = (tmp >> 18) & 0x3F;
                         Luma[9] = (tmp >> 12) & 0x3F;
                         Luma[10] = (tmp >> 6) & 0x3F;
                         Luma[11] = tmp & 0x3F;
 
-                        tmp = bytestream_get_be24(&buf);
+                        tmp = bytestream2_get_be24u(&s->gb);
                         Luma[12] = (tmp >> 18) & 0x3F;
                         Luma[13] = (tmp >> 12) & 0x3F;
                         Luma[14] = (tmp >> 6) & 0x3F;
@@ -384,22 +372,23 @@ static int ulti_decode_frame(AVCodecContext *avctx,
 
                         ulti_convert_yuv(&s->frame, tx, ty, Luma, chroma);
                     } else {
-                        CHECK_OVERREAD_SIZE(4);
-                        tmp = *buf++;
+                        if (bytestream2_get_bytes_left(&s->gb) < 4)
+                            goto err;
+                        tmp = bytestream2_get_byteu(&s->gb);
                         if(tmp & 0x80) {
                             angle = (tmp >> 4) & 0x7;
-                            tmp = (tmp << 8) + *buf++;
+                            tmp = (tmp << 8) + bytestream2_get_byteu(&s->gb);
                             Y[0] = (tmp >> 6) & 0x3F;
                             Y[1] = tmp & 0x3F;
-                            Y[2] = (*buf++) & 0x3F;
-                            Y[3] = (*buf++) & 0x3F;
+                            Y[2] = bytestream2_get_byteu(&s->gb) & 0x3F;
+                            Y[3] = bytestream2_get_byteu(&s->gb) & 0x3F;
                             ulti_grad(&s->frame, tx, ty, Y, chroma, angle); //draw block
                         } else { // some patterns
                             int f0, f1;
-                            f0 = *buf++;
+                            f0 = bytestream2_get_byteu(&s->gb);
                             f1 = tmp;
-                            Y[0] = (*buf++) & 0x3F;
-                            Y[1] = (*buf++) & 0x3F;
+                            Y[0] = bytestream2_get_byteu(&s->gb) & 0x3F;
+                            Y[1] = bytestream2_get_byteu(&s->gb) & 0x3F;
                             ulti_pattern(&s->frame, tx, ty, f1, f0, Y[0], Y[1], chroma);
                         }
                     }
@@ -421,6 +410,11 @@ static int ulti_decode_frame(AVCodecContext *avctx,
     *(AVFrame*)data= s->frame;
 
     return buf_size;
+
+err:
+    av_log(avctx, AV_LOG_ERROR,
+           "Insufficient data\n");
+    return AVERROR_INVALIDDATA;
 }
 
 AVCodec ff_ulti_decoder = {
diff --git a/libavcodec/utils.c b/libavcodec/utils.c
index a88d1a7..2bc1dcf 100644
--- a/libavcodec/utils.c
+++ b/libavcodec/utils.c
@@ -710,6 +710,8 @@ int attribute_align_arg avcodec_open2(AVCodecContext *avctx, AVCodec *codec, AVD
             goto free_and_end;
         }
     }
+    if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))
+        avctx->thread_count = 1;
 
     if (avctx->codec->max_lowres < avctx->lowres) {
         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
@@ -840,6 +842,48 @@ int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
     return ret;
 }
 
+static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
+{
+    int size = 0;
+    const uint8_t *data;
+    uint32_t flags;
+
+    if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
+        return;
+
+    data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
+    if (!data || size < 4)
+        return;
+    flags = bytestream_get_le32(&data);
+    size -= 4;
+    if (size < 4) /* Required for any of the changes */
+        return;
+    if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
+        avctx->channels = bytestream_get_le32(&data);
+        size -= 4;
+    }
+    if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
+        if (size < 8)
+            return;
+        avctx->channel_layout = bytestream_get_le64(&data);
+        size -= 8;
+    }
+    if (size < 4)
+        return;
+    if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
+        avctx->sample_rate = bytestream_get_le32(&data);
+        size -= 4;
+    }
+    if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
+        if (size < 8)
+            return;
+        avctx->width  = bytestream_get_le32(&data);
+        avctx->height = bytestream_get_le32(&data);
+        avcodec_set_dimensions(avctx, avctx->width, avctx->height);
+        size -= 8;
+    }
+}
+
 int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
                          int *got_picture_ptr,
                          AVPacket *avpkt)
@@ -851,6 +895,7 @@ int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *pi
         return -1;
 
     avctx->pkt = avpkt;
+    apply_param_change(avctx, avpkt);
 
     if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
         if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)
@@ -921,47 +966,6 @@ int attribute_align_arg avcodec_decode_audio3(AVCodecContext *avctx, int16_t *sa
 }
 #endif
 
-static void apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
-{
-    int size = 0;
-    const uint8_t *data;
-    uint32_t flags;
-
-    if (!(avctx->codec->capabilities & CODEC_CAP_PARAM_CHANGE))
-        return;
-
-    data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
-    if (!data || size < 4)
-        return;
-    flags = bytestream_get_le32(&data);
-    size -= 4;
-    if (size < 4) /* Required for any of the changes */
-        return;
-    if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
-        avctx->channels = bytestream_get_le32(&data);
-        size -= 4;
-    }
-    if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
-        if (size < 8)
-            return;
-        avctx->channel_layout = bytestream_get_le64(&data);
-        size -= 8;
-    }
-    if (size < 4)
-        return;
-    if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
-        avctx->sample_rate = bytestream_get_le32(&data);
-        size -= 4;
-    }
-    if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
-        if (size < 8)
-            return;
-        avctx->width  = bytestream_get_le32(&data);
-        avctx->height = bytestream_get_le32(&data);
-        size -= 8;
-    }
-}
-
 int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
                                               AVFrame *frame,
                                               int *got_frame_ptr,
diff --git a/libavcodec/utvideo.c b/libavcodec/utvideo.c
index 4c3b2a1..89854c2 100644
--- a/libavcodec/utvideo.c
+++ b/libavcodec/utvideo.c
@@ -31,6 +31,7 @@
 #include "bytestream.h"
 #include "get_bits.h"
 #include "dsputil.h"
+#include "thread.h"
 
 enum {
     PRED_NONE = 0,
@@ -282,6 +283,77 @@ static void restore_median(uint8_t *src, int step, int stride,
     }
 }
 
+/* UtVideo interlaced mode treats every two lines as a single one,
+ * so restoring function should take care of possible padding between
+ * two parts of the same "line".
+ */
+static void restore_median_il(uint8_t *src, int step, int stride,
+                              int width, int height, int slices, int rmode)
+{
+    int i, j, slice;
+    int A, B, C;
+    uint8_t *bsrc;
+    int slice_start, slice_height;
+    const int cmask = ~(rmode ? 3 : 1);
+    const int stride2 = stride << 1;
+
+    for (slice = 0; slice < slices; slice++) {
+        slice_start    = ((slice * height) / slices) & cmask;
+        slice_height   = ((((slice + 1) * height) / slices) & cmask) - slice_start;
+        slice_height >>= 1;
+
+        bsrc = src + slice_start * stride;
+
+        // first line - left neighbour prediction
+        bsrc[0] += 0x80;
+        A = bsrc[0];
+        for (i = step; i < width * step; i += step) {
+            bsrc[i] += A;
+            A = bsrc[i];
+        }
+        for (i = 0; i < width * step; i += step) {
+            bsrc[stride + i] += A;
+            A = bsrc[stride + i];
+        }
+        bsrc += stride2;
+        if (slice_height == 1)
+            continue;
+        // second line - first element has top predition, the rest uses median
+        C = bsrc[-stride2];
+        bsrc[0] += C;
+        A = bsrc[0];
+        for (i = step; i < width * step; i += step) {
+            B = bsrc[i - stride2];
+            bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));
+            C = B;
+            A = bsrc[i];
+        }
+        for (i = 0; i < width * step; i += step) {
+            B = bsrc[i - stride];
+            bsrc[stride + i] += mid_pred(A, B, (uint8_t)(A + B - C));
+            C = B;
+            A = bsrc[stride + i];
+        }
+        bsrc += stride2;
+        // the rest of lines use continuous median prediction
+        for (j = 2; j < slice_height; j++) {
+            for (i = 0; i < width * step; i += step) {
+                B = bsrc[i - stride2];
+                bsrc[i] += mid_pred(A, B, (uint8_t)(A + B - C));
+                C = B;
+                A = bsrc[i];
+            }
+            for (i = 0; i < width * step; i += step) {
+                B = bsrc[i - stride];
+                bsrc[i + stride] += mid_pred(A, B, (uint8_t)(A + B - C));
+                C = B;
+                A = bsrc[i + stride];
+            }
+            bsrc += stride2;
+        }
+    }
+}
+
 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
 {
     const uint8_t *buf = avpkt->data;
@@ -295,15 +367,17 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
     int ret;
 
     if (c->pic.data[0])
-        avctx->release_buffer(avctx, &c->pic);
+        ff_thread_release_buffer(avctx, &c->pic);
 
     c->pic.reference = 1;
     c->pic.buffer_hints = FF_BUFFER_HINTS_VALID;
-    if ((ret = avctx->get_buffer(avctx, &c->pic)) < 0) {
+    if ((ret = ff_thread_get_buffer(avctx, &c->pic)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
         return ret;
     }
 
+    ff_thread_finish_setup(avctx);
+
     /* parse plane structure to retrieve frame flags and validate slice offsets */
     ptr = buf;
     for (i = 0; i < c->planes; i++) {
@@ -381,10 +455,18 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
                                c->frame_pred == PRED_LEFT);
             if (ret)
                 return ret;
-            if (c->frame_pred == PRED_MEDIAN)
-                restore_median(c->pic.data[i], 1, c->pic.linesize[i],
-                               avctx->width >> !!i, avctx->height >> !!i,
-                               c->slices, !i);
+            if (c->frame_pred == PRED_MEDIAN) {
+                if (!c->interlaced) {
+                    restore_median(c->pic.data[i], 1, c->pic.linesize[i],
+                                   avctx->width >> !!i, avctx->height >> !!i,
+                                   c->slices, !i);
+                } else {
+                    restore_median_il(c->pic.data[i], 1, c->pic.linesize[i],
+                                      avctx->width  >> !!i,
+                                      avctx->height >> !!i,
+                                      c->slices, !i);
+                }
+            }
         }
         break;
     case PIX_FMT_YUV422P:
@@ -395,9 +477,17 @@ static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPac
                                c->frame_pred == PRED_LEFT);
             if (ret)
                 return ret;
-            if (c->frame_pred == PRED_MEDIAN)
-                restore_median(c->pic.data[i], 1, c->pic.linesize[i],
-                               avctx->width >> !!i, avctx->height, c->slices, 0);
+            if (c->frame_pred == PRED_MEDIAN) {
+                if (!c->interlaced) {
+                    restore_median(c->pic.data[i], 1, c->pic.linesize[i],
+                                   avctx->width >> !!i, avctx->height,
+                                   c->slices, 0);
+                } else {
+                    restore_median_il(c->pic.data[i], 1, c->pic.linesize[i],
+                                      avctx->width >> !!i, avctx->height,
+                                      c->slices, 0);
+                }
+            }
         }
         break;
     }
@@ -470,7 +560,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
     UtvideoContext * const c = avctx->priv_data;
 
     if (c->pic.data[0])
-        avctx->release_buffer(avctx, &c->pic);
+        ff_thread_release_buffer(avctx, &c->pic);
 
     av_freep(&c->slice_bits);
 
@@ -485,7 +575,7 @@ AVCodec ff_utvideo_decoder = {
     .init           = decode_init,
     .close          = decode_end,
     .decode         = decode_frame,
-    .capabilities   = CODEC_CAP_DR1,
+    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
     .long_name      = NULL_IF_CONFIG_SMALL("Ut Video"),
 };
 
diff --git a/libavcodec/v410enc.c b/libavcodec/v410enc.c
index 95b36c1..11c6abc 100644
--- a/libavcodec/v410enc.c
+++ b/libavcodec/v410enc.c
@@ -67,7 +67,7 @@ static int v410_encode_frame(AVCodecContext *avctx, uint8_t *buf,
         for (j = 0; j < avctx->width; j++) {
             val  = u[j] << 2;
             val |= y[j] << 12;
-            val |= v[j] << 22;
+            val |= (uint32_t) v[j] << 22;
             AV_WL32(dst, val);
             dst += 4;
             output_size += 4;
diff --git a/libavcodec/vaapi_mpeg2.c b/libavcodec/vaapi_mpeg2.c
index 6b08ed2..95107c8 100644
--- a/libavcodec/vaapi_mpeg2.c
+++ b/libavcodec/vaapi_mpeg2.c
@@ -26,8 +26,8 @@
 /** Reconstruct bitstream f_code */
 static inline int mpeg2_get_f_code(MpegEncContext *s)
 {
-    return ((s->mpeg_f_code[0][0] << 12) | (s->mpeg_f_code[0][1] << 8) |
-            (s->mpeg_f_code[1][0] <<  4) |  s->mpeg_f_code[1][1]);
+    return (s->mpeg_f_code[0][0] << 12) | (s->mpeg_f_code[0][1] << 8) |
+           (s->mpeg_f_code[1][0] <<  4) |  s->mpeg_f_code[1][1];
 }
 
 /** Determine frame start: first field for field picture or frame picture */
diff --git a/libavcodec/vaapi_vc1.c b/libavcodec/vaapi_vc1.c
index d519987..df3f77e 100644
--- a/libavcodec/vaapi_vc1.c
+++ b/libavcodec/vaapi_vc1.c
@@ -42,10 +42,10 @@ static inline int vc1_has_MVTYPEMB_bitplane(VC1Context *v)
 {
     if (v->mv_type_is_raw)
         return 0;
-    return (v->s.pict_type == AV_PICTURE_TYPE_P &&
-            (v->mv_mode == MV_PMODE_MIXED_MV ||
-             (v->mv_mode == MV_PMODE_INTENSITY_COMP &&
-              v->mv_mode2 == MV_PMODE_MIXED_MV)));
+    return v->s.pict_type == AV_PICTURE_TYPE_P &&
+           (v->mv_mode == MV_PMODE_MIXED_MV ||
+            (v->mv_mode == MV_PMODE_INTENSITY_COMP &&
+             v->mv_mode2 == MV_PMODE_MIXED_MV));
 }
 
 /** Check whether the SKIPMB bitplane is present */
@@ -53,8 +53,8 @@ static inline int vc1_has_SKIPMB_bitplane(VC1Context *v)
 {
     if (v->skip_is_raw)
         return 0;
-    return (v->s.pict_type == AV_PICTURE_TYPE_P ||
-            (v->s.pict_type == AV_PICTURE_TYPE_B && !v->bi_type));
+    return v->s.pict_type == AV_PICTURE_TYPE_P ||
+           (v->s.pict_type == AV_PICTURE_TYPE_B && !v->bi_type);
 }
 
 /** Check whether the DIRECTMB bitplane is present */
@@ -70,9 +70,9 @@ static inline int vc1_has_ACPRED_bitplane(VC1Context *v)
 {
     if (v->acpred_is_raw)
         return 0;
-    return (v->profile == PROFILE_ADVANCED &&
-            (v->s.pict_type == AV_PICTURE_TYPE_I ||
-             (v->s.pict_type == AV_PICTURE_TYPE_B && v->bi_type)));
+    return v->profile == PROFILE_ADVANCED &&
+           (v->s.pict_type == AV_PICTURE_TYPE_I ||
+            (v->s.pict_type == AV_PICTURE_TYPE_B && v->bi_type));
 }
 
 /** Check whether the OVERFLAGS bitplane is present */
@@ -80,11 +80,11 @@ static inline int vc1_has_OVERFLAGS_bitplane(VC1Context *v)
 {
     if (v->overflg_is_raw)
         return 0;
-    return (v->profile == PROFILE_ADVANCED &&
-            (v->s.pict_type == AV_PICTURE_TYPE_I ||
-             (v->s.pict_type == AV_PICTURE_TYPE_B && v->bi_type)) &&
-            (v->overlap && v->pq <= 8) &&
-            v->condover == CONDOVER_SELECT);
+    return v->profile == PROFILE_ADVANCED &&
+           (v->s.pict_type == AV_PICTURE_TYPE_I ||
+            (v->s.pict_type == AV_PICTURE_TYPE_B && v->bi_type)) &&
+           (v->overlap && v->pq <= 8) &&
+           v->condover == CONDOVER_SELECT;
 }
 
 /** Reconstruct bitstream PTYPE (7.1.1.4, index into Table-35) */
diff --git a/libavcodec/vc1_parser.c b/libavcodec/vc1_parser.c
index e6243d9..0cc5ea0 100644
--- a/libavcodec/vc1_parser.c
+++ b/libavcodec/vc1_parser.c
@@ -184,9 +184,17 @@ static int vc1_split(AVCodecContext *avctx,
     return 0;
 }
 
+static int vc1_parse_init(AVCodecParserContext *s)
+{
+    VC1ParseContext *vpc = s->priv_data;
+    vpc->v.s.slice_context_count = 1;
+    return 0;
+}
+
 AVCodecParser ff_vc1_parser = {
     .codec_ids      = { CODEC_ID_VC1 },
     .priv_data_size = sizeof(VC1ParseContext),
+    .parser_init    = vc1_parse_init,
     .parser_parse   = vc1_parse,
     .parser_close   = ff_parse1_close,
     .split          = vc1_split,
diff --git a/libavcodec/vc1dec.c b/libavcodec/vc1dec.c
index 3cb7661..fa95273 100644
--- a/libavcodec/vc1dec.c
+++ b/libavcodec/vc1dec.c
@@ -568,6 +568,7 @@ static void vc1_mc_1mv(VC1Context *v, int dir)
     }
 
     if (v->rangeredfrm || (v->mv_mode == MV_PMODE_INTENSITY_COMP)
+        || s->h_edge_pos < 22 || v_edge_pos < 22
         || (unsigned)(src_x - s->mspel) > s->h_edge_pos - (mx&3) - 16 - s->mspel * 3
         || (unsigned)(src_y - s->mspel) > v_edge_pos    - (my&3) - 16 - s->mspel * 3) {
         uint8_t *uvbuf = s->edge_emu_buffer + 19 * s->linesize;
@@ -799,6 +800,7 @@ static void vc1_mc_4mv_luma(VC1Context *v, int n, int dir)
     if (fieldmv && (src_y & 1) && src_y < 4)
         src_y--;
     if (v->rangeredfrm || (v->mv_mode == MV_PMODE_INTENSITY_COMP)
+        || s->h_edge_pos < 13 || v_edge_pos < 23
         || (unsigned)(src_x - s->mspel) > s->h_edge_pos - (mx & 3) - 8 - s->mspel * 2
         || (unsigned)(src_y - (s->mspel << fieldmv)) > v_edge_pos - (my & 3) - ((8 + s->mspel * 2) << fieldmv)) {
         srcY -= s->mspel * (1 + (s->linesize << fieldmv));
@@ -998,6 +1000,7 @@ static void vc1_mc_4mv_chroma(VC1Context *v, int dir)
     }
 
     if (v->rangeredfrm || (v->mv_mode == MV_PMODE_INTENSITY_COMP)
+        || s->h_edge_pos < 18 || v_edge_pos < 18
         || (unsigned)uvsrc_x > (s->h_edge_pos >> 1) - 9
         || (unsigned)uvsrc_y > (v_edge_pos    >> 1) - 9) {
         s->dsp.emulated_edge_mc(s->edge_emu_buffer     , srcU, s->uvlinesize,
@@ -1102,6 +1105,7 @@ static void vc1_mc_4mv_chroma4(VC1Context *v)
         if (fieldmv && (uvsrc_y & 1) && uvsrc_y < 2)
             uvsrc_y--;
         if ((v->mv_mode == MV_PMODE_INTENSITY_COMP)
+            || s->h_edge_pos < 10 || v_edge_pos < (5 << fieldmv)
             || (unsigned)uvsrc_x > (s->h_edge_pos >> 1) - 5
             || (unsigned)uvsrc_y > v_edge_pos - (5 << fieldmv)) {
             s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcU, s->uvlinesize,
@@ -2006,7 +2010,7 @@ static void vc1_interp_mc(VC1Context *v)
         srcV = s->edge_emu_buffer + 18 * s->linesize;
     }
 
-    if (v->rangeredfrm
+    if (v->rangeredfrm || s->h_edge_pos < 22 || v_edge_pos < 22
         || (unsigned)(src_x - s->mspel) > s->h_edge_pos - (mx & 3) - 16 - s->mspel * 3
         || (unsigned)(src_y - s->mspel) > v_edge_pos    - (my & 3) - 16 - s->mspel * 3) {
         uint8_t *uvbuf = s->edge_emu_buffer + 19 * s->linesize;
@@ -5338,7 +5342,7 @@ static av_cold int vc1_decode_init(AVCodecContext *avctx)
     if (v->profile == PROFILE_ADVANCED)
         avctx->level = v->level;
 
-    avctx->has_b_frames = !!(avctx->max_b_frames);
+    avctx->has_b_frames = !!avctx->max_b_frames;
 
     s->mb_width  = (avctx->coded_width  + 15) >> 4;
     s->mb_height = (avctx->coded_height + 15) >> 4;
diff --git a/libavcodec/version.h b/libavcodec/version.h
index 9b4f6d7..1317ef0 100644
--- a/libavcodec/version.h
+++ b/libavcodec/version.h
@@ -22,7 +22,7 @@
 
 #define LIBAVCODEC_VERSION_MAJOR 53
 #define LIBAVCODEC_VERSION_MINOR 32
-#define LIBAVCODEC_VERSION_MICRO  0
+#define LIBAVCODEC_VERSION_MICRO  2
 
 #define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
                                                LIBAVCODEC_VERSION_MINOR, \
diff --git a/libavcodec/vorbis.c b/libavcodec/vorbis.c
index 86df288..0b26870 100644
--- a/libavcodec/vorbis.c
+++ b/libavcodec/vorbis.c
@@ -152,7 +152,7 @@ void ff_vorbis_ready_floor1_list(vorbis_floor1_entry * list, int values)
     }
 }
 
-static inline void render_line_unrolled(intptr_t x, intptr_t y, int x1,
+static inline void render_line_unrolled(intptr_t x, uint8_t y, int x1,
                                         intptr_t sy, int ady, int adx,
                                         float *buf)
 {
@@ -175,7 +175,7 @@ static inline void render_line_unrolled(intptr_t x, intptr_t y, int x1,
     }
 }
 
-static void render_line(int x0, int y0, int x1, int y1, float *buf)
+static void render_line(int x0, uint8_t y0, int x1, int y1, float *buf)
 {
     int dy  = y1 - y0;
     int adx = x1 - x0;
@@ -185,10 +185,10 @@ static void render_line(int x0, int y0, int x1, int y1, float *buf)
     if (ady*2 <= adx) { // optimized common case
         render_line_unrolled(x0, y0, x1, sy, ady, adx, buf);
     } else {
-        int base = dy / adx;
-        int x    = x0;
-        int y    = y0;
-        int err  = -adx;
+        int base  = dy / adx;
+        int x     = x0;
+        uint8_t y = y0;
+        int err   = -adx;
         ady -= FFABS(base) * adx;
         while (++x < x1) {
             y += base;
@@ -206,7 +206,8 @@ void ff_vorbis_floor1_render_list(vorbis_floor1_entry * list, int values,
                                   uint16_t *y_list, int *flag,
                                   int multiplier, float *out, int samples)
 {
-    int lx, ly, i;
+    int lx, i;
+    uint8_t ly;
     lx = 0;
     ly = y_list[0] * multiplier;
     for (i = 1; i < values; i++) {
diff --git a/libavcodec/vorbisdec.c b/libavcodec/vorbisdec.c
index 70690dd..bb69fed 100644
--- a/libavcodec/vorbisdec.c
+++ b/libavcodec/vorbisdec.c
@@ -675,7 +675,7 @@ static int vorbis_parse_setup_hdr_residues(vorbis_context *vc)
         res_setup->partition_size = get_bits(gb, 24) + 1;
         /* Validations to prevent a buffer overflow later. */
         if (res_setup->begin>res_setup->end ||
-            res_setup->end > vc->avccontext->channels * vc->blocksize[1] / 2 ||
+            res_setup->end > (res_setup->type == 2 ? vc->avccontext->channels : 1) * vc->blocksize[1] / 2 ||
             (res_setup->end-res_setup->begin) / res_setup->partition_size > V_MAX_PARTITIONS) {
             av_log(vc->avccontext, AV_LOG_ERROR,
                    "partition out of bounds: type, begin, end, size, blocksize: %"PRIu16", %"PRIu32", %"PRIu32", %u, %"PRIu32"\n",
@@ -816,8 +816,7 @@ static void create_map(vorbis_context *vc, unsigned floor_number)
 
         for (idx = 0; idx < n; ++idx) {
             map[idx] = floor(BARK((vf->rate * idx) / (2.0f * n)) *
-                             ((vf->bark_map_size) /
-                              BARK(vf->rate / 2.0f)));
+                             (vf->bark_map_size / BARK(vf->rate / 2.0f)));
             if (vf->bark_map_size-1 < map[idx])
                 map[idx] = vf->bark_map_size - 1;
         }
@@ -975,7 +974,7 @@ static av_cold int vorbis_decode_init(AVCodecContext *avccontext)
     int headers_len    = avccontext->extradata_size;
     uint8_t *header_start[3];
     int header_len[3];
-    GetBitContext *gb = &(vc->gb);
+    GetBitContext *gb = &vc->gb;
     int hdr_type, ret;
 
     vc->avccontext = avccontext;
@@ -1282,6 +1281,7 @@ static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,
                                                            uint8_t *do_not_decode,
                                                            float *vec,
                                                            unsigned vlen,
+                                                           unsigned ch_left,
                                                            int vr_type)
 {
     GetBitContext *gb = &vc->gb;
@@ -1289,6 +1289,7 @@ static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,
     unsigned ptns_to_read = vr->ptns_to_read;
     uint8_t *classifs = vr->classifs;
     unsigned pass, ch_used, i, j, k, l;
+    unsigned max_output = (ch - 1) * vlen;
 
     if (vr_type == 2) {
         for (j = 1; j < ch; ++j)
@@ -1296,8 +1297,15 @@ static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,
         if (do_not_decode[0])
             return 0;
         ch_used = 1;
+        max_output += vr->end / ch;
     } else {
         ch_used = ch;
+        max_output += vr->end;
+    }
+
+    if (max_output > ch_left * vlen) {
+        av_log(vc->avccontext, AV_LOG_ERROR, "Insufficient output buffer\n");
+        return -1;
     }
 
     av_dlog(NULL, " residue type 0/1/2 decode begin, ch: %d  cpc %d  \n", ch, c_p_c);
@@ -1424,14 +1432,15 @@ static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,
 static inline int vorbis_residue_decode(vorbis_context *vc, vorbis_residue *vr,
                                         unsigned ch,
                                         uint8_t *do_not_decode,
-                                        float *vec, unsigned vlen)
+                                        float *vec, unsigned vlen,
+                                        unsigned ch_left)
 {
     if (vr->type == 2)
-        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 2);
+        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, ch_left, 2);
     else if (vr->type == 1)
-        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 1);
+        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, ch_left, 1);
     else if (vr->type == 0)
-        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 0);
+        return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, ch_left, 0);
     else {
         av_log(vc->avccontext, AV_LOG_ERROR, " Invalid residue type while residue decode?! \n");
         return AVERROR_INVALIDDATA;
@@ -1479,6 +1488,8 @@ static int vorbis_parse_audio_packet(vorbis_context *vc)
     uint8_t res_chan[255];
     unsigned res_num = 0;
     int retlen  = 0;
+    unsigned ch_left = vc->audio_channels;
+    unsigned vlen;
 
     if (get_bits1(gb)) {
         av_log(vc->avccontext, AV_LOG_ERROR, "Not a Vorbis I audio packet.\n");
@@ -1498,11 +1509,12 @@ static int vorbis_parse_audio_packet(vorbis_context *vc)
 
     blockflag = vc->modes[mode_number].blockflag;
     blocksize = vc->blocksize[blockflag];
+    vlen = blocksize / 2;
     if (blockflag)
         skip_bits(gb, 2); // previous_window, next_window
 
-    memset(ch_res_ptr,   0, sizeof(float) * vc->audio_channels * blocksize / 2); //FIXME can this be removed ?
-    memset(ch_floor_ptr, 0, sizeof(float) * vc->audio_channels * blocksize / 2); //FIXME can this be removed ?
+    memset(ch_res_ptr,   0, sizeof(float) * vc->audio_channels * vlen); //FIXME can this be removed ?
+    memset(ch_floor_ptr, 0, sizeof(float) * vc->audio_channels * vlen); //FIXME can this be removed ?
 
 // Decode floor
 
@@ -1522,7 +1534,7 @@ static int vorbis_parse_audio_packet(vorbis_context *vc)
             return AVERROR_INVALIDDATA;
         }
         no_residue[i] = ret;
-        ch_floor_ptr += blocksize / 2;
+        ch_floor_ptr += vlen;
     }
 
 // Nonzero vector propagate
@@ -1539,6 +1551,7 @@ static int vorbis_parse_audio_packet(vorbis_context *vc)
     for (i = 0; i < mapping->submaps; ++i) {
         vorbis_residue *residue;
         unsigned ch = 0;
+        int ret;
 
         for (j = 0; j < vc->audio_channels; ++j) {
             if ((mapping->submaps == 1) || (i == mapping->mux[j])) {
@@ -1553,9 +1566,18 @@ static int vorbis_parse_audio_packet(vorbis_context *vc)
             }
         }
         residue = &vc->residues[mapping->submap_residue[i]];
-        vorbis_residue_decode(vc, residue, ch, do_not_decode, ch_res_ptr, blocksize/2);
+        if (ch_left < ch) {
+            av_log(vc->avccontext, AV_LOG_ERROR, "Too many channels in vorbis_floor_decode.\n");
+            return -1;
+        }
+        if (ch) {
+            ret = vorbis_residue_decode(vc, residue, ch, do_not_decode, ch_res_ptr, vlen, ch_left);
+            if (ret < 0)
+                return ret;
+        }
 
-        ch_res_ptr += ch * blocksize / 2;
+        ch_res_ptr += ch * vlen;
+        ch_left -= ch;
     }
 
 // Inverse coupling
@@ -1615,7 +1637,7 @@ static int vorbis_decode_frame(AVCodecContext *avccontext, void *data,
     const uint8_t *buf = avpkt->data;
     int buf_size       = avpkt->size;
     vorbis_context *vc = avccontext->priv_data;
-    GetBitContext *gb = &(vc->gb);
+    GetBitContext *gb = &vc->gb;
     const float *channel_ptrs[255];
     int i, len, ret;
 
diff --git a/libavcodec/vp3.c b/libavcodec/vp3.c
index f44d084..602b5fa 100644
--- a/libavcodec/vp3.c
+++ b/libavcodec/vp3.c
@@ -1378,6 +1378,8 @@ static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
             return i;
         }
     } while (i < 64);
+    // return value is expected to be a valid level
+    i--;
 end:
     // the actual DC+prediction is in the fragment structure
     block[0] = frag->dc * s->qmat[0][inter][plane][0];
diff --git a/libavcodec/vp56.h b/libavcodec/vp56.h
index ceb516d..0607e0d 100644
--- a/libavcodec/vp56.h
+++ b/libavcodec/vp56.h
@@ -30,7 +30,6 @@
 #include "dsputil.h"
 #include "get_bits.h"
 #include "bytestream.h"
-#include "cabac.h"
 #include "vp56dsp.h"
 
 typedef struct vp56_context VP56Context;
diff --git a/libavcodec/wavpack.c b/libavcodec/wavpack.c
index 7d16a9b..6896877 100644
--- a/libavcodec/wavpack.c
+++ b/libavcodec/wavpack.c
@@ -18,20 +18,22 @@
  * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
+
 #define BITSTREAM_READER_LE
+
+#include "libavutil/audioconvert.h"
 #include "avcodec.h"
 #include "get_bits.h"
 #include "unary.h"
-#include "libavutil/audioconvert.h"
 
 /**
  * @file
  * WavPack lossless audio decoder
  */
 
-#define WV_MONO         0x00000004
-#define WV_JOINT_STEREO 0x00000010
-#define WV_FALSE_STEREO 0x40000000
+#define WV_MONO           0x00000004
+#define WV_JOINT_STEREO   0x00000010
+#define WV_FALSE_STEREO   0x40000000
 
 #define WV_HYBRID_MODE    0x00000008
 #define WV_HYBRID_SHAPE   0x00000008
@@ -44,14 +46,14 @@
 #define WV_FLT_ZERO_SENT  0x08
 #define WV_FLT_ZERO_SIGN  0x10
 
-enum WP_ID_Flags{
+enum WP_ID_Flags {
     WP_IDF_MASK   = 0x1F,
     WP_IDF_IGNORE = 0x20,
     WP_IDF_ODD    = 0x40,
     WP_IDF_LONG   = 0x80
 };
 
-enum WP_ID{
+enum WP_ID {
     WP_ID_DUMMY = 0,
     WP_ID_ENCINFO,
     WP_ID_DECTERMS,
@@ -178,7 +180,7 @@ static av_always_inline int wp_exp2(int16_t val)
 {
     int res, neg = 0;
 
-    if(val < 0){
+    if (val < 0) {
         val = -val;
         neg = 1;
     }
@@ -193,13 +195,13 @@ static av_always_inline int wp_log2(int32_t val)
 {
     int bits;
 
-    if(!val)
+    if (!val)
         return 0;
-    if(val == 1)
+    if (val == 1)
         return 256;
     val += val >> 9;
     bits = av_log2(val) + 1;
-    if(bits < 9)
+    if (bits < 9)
         return (bits << 8) + wp_log2_table[(val << (9 - bits)) & 0xFF];
     else
         return (bits << 8) + wp_log2_table[(val >> (bits - 9)) & 0xFF];
@@ -209,33 +211,35 @@ static av_always_inline int wp_log2(int32_t val)
 
 // macros for manipulating median values
 #define GET_MED(n) ((c->median[n] >> 4) + 1)
-#define DEC_MED(n) c->median[n] -= ((c->median[n] + (128>>n) - 2) / (128>>n)) * 2
-#define INC_MED(n) c->median[n] += ((c->median[n] + (128>>n)) / (128>>n)) * 5
+#define DEC_MED(n) c->median[n] -= ((c->median[n] + (128 >> n) - 2) / (128 >> n)) * 2
+#define INC_MED(n) c->median[n] += ((c->median[n] + (128 >> n)    ) / (128 >> n)) * 5
 
 // macros for applying weight
 #define UPDATE_WEIGHT_CLIP(weight, delta, samples, in) \
-        if(samples && in){ \
-            if((samples ^ in) < 0){ \
-                weight -= delta; \
-                if(weight < -1024) weight = -1024; \
-            }else{ \
-                weight += delta; \
-                if(weight > 1024) weight = 1024; \
-            } \
-        }
+    if (samples && in) { \
+        if ((samples ^ in) < 0) { \
+            weight -= delta; \
+            if (weight < -1024) \
+                weight = -1024; \
+        } else { \
+            weight += delta; \
+            if (weight > 1024) \
+                weight = 1024; \
+        } \
+    }
 
 
 static av_always_inline int get_tail(GetBitContext *gb, int k)
 {
     int p, e, res;
 
-    if(k<1)return 0;
+    if (k < 1)
+        return 0;
     p = av_log2(k);
     e = (1 << (p + 1)) - k - 1;
     res = p ? get_bits(gb, p) : 0;
-    if(res >= e){
-        res = (res<<1) - e + get_bits1(gb);
-    }
+    if (res >= e)
+        res = (res << 1) - e + get_bits1(gb);
     return res;
 }
 
@@ -243,37 +247,38 @@ static void update_error_limit(WavpackFrameContext *ctx)
 {
     int i, br[2], sl[2];
 
-    for(i = 0; i <= ctx->stereo_in; i++){
+    for (i = 0; i <= ctx->stereo_in; i++) {
         ctx->ch[i].bitrate_acc += ctx->ch[i].bitrate_delta;
         br[i] = ctx->ch[i].bitrate_acc >> 16;
         sl[i] = LEVEL_DECAY(ctx->ch[i].slow_level);
     }
-    if(ctx->stereo_in && ctx->hybrid_bitrate){
+    if (ctx->stereo_in && ctx->hybrid_bitrate) {
         int balance = (sl[1] - sl[0] + br[1] + 1) >> 1;
-        if(balance > br[0]){
+        if (balance > br[0]) {
             br[1] = br[0] << 1;
             br[0] = 0;
-        }else if(-balance > br[0]){
+        } else if (-balance > br[0]) {
             br[0] <<= 1;
             br[1] = 0;
-        }else{
+        } else {
             br[1] = br[0] + balance;
             br[0] = br[0] - balance;
         }
     }
-    for(i = 0; i <= ctx->stereo_in; i++){
-        if(ctx->hybrid_bitrate){
-            if(sl[i] - br[i] > -0x100)
+    for (i = 0; i <= ctx->stereo_in; i++) {
+        if (ctx->hybrid_bitrate) {
+            if (sl[i] - br[i] > -0x100)
                 ctx->ch[i].error_limit = wp_exp2(sl[i] - br[i] + 0x100);
             else
                 ctx->ch[i].error_limit = 0;
-        }else{
+        } else {
             ctx->ch[i].error_limit = wp_exp2(br[i]);
         }
     }
 }
 
-static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb, int channel, int *last)
+static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb,
+                        int channel, int *last)
 {
     int t, t2;
     int sign, base, add, ret;
@@ -281,25 +286,26 @@ static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb, int channel
 
     *last = 0;
 
-    if((ctx->ch[0].median[0] < 2U) && (ctx->ch[1].median[0] < 2U) && !ctx->zero && !ctx->one){
-        if(ctx->zeroes){
+    if ((ctx->ch[0].median[0] < 2U) && (ctx->ch[1].median[0] < 2U) &&
+        !ctx->zero && !ctx->one) {
+        if (ctx->zeroes) {
             ctx->zeroes--;
-            if(ctx->zeroes){
+            if (ctx->zeroes) {
                 c->slow_level -= LEVEL_DECAY(c->slow_level);
                 return 0;
             }
-        }else{
+        } else {
             t = get_unary_0_33(gb);
-            if(t >= 2){
-                if(get_bits_left(gb) < t-1)
+            if (t >= 2) {
+                if (get_bits_left(gb) < t - 1)
                     goto error;
                 t = get_bits(gb, t - 1) | (1 << (t-1));
-            }else{
-                if(get_bits_left(gb) < 0)
+            } else {
+                if (get_bits_left(gb) < 0)
                     goto error;
             }
             ctx->zeroes = t;
-            if(ctx->zeroes){
+            if (ctx->zeroes) {
                 memset(ctx->ch[0].median, 0, sizeof(ctx->ch[0].median));
                 memset(ctx->ch[1].median, 0, sizeof(ctx->ch[1].median));
                 c->slow_level -= LEVEL_DECAY(c->slow_level);
@@ -308,81 +314,81 @@ static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb, int channel
         }
     }
 
-    if(ctx->zero){
+    if (ctx->zero) {
         t = 0;
         ctx->zero = 0;
-    }else{
+    } else {
         t = get_unary_0_33(gb);
-        if(get_bits_left(gb) < 0)
+        if (get_bits_left(gb) < 0)
             goto error;
-        if(t == 16) {
+        if (t == 16) {
             t2 = get_unary_0_33(gb);
-            if(t2 < 2){
-                if(get_bits_left(gb) < 0)
+            if (t2 < 2) {
+                if (get_bits_left(gb) < 0)
                     goto error;
                 t += t2;
-            }else{
-                if(get_bits_left(gb) < t2 - 1)
+            } else {
+                if (get_bits_left(gb) < t2 - 1)
                     goto error;
                 t += get_bits(gb, t2 - 1) | (1 << (t2 - 1));
             }
         }
 
-        if(ctx->one){
-            ctx->one = t&1;
-            t = (t>>1) + 1;
-        }else{
-            ctx->one = t&1;
+        if (ctx->one) {
+            ctx->one = t & 1;
+            t = (t >> 1) + 1;
+        } else {
+            ctx->one = t & 1;
             t >>= 1;
         }
         ctx->zero = !ctx->one;
     }
 
-    if(ctx->hybrid && !channel)
+    if (ctx->hybrid && !channel)
         update_error_limit(ctx);
 
-    if(!t){
+    if (!t) {
         base = 0;
-        add = GET_MED(0) - 1;
+        add  = GET_MED(0) - 1;
         DEC_MED(0);
-    }else if(t == 1){
+    } else if (t == 1) {
         base = GET_MED(0);
-        add = GET_MED(1) - 1;
+        add  = GET_MED(1) - 1;
         INC_MED(0);
         DEC_MED(1);
-    }else if(t == 2){
+    } else if (t == 2) {
         base = GET_MED(0) + GET_MED(1);
-        add = GET_MED(2) - 1;
+        add  = GET_MED(2) - 1;
         INC_MED(0);
         INC_MED(1);
         DEC_MED(2);
-    }else{
+    } else {
         base = GET_MED(0) + GET_MED(1) + GET_MED(2) * (t - 2);
-        add = GET_MED(2) - 1;
+        add  = GET_MED(2) - 1;
         INC_MED(0);
         INC_MED(1);
         INC_MED(2);
     }
-    if(!c->error_limit){
+    if (!c->error_limit) {
         ret = base + get_tail(gb, add);
         if (get_bits_left(gb) <= 0)
             goto error;
-    }else{
-        int mid = (base*2 + add + 1) >> 1;
-        while(add > c->error_limit){
-            if(get_bits_left(gb) <= 0)
+    } else {
+        int mid = (base * 2 + add + 1) >> 1;
+        while (add > c->error_limit) {
+            if (get_bits_left(gb) <= 0)
                 goto error;
-            if(get_bits1(gb)){
+            if (get_bits1(gb)) {
                 add -= (mid - base);
                 base = mid;
-            }else
+            } else
                 add = mid - base - 1;
-            mid = (base*2 + add + 1) >> 1;
+            mid = (base * 2 + add + 1) >> 1;
         }
         ret = mid;
     }
     sign = get_bits1(gb);
-    if(ctx->hybrid_bitrate)
+    if (ctx->hybrid_bitrate)
         c->slow_level += wp_log2(ret) - LEVEL_DECAY(c->slow_level);
     return sign ? ~ret : ret;
 
@@ -391,23 +397,24 @@ error:
     return 0;
 }
 
-static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc, int S)
+static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc,
+                                       int S)
 {
     int bit;
 
-    if(s->extra_bits){
+    if (s->extra_bits){
         S <<= s->extra_bits;
 
-        if(s->got_extra_bits && get_bits_left(&s->gb_extra_bits) >= s->extra_bits){
+        if (s->got_extra_bits && get_bits_left(&s->gb_extra_bits) >= s->extra_bits) {
             S |= get_bits(&s->gb_extra_bits, s->extra_bits);
-            *crc = *crc * 9 + (S&0xffff) * 3 + ((unsigned)S>>16);
+            *crc = *crc * 9 + (S & 0xffff) * 3 + ((unsigned)S >> 16);
         }
     }
 
     bit = (S & s->and) | s->or;
     bit = (((S + bit) << s->shift) - bit) << s->post_shift;
 
-    if(s->hybrid)
+    if (s->hybrid)
         bit = av_clip(bit, -s->hybrid_maxclip - 1, s->hybrid_maxclip);
 
     return bit;
@@ -423,58 +430,58 @@ static float wv_get_value_float(WavpackFrameContext *s, uint32_t *crc, int S)
     int sign;
     int exp = s->float_max_exp;
 
-    if(s->got_extra_bits){
-        const int max_bits = 1 + 23 + 8 + 1;
+    if (s->got_extra_bits) {
+        const int max_bits  = 1 + 23 + 8 + 1;
         const int left_bits = get_bits_left(&s->gb_extra_bits);
 
-        if(left_bits + 8 * FF_INPUT_BUFFER_PADDING_SIZE < max_bits)
+        if (left_bits + 8 * FF_INPUT_BUFFER_PADDING_SIZE < max_bits)
             return 0.0;
     }
 
-    if(S){
+    if (S) {
         S <<= s->float_shift;
         sign = S < 0;
-        if(sign)
+        if (sign)
             S = -S;
-        if(S >= 0x1000000){
-            if(s->got_extra_bits && get_bits1(&s->gb_extra_bits)){
+        if (S >= 0x1000000) {
+            if (s->got_extra_bits && get_bits1(&s->gb_extra_bits))
                 S = get_bits(&s->gb_extra_bits, 23);
-            }else{
+            else
                 S = 0;
-            }
             exp = 255;
-        }else if(exp){
+        } else if (exp) {
             int shift = 23 - av_log2(S);
             exp = s->float_max_exp;
-            if(exp <= shift){
+            if (exp <= shift)
                 shift = --exp;
-            }
             exp -= shift;
 
-            if(shift){
+            if (shift) {
                 S <<= shift;
-                if((s->float_flag & WV_FLT_SHIFT_ONES) ||
-                   (s->got_extra_bits && (s->float_flag & WV_FLT_SHIFT_SAME) && get_bits1(&s->gb_extra_bits)) ){
+                if ((s->float_flag & WV_FLT_SHIFT_ONES) ||
+                    (s->got_extra_bits && (s->float_flag & WV_FLT_SHIFT_SAME) &&
+                     get_bits1(&s->gb_extra_bits))) {
                     S |= (1 << shift) - 1;
-                } else if(s->got_extra_bits && (s->float_flag & WV_FLT_SHIFT_SENT)){
+                } else if (s->got_extra_bits &&
+                           (s->float_flag & WV_FLT_SHIFT_SENT)) {
                     S |= get_bits(&s->gb_extra_bits, shift);
                 }
             }
-        }else{
+        } else {
             exp = s->float_max_exp;
         }
         S &= 0x7fffff;
-    }else{
+    } else {
         sign = 0;
         exp = 0;
-        if(s->got_extra_bits && (s->float_flag & WV_FLT_ZERO_SENT)){
-            if(get_bits1(&s->gb_extra_bits)){
+        if (s->got_extra_bits && (s->float_flag & WV_FLT_ZERO_SENT)) {
+            if (get_bits1(&s->gb_extra_bits)) {
                 S = get_bits(&s->gb_extra_bits, 23);
-                if(s->float_max_exp >= 25)
+                if (s->float_max_exp >= 25)
                     exp = get_bits(&s->gb_extra_bits, 8);
                 sign = get_bits1(&s->gb_extra_bits);
-            }else{
-                if(s->float_flag & WV_FLT_ZERO_SIGN)
+            } else {
+                if (s->float_flag & WV_FLT_ZERO_SIGN)
                     sign = get_bits1(&s->gb_extra_bits);
             }
         }
@@ -492,7 +499,8 @@ static void wv_reset_saved_context(WavpackFrameContext *s)
     s->sc.crc = s->extra_sc.crc = 0xFFFFFFFF;
 }
 
-static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb, void *dst, const int type)
+static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb,
+                                   void *dst, const int type)
 {
     int i, j, count = 0;
     int last, t;
@@ -506,69 +514,71 @@ static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb, vo
     const int channel_pad = s->avctx->channels - 2;
 
     s->one = s->zero = s->zeroes = 0;
-    do{
+    do {
         L = wv_get_value(s, gb, 0, &last);
-        if(last) break;
+        if (last)
+            break;
         R = wv_get_value(s, gb, 1, &last);
-        if(last) break;
-        for(i = 0; i < s->terms; i++){
+        if (last)
+            break;
+        for (i = 0; i < s->terms; i++) {
             t = s->decorr[i].value;
-            if(t > 0){
-                if(t > 8){
-                    if(t & 1){
+            if (t > 0) {
+                if (t > 8) {
+                    if (t & 1) {
                         A = 2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
                         B = 2 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1];
-                    }else{
+                    } else {
                         A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
                         B = (3 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1]) >> 1;
                     }
                     s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
                     s->decorr[i].samplesB[1] = s->decorr[i].samplesB[0];
                     j = 0;
-                }else{
+                } else {
                     A = s->decorr[i].samplesA[pos];
                     B = s->decorr[i].samplesB[pos];
                     j = (pos + t) & 7;
                 }
-                if(type != AV_SAMPLE_FMT_S16){
+                if (type != AV_SAMPLE_FMT_S16) {
                     L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
                     R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);
-                }else{
+                } else {
                     L2 = L + ((s->decorr[i].weightA * A + 512) >> 10);
                     R2 = R + ((s->decorr[i].weightB * B + 512) >> 10);
                 }
-                if(A && L) s->decorr[i].weightA -= ((((L ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
-                if(B && R) s->decorr[i].weightB -= ((((R ^ B) >> 30) & 2) - 1) * s->decorr[i].delta;
+                if (A && L) s->decorr[i].weightA -= ((((L ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
+                if (B && R) s->decorr[i].weightB -= ((((R ^ B) >> 30) & 2) - 1) * s->decorr[i].delta;
                 s->decorr[i].samplesA[j] = L = L2;
                 s->decorr[i].samplesB[j] = R = R2;
-            }else if(t == -1){
-                if(type != AV_SAMPLE_FMT_S16)
+            } else if (t == -1) {
+                if (type != AV_SAMPLE_FMT_S16)
                     L2 = L + ((s->decorr[i].weightA * (int64_t)s->decorr[i].samplesA[0] + 512) >> 10);
                 else
                     L2 = L + ((s->decorr[i].weightA * s->decorr[i].samplesA[0] + 512) >> 10);
                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);
                 L = L2;
-                if(type != AV_SAMPLE_FMT_S16)
+                if (type != AV_SAMPLE_FMT_S16)
                     R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);
                 else
                     R2 = R + ((s->decorr[i].weightB * L2 + 512) >> 10);
                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, L2, R);
                 R = R2;
                 s->decorr[i].samplesA[0] = R;
-            }else{
-                if(type != AV_SAMPLE_FMT_S16)
+            } else {
+                if (type != AV_SAMPLE_FMT_S16)
                     R2 = R + ((s->decorr[i].weightB * (int64_t)s->decorr[i].samplesB[0] + 512) >> 10);
                 else
                     R2 = R + ((s->decorr[i].weightB * s->decorr[i].samplesB[0] + 512) >> 10);
                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, s->decorr[i].samplesB[0], R);
                 R = R2;
 
-                if(t == -3){
+                if (t == -3) {
                     R2 = s->decorr[i].samplesA[0];
                     s->decorr[i].samplesA[0] = R;
                 }
 
-                if(type != AV_SAMPLE_FMT_S16)
+                if (type != AV_SAMPLE_FMT_S16)
                     L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);
                 else
                     L2 = L + ((s->decorr[i].weightA * R2 + 512) >> 10);
@@ -578,15 +588,15 @@ static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb, vo
             }
         }
         pos = (pos + 1) & 7;
-        if(s->joint)
+        if (s->joint)
             L += (R -= (L >> 1));
         crc = (crc * 3 + L) * 3 + R;
 
-        if(type == AV_SAMPLE_FMT_FLT){
+        if (type == AV_SAMPLE_FMT_FLT) {
             *dstfl++ = wv_get_value_float(s, &crc_extra_bits, L);
             *dstfl++ = wv_get_value_float(s, &crc_extra_bits, R);
             dstfl += channel_pad;
-        } else if(type == AV_SAMPLE_FMT_S32){
+        } else if (type == AV_SAMPLE_FMT_S32) {
             *dst32++ = wv_get_value_integer(s, &crc_extra_bits, L);
             *dst32++ = wv_get_value_integer(s, &crc_extra_bits, R);
             dst32 += channel_pad;
@@ -598,20 +608,21 @@ static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb, vo
         count++;
     } while (!last && count < s->samples);
 
-        wv_reset_saved_context(s);
-        if(crc != s->CRC){
-            av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
-            return -1;
-        }
-        if(s->got_extra_bits && crc_extra_bits != s->crc_extra_bits){
-            av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
-            return -1;
-        }
+    wv_reset_saved_context(s);
+    if (crc != s->CRC) {
+        av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
+        return -1;
+    }
+    if (s->got_extra_bits && crc_extra_bits != s->crc_extra_bits) {
+        av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
+        return -1;
+    }
 
     return count * 2;
 }
 
-static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb, void *dst, const int type)
+static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb,
+                                 void *dst, const int type)
 {
     int i, j, count = 0;
     int last, t;
@@ -625,55 +636,57 @@ static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb, void
     const int channel_stride = s->avctx->channels;
 
     s->one = s->zero = s->zeroes = 0;
-    do{
+    do {
         T = wv_get_value(s, gb, 0, &last);
         S = 0;
-        if(last) break;
-        for(i = 0; i < s->terms; i++){
+        if (last)
+            break;
+        for (i = 0; i < s->terms; i++) {
             t = s->decorr[i].value;
-            if(t > 8){
-                if(t & 1)
-                    A = 2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
+            if (t > 8) {
+                if (t & 1)
+                    A =  2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
                 else
                     A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
                 s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
                 j = 0;
-            }else{
+            } else {
                 A = s->decorr[i].samplesA[pos];
                 j = (pos + t) & 7;
             }
-            if(type != AV_SAMPLE_FMT_S16)
+            if (type != AV_SAMPLE_FMT_S16)
                 S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
             else
                 S = T + ((s->decorr[i].weightA * A + 512) >> 10);
-            if(A && T) s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
+            if (A && T)
+                s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
             s->decorr[i].samplesA[j] = T = S;
         }
         pos = (pos + 1) & 7;
         crc = crc * 3 + S;
 
-        if(type == AV_SAMPLE_FMT_FLT){
+        if (type == AV_SAMPLE_FMT_FLT) {
             *dstfl = wv_get_value_float(s, &crc_extra_bits, S);
             dstfl += channel_stride;
-        }else if(type == AV_SAMPLE_FMT_S32){
+        } else if (type == AV_SAMPLE_FMT_S32) {
             *dst32 = wv_get_value_integer(s, &crc_extra_bits, S);
             dst32 += channel_stride;
-        }else{
+        } else {
             *dst16 = wv_get_value_integer(s, &crc_extra_bits, S);
             dst16 += channel_stride;
         }
         count++;
     } while (!last && count < s->samples);
 
-        wv_reset_saved_context(s);
-        if(crc != s->CRC){
-            av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
-            return -1;
-        }
-        if(s->got_extra_bits && crc_extra_bits != s->crc_extra_bits){
-            av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
-            return -1;
-        }
+    wv_reset_saved_context(s);
+    if (crc != s->CRC) {
+        av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
+        return -1;
+    }
+    if (s->got_extra_bits && crc_extra_bits != s->crc_extra_bits) {
+        av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
+        return -1;
+    }
 
     return count;
 }
@@ -681,11 +694,11 @@ static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb, void
 static av_cold int wv_alloc_frame_context(WavpackContext *c)
 {
 
-    if(c->fdec_num == WV_MAX_FRAME_DECODERS)
+    if (c->fdec_num == WV_MAX_FRAME_DECODERS)
         return -1;
 
     c->fdec[c->fdec_num] = av_mallocz(sizeof(**c->fdec));
-    if(!c->fdec[c->fdec_num])
+    if (!c->fdec[c->fdec_num])
         return -1;
     c->fdec_num++;
     c->fdec[c->fdec_num - 1]->avctx = c->avctx;
@@ -699,20 +712,21 @@ static av_cold int wavpack_decode_init(AVCodecContext *avctx)
     WavpackContext *s = avctx->priv_data;
 
     s->avctx = avctx;
-    if(avctx->bits_per_coded_sample <= 16)
+    if (avctx->bits_per_coded_sample <= 16)
         avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     else
         avctx->sample_fmt = AV_SAMPLE_FMT_S32;
-    if(avctx->channels <= 2 && !avctx->channel_layout)
-        avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
+    if (avctx->channels <= 2 && !avctx->channel_layout)
+        avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO :
+                                                         AV_CH_LAYOUT_MONO;
 
     s->multichannel = avctx->channels > 2;
     /* lavf demuxer does not provide extradata, Matroska stores 0x403
        there, use this to detect decoding mode for multichannel */
     s->mkv_mode = 0;
-    if(s->multichannel && avctx->extradata && avctx->extradata_size == 2){
+    if (s->multichannel && avctx->extradata && avctx->extradata_size == 2) {
         int ver = AV_RL16(avctx->extradata);
-        if(ver >= 0x402 && ver <= 0x410)
+        if (ver >= 0x402 && ver <= 0x410)
             s->mkv_mode = 1;
     }
 
@@ -729,7 +743,7 @@ static av_cold int wavpack_decode_end(AVCodecContext *avctx)
     WavpackContext *s = avctx->priv_data;
     int i;
 
-    for(i = 0; i < s->fdec_num; i++)
+    for (i = 0; i < s->fdec_num; i++)
         av_freep(&s->fdec[i]);
     s->fdec_num = 0;
 
@@ -744,101 +758,96 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
     WavpackFrameContext *s;
     void *samples = data;
     int samplecount;
-    int got_terms = 0, got_weights = 0, got_samples = 0, got_entropy = 0, got_bs = 0, got_float = 0;
-    int got_hybrid = 0;
-    const uint8_t* orig_buf = buf;
-    const uint8_t* buf_end = buf + buf_size;
+    int got_terms   = 0, got_weights = 0, got_samples = 0,
+        got_entropy = 0, got_bs      = 0, got_float   = 0, got_hybrid = 0;
+    const uint8_t *orig_buf = buf;
+    const uint8_t *buf_end  = buf + buf_size;
     int i, j, id, size, ssize, weights, t;
     int bpp, chan, chmask;
 
-    if (buf_size == 0){
+    if (buf_size == 0) {
         *got_frame_ptr = 0;
         return 0;
     }
 
-    if(block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0){
+    if (block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0) {
         av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");
         return -1;
     }
 
     s = wc->fdec[block_no];
-    if(!s){
+    if (!s) {
         av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n", block_no);
         return -1;
     }
 
-        memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
-        memset(s->ch, 0, sizeof(s->ch));
-        s->extra_bits = 0;
-        s->and = s->or = s->shift = 0;
-        s->got_extra_bits = 0;
+    memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
+    memset(s->ch, 0, sizeof(s->ch));
+    s->extra_bits = 0;
+    s->and = s->or = s->shift = 0;
+    s->got_extra_bits = 0;
 
-    if(!wc->mkv_mode){
+    if (!wc->mkv_mode) {
         s->samples = AV_RL32(buf); buf += 4;
-        if(!s->samples){
+        if (!s->samples) {
             *got_frame_ptr = 0;
             return 0;
         }
-    }else{
+    } else {
         s->samples = wc->samples;
     }
     s->frame_flags = AV_RL32(buf); buf += 4;
-    if(s->frame_flags&0x80){
-        avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
-    } else if((s->frame_flags&0x03) <= 1){
-        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
-    } else {
-        avctx->sample_fmt = AV_SAMPLE_FMT_S32;
-    }
     bpp = av_get_bytes_per_sample(avctx->sample_fmt);
     samples = (uint8_t*)samples + bpp * wc->ch_offset;
 
-    s->stereo = !(s->frame_flags & WV_MONO);
-    s->stereo_in = (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;
-    s->joint = s->frame_flags & WV_JOINT_STEREO;
-    s->hybrid = s->frame_flags & WV_HYBRID_MODE;
-    s->hybrid_bitrate = s->frame_flags & WV_HYBRID_BITRATE;
+    s->stereo         = !(s->frame_flags & WV_MONO);
+    s->stereo_in      =  (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;
+    s->joint          =   s->frame_flags & WV_JOINT_STEREO;
+    s->hybrid         =   s->frame_flags & WV_HYBRID_MODE;
+    s->hybrid_bitrate =   s->frame_flags & WV_HYBRID_BITRATE;
     s->hybrid_maxclip = (1LL << ((((s->frame_flags & 0x03) + 1) << 3) - 1)) - 1;
-    s->post_shift = 8 * (bpp-1-(s->frame_flags&0x03)) + ((s->frame_flags >> 13) & 0x1f);
-    s->CRC = AV_RL32(buf); buf += 4;
-    if(wc->mkv_mode)
+    s->post_shift     = 8 * (bpp - 1 - (s->frame_flags & 0x03)) +
+                        ((s->frame_flags >> 13) & 0x1f);
+    s->CRC            = AV_RL32(buf); buf += 4;
+    if (wc->mkv_mode)
         buf += 4; //skip block size;
 
     wc->ch_offset += 1 + s->stereo;
 
     // parse metadata blocks
-    while(buf < buf_end){
-        id = *buf++;
+    while (buf < buf_end) {
+        id   = *buf++;
         size = *buf++;
-        if(id & WP_IDF_LONG) {
+        if (id & WP_IDF_LONG) {
             size |= (*buf++) << 8;
             size |= (*buf++) << 16;
         }
         size <<= 1; // size is specified in words
         ssize = size;
-        if(id & WP_IDF_ODD) size--;
-        if(size < 0){
+        if (id & WP_IDF_ODD)
+            size--;
+        if (size < 0) {
             av_log(avctx, AV_LOG_ERROR, "Got incorrect block %02X with size %i\n", id, size);
             break;
         }
-        if(buf + ssize > buf_end){
+        if (buf + ssize > buf_end) {
             av_log(avctx, AV_LOG_ERROR, "Block size %i is out of bounds\n", size);
             break;
         }
-        if(id & WP_IDF_IGNORE){
+        if (id & WP_IDF_IGNORE) {
             buf += ssize;
             continue;
         }
-        switch(id & WP_IDF_MASK){
+        switch (id & WP_IDF_MASK) {
         case WP_ID_DECTERMS:
-            if(size > MAX_TERMS){
+            if (size > MAX_TERMS) {
                 av_log(avctx, AV_LOG_ERROR, "Too many decorrelation terms\n");
                 s->terms = 0;
                 buf += ssize;
                 continue;
             }
             s->terms = size;
-            for(i = 0; i < s->terms; i++) {
+            for (i = 0; i < s->terms; i++) {
                 s->decorr[s->terms - i - 1].value = (*buf & 0x1F) - 5;
                 s->decorr[s->terms - i - 1].delta = *buf >> 5;
                 buf++;
@@ -846,56 +855,57 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
             got_terms = 1;
             break;
         case WP_ID_DECWEIGHTS:
-            if(!got_terms){
+            if (!got_terms) {
                 av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
                 continue;
             }
             weights = size >> s->stereo_in;
-            if(weights > MAX_TERMS || weights > s->terms){
+            if (weights > MAX_TERMS || weights > s->terms) {
                 av_log(avctx, AV_LOG_ERROR, "Too many decorrelation weights\n");
                 buf += ssize;
                 continue;
             }
-            for(i = 0; i < weights; i++) {
+            for (i = 0; i < weights; i++) {
                 t = (int8_t)(*buf++);
                 s->decorr[s->terms - i - 1].weightA = t << 3;
-                if(s->decorr[s->terms - i - 1].weightA > 0)
-                    s->decorr[s->terms - i - 1].weightA += (s->decorr[s->terms - i - 1].weightA + 64) >> 7;
-                if(s->stereo_in){
+                if (s->decorr[s->terms - i - 1].weightA > 0)
+                    s->decorr[s->terms - i - 1].weightA +=
+                            (s->decorr[s->terms - i - 1].weightA + 64) >> 7;
+                if (s->stereo_in) {
                     t = (int8_t)(*buf++);
                     s->decorr[s->terms - i - 1].weightB = t << 3;
-                    if(s->decorr[s->terms - i - 1].weightB > 0)
-                        s->decorr[s->terms - i - 1].weightB += (s->decorr[s->terms - i - 1].weightB + 64) >> 7;
+                    if (s->decorr[s->terms - i - 1].weightB > 0)
+                        s->decorr[s->terms - i - 1].weightB +=
+                                (s->decorr[s->terms - i - 1].weightB + 64) >> 7;
                 }
             }
             got_weights = 1;
             break;
         case WP_ID_DECSAMPLES:
-            if(!got_terms){
+            if (!got_terms) {
                 av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
                 continue;
             }
             t = 0;
-            for(i = s->terms - 1; (i >= 0) && (t < size); i--) {
-                if(s->decorr[i].value > 8){
+            for (i = s->terms - 1; (i >= 0) && (t < size); i--) {
+                if (s->decorr[i].value > 8) {
                     s->decorr[i].samplesA[0] = wp_exp2(AV_RL16(buf)); buf += 2;
                     s->decorr[i].samplesA[1] = wp_exp2(AV_RL16(buf)); buf += 2;
-                    if(s->stereo_in){
+                    if (s->stereo_in) {
                         s->decorr[i].samplesB[0] = wp_exp2(AV_RL16(buf)); buf += 2;
                         s->decorr[i].samplesB[1] = wp_exp2(AV_RL16(buf)); buf += 2;
                         t += 4;
                     }
                     t += 4;
-                }else if(s->decorr[i].value < 0){
+                } else if (s->decorr[i].value < 0) {
                     s->decorr[i].samplesA[0] = wp_exp2(AV_RL16(buf)); buf += 2;
                     s->decorr[i].samplesB[0] = wp_exp2(AV_RL16(buf)); buf += 2;
                     t += 4;
-                }else{
-                    for(j = 0; j < s->decorr[i].value; j++){
+                } else {
+                    for (j = 0; j < s->decorr[i].value; j++) {
                         s->decorr[i].samplesA[j] = wp_exp2(AV_RL16(buf)); buf += 2;
-                        if(s->stereo_in){
+                        if (s->stereo_in)
                             s->decorr[i].samplesB[j] = wp_exp2(AV_RL16(buf)); buf += 2;
-                        }
                     }
                     t += s->decorr[i].value * 2 * (s->stereo_in + 1);
                 }
@@ -903,13 +913,14 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
             got_samples = 1;
             break;
         case WP_ID_ENTROPY:
-            if(size != 6 * (s->stereo_in + 1)){
-                av_log(avctx, AV_LOG_ERROR, "Entropy vars size should be %i, got %i", 6 * (s->stereo_in + 1), size);
+            if (size != 6 * (s->stereo_in + 1)) {
+                av_log(avctx, AV_LOG_ERROR, "Entropy vars size should be %i, "
+                       "got %i", 6 * (s->stereo_in + 1), size);
                 buf += ssize;
                 continue;
             }
-            for(j = 0; j <= s->stereo_in; j++){
-                for(i = 0; i < 3; i++){
+            for (j = 0; j <= s->stereo_in; j++) {
+                for (i = 0; i < 3; i++) {
                     s->ch[j].median[i] = wp_exp2(AV_RL16(buf));
                     buf += 2;
                 }
@@ -917,56 +928,56 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
             got_entropy = 1;
             break;
         case WP_ID_HYBRID:
-            if(s->hybrid_bitrate){
-                for(i = 0; i <= s->stereo_in; i++){
+            if (s->hybrid_bitrate) {
+                for (i = 0; i <= s->stereo_in; i++) {
                     s->ch[i].slow_level = wp_exp2(AV_RL16(buf));
                     buf += 2;
                     size -= 2;
                 }
             }
-            for(i = 0; i < (s->stereo_in + 1); i++){
+            for (i = 0; i < (s->stereo_in + 1); i++) {
                 s->ch[i].bitrate_acc = AV_RL16(buf) << 16;
                 buf += 2;
                 size -= 2;
             }
-            if(size > 0){
-                for(i = 0; i < (s->stereo_in + 1); i++){
+            if (size > 0) {
+                for (i = 0; i < (s->stereo_in + 1); i++) {
                     s->ch[i].bitrate_delta = wp_exp2((int16_t)AV_RL16(buf));
                     buf += 2;
                 }
-            }else{
-                for(i = 0; i < (s->stereo_in + 1); i++)
+            } else {
+                for (i = 0; i < (s->stereo_in + 1); i++)
                     s->ch[i].bitrate_delta = 0;
             }
             got_hybrid = 1;
             break;
         case WP_ID_INT32INFO:
-            if(size != 4){
+            if (size != 4) {
                 av_log(avctx, AV_LOG_ERROR, "Invalid INT32INFO, size = %i, sent_bits = %i\n", size, *buf);
                 buf += ssize;
                 continue;
             }
-            if(buf[0])
+            if (buf[0])
                 s->extra_bits = buf[0];
-            else if(buf[1])
+            else if (buf[1])
                 s->shift = buf[1];
-            else if(buf[2]){
+            else if (buf[2]){
                 s->and = s->or = 1;
                 s->shift = buf[2];
-            }else if(buf[3]){
-                s->and = 1;
+            } else if(buf[3]) {
+                s->and   = 1;
                 s->shift = buf[3];
             }
             buf += 4;
             break;
         case WP_ID_FLOATINFO:
-            if(size != 4){
+            if (size != 4) {
                 av_log(avctx, AV_LOG_ERROR, "Invalid FLOATINFO, size = %i\n", size);
                 buf += ssize;
                 continue;
             }
-            s->float_flag = buf[0];
-            s->float_shift = buf[1];
+            s->float_flag    = buf[0];
+            s->float_shift   = buf[1];
             s->float_max_exp = buf[2];
             buf += 4;
             got_float = 1;
@@ -980,8 +991,9 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
             got_bs = 1;
             break;
         case WP_ID_EXTRABITS:
-            if(size <= 4){
-                av_log(avctx, AV_LOG_ERROR, "Invalid EXTRABITS, size = %i\n", size);
+            if (size <= 4) {
+                av_log(avctx, AV_LOG_ERROR, "Invalid EXTRABITS, size = %i\n",
+                       size);
                 buf += size;
                 continue;
             }
@@ -993,89 +1005,84 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
             s->got_extra_bits = 1;
             break;
         case WP_ID_CHANINFO:
-            if(size <= 1){
+            if (size <= 1) {
                 av_log(avctx, AV_LOG_ERROR, "Insufficient channel information\n");
                 return -1;
             }
             chan = *buf++;
-            switch(size - 2){
-            case 0:
-                chmask = *buf;
-                break;
-            case 1:
-                chmask = AV_RL16(buf);
-                break;
-            case 2:
-                chmask = AV_RL24(buf);
-                break;
-            case 3:
-                chmask = AV_RL32(buf);
-                break;
+            switch (size - 2) {
+            case 0: chmask = *buf;         break;
+            case 1: chmask = AV_RL16(buf); break;
+            case 2: chmask = AV_RL24(buf); break;
+            case 3: chmask = AV_RL32(buf); break;
             case 5:
                 chan |= (buf[1] & 0xF) << 8;
                 chmask = AV_RL24(buf + 2);
                 break;
             default:
-                av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n", size);
-                chan = avctx->channels;
+                av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n",
+                       size);
+                chan   = avctx->channels;
                 chmask = avctx->channel_layout;
             }
-            if(chan != avctx->channels){
-                av_log(avctx, AV_LOG_ERROR, "Block reports total %d channels, decoder believes it's %d channels\n",
-                       chan, avctx->channels);
+            if (chan != avctx->channels) {
+                av_log(avctx, AV_LOG_ERROR, "Block reports total %d channels, "
+                       "decoder believes it's %d channels\n", chan,
+                       avctx->channels);
                 return -1;
             }
-            if(!avctx->channel_layout)
+            if (!avctx->channel_layout)
                 avctx->channel_layout = chmask;
             buf += size - 1;
             break;
         default:
             buf += size;
         }
-        if(id & WP_IDF_ODD) buf++;
+        if (id & WP_IDF_ODD)
+            buf++;
     }
 
-        if(!got_terms){
-            av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");
-            return -1;
-        }
-        if(!got_weights){
-            av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");
-            return -1;
-        }
-        if(!got_samples){
-            av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");
-            return -1;
-        }
-        if(!got_entropy){
-            av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");
-            return -1;
-        }
-        if(s->hybrid && !got_hybrid){
-            av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");
-            return -1;
-        }
-        if(!got_bs){
-            av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
-            return -1;
-        }
-        if(!got_float && avctx->sample_fmt == AV_SAMPLE_FMT_FLT){
-            av_log(avctx, AV_LOG_ERROR, "Float information not found\n");
-            return -1;
-        }
-        if(s->got_extra_bits && avctx->sample_fmt != AV_SAMPLE_FMT_FLT){
-            const int size = get_bits_left(&s->gb_extra_bits);
-            const int wanted = s->samples * s->extra_bits << s->stereo_in;
-            if(size < wanted){
-                av_log(avctx, AV_LOG_ERROR, "Too small EXTRABITS\n");
-                s->got_extra_bits = 0;
-            }
+    if (!got_terms) {
+        av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");
+        return -1;
+    }
+    if (!got_weights) {
+        av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");
+        return -1;
+    }
+    if (!got_samples) {
+        av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");
+        return -1;
+    }
+    if (!got_entropy) {
+        av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");
+        return -1;
+    }
+    if (s->hybrid && !got_hybrid) {
+        av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");
+        return -1;
+    }
+    if (!got_bs) {
+        av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
+        return -1;
+    }
+    if (!got_float && avctx->sample_fmt == AV_SAMPLE_FMT_FLT) {
+        av_log(avctx, AV_LOG_ERROR, "Float information not found\n");
+        return -1;
+    }
+    if (s->got_extra_bits && avctx->sample_fmt != AV_SAMPLE_FMT_FLT) {
+        const int size   = get_bits_left(&s->gb_extra_bits);
+        const int wanted = s->samples * s->extra_bits << s->stereo_in;
+        if (size < wanted) {
+            av_log(avctx, AV_LOG_ERROR, "Too small EXTRABITS\n");
+            s->got_extra_bits = 0;
         }
+    }
 
-    if(s->stereo_in){
-        if(avctx->sample_fmt == AV_SAMPLE_FMT_S16)
+    if (s->stereo_in) {
+        if (avctx->sample_fmt == AV_SAMPLE_FMT_S16)
             samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_S16);
-        else if(avctx->sample_fmt == AV_SAMPLE_FMT_S32)
+        else if (avctx->sample_fmt == AV_SAMPLE_FMT_S32)
             samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_S32);
         else
             samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_FLT);
@@ -1084,12 +1091,12 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
             return -1;
 
         samplecount >>= 1;
-    }else{
+    } else {
         const int channel_stride = avctx->channels;
 
-        if(avctx->sample_fmt == AV_SAMPLE_FMT_S16)
+        if (avctx->sample_fmt == AV_SAMPLE_FMT_S16)
             samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_S16);
-        else if(avctx->sample_fmt == AV_SAMPLE_FMT_S32)
+        else if (avctx->sample_fmt == AV_SAMPLE_FMT_S32)
             samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_S32);
         else
             samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_FLT);
@@ -1097,29 +1104,29 @@ static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
         if (samplecount < 0)
             return -1;
 
-        if(s->stereo && avctx->sample_fmt == AV_SAMPLE_FMT_S16){
+        if (s->stereo && avctx->sample_fmt == AV_SAMPLE_FMT_S16) {
             int16_t *dst = (int16_t*)samples + 1;
             int16_t *src = (int16_t*)samples;
             int cnt = samplecount;
-            while(cnt--){
+            while (cnt--) {
                 *dst = *src;
                 src += channel_stride;
                 dst += channel_stride;
             }
-        }else if(s->stereo && avctx->sample_fmt == AV_SAMPLE_FMT_S32){
+        } else if (s->stereo && avctx->sample_fmt == AV_SAMPLE_FMT_S32) {
             int32_t *dst = (int32_t*)samples + 1;
             int32_t *src = (int32_t*)samples;
             int cnt = samplecount;
-            while(cnt--){
+            while (cnt--) {
                 *dst = *src;
                 src += channel_stride;
                 dst += channel_stride;
             }
-        }else if(s->stereo){
+        } else if (s->stereo) {
             float *dst = (float*)samples + 1;
             float *src = (float*)samples;
             int cnt = samplecount;
-            while(cnt--){
+            while (cnt--) {
                 *dst = *src;
                 src += channel_stride;
                 dst += channel_stride;
@@ -1144,23 +1151,27 @@ static void wavpack_decode_flush(AVCodecContext *avctx)
 static int wavpack_decode_frame(AVCodecContext *avctx, void *data,
                                 int *got_frame_ptr, AVPacket *avpkt)
 {
-    WavpackContext *s = avctx->priv_data;
+    WavpackContext *s  = avctx->priv_data;
     const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
-    int frame_size, ret;
+    int buf_size       = avpkt->size;
+    int frame_size, ret, frame_flags;
     int samplecount = 0;
 
-    s->block = 0;
+    s->block     = 0;
     s->ch_offset = 0;
 
     /* determine number of samples */
-    if(s->mkv_mode){
-        s->samples = AV_RL32(buf); buf += 4;
+    if (s->mkv_mode) {
+        s->samples  = AV_RL32(buf); buf += 4;
+        frame_flags = AV_RL32(buf);
     } else {
-        if (s->multichannel)
-            s->samples = AV_RL32(buf + 4);
-        else
-            s->samples = AV_RL32(buf);
+        if (s->multichannel) {
+            s->samples  = AV_RL32(buf + 4);
+            frame_flags = AV_RL32(buf + 8);
+        } else {
+            s->samples  = AV_RL32(buf);
+            frame_flags = AV_RL32(buf + 4);
+        }
     }
     if (s->samples <= 0) {
         av_log(avctx, AV_LOG_ERROR, "Invalid number of samples: %d\n",
@@ -1168,6 +1179,14 @@ static int wavpack_decode_frame(AVCodecContext *avctx, void *data,
         return AVERROR(EINVAL);
     }
 
+    if (frame_flags & 0x80) {
+        avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    } else if ((frame_flags & 0x03) <= 1) {
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    } else {
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32;
+    }
+
     /* get output buffer */
     s->frame.nb_samples = s->samples;
     if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
@@ -1175,26 +1194,27 @@ static int wavpack_decode_frame(AVCodecContext *avctx, void *data,
         return ret;
     }
 
-    while(buf_size > 0){
-        if(!s->multichannel){
+    while (buf_size > 0) {
+        if (!s->multichannel) {
             frame_size = buf_size;
-        }else{
-            if(!s->mkv_mode){
+        } else {
+            if (!s->mkv_mode) {
                 frame_size = AV_RL32(buf) - 12; buf += 4; buf_size -= 4;
-            }else{
-                if(buf_size < 12) //MKV files can have zero flags after last block
+            } else {
+                if (buf_size < 12) //MKV files can have zero flags after last block
                     break;
                 frame_size = AV_RL32(buf + 8) + 12;
             }
         }
-        if(frame_size < 0 || frame_size > buf_size){
-            av_log(avctx, AV_LOG_ERROR, "Block %d has invalid size (size %d vs. %d bytes left)\n",
-                   s->block, frame_size, buf_size);
+        if (frame_size < 0 || frame_size > buf_size) {
+            av_log(avctx, AV_LOG_ERROR, "Block %d has invalid size (size %d "
+                   "vs. %d bytes left)\n", s->block, frame_size, buf_size);
             wavpack_decode_flush(avctx);
             return -1;
         }
-        if((samplecount = wavpack_decode_block(avctx, s->block, s->frame.data[0],
-                                               got_frame_ptr, buf, frame_size)) < 0) {
+        if ((samplecount = wavpack_decode_block(avctx, s->block,
+                                                s->frame.data[0], got_frame_ptr,
+                                                buf, frame_size)) < 0) {
             wavpack_decode_flush(avctx);
             return -1;
         }
@@ -1218,5 +1238,5 @@ AVCodec ff_wavpack_decoder = {
     .decode         = wavpack_decode_frame,
     .flush          = wavpack_decode_flush,
     .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
-    .long_name = NULL_IF_CONFIG_SMALL("WavPack"),
+    .long_name      = NULL_IF_CONFIG_SMALL("WavPack"),
 };
diff --git a/libavcodec/x86/Makefile b/libavcodec/x86/Makefile
index aa97942..2abe4fb 100644
--- a/libavcodec/x86/Makefile
+++ b/libavcodec/x86/Makefile
@@ -33,6 +33,7 @@ YASM-OBJS-$(CONFIG_AC3DSP)             += x86/ac3dsp.o
 MMX-OBJS-$(CONFIG_CAVS_DECODER)        += x86/cavsdsp_mmx.o
 MMX-OBJS-$(CONFIG_DNXHD_ENCODER)       += x86/dnxhd_mmx.o
 MMX-OBJS-$(CONFIG_MPEGAUDIODSP)        += x86/mpegaudiodec_mmx.o
+YASM-OBJS-$(CONFIG_MPEGAUDIODSP)       += x86/imdct36_sse.o
 MMX-OBJS-$(CONFIG_ENCODERS)            += x86/dsputilenc_mmx.o
 YASM-OBJS-$(CONFIG_ENCODERS)           += x86/dsputilenc_yasm.o
 MMX-OBJS-$(CONFIG_GPL)                 += x86/idct_mmx.o
diff --git a/libavcodec/x86/imdct36_sse.asm b/libavcodec/x86/imdct36_sse.asm
new file mode 100644
index 0000000..2908459
--- /dev/null
+++ b/libavcodec/x86/imdct36_sse.asm
@@ -0,0 +1,721 @@
+;******************************************************************************
+;* 36 point SSE-optimized IMDCT transform
+;* Copyright (c) 2011 Vitor Sessak
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "libavutil/x86/x86inc.asm"
+%include "libavutil/x86/x86util.asm"
+
+SECTION_RODATA
+
+align 16
+ps_mask:  dd 0, ~0, ~0, ~0
+ps_mask2: dd 0, ~0,  0, ~0
+ps_mask3: dd 0,  0,  0, ~0
+ps_mask4: dd 0, ~0,  0,  0
+
+ps_val1:  dd          -0.5,          -0.5, -0.8660254038, -0.8660254038
+ps_val2:  dd           1.0,           1.0,  0.8660254038,  0.8660254038
+ps_val3:  dd  0.1736481777,  0.1736481777,  0.3420201433,  0.3420201433
+ps_val4:  dd -0.7660444431, -0.7660444431,  0.8660254038,  0.8660254038
+ps_val5:  dd -0.9396926208, -0.9396926208, -0.9848077530, -0.9848077530
+ps_val6:  dd           0.5,           0.5, -0.6427876097, -0.6427876097
+ps_val7:  dd           1.0,           1.0, -0.6427876097, -0.6427876097
+
+ps_p1p1m1m1: dd 0,          0, 0x80000000, 0x80000000
+ps_p1m1p1m1: dd 0, 0x80000000,          0, 0x80000000
+
+ps_cosh:       dd 1.0, 0.50190991877167369479,  1.0,  5.73685662283492756461
+               dd 1.0, 0.51763809020504152469,  1.0,  1.93185165257813657349
+               dd 1.0, 0.55168895948124587824, -1.0, -1.18310079157624925896
+               dd 1.0, 0.61038729438072803416, -1.0, -0.87172339781054900991
+               dd 1.0, 0.70710678118654752439,  0.0,  0.0
+
+ps_cosh_sse3:  dd 1.0, -0.50190991877167369479,  1.0, -5.73685662283492756461
+               dd 1.0, -0.51763809020504152469,  1.0, -1.93185165257813657349
+               dd 1.0, -0.55168895948124587824, -1.0,  1.18310079157624925896
+               dd 1.0, -0.61038729438072803416, -1.0,  0.87172339781054900991
+               dd 1.0,  0.70710678118654752439,  0.0,  0.0
+
+costabs:  times 4 dd  0.98480773
+          times 4 dd  0.93969262
+          times 4 dd  0.86602539
+          times 4 dd -0.76604444
+          times 4 dd -0.64278764
+          times 4 dd  0.50000000
+          times 4 dd -0.50000000
+          times 4 dd -0.34202015
+          times 4 dd -0.17364818
+          times 4 dd  0.50190992
+          times 4 dd  0.51763808
+          times 4 dd  0.55168896
+          times 4 dd  0.61038726
+          times 4 dd  0.70710677
+          times 4 dd  0.87172341
+          times 4 dd  1.18310082
+          times 4 dd  1.93185163
+          times 4 dd  5.73685646
+
+%define SBLIMIT 32
+SECTION_TEXT
+
+%macro PSHUFD 3
+%if cpuflag(sse2) && notcpuflag(avx)
+    pshufd %1, %2, %3
+%else
+    shufps %1, %2, %2, %3
+%endif
+%endmacro
+
+; input  %2={x1,x2,x3,x4}, %3={y1,y2,y3,y4}
+; output %1={x3,x4,y1,y2}
+%macro BUILDINVHIGHLOW 3
+%if cpuflag(avx)
+    shufps %1, %2, %3, 0x4e
+%else
+    movlhps %1, %3
+    movhlps %1, %2
+%endif
+%endmacro
+
+; input  %2={x1,x2,x3,x4}, %3={y1,y2,y3,y4}
+; output %1={x4,y1,y2,y3}
+%macro ROTLEFT 3
+%if cpuflag(ssse3)
+    palignr  %1, %3, %2, 12
+%else
+    BUILDINVHIGHLOW %1, %2, %3
+    shufps  %1, %1, %3, 0x99
+%endif
+%endmacro
+
+%macro INVERTHL 2
+%if cpuflag(sse2)
+    PSHUFD  %1, %2, 0x4e
+%else
+    movhlps %1, %2
+    movlhps %1, %2
+%endif
+%endmacro
+
+%macro BUTTERF 3
+    INVERTHL %2, %1
+    xorps    %1, [ps_p1p1m1m1]
+    addps    %1, %2
+%if cpuflag(sse3)
+    mulps    %1, %1, [ps_cosh_sse3 + %3]
+    PSHUFD   %2, %1, 0xb1
+    addsubps %1, %1, %2
+%else
+    mulps    %1, [ps_cosh + %3]
+    PSHUFD   %2, %1, 0xb1
+    xorps    %1, [ps_p1m1p1m1]
+    addps    %1, %2
+%endif
+%endmacro
+
+%macro STORE 4
+    movhlps %2, %1
+    movss   [%3       ], %1
+    movss   [%3 + 2*%4], %2
+    shufps  %1, %1, 0xb1
+    movss   [%3 +   %4], %1
+    movhlps %2, %1
+    movss   [%3 + 3*%4], %2
+%endmacro
+
+%macro LOAD 4
+    movlps  %1, [%3       ]
+    movhps  %1, [%3 +   %4]
+    movlps  %2, [%3 + 2*%4]
+    movhps  %2, [%3 + 3*%4]
+    shufps  %1, %2, 0x88
+%endmacro
+
+%macro LOADA64 2
+%if cpuflag(avx)
+   movu     %1, [%2]
+%else
+   movlps   %1, [%2]
+   movhps   %1, [%2 + 8]
+%endif
+%endmacro
+
+%macro DEFINE_IMDCT 0
+cglobal imdct36_float, 4,4,9, out, buf, in, win
+
+    ; for(i=17;i>=1;i--) in[i] += in[i-1];
+    LOADA64 m0, inq
+    LOADA64 m1, inq + 16
+
+    ROTLEFT m5, m0, m1
+
+    PSHUFD  m6, m0, 0x93
+    andps   m6, m6, [ps_mask]
+    addps   m0, m0, m6
+
+    LOADA64 m2, inq + 32
+
+    ROTLEFT m7, m1, m2
+
+    addps   m1, m1, m5
+    LOADA64 m3, inq + 48
+
+    ROTLEFT m5, m2, m3
+
+    xorps   m4, m4, m4
+    movlps  m4, [inq+64]
+    BUILDINVHIGHLOW m6, m3, m4
+    shufps  m6, m6, m4, 0xa9
+
+    addps   m4, m4, m6
+    addps   m2, m2, m7
+    addps   m3, m3, m5
+
+    ; for(i=17;i>=3;i-=2) in[i] += in[i-2];
+    movlhps m5, m5, m0
+    andps   m5, m5, [ps_mask3]
+
+    BUILDINVHIGHLOW m7, m0, m1
+    andps   m7, m7, [ps_mask2]
+
+    addps   m0, m0, m5
+
+    BUILDINVHIGHLOW m6, m1, m2
+    andps   m6, m6, [ps_mask2]
+
+    addps  m1, m1, m7
+
+    BUILDINVHIGHLOW m7, m2, m3
+    andps   m7, m7, [ps_mask2]
+
+    addps   m2, m2, m6
+
+    movhlps m6, m6, m3
+    andps   m6, m6, [ps_mask4]
+
+    addps  m3, m3, m7
+    addps  m4, m4, m6
+
+    ; Populate tmp[]
+    movlhps m6, m1, m5    ; zero out high values
+    subps   m6, m6, m4
+
+    subps  m5, m0, m3
+
+%ifdef ARCH_X86_64
+    SWAP   m5, m8
+%endif
+
+    mulps  m7, m2, [ps_val1]
+
+%ifdef ARCH_X86_64
+    mulps  m5, m8, [ps_val2]
+%else
+    mulps  m5, m5, [ps_val2]
+%endif
+    addps  m7, m7, m5
+
+    mulps  m5, m6, [ps_val1]
+    subps  m7, m7, m5
+
+%ifdef ARCH_X86_64
+    SWAP   m5, m8
+%else
+    subps  m5, m0, m3
+%endif
+
+    subps  m5, m5, m6
+    addps  m5, m5, m2
+
+    shufps m6, m4, m3, 0xe4
+    subps  m6, m6, m2
+    mulps  m6, m6, [ps_val3]
+
+    addps  m4, m4, m1
+    mulps  m4, m4, [ps_val4]
+
+    shufps m1, m1, m0, 0xe4
+    addps  m1, m1, m2
+    mulps  m1, m1, [ps_val5]
+
+    mulps  m3, m3, [ps_val6]
+    mulps  m0, m0, [ps_val7]
+    addps  m0, m0, m3
+
+    xorps  m2, m1, [ps_p1p1m1m1]
+    subps  m2, m2, m4
+    addps  m2, m2, m0
+
+    addps  m3, m4, m0
+    subps  m3, m3, m6
+    xorps  m3, m3, [ps_p1p1m1m1]
+
+    shufps m0, m0, m4, 0xe4
+    subps  m0, m0, m1
+    addps  m0, m0, m6
+
+    BUILDINVHIGHLOW m4, m2, m3
+    shufps  m3, m3, m2, 0x4e
+
+    ; we have tmp = {SwAPLH(m0), SwAPLH(m7), m3, m4, m5}
+
+    BUTTERF  m0, m1, 0
+    BUTTERF  m7, m2, 16
+    BUTTERF  m3, m6, 32
+    BUTTERF  m4, m1, 48
+
+    mulps   m5, m5, [ps_cosh + 64]
+    PSHUFD  m1, m5, 0xe1
+    xorps   m5, m5, [ps_p1m1p1m1]
+    addps   m5, m5, m1
+
+    ; permutates:
+    ; m0    0  1  2  3     =>     2  6 10 14   m1
+    ; m7    4  5  6  7     =>     3  7 11 15   m2
+    ; m3    8  9 10 11     =>    17 13  9  5   m3
+    ; m4   12 13 14 15     =>    16 12  8  4   m5
+    ; m5   16 17 xx xx     =>     0  1 xx xx   m0
+
+    unpckhps m1, m0, m7
+    unpckhps m6, m3, m4
+    movhlps  m2, m6, m1
+    movlhps  m1, m1, m6
+
+    unpcklps m5, m5, m4
+    unpcklps m3, m3, m7
+    movhlps  m4, m3, m5
+    movlhps  m5, m5, m3
+    SWAP m4, m3
+    ; permutation done
+
+    PSHUFD  m6, m2, 0xb1
+    movss   m4, [bufq + 4*68]
+    movss   m7, [bufq + 4*64]
+    unpcklps  m7, m7, m4
+    mulps   m6, m6, [winq + 16*4]
+    addps   m6, m6, m7
+    movss   [outq + 64*SBLIMIT], m6
+    shufps  m6, m6, m6, 0xb1
+    movss   [outq + 68*SBLIMIT], m6
+
+    mulps   m6, m3, [winq + 4*4]
+    LOAD    m4, m7, bufq + 4*16, 16
+    addps   m6, m6, m4
+    STORE   m6, m7, outq + 16*SBLIMIT, 4*SBLIMIT
+
+    shufps  m4, m0, m3, 0xb5
+    mulps   m4, m4, [winq + 8*4]
+    LOAD    m7, m6, bufq + 4*32, 16
+    addps   m4, m4, m7
+    STORE   m4, m6, outq + 32*SBLIMIT, 4*SBLIMIT
+
+    shufps  m3, m3, m2, 0xb1
+    mulps   m3, m3, [winq + 12*4]
+    LOAD    m7, m6, bufq + 4*48, 16
+    addps   m3, m3, m7
+    STORE   m3, m7, outq + 48*SBLIMIT, 4*SBLIMIT
+
+    mulps   m2, m2, [winq]
+    LOAD    m6, m7, bufq, 16
+    addps   m2, m2, m6
+    STORE   m2, m7, outq, 4*SBLIMIT
+
+    mulps    m4, m1, [winq + 20*4]
+    STORE    m4, m7, bufq, 16
+
+    mulps    m3, m5, [winq + 24*4]
+    STORE    m3, m7, bufq + 4*16, 16
+
+    shufps   m0, m0, m5, 0xb0
+    mulps    m0, m0, [winq + 28*4]
+    STORE    m0, m7, bufq + 4*32, 16
+
+    shufps   m5, m5, m1, 0xb1
+    mulps    m5, m5, [winq + 32*4]
+    STORE    m5, m7, bufq + 4*48, 16
+
+    shufps   m1, m1, m1, 0xb1
+    mulps    m1, m1, [winq + 36*4]
+    movss    [bufq + 4*64], m1
+    shufps   m1, m1, 0xb1
+    movss    [bufq + 4*68], m1
+    RET
+%endmacro
+
+INIT_XMM sse
+DEFINE_IMDCT
+
+INIT_XMM sse2
+DEFINE_IMDCT
+
+INIT_XMM sse3
+DEFINE_IMDCT
+
+INIT_XMM ssse3
+DEFINE_IMDCT
+
+INIT_XMM avx
+DEFINE_IMDCT
+
+INIT_XMM sse
+
+%ifdef ARCH_X86_64
+%define SPILL SWAP
+%define UNSPILL SWAP
+%define SPILLED(x) m %+ x
+%else
+%define SPILLED(x) [tmpq+(x-8)*16 + 32*4]
+%macro SPILL 2 ; xmm#, mempos
+    movaps SPILLED(%2), m%1
+%endmacro
+%macro UNSPILL 2
+    movaps m%1, SPILLED(%2)
+%endmacro
+%endif
+
+%macro DEFINE_FOUR_IMDCT 0
+cglobal four_imdct36_float, 5,5,8, out, buf, in, win, tmp
+    movlps  m0, [inq+64]
+    movhps  m0, [inq+64 +   72]
+    movlps  m3, [inq+64 + 2*72]
+    movhps  m3, [inq+64 + 3*72]
+
+    shufps  m5, m0, m3, 0xdd
+    shufps  m0, m0, m3, 0x88
+
+    mova     m1, [inq+48]
+    movu     m6, [inq+48 +   72]
+    mova     m7, [inq+48 + 2*72]
+    movu     m3, [inq+48 + 3*72]
+
+    TRANSPOSE4x4PS 1, 6, 7, 3, 4
+
+    addps   m4, m6, m7
+    mova    [tmpq+4*28], m4
+
+    addps    m7, m3
+    addps    m6, m1
+    addps    m3, m0
+    addps    m0, m5
+    addps    m0, m7
+    addps    m7, m6
+    mova    [tmpq+4*12], m7
+    SPILL   3, 12
+
+    mova     m4, [inq+32]
+    movu     m5, [inq+32 +   72]
+    mova     m2, [inq+32 + 2*72]
+    movu     m7, [inq+32 + 3*72]
+
+    TRANSPOSE4x4PS 4, 5, 2, 7, 3
+
+    addps   m1, m7
+    SPILL   1, 11
+
+    addps   m3, m5, m2
+    SPILL   3, 13
+
+    addps    m7, m2
+    addps    m5, m4
+    addps    m6, m7
+    mova    [tmpq], m6
+    addps   m7, m5
+    mova    [tmpq+4*16], m7
+
+    mova    m2, [inq+16]
+    movu    m7, [inq+16 +   72]
+    mova    m1, [inq+16 + 2*72]
+    movu    m6, [inq+16 + 3*72]
+
+    TRANSPOSE4x4PS 2, 7, 1, 6, 3
+
+    addps   m4, m6
+    addps   m6, m1
+    addps   m1, m7
+    addps   m7, m2
+    addps   m5, m6
+    SPILL   5, 15
+    addps   m6, m7
+    mulps   m6, [costabs + 16*2]
+    mova    [tmpq+4*8], m6
+    SPILL   1, 10
+    SPILL   0, 14
+
+    mova    m1, [inq]
+    movu    m6, [inq +   72]
+    mova    m3, [inq + 2*72]
+    movu    m5, [inq + 3*72]
+
+    TRANSPOSE4x4PS 1, 6, 3, 5, 0
+
+    addps    m2, m5
+    addps    m5, m3
+    addps    m7, m5
+    addps    m3, m6
+    addps    m6, m1
+    SPILL    7, 8
+    addps    m5, m6
+    SPILL    6, 9
+    addps    m6, m4, SPILLED(12)
+    subps    m6, m2
+    UNSPILL  7, 11
+    SPILL    5, 11
+    subps    m5, m1, m7
+    mulps    m7, [costabs + 16*5]
+    addps    m7, m1
+    mulps    m0, m6, [costabs + 16*6]
+    addps    m0, m5
+    mova     [tmpq+4*24], m0
+    addps    m6, m5
+    mova     [tmpq+4*4], m6
+    addps    m6, m4, m2
+    mulps    m6, [costabs + 16*1]
+    subps    m4, SPILLED(12)
+    mulps    m4, [costabs + 16*8]
+    addps    m2, SPILLED(12)
+    mulps    m2, [costabs + 16*3]
+    subps    m5, m7, m6
+    subps    m5, m2
+    addps    m6, m7
+    addps    m6, m4
+    addps    m7, m2
+    subps    m7, m4
+    mova     [tmpq+4*20], m7
+    mova     m2, [tmpq+4*28]
+    mova     [tmpq+4*28], m5
+    UNSPILL  7, 13
+    subps    m5, m7, m2
+    mulps    m5, [costabs + 16*7]
+    UNSPILL  1, 10
+    mulps    m1, [costabs + 16*2]
+    addps    m4, m3, m2
+    mulps    m4, [costabs + 16*4]
+    addps    m2, m7
+    addps    m7, m3
+    mulps    m7, [costabs]
+    subps    m3, m2
+    mulps    m3, [costabs + 16*2]
+    addps    m2, m7, m5
+    addps    m2, m1
+    SPILL    2, 10
+    addps    m7, m4
+    subps    m7, m1
+    SPILL    7, 12
+    subps    m5, m4
+    subps    m5, m1
+    UNSPILL  0, 14
+    SPILL    5, 13
+    addps    m1, m0, SPILLED(15)
+    subps    m1, SPILLED(8)
+    mova     m4, [costabs + 16*5]
+    mulps    m4, [tmpq]
+    UNSPILL  2, 9
+    addps    m4, m2
+    subps    m2, [tmpq]
+    mulps    m5, m1, [costabs + 16*6]
+    addps    m5, m2
+    SPILL    5, 9
+    addps    m2, m1
+    SPILL    2, 14
+    UNSPILL  5, 15
+    subps    m7, m5, m0
+    addps    m5, SPILLED(8)
+    mulps    m5, [costabs + 16*1]
+    mulps    m7, [costabs + 16*8]
+    addps    m0, SPILLED(8)
+    mulps    m0, [costabs + 16*3]
+    subps    m2, m4, m5
+    subps    m2, m0
+    SPILL    2, 15
+    addps    m5, m4
+    addps    m5, m7
+    addps    m4, m0
+    subps    m4, m7
+    SPILL    4, 8
+    mova     m7, [tmpq+4*16]
+    mova     m2, [tmpq+4*12]
+    addps    m0, m7, m2
+    subps    m0, SPILLED(11)
+    mulps    m0, [costabs + 16*2]
+    addps    m4, m7, SPILLED(11)
+    mulps    m4, [costabs]
+    subps    m7, m2
+    mulps    m7, [costabs + 16*7]
+    addps    m2, SPILLED(11)
+    mulps    m2, [costabs + 16*4]
+    addps    m1, m7, [tmpq+4*8]
+    addps    m1, m4
+    addps    m4, m2
+    subps    m4, [tmpq+4*8]
+    SPILL    4, 11
+    subps    m7, m2
+    subps    m7, [tmpq+4*8]
+    addps    m4, m6, SPILLED(10)
+    subps    m6, SPILLED(10)
+    addps    m2, m5, m1
+    mulps    m2, [costabs + 16*9]
+    subps    m5, m1
+    mulps    m5, [costabs + 16*17]
+    subps    m1, m4, m2
+    addps    m4, m2
+    mulps    m2, m1, [winq+4*36]
+    addps    m2, [bufq+4*36]
+    mova     [outq+1152], m2
+    mulps    m1, [winq+4*32]
+    addps    m1, [bufq+4*32]
+    mova     [outq+1024], m1
+    mulps    m1, m4, [winq+4*116]
+    mova     [bufq+4*36], m1
+    mulps    m4, [winq+4*112]
+    mova     [bufq+4*32], m4
+    addps    m2, m6, m5
+    subps    m6, m5
+    mulps    m1, m6, [winq+4*68]
+    addps    m1, [bufq+4*68]
+    mova     [outq+2176], m1
+    mulps    m6, [winq]
+    addps    m6, [bufq]
+    mova     [outq], m6
+    mulps    m1, m2, [winq+4*148]
+    mova     [bufq+4*68], m1
+    mulps    m2, [winq+4*80]
+    mova     [bufq], m2
+    addps    m5, m3, [tmpq+4*24]
+    mova     m2, [tmpq+4*24]
+    subps    m2, m3
+    mova     m1, SPILLED(9)
+    subps    m1, m0
+    mulps    m1, [costabs + 16*10]
+    addps    m0, SPILLED(9)
+    mulps    m0, [costabs + 16*16]
+    addps    m6, m5, m1
+    subps    m5, m1
+    mulps    m3, m5, [winq+4*40]
+    addps    m3, [bufq+4*40]
+    mova     [outq+1280], m3
+    mulps    m5, [winq+4*28]
+    addps    m5, [bufq+4*28]
+    mova     [outq+896], m5
+    mulps    m1, m6, [winq+4*120]
+    mova     [bufq+4*40], m1
+    mulps    m6, [winq+4*108]
+    mova     [bufq+4*28], m6
+    addps    m1, m2, m0
+    subps    m2, m0
+    mulps    m5, m2, [winq+4*64]
+    addps    m5, [bufq+4*64]
+    mova     [outq+2048], m5
+    mulps    m2, [winq+4*4]
+    addps    m2, [bufq+4*4]
+    mova     [outq+128], m2
+    mulps    m0, m1, [winq+4*144]
+    mova     [bufq+4*64], m0
+    mulps    m1, [winq+4*84]
+    mova     [bufq+4*4], m1
+    mova     m1, [tmpq+4*28]
+    mova     m5, m1
+    addps    m1, SPILLED(13)
+    subps    m5, SPILLED(13)
+    UNSPILL  3, 15
+    addps    m2, m7, m3
+    mulps    m2, [costabs + 16*11]
+    subps    m3, m7
+    mulps    m3, [costabs + 16*15]
+    addps    m0, m2, m1
+    subps    m1, m2
+    SWAP     m0, m2
+    mulps    m6, m1, [winq+4*44]
+    addps    m6, [bufq+4*44]
+    mova     [outq+1408], m6
+    mulps    m1, [winq+4*24]
+    addps    m1, [bufq+4*24]
+    mova     [outq+768], m1
+    mulps    m0, m2, [winq+4*124]
+    mova     [bufq+4*44], m0
+    mulps    m2, [winq+4*104]
+    mova     [bufq+4*24], m2
+    addps    m0, m5, m3
+    subps    m5, m3
+    mulps    m1, m5, [winq+4*60]
+    addps    m1, [bufq+4*60]
+    mova     [outq+1920], m1
+    mulps    m5, [winq+4*8]
+    addps    m5, [bufq+4*8]
+    mova     [outq+256], m5
+    mulps    m1, m0, [winq+4*140]
+    mova     [bufq+4*60], m1
+    mulps    m0, [winq+4*88]
+    mova     [bufq+4*8], m0
+    mova     m1, [tmpq+4*20]
+    addps    m1, SPILLED(12)
+    mova     m2, [tmpq+4*20]
+    subps    m2, SPILLED(12)
+    UNSPILL  7, 8
+    subps    m0, m7, SPILLED(11)
+    addps    m7, SPILLED(11)
+    mulps    m4, m7, [costabs + 16*12]
+    mulps    m0, [costabs + 16*14]
+    addps    m5, m1, m4
+    subps    m1, m4
+    mulps    m7, m1, [winq+4*48]
+    addps    m7, [bufq+4*48]
+    mova     [outq+1536], m7
+    mulps    m1, [winq+4*20]
+    addps    m1, [bufq+4*20]
+    mova     [outq+640], m1
+    mulps    m1, m5, [winq+4*128]
+    mova     [bufq+4*48], m1
+    mulps    m5, [winq+4*100]
+    mova     [bufq+4*20], m5
+    addps    m6, m2, m0
+    subps    m2, m0
+    mulps    m1, m2, [winq+4*56]
+    addps    m1, [bufq+4*56]
+    mova     [outq+1792], m1
+    mulps    m2, [winq+4*12]
+    addps    m2, [bufq+4*12]
+    mova     [outq+384], m2
+    mulps    m0, m6, [winq+4*136]
+    mova    [bufq+4*56], m0
+    mulps    m6, [winq+4*92]
+    mova     [bufq+4*12], m6
+    UNSPILL  0, 14
+    mulps    m0, [costabs + 16*13]
+    mova     m3, [tmpq+4*4]
+    addps    m2, m0, m3
+    subps    m3, m0
+    mulps    m0, m3, [winq+4*52]
+    addps    m0, [bufq+4*52]
+    mova     [outq+1664], m0
+    mulps    m3, [winq+4*16]
+    addps    m3, [bufq+4*16]
+    mova     [outq+512], m3
+    mulps    m0, m2, [winq+4*132]
+    mova     [bufq+4*52], m0
+    mulps    m2, [winq+4*96]
+    mova     [bufq+4*16], m2
+    RET
+%endmacro
+
+INIT_XMM sse
+DEFINE_FOUR_IMDCT
+
+INIT_XMM avx
+DEFINE_FOUR_IMDCT
diff --git a/libavcodec/x86/mpegaudiodec_mmx.c b/libavcodec/x86/mpegaudiodec_mmx.c
index b644615..06ffbca 100644
--- a/libavcodec/x86/mpegaudiodec_mmx.c
+++ b/libavcodec/x86/mpegaudiodec_mmx.c
@@ -24,6 +24,18 @@
 #include "libavcodec/dsputil.h"
 #include "libavcodec/mpegaudiodsp.h"
 
+void ff_imdct36_float_sse(float *out, float *buf, float *in, float *win);
+void ff_imdct36_float_sse2(float *out, float *buf, float *in, float *win);
+void ff_imdct36_float_sse3(float *out, float *buf, float *in, float *win);
+void ff_imdct36_float_ssse3(float *out, float *buf, float *in, float *win);
+void ff_imdct36_float_avx(float *out, float *buf, float *in, float *win);
+void ff_four_imdct36_float_sse(float *out, float *buf, float *in, float *win,
+                               float *tmpbuf);
+void ff_four_imdct36_float_avx(float *out, float *buf, float *in, float *win,
+                               float *tmpbuf);
+
+DECLARE_ALIGNED(16, static float, mdct_win_sse)[2][4][4*40];
+
 #define MACS(rt, ra, rb) rt+=(ra)*(rb)
 #define MLSS(rt, ra, rb) rt-=(ra)*(rb)
 
@@ -147,11 +159,79 @@ static void apply_window_mp3(float *in, float *win, int *unused, float *out,
     *out = sum;
 }
 
+
+#define DECL_IMDCT_BLOCKS(CPU1, CPU2)                                       \
+static void imdct36_blocks_ ## CPU1(float *out, float *buf, float *in,      \
+                               int count, int switch_point, int block_type) \
+{                                                                           \
+    int align_end = count - (count & 3);                                \
+    int j;                                                              \
+    for (j = 0; j < align_end; j+= 4) {                                 \
+        LOCAL_ALIGNED_16(float, tmpbuf, [1024]);                        \
+        float *win = mdct_win_sse[switch_point && j < 4][block_type];   \
+        /* apply window & overlap with previous buffer */               \
+                                                                        \
+        /* select window */                                             \
+        ff_four_imdct36_float_ ## CPU2(out, buf, in, win, tmpbuf);      \
+        in      += 4*18;                                                \
+        buf     += 4*18;                                                \
+        out     += 4;                                                   \
+    }                                                                   \
+    for (; j < count; j++) {                                            \
+        /* apply window & overlap with previous buffer */               \
+                                                                        \
+        /* select window */                                             \
+        int win_idx = (switch_point && j < 2) ? 0 : block_type;         \
+        float *win = ff_mdct_win_float[win_idx + (4 & -(j & 1))];       \
+                                                                        \
+        ff_imdct36_float_ ## CPU1(out, buf, in, win);                   \
+                                                                        \
+        in  += 18;                                                      \
+        buf++;                                                          \
+        out++;                                                          \
+    }                                                                   \
+}
+
+DECL_IMDCT_BLOCKS(sse,sse)
+DECL_IMDCT_BLOCKS(sse2,sse)
+DECL_IMDCT_BLOCKS(sse3,sse)
+DECL_IMDCT_BLOCKS(ssse3,sse)
+DECL_IMDCT_BLOCKS(avx,avx)
+
 void ff_mpadsp_init_mmx(MPADSPContext *s)
 {
     int mm_flags = av_get_cpu_flags();
 
+    int i, j;
+    for (j = 0; j < 4; j++) {
+        for (i = 0; i < 40; i ++) {
+            mdct_win_sse[0][j][4*i    ] = ff_mdct_win_float[j    ][i];
+            mdct_win_sse[0][j][4*i + 1] = ff_mdct_win_float[j + 4][i];
+            mdct_win_sse[0][j][4*i + 2] = ff_mdct_win_float[j    ][i];
+            mdct_win_sse[0][j][4*i + 3] = ff_mdct_win_float[j + 4][i];
+            mdct_win_sse[1][j][4*i    ] = ff_mdct_win_float[0    ][i];
+            mdct_win_sse[1][j][4*i + 1] = ff_mdct_win_float[4    ][i];
+            mdct_win_sse[1][j][4*i + 2] = ff_mdct_win_float[j    ][i];
+            mdct_win_sse[1][j][4*i + 3] = ff_mdct_win_float[j + 4][i];
+        }
+    }
+
     if (mm_flags & AV_CPU_FLAG_SSE2) {
         s->apply_window_float = apply_window_mp3;
     }
+#if HAVE_YASM
+    if (mm_flags & AV_CPU_FLAG_AVX && HAVE_AVX) {
+        s->imdct36_blocks_float = imdct36_blocks_avx;
+#if HAVE_SSE
+    } else if (mm_flags & AV_CPU_FLAG_SSSE3) {
+        s->imdct36_blocks_float = imdct36_blocks_ssse3;
+    } else if (mm_flags & AV_CPU_FLAG_SSE3) {
+        s->imdct36_blocks_float = imdct36_blocks_sse3;
+    } else if (mm_flags & AV_CPU_FLAG_SSE2) {
+        s->imdct36_blocks_float = imdct36_blocks_sse2;
+    } else if (mm_flags & AV_CPU_FLAG_SSE) {
+        s->imdct36_blocks_float = imdct36_blocks_sse;
+#endif /* HAVE_SSE */
+    }
+#endif /* HAVE_YASM */
 }
diff --git a/libavcodec/zmbv.c b/libavcodec/zmbv.c
index 3213480..a36a844 100644
--- a/libavcodec/zmbv.c
+++ b/libavcodec/zmbv.c
@@ -613,7 +613,7 @@ static av_cold int decode_init(AVCodecContext *avctx)
     c->bpp = avctx->bits_per_coded_sample;
 
     // Needed if zlib unused or init aborted before inflateInit
-    memset(&(c->zstream), 0, sizeof(z_stream));
+    memset(&c->zstream, 0, sizeof(z_stream));
 
     avctx->pix_fmt = PIX_FMT_RGB24;
     c->decomp_size = (avctx->width + 255) * 4 * (avctx->height + 64);
@@ -630,7 +630,7 @@ static av_cold int decode_init(AVCodecContext *avctx)
     c->zstream.zalloc = Z_NULL;
     c->zstream.zfree = Z_NULL;
     c->zstream.opaque = Z_NULL;
-    zret = inflateInit(&(c->zstream));
+    zret = inflateInit(&c->zstream);
     if (zret != Z_OK) {
         av_log(avctx, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
         return 1;
@@ -654,7 +654,7 @@ static av_cold int decode_end(AVCodecContext *avctx)
 
     if (c->pic.data[0])
         avctx->release_buffer(avctx, &c->pic);
-    inflateEnd(&(c->zstream));
+    inflateEnd(&c->zstream);
     av_freep(&c->cur);
     av_freep(&c->prev);
 
diff --git a/libavcodec/zmbvenc.c b/libavcodec/zmbvenc.c
index 2230436..75fcffe 100644
--- a/libavcodec/zmbvenc.c
+++ b/libavcodec/zmbvenc.c
@@ -269,7 +269,7 @@ static av_cold int encode_init(AVCodecContext *avctx)
     }
 
     // Needed if zlib unused or init aborted before deflateInit
-    memset(&(c->zstream), 0, sizeof(z_stream));
+    memset(&c->zstream, 0, sizeof(z_stream));
     c->comp_size = avctx->width * avctx->height + 1024 +
         ((avctx->width + ZMBV_BLOCK - 1) / ZMBV_BLOCK) * ((avctx->height + ZMBV_BLOCK - 1) / ZMBV_BLOCK) * 2 + 4;
     if ((c->work_buf = av_malloc(c->comp_size)) == NULL) {
@@ -294,7 +294,7 @@ static av_cold int encode_init(AVCodecContext *avctx)
     c->zstream.zalloc = Z_NULL;
     c->zstream.zfree = Z_NULL;
     c->zstream.opaque = Z_NULL;
-    zret = deflateInit(&(c->zstream), lvl);
+    zret = deflateInit(&c->zstream, lvl);
     if (zret != Z_OK) {
         av_log(avctx, AV_LOG_ERROR, "Inflate init error: %d\n", zret);
         return -1;
@@ -317,7 +317,7 @@ static av_cold int encode_end(AVCodecContext *avctx)
     av_freep(&c->comp_buf);
     av_freep(&c->work_buf);
 
-    deflateEnd(&(c->zstream));
+    deflateEnd(&c->zstream);
     av_freep(&c->prev);
 
     return 0;
diff --git a/libavdevice/bktr.c b/libavdevice/bktr.c
index e6a1e8b..8abe5ef 100644
--- a/libavdevice/bktr.c
+++ b/libavdevice/bktr.c
@@ -292,7 +292,7 @@ static int grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)
 
 
     if (bktr_init(s1->filename, width, height, s->standard,
-            &(s->video_fd), &(s->tuner_fd), -1, 0.0) < 0) {
+                  &s->video_fd, &s->tuner_fd, -1, 0.0) < 0) {
         ret = AVERROR(EIO);
         goto out;
     }
diff --git a/libavdevice/timefilter.c b/libavdevice/timefilter.c
index 332d33b..136661a 100644
--- a/libavdevice/timefilter.c
+++ b/libavdevice/timefilter.c
@@ -69,7 +69,7 @@ double ff_timefilter_update(TimeFilter *self, double system_time, double period)
         loop_error          = system_time - self->cycle_time;
 
         /// update loop
-        self->cycle_time   += FFMAX(self->feedback2_factor, 1.0/(self->count)) * loop_error;
+        self->cycle_time   += FFMAX(self->feedback2_factor, 1.0 / self->count) * loop_error;
         self->clock_period += self->feedback3_factor * loop_error / period;
     }
     return self->cycle_time;
diff --git a/libavdevice/v4l2.c b/libavdevice/v4l2.c
index eb16171..191decd 100644
--- a/libavdevice/v4l2.c
+++ b/libavdevice/v4l2.c
@@ -36,6 +36,7 @@
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/time.h>
+#include <poll.h>
 #if HAVE_SYS_VIDEOIO_H
 #include <sys/videoio.h>
 #else
@@ -48,22 +49,22 @@
 #include "libavutil/parseutils.h"
 #include "libavutil/pixdesc.h"
 #include "libavutil/avstring.h"
+#include "libavutil/mathematics.h"
 
 static const int desired_video_buffers = 256;
 
-enum io_method {
-    io_read,
-    io_mmap,
-    io_userptr
-};
+#define V4L_ALLFORMATS  3
+#define V4L_RAWFORMATS  1
+#define V4L_COMPFORMATS 2
 
 struct video_data {
     AVClass *class;
     int fd;
     int frame_format; /* V4L2_PIX_FMT_* */
-    enum io_method io_method;
     int width, height;
     int frame_size;
+    int timeout;
+    int interlaced;
     int top_field_first;
 
     int buffers;
@@ -71,8 +72,10 @@ struct video_data {
     unsigned int *buf_len;
     char *standard;
     int channel;
-    char *video_size; /**< String describing video size, set by a private option. */
+    char *video_size;   /**< String describing video size,
+                             set by a private option. */
     char *pixel_format; /**< Set by a private option. */
+    int list_format;    /**< Set by a private option. */
     char *framerate;    /**< Set by a private option. */
 };
 
@@ -106,7 +109,7 @@ static struct fmt_map fmt_conversion_table[] = {
     { PIX_FMT_NONE,    CODEC_ID_MJPEG,    V4L2_PIX_FMT_JPEG    },
 };
 
-static int device_open(AVFormatContext *ctx, uint32_t *capabilities)
+static int device_open(AVFormatContext *ctx)
 {
     struct v4l2_capability cap;
     int fd;
@@ -116,65 +119,89 @@ static int device_open(AVFormatContext *ctx, uint32_t *capabilities)
     if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
         flags |= O_NONBLOCK;
     }
+
     fd = open(ctx->filename, flags, 0);
     if (fd < 0) {
+        err = errno;
+
         av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
-                 ctx->filename, strerror(errno));
+               ctx->filename, strerror(err));
 
-        return AVERROR(errno);
+        return AVERROR(err);
     }
 
     res = ioctl(fd, VIDIOC_QUERYCAP, &cap);
-    // ENOIOCTLCMD definition only availble on __KERNEL__
-    if (res < 0 && ((err = errno) == 515)) {
-        av_log(ctx, AV_LOG_ERROR, "QUERYCAP not implemented, probably V4L device but not supporting V4L2\n");
-        close(fd);
-
-        return AVERROR(515);
-    }
     if (res < 0) {
+        err = errno;
         av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
-                 strerror(errno));
-        close(fd);
+               strerror(err));
 
-        return AVERROR(err);
+        goto fail;
     }
-    if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
-        av_log(ctx, AV_LOG_ERROR, "Not a video capture device\n");
-        close(fd);
 
-        return AVERROR(ENODEV);
+    av_log(ctx, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n",
+           fd, cap.capabilities);
+
+    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
+        av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
+        err = ENODEV;
+
+        goto fail;
+    }
+
+    if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
+        av_log(ctx, AV_LOG_ERROR,
+               "The device does not support the streaming I/O method.\n");
+        err = ENOSYS;
+
+        goto fail;
     }
-    *capabilities = cap.capabilities;
 
     return fd;
+
+fail:
+    close(fd);
+    return AVERROR(err);
 }
 
-static int device_init(AVFormatContext *ctx, int *width, int *height, uint32_t pix_fmt)
+static int device_init(AVFormatContext *ctx, int *width, int *height,
+                       uint32_t pix_fmt)
 {
     struct video_data *s = ctx->priv_data;
     int fd = s->fd;
-    struct v4l2_format fmt;
+    struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
+    struct v4l2_pix_format *pix = &fmt.fmt.pix;
+
     int res;
 
-    memset(&fmt, 0, sizeof(struct v4l2_format));
-    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
-    fmt.fmt.pix.width = *width;
-    fmt.fmt.pix.height = *height;
-    fmt.fmt.pix.pixelformat = pix_fmt;
-    fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
+    pix->width = *width;
+    pix->height = *height;
+    pix->pixelformat = pix_fmt;
+    pix->field = V4L2_FIELD_ANY;
+
     res = ioctl(fd, VIDIOC_S_FMT, &fmt);
+
     if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
-        av_log(ctx, AV_LOG_INFO, "The V4L2 driver changed the video from %dx%d to %dx%d\n", *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
+        av_log(ctx, AV_LOG_INFO,
+               "The V4L2 driver changed the video from %dx%d to %dx%d\n",
+               *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
         *width = fmt.fmt.pix.width;
         *height = fmt.fmt.pix.height;
     }
 
     if (pix_fmt != fmt.fmt.pix.pixelformat) {
-        av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver changed the pixel format from 0x%08X to 0x%08X\n", pix_fmt, fmt.fmt.pix.pixelformat);
+        av_log(ctx, AV_LOG_DEBUG,
+               "The V4L2 driver changed the pixel format "
+               "from 0x%08X to 0x%08X\n",
+               pix_fmt, fmt.fmt.pix.pixelformat);
         res = -1;
     }
 
+    if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
+        av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver using the interlaced mode");
+        s->interlaced = 1;
+    }
+
     return res;
 }
 
@@ -237,16 +264,81 @@ static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
     return CODEC_ID_NONE;
 }
 
+#if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
+static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
+{
+    struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
+
+    while(!ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
+        switch (vfse.type) {
+        case V4L2_FRMSIZE_TYPE_DISCRETE:
+            av_log(ctx, AV_LOG_INFO, " %ux%u",
+                   vfse.discrete.width, vfse.discrete.height);
+        break;
+        case V4L2_FRMSIZE_TYPE_CONTINUOUS:
+        case V4L2_FRMSIZE_TYPE_STEPWISE:
+            av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
+                   vfse.stepwise.min_width,
+                   vfse.stepwise.max_width,
+                   vfse.stepwise.step_width,
+                   vfse.stepwise.min_height,
+                   vfse.stepwise.max_height,
+                   vfse.stepwise.step_height);
+        }
+        vfse.index++;
+    }
+}
+#endif
+
+static void list_formats(AVFormatContext *ctx, int fd, int type)
+{
+    struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
+
+    while(!ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
+        enum CodecID codec_id = fmt_v4l2codec(vfd.pixelformat);
+        enum PixelFormat pix_fmt = fmt_v4l2ff(vfd.pixelformat, codec_id);
+
+        vfd.index++;
+
+        if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
+            type & V4L_RAWFORMATS) {
+            const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
+            av_log(ctx, AV_LOG_INFO, "R : %9s : %20s :",
+                   fmt_name ? fmt_name : "Unsupported",
+                   vfd.description);
+        } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
+                   type & V4L_COMPFORMATS) {
+            AVCodec *codec = avcodec_find_encoder(codec_id);
+            av_log(ctx, AV_LOG_INFO, "C : %9s : %20s :",
+                   codec ? codec->name : "Unsupported",
+                   vfd.description);
+        } else {
+            continue;
+        }
+
+#ifdef V4L2_FMT_FLAG_EMULATED
+        if (vfd.flags & V4L2_FMT_FLAG_EMULATED) {
+            av_log(ctx, AV_LOG_WARNING, "%s", "Emulated");
+            continue;
+        }
+#endif
+#if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
+        list_framesizes(ctx, fd, vfd.pixelformat);
+#endif
+        av_log(ctx, AV_LOG_INFO, "\n");
+    }
+}
+
 static int mmap_init(AVFormatContext *ctx)
 {
-    struct video_data *s = ctx->priv_data;
-    struct v4l2_requestbuffers req;
     int i, res;
+    struct video_data *s = ctx->priv_data;
+    struct v4l2_requestbuffers req = {
+        .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
+        .count  = desired_video_buffers,
+        .memory = V4L2_MEMORY_MMAP
+    };
 
-    memset(&req, 0, sizeof(struct v4l2_requestbuffers));
-    req.count = desired_video_buffers;
-    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
-    req.memory = V4L2_MEMORY_MMAP;
     res = ioctl(s->fd, VIDIOC_REQBUFS, &req);
     if (res < 0) {
         if (errno == EINVAL) {
@@ -279,12 +371,12 @@ static int mmap_init(AVFormatContext *ctx)
     }
 
     for (i = 0; i < req.count; i++) {
-        struct v4l2_buffer buf;
+        struct v4l2_buffer buf = {
+            .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
+            .index  = i,
+            .memory = V4L2_MEMORY_MMAP
+        };
 
-        memset(&buf, 0, sizeof(struct v4l2_buffer));
-        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
-        buf.memory = V4L2_MEMORY_MMAP;
-        buf.index = i;
         res = ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
         if (res < 0) {
             av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
@@ -294,12 +386,16 @@ static int mmap_init(AVFormatContext *ctx)
 
         s->buf_len[i] = buf.length;
         if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
-            av_log(ctx, AV_LOG_ERROR, "Buffer len [%d] = %d != %d\n", i, s->buf_len[i], s->frame_size);
+            av_log(ctx, AV_LOG_ERROR,
+                   "Buffer len [%d] = %d != %d\n",
+                   i, s->buf_len[i], s->frame_size);
 
             return -1;
         }
-        s->buf_start[i] = mmap (NULL, buf.length,
-                        PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, buf.m.offset);
+        s->buf_start[i] = mmap(NULL, buf.length,
+                               PROT_READ | PROT_WRITE, MAP_SHARED,
+                               s->fd, buf.m.offset);
+
         if (s->buf_start[i] == MAP_FAILED) {
             av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
 
@@ -310,22 +406,15 @@ static int mmap_init(AVFormatContext *ctx)
     return 0;
 }
 
-static int read_init(AVFormatContext *ctx)
-{
-    return -1;
-}
-
 static void mmap_release_buffer(AVPacket *pkt)
 {
-    struct v4l2_buffer buf;
+    struct v4l2_buffer buf = { 0 };
     int res, fd;
     struct buff_data *buf_descriptor = pkt->priv;
 
-    if (pkt->data == NULL) {
-         return;
-    }
+    if (pkt->data == NULL)
+        return;
 
-    memset(&buf, 0, sizeof(struct v4l2_buffer));
     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
     buf.memory = V4L2_MEMORY_MMAP;
     buf.index = buf_descriptor->index;
@@ -333,9 +422,10 @@ static void mmap_release_buffer(AVPacket *pkt)
     av_free(buf_descriptor);
 
     res = ioctl(fd, VIDIOC_QBUF, &buf);
-    if (res < 0) {
-        av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
-    }
+    if (res < 0)
+        av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
+               strerror(errno));
+
     pkt->data = NULL;
     pkt->size = 0;
 }
@@ -343,13 +433,20 @@ static void mmap_release_buffer(AVPacket *pkt)
 static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
 {
     struct video_data *s = ctx->priv_data;
-    struct v4l2_buffer buf;
+    struct v4l2_buffer buf = {
+        .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
+        .memory = V4L2_MEMORY_MMAP
+    };
     struct buff_data *buf_descriptor;
+    struct pollfd p = { .fd = s->fd, .events = POLLIN };
     int res;
 
-    memset(&buf, 0, sizeof(struct v4l2_buffer));
-    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
-    buf.memory = V4L2_MEMORY_MMAP;
+    res = poll(&p, 1, s->timeout);
+    if (res < 0)
+        return AVERROR(errno);
+
+    if (!(p.revents & (POLLIN | POLLERR | POLLHUP)))
+        return AVERROR(EAGAIN);
 
     /* FIXME: Some special treatment might be needed in case of loss of signal... */
     while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
@@ -359,13 +456,16 @@ static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
 
             return AVERROR(EAGAIN);
         }
-        av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", strerror(errno));
+        av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n",
+               strerror(errno));
 
         return AVERROR(errno);
     }
     assert (buf.index < s->buffers);
     if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
-        av_log(ctx, AV_LOG_ERROR, "The v4l2 frame is %d bytes, but %d bytes are expected\n", buf.bytesused, s->frame_size);
+        av_log(ctx, AV_LOG_ERROR,
+               "The v4l2 frame is %d bytes, but %d bytes are expected\n",
+               buf.bytesused, s->frame_size);
 
         return AVERROR_INVALIDDATA;
     }
@@ -392,11 +492,6 @@ static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
     return s->buf_len[buf.index];
 }
 
-static int read_frame(AVFormatContext *ctx, AVPacket *pkt)
-{
-    return -1;
-}
-
 static int mmap_start(AVFormatContext *ctx)
 {
     struct video_data *s = ctx->priv_data;
@@ -404,16 +499,16 @@ static int mmap_start(AVFormatContext *ctx)
     int i, res;
 
     for (i = 0; i < s->buffers; i++) {
-        struct v4l2_buffer buf;
-
-        memset(&buf, 0, sizeof(struct v4l2_buffer));
-        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
-        buf.memory = V4L2_MEMORY_MMAP;
-        buf.index  = i;
+        struct v4l2_buffer buf = {
+            .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,
+            .index  = i,
+            .memory = V4L2_MEMORY_MMAP
+        };
 
         res = ioctl(s->fd, VIDIOC_QBUF, &buf);
         if (res < 0) {
-            av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
+            av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
+                   strerror(errno));
 
             return AVERROR(errno);
         }
@@ -422,7 +517,8 @@ static int mmap_start(AVFormatContext *ctx)
     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
     res = ioctl(s->fd, VIDIOC_STREAMON, &type);
     if (res < 0) {
-        av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", strerror(errno));
+        av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n",
+               strerror(errno));
 
         return AVERROR(errno);
     }
@@ -450,22 +546,23 @@ static void mmap_close(struct video_data *s)
 static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
 {
     struct video_data *s = s1->priv_data;
-    struct v4l2_input input;
-    struct v4l2_standard standard;
+    struct v4l2_input input = { 0 };
+    struct v4l2_standard standard = { 0 };
     struct v4l2_streamparm streamparm = { 0 };
     struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
+    AVRational framerate_q = { 0 };
     int i, ret;
-    AVRational framerate_q;
 
     streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
 
-    if (s->framerate && (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
-        av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", s->framerate);
+    if (s->framerate &&
+        (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
+        av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
+               s->framerate);
         return ret;
     }
 
     /* set tv video input */
-    memset (&input, 0, sizeof (input));
     input.index = s->channel;
     if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
         av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
@@ -475,7 +572,8 @@ static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
     av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
             s->channel, input.name);
     if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
-        av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set input(%d) failed\n",
+        av_log(s1, AV_LOG_ERROR,
+               "The V4L2 driver ioctl set input(%d) failed\n",
                 s->channel);
         return AVERROR(EIO);
     }
@@ -484,11 +582,11 @@ static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
         av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
                s->standard);
         /* set tv standard */
-        memset (&standard, 0, sizeof (standard));
         for(i=0;;i++) {
             standard.index = i;
             if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
-                av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
+                av_log(s1, AV_LOG_ERROR,
+                       "The V4L2 driver ioctl set standard(%s) failed\n",
                        s->standard);
                 return AVERROR(EIO);
             }
@@ -498,10 +596,12 @@ static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
             }
         }
 
-        av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
+        av_log(s1, AV_LOG_DEBUG,
+               "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
                s->standard, (uint64_t)standard.id);
         if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
-            av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
+            av_log(s1, AV_LOG_ERROR,
+                   "The V4L2 driver ioctl set standard(%s) failed\n",
                    s->standard);
             return AVERROR(EIO);
         }
@@ -512,6 +612,7 @@ static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
                framerate_q.den, framerate_q.num);
         tpf->numerator   = framerate_q.den;
         tpf->denominator = framerate_q.num;
+
         if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
             av_log(s1, AV_LOG_ERROR,
                    "ioctl set time per frame(%d/%d) failed\n",
@@ -522,20 +623,25 @@ static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
         if (framerate_q.num != tpf->denominator ||
             framerate_q.den != tpf->numerator) {
             av_log(s1, AV_LOG_INFO,
-                   "The driver changed the time per frame from %d/%d to %d/%d\n",
+                   "The driver changed the time per frame from "
+                   "%d/%d to %d/%d\n",
                    framerate_q.den, framerate_q.num,
                    tpf->numerator, tpf->denominator);
         }
     } else {
-        /* if timebase value is not set, read the timebase value from the driver */
         if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
-            av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", strerror(errno));
+            av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",
+                   strerror(errno));
             return AVERROR(errno);
         }
     }
     s1->streams[0]->codec->time_base.den = tpf->denominator;
     s1->streams[0]->codec->time_base.num = tpf->numerator;
 
+    s->timeout = 100 +
+        av_rescale_q(1, s1->streams[0]->codec->time_base,
+                        (AVRational){1, 1000});
+
     return 0;
 }
 
@@ -563,6 +669,7 @@ static uint32_t device_try_init(AVFormatContext *s1,
             }
         }
     }
+
     if (desired_format != 0) {
         *codec_id = fmt_v4l2codec(desired_format);
         assert(*codec_id != CODEC_ID_NONE);
@@ -576,7 +683,7 @@ static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
     struct video_data *s = s1->priv_data;
     AVStream *st;
     int res = 0;
-    uint32_t desired_format, capabilities;
+    uint32_t desired_format;
     enum CodecID codec_id;
     enum PixelFormat pix_fmt = PIX_FMT_NONE;
 
@@ -585,42 +692,66 @@ static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
         res = AVERROR(ENOMEM);
         goto out;
     }
-    avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
 
-    if (s->video_size && (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
-        av_log(s1, AV_LOG_ERROR, "Could not parse video size '%s'.\n", s->video_size);
+    s->fd = device_open(s1);
+    if (s->fd < 0) {
+        res = s->fd;
         goto out;
     }
-    if (s->pixel_format && (pix_fmt = av_get_pix_fmt(s->pixel_format)) == PIX_FMT_NONE) {
-        av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n", s->pixel_format);
-        res = AVERROR(EINVAL);
+
+    if (s->list_format) {
+        list_formats(s1, s->fd, s->list_format);
+        res = AVERROR_EXIT;
         goto out;
     }
 
-    capabilities = 0;
-    s->fd = device_open(s1, &capabilities);
-    if (s->fd < 0) {
-        res = AVERROR(EIO);
+    avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
+
+    if (s->video_size &&
+        (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
+        av_log(s1, AV_LOG_ERROR, "Could not parse video size '%s'.\n",
+               s->video_size);
         goto out;
     }
-    av_log(s1, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n", s->fd, capabilities);
+
+    if (s->pixel_format) {
+        AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
+
+        if (codec)
+            s1->video_codec_id = codec->id;
+
+        pix_fmt = av_get_pix_fmt(s->pixel_format);
+
+        if (pix_fmt == PIX_FMT_NONE && !codec) {
+            av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
+                   s->pixel_format);
+
+            res = AVERROR(EINVAL);
+            goto out;
+        }
+    }
 
     if (!s->width && !s->height) {
         struct v4l2_format fmt;
 
-        av_log(s1, AV_LOG_VERBOSE, "Querying the device for the current frame size\n");
+        av_log(s1, AV_LOG_VERBOSE,
+               "Querying the device for the current frame size\n");
         fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
         if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
-            av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", strerror(errno));
+            av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
+                   strerror(errno));
             res = AVERROR(errno);
             goto out;
         }
+
         s->width  = fmt.fmt.pix.width;
         s->height = fmt.fmt.pix.height;
-        av_log(s1, AV_LOG_VERBOSE, "Setting frame size to %dx%d\n", s->width, s->height);
+        av_log(s1, AV_LOG_VERBOSE,
+               "Setting frame size to %dx%d\n", s->width, s->height);
     }
 
-    desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height, &codec_id);
+    desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height,
+                                     &codec_id);
     if (desired_format == 0) {
         av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
                "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
@@ -629,35 +760,32 @@ static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
         res = AVERROR(EIO);
         goto out;
     }
+
     if ((res = av_image_check_size(s->width, s->height, 0, s1) < 0))
         goto out;
+
     s->frame_format = desired_format;
 
     if ((res = v4l2_set_parameters(s1, ap) < 0))
         goto out;
 
     st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
-    s->frame_size = avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
-    if (capabilities & V4L2_CAP_STREAMING) {
-        s->io_method = io_mmap;
-        res = mmap_init(s1);
-        if (res == 0) {
-            res = mmap_start(s1);
-        }
-    } else {
-        s->io_method = io_read;
-        res = read_init(s1);
-    }
-    if (res < 0) {
-        close(s->fd);
+    s->frame_size =
+        avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
 
-        res = AVERROR(EIO);
+    if ((res = mmap_init(s1)) ||
+        (res = mmap_start(s1)) < 0) {
+        close(s->fd);
         goto out;
     }
+
     s->top_field_first = first_field(s->fd);
 
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id = codec_id;
+    if (codec_id == CODEC_ID_RAWVIDEO)
+        st->codec->codec_tag =
+            avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
     st->codec->width = s->width;
     st->codec->height = s->height;
     st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
@@ -669,26 +797,17 @@ out:
 static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
 {
     struct video_data *s = s1->priv_data;
+    AVFrame *frame = s1->streams[0]->codec->coded_frame;
     int res;
 
-    if (s->io_method == io_mmap) {
-        av_init_packet(pkt);
-        res = mmap_read_frame(s1, pkt);
-    } else if (s->io_method == io_read) {
-        if (av_new_packet(pkt, s->frame_size) < 0)
-            return AVERROR(EIO);
-
-        res = read_frame(s1, pkt);
-    } else {
-        return AVERROR(EIO);
-    }
-    if (res < 0) {
+    av_init_packet(pkt);
+    if ((res = mmap_read_frame(s1, pkt)) < 0) {
         return res;
     }
 
-    if (s1->streams[0]->codec->coded_frame) {
-        s1->streams[0]->codec->coded_frame->interlaced_frame = 1;
-        s1->streams[0]->codec->coded_frame->top_field_first = s->top_field_first;
+    if (frame && s->interlaced) {
+        frame->interlaced_frame = 1;
+        frame->top_field_first = s->top_field_first;
     }
 
     return pkt->size;
@@ -698,9 +817,7 @@ static int v4l2_read_close(AVFormatContext *s1)
 {
     struct video_data *s = s1->priv_data;
 
-    if (s->io_method == io_mmap) {
-        mmap_close(s);
-    }
+    mmap_close(s);
 
     close(s->fd);
     return 0;
@@ -709,11 +826,16 @@ static int v4l2_read_close(AVFormatContext *s1)
 #define OFFSET(x) offsetof(struct video_data, x)
 #define DEC AV_OPT_FLAG_DECODING_PARAM
 static const AVOption options[] = {
-    { "standard", "", offsetof(struct video_data, standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
-    { "channel",  "", offsetof(struct video_data, channel),  AV_OPT_TYPE_INT,    {.dbl = 0 }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
-    { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
-    { "pixel_format", "", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
-    { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
+    { "standard",     "TV standard, used only by analog frame grabber",            OFFSET(standard),     AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0,       DEC },
+    { "channel",      "TV channel, used only by frame grabber",                    OFFSET(channel),      AV_OPT_TYPE_INT,    {.dbl = 0 },    0, INT_MAX, DEC },
+    { "video_size",   "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size),   AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
+    { "pixel_format", "Preferred pixel format",                                    OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
+    { "input_format", "Preferred pixel format (for raw video) or codec name",      OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
+    { "framerate",    "",                                                          OFFSET(framerate),    AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       DEC },
+    { "list_formats", "List available formats and exit",                           OFFSET(list_format),  AV_OPT_TYPE_INT,    {.dbl = 0 },  0, INT_MAX, DEC, "list_formats" },
+    { "all",          "Show all available formats",                                OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.dbl = V4L_ALLFORMATS  },    0, INT_MAX, DEC, "list_formats" },
+    { "raw",          "Show only non-compressed formats",                          OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.dbl = V4L_RAWFORMATS  },    0, INT_MAX, DEC, "list_formats" },
+    { "compressed",   "Show only compressed formats",                              OFFSET(list_format),  AV_OPT_TYPE_CONST,  {.dbl = V4L_COMPFORMATS },    0, INT_MAX, DEC, "list_formats" },
     { NULL },
 };
 
diff --git a/libavfilter/avfilter.h b/libavfilter/avfilter.h
index 70efc5c..cffcfca 100644
--- a/libavfilter/avfilter.h
+++ b/libavfilter/avfilter.h
@@ -164,6 +164,7 @@ static inline void avfilter_copy_buffer_ref_props(AVFilterBufferRef *dst, AVFilt
     switch (src->type) {
     case AVMEDIA_TYPE_VIDEO: *dst->video = *src->video; break;
     case AVMEDIA_TYPE_AUDIO: *dst->audio = *src->audio; break;
+    default: break;
     }
 }
 
diff --git a/libavfilter/vf_drawtext.c b/libavfilter/vf_drawtext.c
index 060c3a4..dcde542 100644
--- a/libavfilter/vf_drawtext.c
+++ b/libavfilter/vf_drawtext.c
@@ -429,7 +429,7 @@ static av_cold void uninit(AVFilterContext *ctx)
 
 static inline int is_newline(uint32_t c)
 {
-    return (c == '\n' || c == '\r' || c == '\f' || c == '\v');
+    return c == '\n' || c == '\r' || c == '\f' || c == '\v';
 }
 
 static int dtext_prepare_text(AVFilterContext *ctx)
diff --git a/libavfilter/vsrc_buffer.c b/libavfilter/vsrc_buffer.c
index 7ef19a1..178b3e6 100644
--- a/libavfilter/vsrc_buffer.c
+++ b/libavfilter/vsrc_buffer.c
@@ -36,6 +36,12 @@ typedef struct {
     AVRational        pixel_aspect;
 } BufferSourceContext;
 
+#define CHECK_PARAM_CHANGE(s, c, width, height, format)\
+    if (c->w != width || c->h != height || c->pix_fmt != format) {\
+        av_log(s, AV_LOG_ERROR, "Changing frame properties on the fly is not supported.\n");\
+        return AVERROR(EINVAL);\
+    }
+
 int av_vsrc_buffer_add_frame(AVFilterContext *buffer_filter, AVFrame *frame,
                              int64_t pts, AVRational pixel_aspect)
 {
@@ -49,6 +55,8 @@ int av_vsrc_buffer_add_frame(AVFilterContext *buffer_filter, AVFrame *frame,
         //return -1;
     }
 
+    CHECK_PARAM_CHANGE(buffer_filter, c, frame->width, frame->height, frame->format);
+
     c->buf = avfilter_get_video_buffer(buffer_filter->outputs[0], AV_PERM_WRITE,
                                        c->w, c->h);
     av_image_copy(c->buf->data, c->buf->linesize, frame->data, frame->linesize,
@@ -73,6 +81,8 @@ int av_buffersrc_buffer(AVFilterContext *s, AVFilterBufferRef *buf)
         return AVERROR(EINVAL);
     }
 
+    CHECK_PARAM_CHANGE(s, c, buf->video->w, buf->video->h, buf->format);
+
     c->buf = buf;
 
     return 0;
@@ -147,7 +157,7 @@ static int request_frame(AVFilterLink *link)
 static int poll_frame(AVFilterLink *link)
 {
     BufferSourceContext *c = link->src->priv;
-    return !!(c->buf);
+    return !!c->buf;
 }
 
 AVFilter avfilter_vsrc_buffer = {
diff --git a/libavformat/Makefile b/libavformat/Makefile
index de44050..3902e89 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -22,6 +22,7 @@ OBJS-$(CONFIG_AAC_DEMUXER)               += aacdec.o rawdec.o
 OBJS-$(CONFIG_AC3_DEMUXER)               += ac3dec.o rawdec.o
 OBJS-$(CONFIG_AC3_MUXER)                 += rawenc.o
 OBJS-$(CONFIG_ADX_DEMUXER)               += adxdec.o
+OBJS-$(CONFIG_ADX_MUXER)                 += rawenc.o
 OBJS-$(CONFIG_ADTS_MUXER)                += adtsenc.o
 OBJS-$(CONFIG_AEA_DEMUXER)               += aea.o pcm.o
 OBJS-$(CONFIG_AIFF_DEMUXER)              += aiffdec.o riff.o pcm.o
@@ -348,6 +349,8 @@ OBJS-$(CONFIG_TCP_PROTOCOL)              += tcp.o
 OBJS-$(CONFIG_TLS_PROTOCOL)              += tls.o
 OBJS-$(CONFIG_UDP_PROTOCOL)              += udp.o
 
+SKIPHEADERS-$(CONFIG_NETWORK)            += network.h rtsp.h
+
 EXAMPLES  = metadata output
 TESTPROGS = seek
 TOOLS     = pktdumper probetest
diff --git a/libavformat/adxdec.c b/libavformat/adxdec.c
index dca9748..ab11d83 100644
--- a/libavformat/adxdec.c
+++ b/libavformat/adxdec.c
@@ -109,4 +109,5 @@ AVInputFormat ff_adx_demuxer = {
     .read_packet    = adx_read_packet,
     .extensions     = "adx",
     .value          = CODEC_ID_ADPCM_ADX,
+    .flags          = AVFMT_GENERIC_INDEX,
 };
diff --git a/libavformat/allformats.c b/libavformat/allformats.c
index 1debddb..523b113 100644
--- a/libavformat/allformats.c
+++ b/libavformat/allformats.c
@@ -52,7 +52,7 @@ void av_register_all(void)
     REGISTER_DEMUXER  (AAC, aac);
     REGISTER_MUXDEMUX (AC3, ac3);
     REGISTER_MUXER    (ADTS, adts);
-    REGISTER_DEMUXER  (ADX, adx);
+    REGISTER_MUXDEMUX (ADX, adx);
     REGISTER_DEMUXER  (AEA, aea);
     REGISTER_MUXDEMUX (AIFF, aiff);
     REGISTER_MUXDEMUX (AMR, amr);
diff --git a/libavformat/avio.c b/libavformat/avio.c
index 4750a9d..ee4dfb6 100644
--- a/libavformat/avio.c
+++ b/libavformat/avio.c
@@ -129,7 +129,7 @@ static int url_alloc_for_protocol (URLContext **puc, struct URLProtocol *up,
     int err;
 
 #if CONFIG_NETWORK
-    if (!ff_network_init())
+    if (up->flags & URL_PROTOCOL_FLAG_NETWORK && !ff_network_init())
         return AVERROR(EIO);
 #endif
     uc = av_mallocz(sizeof(URLContext) + strlen(filename) + 1);
@@ -159,7 +159,8 @@ static int url_alloc_for_protocol (URLContext **puc, struct URLProtocol *up,
  fail:
     *puc = NULL;
 #if CONFIG_NETWORK
-    ff_network_close();
+    if (up->flags & URL_PROTOCOL_FLAG_NETWORK)
+        ff_network_close();
 #endif
     return err;
 }
@@ -380,7 +381,8 @@ int ffurl_close(URLContext *h)
     if (h->is_connected && h->prot->url_close)
         ret = h->prot->url_close(h);
 #if CONFIG_NETWORK
-    ff_network_close();
+    if (h->prot->flags & URL_PROTOCOL_FLAG_NETWORK)
+        ff_network_close();
 #endif
     if (h->prot->priv_data_size) {
         if (h->prot->priv_data_class)
diff --git a/libavformat/avio.h b/libavformat/avio.h
index dec2a5e..e73264f 100644
--- a/libavformat/avio.h
+++ b/libavformat/avio.h
@@ -146,6 +146,7 @@ typedef struct URLContext {
 } URLContext;
 
 #define URL_PROTOCOL_FLAG_NESTED_SCHEME 1 /*< The protocol name can be the first part of a nested protocol scheme */
+#define URL_PROTOCOL_FLAG_NETWORK       2 /*< The protocol uses network */
 
 /**
  * @deprecated This struct is to be made private. Use the higher-level
diff --git a/libavformat/aviobuf.c b/libavformat/aviobuf.c
index 898f35d..6cd2cef 100644
--- a/libavformat/aviobuf.c
+++ b/libavformat/aviobuf.c
@@ -168,7 +168,7 @@ static void flush_buffer(AVIOContext *s)
 
 void avio_w8(AVIOContext *s, int b)
 {
-    *(s->buf_ptr)++ = b;
+    *s->buf_ptr++ = b;
     if (s->buf_ptr >= s->buf_end)
         flush_buffer(s);
 }
@@ -565,6 +565,10 @@ static void fill_buffer(AVIOContext *s)
     int len= s->buffer_size - (dst - s->buffer);
     int max_buffer_size = s->max_packet_size ? s->max_packet_size : IO_BUFFER_SIZE;
 
+    /* can't fill the buffer without read_packet, just set EOF if appropiate */
+    if (!s->read_packet && s->buf_ptr >= s->buf_end)
+        s->eof_reached = 1;
+
     /* no need to do anything if EOF already reached */
     if (s->eof_reached)
         return;
diff --git a/libavformat/electronicarts.c b/libavformat/electronicarts.c
index 0facc8a..01ba479 100644
--- a/libavformat/electronicarts.c
+++ b/libavformat/electronicarts.c
@@ -434,6 +434,11 @@ static int ea_read_header(AVFormatContext *s,
             ea->audio_codec = 0;
             return 1;
         }
+        if (ea->bytes <= 0) {
+            av_log(s, AV_LOG_ERROR, "Invalid number of bytes per sample: %d\n", ea->bytes);
+            ea->audio_codec = CODEC_ID_NONE;
+            return 1;
+        }
 
         /* initialize the audio decoder stream */
         st = avformat_new_stream(s, NULL);
diff --git a/libavformat/flvdec.c b/libavformat/flvdec.c
index 4f1c805..2f770b3 100644
--- a/libavformat/flvdec.c
+++ b/libavformat/flvdec.c
@@ -441,7 +441,7 @@ static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
     int ret, i, type, size, flags, is_audio;
     int64_t next, pos;
     int64_t dts, pts = AV_NOPTS_VALUE;
-    int sample_rate, channels;
+    int sample_rate = 0, channels = 0;
     AVStream *st = NULL;
 
  for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
diff --git a/libavformat/gopher.c b/libavformat/gopher.c
index c033861..a149f7f 100644
--- a/libavformat/gopher.c
+++ b/libavformat/gopher.c
@@ -121,4 +121,5 @@ URLProtocol ff_gopher_protocol = {
     .url_write      = gopher_write,
     .url_close      = gopher_close,
     .priv_data_size = sizeof(GopherContext),
+    .flags          = URL_PROTOCOL_FLAG_NETWORK,
 };
diff --git a/libavformat/http.c b/libavformat/http.c
index 7badf72..eea8ded 100644
--- a/libavformat/http.c
+++ b/libavformat/http.c
@@ -565,6 +565,7 @@ URLProtocol ff_http_protocol = {
     .url_get_file_handle = http_get_file_handle,
     .priv_data_size      = sizeof(HTTPContext),
     .priv_data_class     = &http_context_class,
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
 #endif
 #if CONFIG_HTTPS_PROTOCOL
@@ -578,6 +579,7 @@ URLProtocol ff_https_protocol = {
     .url_get_file_handle = http_get_file_handle,
     .priv_data_size      = sizeof(HTTPContext),
     .priv_data_class     = &https_context_class,
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
 #endif
 
@@ -693,5 +695,6 @@ URLProtocol ff_httpproxy_protocol = {
     .url_close           = http_proxy_close,
     .url_get_file_handle = http_get_file_handle,
     .priv_data_size      = sizeof(HTTPContext),
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
 #endif
diff --git a/libavformat/ipmovie.c b/libavformat/ipmovie.c
index 4bd3580..daa44b1 100644
--- a/libavformat/ipmovie.c
+++ b/libavformat/ipmovie.c
@@ -89,6 +89,7 @@ typedef struct IPMVEContext {
     int64_t video_pts;
     uint32_t     palette[256];
     int          has_palette;
+    int          changed;
 
     unsigned int audio_bits;
     unsigned int audio_channels;
@@ -116,6 +117,11 @@ static int load_ipmovie_packet(IPMVEContext *s, AVIOContext *pb,
     int chunk_type;
 
     if (s->audio_chunk_offset) {
+        if (s->audio_type == CODEC_ID_NONE) {
+            av_log(NULL, AV_LOG_ERROR, "Can not read audio packet before"
+                   "audio codec is known\n");
+                return CHUNK_BAD;
+        }
 
         /* adjust for PCM audio by skipping chunk header */
         if (s->audio_type != CODEC_ID_INTERPLAY_DPCM) {
@@ -138,7 +144,7 @@ static int load_ipmovie_packet(IPMVEContext *s, AVIOContext *pb,
             (s->audio_chunk_size / s->audio_channels / (s->audio_bits / 8));
         else
             s->audio_frame_count +=
-                (s->audio_chunk_size - 6) / s->audio_channels;
+                (s->audio_chunk_size - 6 - s->audio_channels) / s->audio_channels;
 
         av_dlog(NULL, "sending audio frame with pts %"PRId64" (%d audio frames)\n",
                 pkt->pts, s->audio_frame_count);
@@ -163,6 +169,10 @@ static int load_ipmovie_packet(IPMVEContext *s, AVIOContext *pb,
             }
         }
 
+        if (s->changed) {
+            ff_add_param_change(pkt, 0, 0, 0, s->video_width, s->video_height);
+            s->changed = 0;
+        }
         pkt->pos= s->decode_map_chunk_offset;
         avio_seek(pb, s->decode_map_chunk_offset, SEEK_SET);
         s->decode_map_chunk_offset = 0;
@@ -218,6 +228,7 @@ static int process_ipmovie_chunk(IPMVEContext *s, AVIOContext *pb,
     int first_color, last_color;
     int audio_flags;
     unsigned char r, g, b;
+    unsigned int width, height;
 
     /* see if there are any pending packets */
     chunk_type = load_ipmovie_packet(s, pb, pkt);
@@ -374,8 +385,16 @@ static int process_ipmovie_chunk(IPMVEContext *s, AVIOContext *pb,
                 chunk_type = CHUNK_BAD;
                 break;
             }
-            s->video_width = AV_RL16(&scratch[0]) * 8;
-            s->video_height = AV_RL16(&scratch[2]) * 8;
+            width  = AV_RL16(&scratch[0]) * 8;
+            height = AV_RL16(&scratch[2]) * 8;
+            if (width != s->video_width) {
+                s->video_width = width;
+                s->changed++;
+            }
+            if (height != s->video_height) {
+                s->video_height = height;
+                s->changed++;
+            }
             if (opcode_version < 2 || !AV_RL16(&scratch[6])) {
                 s->video_bpp = 8;
             } else {
diff --git a/libavformat/librtmp.c b/libavformat/librtmp.c
index c04c833..2d028b0 100644
--- a/libavformat/librtmp.c
+++ b/libavformat/librtmp.c
@@ -162,6 +162,7 @@ URLProtocol ff_rtmp_protocol = {
     .url_read_seek       = rtmp_read_seek,
     .url_get_file_handle = rtmp_get_file_handle,
     .priv_data_size      = sizeof(RTMP),
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
 
 URLProtocol ff_rtmpt_protocol = {
@@ -174,6 +175,7 @@ URLProtocol ff_rtmpt_protocol = {
     .url_read_seek       = rtmp_read_seek,
     .url_get_file_handle = rtmp_get_file_handle,
     .priv_data_size      = sizeof(RTMP),
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
 
 URLProtocol ff_rtmpe_protocol = {
@@ -186,6 +188,7 @@ URLProtocol ff_rtmpe_protocol = {
     .url_read_seek       = rtmp_read_seek,
     .url_get_file_handle = rtmp_get_file_handle,
     .priv_data_size      = sizeof(RTMP),
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
 
 URLProtocol ff_rtmpte_protocol = {
@@ -198,6 +201,7 @@ URLProtocol ff_rtmpte_protocol = {
     .url_read_seek       = rtmp_read_seek,
     .url_get_file_handle = rtmp_get_file_handle,
     .priv_data_size      = sizeof(RTMP),
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
 
 URLProtocol ff_rtmps_protocol = {
@@ -210,4 +214,5 @@ URLProtocol ff_rtmps_protocol = {
     .url_read_seek       = rtmp_read_seek,
     .url_get_file_handle = rtmp_get_file_handle,
     .priv_data_size      = sizeof(RTMP),
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
diff --git a/libavformat/matroskadec.c b/libavformat/matroskadec.c
index 2684d6e..e5fbd43 100644
--- a/libavformat/matroskadec.c
+++ b/libavformat/matroskadec.c
@@ -1188,7 +1188,6 @@ static int matroska_parse_seekhead_entry(MatroskaDemuxContext *matroska, int idx
 static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
 {
     EbmlList *seekhead_list = &matroska->seekhead;
-    MatroskaSeekhead *seekhead = seekhead_list->elem;
     int64_t before_pos = avio_tell(matroska->ctx->pb);
     int i;
 
@@ -1198,6 +1197,7 @@ static void matroska_execute_seekhead(MatroskaDemuxContext *matroska)
         return;
 
     for (i = 0; i < seekhead_list->nb_elem; i++) {
+        MatroskaSeekhead *seekhead = seekhead_list->elem;
         if (seekhead[i].pos <= before_pos)
             continue;
 
diff --git a/libavformat/mmsh.c b/libavformat/mmsh.c
index fa1a467..5e9d0bc 100644
--- a/libavformat/mmsh.c
+++ b/libavformat/mmsh.c
@@ -364,4 +364,5 @@ URLProtocol ff_mmsh_protocol = {
     .url_read       = mmsh_read,
     .url_close      = mmsh_close,
     .priv_data_size = sizeof(MMSHContext),
+    .flags          = URL_PROTOCOL_FLAG_NETWORK,
 };
diff --git a/libavformat/mmst.c b/libavformat/mmst.c
index 753b05c..93ad073 100644
--- a/libavformat/mmst.c
+++ b/libavformat/mmst.c
@@ -606,7 +606,7 @@ static int mms_read(URLContext *h, uint8_t *buf, int size)
                     // copy the data to the packet buffer.
                     result = ff_mms_read_data(mms, buf, size);
                     if (result == 0) {
-                        av_dlog(NULL, "read asf media paket size is zero!\n");
+                        av_dlog(NULL, "Read ASF media packet size is zero!\n");
                         break;
                     }
                 }
@@ -625,4 +625,5 @@ URLProtocol ff_mmst_protocol = {
     .url_read       = mms_read,
     .url_close      = mms_close,
     .priv_data_size = sizeof(MMSTContext),
+    .flags          = URL_PROTOCOL_FLAG_NETWORK,
 };
diff --git a/libavformat/mov.c b/libavformat/mov.c
index d3674d9..63089b9 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -559,7 +559,8 @@ static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
 {
     AVStream *st;
     uint8_t version;
-    uint32_t flags, layout_tag, bitmap, num_descr;
+    uint32_t flags, layout_tag, bitmap, num_descr, label_mask;
+    int i;
 
     if (c->fc->nb_streams < 1)
         return 0;
@@ -581,9 +582,7 @@ static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
     av_dlog(c->fc, "chan: size=%ld version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
             atom.size, version, flags, layout_tag, bitmap, num_descr);
 
-#if 0
-    /* TODO: use the channel descriptions if the layout tag is 0 */
-    int i;
+    label_mask = 0;
     for (i = 0; i < num_descr; i++) {
         uint32_t label, cflags;
         float coords[3];
@@ -592,10 +591,19 @@ static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
         AV_WN32(&coords[0], avio_rl32(pb)); // mCoordinates[0]
         AV_WN32(&coords[1], avio_rl32(pb)); // mCoordinates[1]
         AV_WN32(&coords[2], avio_rl32(pb)); // mCoordinates[2]
+        if (layout_tag == 0) {
+            uint32_t mask_incr = ff_mov_get_channel_label(label);
+            if (mask_incr == 0) {
+                label_mask = 0;
+                break;
+            }
+            label_mask |= mask_incr;
+        }
     }
-#endif
-
-    st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
+    if (layout_tag == 0)
+        st->codec->channel_layout = label_mask;
+    else
+        st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
 
     return 0;
 }
diff --git a/libavformat/mov_chan.c b/libavformat/mov_chan.c
index 3c1ced6..5728ebd 100644
--- a/libavformat/mov_chan.c
+++ b/libavformat/mov_chan.c
@@ -428,8 +428,7 @@ uint64_t ff_mov_get_channel_layout(uint32_t tag, uint32_t bitmap)
     int i, channels;
     const struct MovChannelLayoutMap *layout_map;
 
-    /* handle the use of the channel descriptions */
-    /* TODO: map MOV channel labels to Libav channels */
+    /* use ff_mov_get_channel_label() to build a layout instead */
     if (tag == MOV_CH_LAYOUT_USE_DESCRIPTIONS)
         return 0;
 
@@ -451,6 +450,19 @@ uint64_t ff_mov_get_channel_layout(uint32_t tag, uint32_t bitmap)
     return layout_map[i].layout;
 }
 
+uint32_t ff_mov_get_channel_label(uint32_t label)
+{
+    if (label == 0)
+        return 0;
+    if (label <= 18)
+        return 1U << (label - 1);
+    if (label == 38)
+        return AV_CH_STEREO_LEFT;
+    if (label == 39)
+        return AV_CH_STEREO_RIGHT;
+    return 0;
+}
+
 uint32_t ff_mov_get_channel_layout_tag(enum CodecID codec_id,
                                        uint64_t channel_layout,
                                        uint32_t *bitmap)
diff --git a/libavformat/mov_chan.h b/libavformat/mov_chan.h
index 9723340..abb6916 100644
--- a/libavformat/mov_chan.h
+++ b/libavformat/mov_chan.h
@@ -40,6 +40,14 @@
 uint64_t ff_mov_get_channel_layout(uint32_t tag, uint32_t bitmap);
 
 /**
+ * Get the channel layout for the specified channel layout tag.
+ *
+ * @param[in]  tag     channel label
+ * @return             channel layout mask fragment
+ */
+uint32_t ff_mov_get_channel_label(uint32_t label);
+
+/**
  * Get the channel layout tag for the specified codec id and channel layout.
  * If the layout tag was not found, use a channel bitmap if possible.
  *
diff --git a/libavformat/movenc.c b/libavformat/movenc.c
index e11eb50..85b5667 100644
--- a/libavformat/movenc.c
+++ b/libavformat/movenc.c
@@ -2317,7 +2317,8 @@ static int mov_write_header(AVFormatContext *s)
 #endif
     if (t = av_dict_get(s->metadata, "creation_time", NULL, 0))
         mov->time = ff_iso8601_to_unix_time(t->value);
-    mov->time += 0x7C25B080; //1970 based -> 1904 based
+    if (mov->time)
+        mov->time += 0x7C25B080; // 1970 based -> 1904 based
 
     if (mov->chapter_track)
         mov_create_chapter_track(s, mov->chapter_track);
diff --git a/libavformat/mpegenc.c b/libavformat/mpegenc.c
index d537af6..b2ca35a 100644
--- a/libavformat/mpegenc.c
+++ b/libavformat/mpegenc.c
@@ -429,7 +429,7 @@ static int mpeg_mux_init(AVFormatContext *ctx)
     if (!s->mux_rate) {
         /* we increase slightly the bitrate to take into account the
            headers. XXX: compute it exactly */
-        bitrate += bitrate*5/100;
+        bitrate += bitrate / 20;
         bitrate += 10000;
         s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
     }
diff --git a/libavformat/mtv.c b/libavformat/mtv.c
index c3fb15c..2243733 100644
--- a/libavformat/mtv.c
+++ b/libavformat/mtv.c
@@ -53,7 +53,7 @@ typedef struct MTVDemuxContext {
 static int mtv_probe(AVProbeData *p)
 {
     /* Magic is 'AMV' */
-    if(*(p->buf) != 'A' || *(p->buf+1) != 'M' || *(p->buf+2) != 'V')
+    if (*p->buf != 'A' || *(p->buf + 1) != 'M' || *(p->buf + 2) != 'V')
         return 0;
 
     /* Check for nonzero in bpp and (width|height) header fields */
@@ -106,6 +106,12 @@ static int mtv_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
     avio_skip(pb, 4);
     audio_subsegments = avio_rl16(pb);
+
+    if (audio_subsegments == 0) {
+        av_log_ask_for_sample(s, "MTV files without audio are not supported\n");
+        return AVERROR_INVALIDDATA;
+    }
+
     mtv->full_segment_size =
         audio_subsegments * (MTV_AUDIO_PADDING_SIZE + MTV_ASUBCHUNK_DATA_SIZE) +
         mtv->img_segment_size;
diff --git a/libavformat/rawdec.c b/libavformat/rawdec.c
index 589cdd5..3e2dd05 100644
--- a/libavformat/rawdec.c
+++ b/libavformat/rawdec.c
@@ -129,6 +129,7 @@ int ff_raw_audio_read_header(AVFormatContext *s,
     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
     st->codec->codec_id = s->iformat->value;
     st->need_parsing = AVSTREAM_PARSE_FULL;
+    st->start_time = 0;
     /* the parameters will be extracted from the compressed bitstream */
 
     return 0;
diff --git a/libavformat/rawenc.c b/libavformat/rawenc.c
index 5f2065e..6e9f4b7 100644
--- a/libavformat/rawenc.c
+++ b/libavformat/rawenc.c
@@ -45,6 +45,18 @@ AVOutputFormat ff_ac3_muxer = {
 };
 #endif
 
+#if CONFIG_ADX_MUXER
+AVOutputFormat ff_adx_muxer = {
+    .name              = "adx",
+    .long_name         = NULL_IF_CONFIG_SMALL("CRI ADX"),
+    .extensions        = "adx",
+    .audio_codec       = CODEC_ID_ADPCM_ADX,
+    .video_codec       = CODEC_ID_NONE,
+    .write_packet      = ff_raw_write_packet,
+    .flags             = AVFMT_NOTIMESTAMPS,
+};
+#endif
+
 #if CONFIG_DIRAC_MUXER
 AVOutputFormat ff_dirac_muxer = {
     .name              = "dirac",
diff --git a/libavformat/riff.c b/libavformat/riff.c
index 1d226ab..8489bc7 100644
--- a/libavformat/riff.c
+++ b/libavformat/riff.c
@@ -172,6 +172,7 @@ const AVCodecTag ff_codec_bmp_tags[] = {
     { CODEC_ID_RAWVIDEO,     MKTAG('2', 'V', 'u', '1') },
     { CODEC_ID_RAWVIDEO,     MKTAG('2', 'v', 'u', 'y') },
     { CODEC_ID_RAWVIDEO,     MKTAG('y', 'u', 'v', 's') },
+    { CODEC_ID_RAWVIDEO,     MKTAG('y', 'u', 'v', '2') },
     { CODEC_ID_RAWVIDEO,     MKTAG('P', '4', '2', '2') },
     { CODEC_ID_RAWVIDEO,     MKTAG('Y', 'V', '1', '2') },
     { CODEC_ID_RAWVIDEO,     MKTAG('Y', 'V', '1', '6') },
diff --git a/libavformat/rmdec.c b/libavformat/rmdec.c
index 66b6f8a..75e4833 100644
--- a/libavformat/rmdec.c
+++ b/libavformat/rmdec.c
@@ -661,7 +661,7 @@ static int rm_assemble_video_frame(AVFormatContext *s, AVIOContext *pb,
     vst->videobufpos += len;
     rm->remaining_len-= len;
 
-    if(type == 2 || (vst->videobufpos) == vst->videobufsize){
+    if (type == 2 || vst->videobufpos == vst->videobufsize) {
         vst->pkt.data[0] = vst->cur_slice-1;
         *pkt= vst->pkt;
         vst->pkt.data= NULL;
diff --git a/libavformat/rmenc.c b/libavformat/rmenc.c
index 0846a0a..0312d16 100644
--- a/libavformat/rmenc.c
+++ b/libavformat/rmenc.c
@@ -355,7 +355,7 @@ static int rm_write_audio(AVFormatContext *s, const uint8_t *buf, int size, int
     int i;
 
     /* XXX: suppress this malloc */
-    buf1= (uint8_t*) av_malloc( size * sizeof(uint8_t) );
+    buf1 = av_malloc(size * sizeof(uint8_t));
 
     write_packet_header(s, stream, size, !!(flags & AV_PKT_FLAG_KEY));
 
diff --git a/libavformat/rtmpproto.c b/libavformat/rtmpproto.c
index 53d912e..867969a 100644
--- a/libavformat/rtmpproto.c
+++ b/libavformat/rtmpproto.c
@@ -1000,4 +1000,5 @@ URLProtocol ff_rtmp_protocol = {
     .url_write      = rtmp_write,
     .url_close      = rtmp_close,
     .priv_data_size = sizeof(RTMPContext),
+    .flags          = URL_PROTOCOL_FLAG_NETWORK,
 };
diff --git a/libavformat/rtpproto.c b/libavformat/rtpproto.c
index 93cad3c..03794ae 100644
--- a/libavformat/rtpproto.c
+++ b/libavformat/rtpproto.c
@@ -330,4 +330,5 @@ URLProtocol ff_rtp_protocol = {
     .url_close           = rtp_close,
     .url_get_file_handle = rtp_get_file_handle,
     .priv_data_size      = sizeof(RTPContext),
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
diff --git a/libavformat/rtsp.c b/libavformat/rtsp.c
index fcf168d..2858a9a 100644
--- a/libavformat/rtsp.c
+++ b/libavformat/rtsp.c
@@ -1103,7 +1103,7 @@ int ff_rtsp_make_setup_request(AVFormatContext *s, const char *host, int port,
                               int lower_transport, const char *real_challenge)
 {
     RTSPState *rt = s->priv_data;
-    int rtx, j, i, err, interleave = 0;
+    int rtx = 0, j, i, err, interleave = 0;
     RTSPStream *rtsp_st;
     RTSPMessageHeader reply1, *reply = &reply1;
     char cmd[2048];
diff --git a/libavformat/sierravmd.c b/libavformat/sierravmd.c
index 1b5f04b..81ff46f 100644
--- a/libavformat/sierravmd.c
+++ b/libavformat/sierravmd.c
@@ -206,7 +206,7 @@ static int vmd_read_header(AVFormatContext *s,
                 vmd->frame_table[total_frames].pts = current_audio_pts;
                 total_frames++;
                 if(!current_audio_pts)
-                    current_audio_pts += sound_buffers;
+                    current_audio_pts += sound_buffers - 1;
                 else
                     current_audio_pts++;
                 break;
diff --git a/libavformat/spdifenc.c b/libavformat/spdifenc.c
index d541aba..5a1b8e4 100644
--- a/libavformat/spdifenc.c
+++ b/libavformat/spdifenc.c
@@ -220,7 +220,10 @@ static int spdif_header_dts4(AVFormatContext *s, AVPacket *pkt, int core_size,
     }
 
     ctx->out_bytes   = sizeof(dtshd_start_code) + 2 + pkt_size;
-    ctx->length_code = ctx->out_bytes;
+
+    /* Align so that (length_code & 0xf) == 0x8. This is reportedly needed
+     * with some receivers, but the exact requirement is unconfirmed. */
+    ctx->length_code = FFALIGN(ctx->out_bytes + 0x8, 0x10) - 0x8;
 
     av_fast_malloc(&ctx->hd_buf, &ctx->hd_buf_size, ctx->out_bytes);
     if (!ctx->hd_buf)
diff --git a/libavformat/tcp.c b/libavformat/tcp.c
index 0d3aeaf..fdb457e 100644
--- a/libavformat/tcp.c
+++ b/libavformat/tcp.c
@@ -204,4 +204,5 @@ URLProtocol ff_tcp_protocol = {
     .url_close           = tcp_close,
     .url_get_file_handle = tcp_get_file_handle,
     .priv_data_size      = sizeof(TCPContext),
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
diff --git a/libavformat/tls.c b/libavformat/tls.c
index 26f5ee5..fb84fa8 100644
--- a/libavformat/tls.c
+++ b/libavformat/tls.c
@@ -248,4 +248,5 @@ URLProtocol ff_tls_protocol = {
     .url_write      = tls_write,
     .url_close      = tls_close,
     .priv_data_size = sizeof(TLSContext),
+    .flags          = URL_PROTOCOL_FLAG_NETWORK,
 };
diff --git a/libavformat/tta.c b/libavformat/tta.c
index 37a359b..6bf0979 100644
--- a/libavformat/tta.c
+++ b/libavformat/tta.c
@@ -125,8 +125,8 @@ static int tta_read_packet(AVFormatContext *s, AVPacket *pkt)
     int size, ret;
 
     // FIXME!
-    if (c->currentframe > c->totalframes)
-        return -1;
+    if (c->currentframe >= c->totalframes)
+        return AVERROR_EOF;
 
     size = st->index_entries[c->currentframe].size;
 
diff --git a/libavformat/udp.c b/libavformat/udp.c
index 2bdd3dc..8bb63c6 100644
--- a/libavformat/udp.c
+++ b/libavformat/udp.c
@@ -491,4 +491,5 @@ URLProtocol ff_udp_protocol = {
     .url_close           = udp_close,
     .url_get_file_handle = udp_get_file_handle,
     .priv_data_size      = sizeof(UDPContext),
+    .flags               = URL_PROTOCOL_FLAG_NETWORK,
 };
diff --git a/libavformat/url.h b/libavformat/url.h
index ea8c7ab..14832af 100644
--- a/libavformat/url.h
+++ b/libavformat/url.h
@@ -33,6 +33,7 @@
 
 #if !FF_API_OLD_AVIO
 #define URL_PROTOCOL_FLAG_NESTED_SCHEME 1 /*< The protocol name can be the first part of a nested protocol scheme */
+#define URL_PROTOCOL_FLAG_NETWORK       2 /*< The protocol uses network */
 
 extern int (*url_interrupt_cb)(void);
 
diff --git a/libavformat/utils.c b/libavformat/utils.c
index aa2c276..a796658 100644
--- a/libavformat/utils.c
+++ b/libavformat/utils.c
@@ -31,6 +31,7 @@
 #include "libavutil/pixdesc.h"
 #include "metadata.h"
 #include "id3v2.h"
+#include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
 #include "libavutil/mathematics.h"
 #include "libavutil/parseutils.h"
@@ -1248,57 +1249,63 @@ static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
     return 0;
 }
 
+static int read_from_packet_buffer(AVFormatContext *s, AVPacket *pkt)
+{
+    AVPacketList *pktl = s->packet_buffer;
+    av_assert0(pktl);
+    *pkt = pktl->pkt;
+    s->packet_buffer = pktl->next;
+    av_freep(&pktl);
+    return 0;
+}
+
 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
 {
-    AVPacketList *pktl;
-    int eof=0;
-    const int genpts= s->flags & AVFMT_FLAG_GENPTS;
+    const int genpts = s->flags & AVFMT_FLAG_GENPTS;
+    int          eof = 0;
+
+    if (!genpts)
+        return s->packet_buffer ? read_from_packet_buffer(s, pkt) :
+                                  read_frame_internal(s, pkt);
+
+    for (;;) {
+        int ret;
+        AVPacketList *pktl = s->packet_buffer;
 
-    for(;;){
-        pktl = s->packet_buffer;
         if (pktl) {
-            AVPacket *next_pkt= &pktl->pkt;
+            AVPacket *next_pkt = &pktl->pkt;
 
-            if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
+            if (next_pkt->dts != AV_NOPTS_VALUE) {
                 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
-                while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
-                    if(   pktl->pkt.stream_index == next_pkt->stream_index
-                       && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
-                       && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
-                        next_pkt->pts= pktl->pkt.dts;
+                while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
+                    if (pktl->pkt.stream_index == next_pkt->stream_index &&
+                        (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
+                         av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
+                        next_pkt->pts = pktl->pkt.dts;
                     }
-                    pktl= pktl->next;
+                    pktl = pktl->next;
                 }
                 pktl = s->packet_buffer;
             }
 
-            if(   next_pkt->pts != AV_NOPTS_VALUE
-               || next_pkt->dts == AV_NOPTS_VALUE
-               || !genpts || eof){
-                /* read packet from packet buffer, if there is data */
-                *pkt = *next_pkt;
-                s->packet_buffer = pktl->next;
-                av_free(pktl);
-                return 0;
-            }
+            /* read packet from packet buffer, if there is data */
+            if (!(next_pkt->pts == AV_NOPTS_VALUE &&
+                  next_pkt->dts != AV_NOPTS_VALUE && !eof))
+                return read_from_packet_buffer(s, pkt);
         }
-        if(genpts){
-            int ret= read_frame_internal(s, pkt);
-            if(ret<0){
-                if(pktl && ret != AVERROR(EAGAIN)){
-                    eof=1;
-                    continue;
-                }else
-                    return ret;
-            }
 
-            if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
-                                           &s->packet_buffer_end)) < 0)
-                return AVERROR(ENOMEM);
-        }else{
-            assert(!s->packet_buffer);
-            return read_frame_internal(s, pkt);
+        ret = read_frame_internal(s, pkt);
+        if (ret < 0) {
+            if (pktl && ret != AVERROR(EAGAIN)) {
+                eof = 1;
+                continue;
+            } else
+                return ret;
         }
+
+        if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
+                          &s->packet_buffer_end)) < 0)
+            return AVERROR(ENOMEM);
     }
 }
 
@@ -2126,7 +2133,7 @@ static int has_decode_delay_been_guessed(AVStream *st)
 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
 {
     AVCodec *codec;
-    int got_picture, ret = 0;
+    int got_picture = 1, ret = 0;
     AVFrame picture;
     AVPacket pkt = *avpkt;
 
@@ -2139,7 +2146,8 @@ static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **option
             return ret;
     }
 
-    while (pkt.size > 0 && ret >= 0 &&
+    while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
+           ret >= 0 &&
            (!has_codec_parameters(st->codec)  ||
            !has_decode_delay_been_guessed(st) ||
            (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
@@ -2292,11 +2300,6 @@ int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
         assert(!st->codec->codec);
         codec = avcodec_find_decoder(st->codec->codec_id);
 
-        /* this function doesn't flush the decoders, so force thread count
-         * to 1 to fix behavior when thread count > number of frames in the file */
-        if (options)
-            av_dict_set(&options[i], "threads", "1", 0);
-
         /* Ensure that subtitle_header is properly set. */
         if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
             && codec && !st->codec->codec)
@@ -2371,10 +2374,22 @@ int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
             continue;
 
         if (ret < 0) {
-            /* EOF or error */
+            /* EOF or error*/
+            AVPacket empty_pkt = { 0 };
+            int err;
+            av_init_packet(&empty_pkt);
+
             ret = -1; /* we could not have all the codec parameters before EOF */
             for(i=0;i<ic->nb_streams;i++) {
                 st = ic->streams[i];
+
+                /* flush the decoders */
+                while ((err = try_decode_frame(st, &empty_pkt,
+                                               (options && i < orig_nb_streams) ?
+                                                &options[i] : NULL)) >= 0)
+                    if (has_codec_parameters(st->codec))
+                        break;
+
                 if (!has_codec_parameters(st->codec)){
                     char buf[256];
                     avcodec_string(buf, sizeof(buf), st->codec, 0);
@@ -2444,7 +2459,7 @@ int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
            least one frame of codec data, this makes sure the codec initializes
            the channel configuration and does not only trust the values from the container.
         */
-        try_decode_frame(st, pkt, (options && i < orig_nb_streams )? &options[i] : NULL);
+        try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
 
         st->codec_info_nb_frames++;
         count++;
@@ -2549,8 +2564,11 @@ int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
 #endif
 
  find_stream_info_err:
-    for (i=0; i < ic->nb_streams; i++)
+    for (i=0; i < ic->nb_streams; i++) {
+        if (ic->streams[i]->codec)
+            ic->streams[i]->codec->thread_count = 0;
         av_freep(&ic->streams[i]->info);
+    }
     return ret;
 }
 
diff --git a/libavformat/vqf.c b/libavformat/vqf.c
index aba763d..4f8f07c 100644
--- a/libavformat/vqf.c
+++ b/libavformat/vqf.c
@@ -24,6 +24,7 @@
 #include "libavutil/intreadwrite.h"
 #include "libavutil/dict.h"
 #include "libavutil/mathematics.h"
+#include "riff.h"
 
 typedef struct VqfContext {
     int frame_bit_len;
@@ -45,11 +46,11 @@ static int vqf_probe(AVProbeData *probe_packet)
     return AVPROBE_SCORE_MAX/2;
 }
 
-static void add_metadata(AVFormatContext *s, const char *tag,
+static void add_metadata(AVFormatContext *s, uint32_t tag,
                          unsigned int tag_len, unsigned int remaining)
 {
     int len = FFMIN(tag_len, remaining);
-    char *buf;
+    char *buf, key[5] = {0};
 
     if (len == UINT_MAX)
         return;
@@ -59,9 +60,32 @@ static void add_metadata(AVFormatContext *s, const char *tag,
         return;
     avio_read(s->pb, buf, len);
     buf[len] = 0;
-    av_dict_set(&s->metadata, tag, buf, AV_DICT_DONT_STRDUP_VAL);
+    AV_WL32(key, tag);
+    av_dict_set(&s->metadata, key, buf, AV_DICT_DONT_STRDUP_VAL);
 }
 
+static const AVMetadataConv vqf_metadata_conv[] = {
+    { "(c) ", "copyright" },
+    { "ARNG", "arranger"  },
+    { "AUTH", "author"    },
+    { "BAND", "band"      },
+    { "CDCT", "conductor" },
+    { "COMT", "comment"   },
+    { "FILE", "filename"  },
+    { "GENR", "genre"     },
+    { "LABL", "publisher" },
+    { "MUSC", "composer"  },
+    { "NAME", "title"     },
+    { "NOTE", "note"      },
+    { "PROD", "producer"  },
+    { "PRSN", "personnel" },
+    { "REMX", "remixer"   },
+    { "SING", "singer"    },
+    { "TRCK", "track"     },
+    { "WORD", "words"     },
+    { 0 },
+};
+
 static int vqf_read_header(AVFormatContext *s, AVFormatParameters *ap)
 {
     VqfContext *c = s->priv_data;
@@ -110,41 +134,25 @@ static int vqf_read_header(AVFormatContext *s, AVFormatParameters *ap)
 
             st->codec->bit_rate              = read_bitrate*1000;
             break;
-        case MKTAG('N','A','M','E'):
-            add_metadata(s, "title"    , len, header_size);
-            break;
-        case MKTAG('(','c',')',' '):
-            add_metadata(s, "copyright", len, header_size);
-            break;
-        case MKTAG('A','U','T','H'):
-            add_metadata(s, "author"   , len, header_size);
-            break;
-        case MKTAG('A','L','B','M'):
-            add_metadata(s, "album"    , len, header_size);
-            break;
-        case MKTAG('T','R','C','K'):
-            add_metadata(s, "track"    , len, header_size);
-            break;
-        case MKTAG('C','O','M','T'):
-            add_metadata(s, "comment"  , len, header_size);
-            break;
-        case MKTAG('F','I','L','E'):
-            add_metadata(s, "filename" , len, header_size);
-            break;
-        case MKTAG('D','S','I','Z'):
-            add_metadata(s, "size"     , len, header_size);
-            break;
-        case MKTAG('D','A','T','E'):
-            add_metadata(s, "date"     , len, header_size);
+        case MKTAG('D','S','I','Z'): // size of compressed data
+        {
+            char buf[8] = {0};
+            int size = avio_rb32(s->pb);
+
+            snprintf(buf, sizeof(buf), "%d", size);
+            av_dict_set(&s->metadata, "size", buf, 0);
+        }
             break;
-        case MKTAG('G','E','N','R'):
-            add_metadata(s, "genre"    , len, header_size);
+        case MKTAG('Y','E','A','R'): // recording date
+        case MKTAG('E','N','C','D'): // compression date
+        case MKTAG('E','X','T','R'): // reserved
+        case MKTAG('_','Y','M','H'): // reserved
+        case MKTAG('_','N','T','T'): // reserved
+        case MKTAG('_','I','D','3'): // reserved for ID3 tags
+            avio_skip(s->pb, FFMIN(len, header_size));
             break;
         default:
-            av_log(s, AV_LOG_ERROR, "Unknown chunk: %c%c%c%c\n",
-                   ((char*)&chunk_tag)[0], ((char*)&chunk_tag)[1],
-                   ((char*)&chunk_tag)[2], ((char*)&chunk_tag)[3]);
-            avio_skip(s->pb, FFMIN(len, header_size));
+            add_metadata(s, chunk_tag, len, header_size);
             break;
         }
 
@@ -201,6 +209,8 @@ static int vqf_read_header(AVFormatContext *s, AVFormatParameters *ap)
     st->codec->extradata_size = 12;
     memcpy(st->codec->extradata, comm_chunk, 12);
 
+    ff_metadata_conv_ctx(s, NULL, vqf_metadata_conv);
+
     return 0;
 }
 
@@ -265,5 +275,5 @@ AVInputFormat ff_vqf_demuxer = {
     .read_header    = vqf_read_header,
     .read_packet    = vqf_read_packet,
     .read_seek      = vqf_read_seek,
-    .extensions = "vqf",
+    .extensions     = "vqf,vql,vqe",
 };
diff --git a/libavformat/wtv.c b/libavformat/wtv.c
index e4b9ae5..c619868 100644
--- a/libavformat/wtv.c
+++ b/libavformat/wtv.c
@@ -302,6 +302,8 @@ static void wtvfile_close(AVIOContext *pb)
 {
     WtvFile *wf = pb->opaque;
     av_free(wf->sectors);
+    av_free(wf);
+    av_free(pb->buffer);
     av_free(pb);
 }
 
@@ -1093,6 +1095,7 @@ static int read_seek(AVFormatContext *s, int stream_index,
 static int read_close(AVFormatContext *s)
 {
     WtvContext *wtv = s->priv_data;
+    av_free(wtv->index_entries);
     wtvfile_close(wtv->pb);
     return 0;
 }
diff --git a/libavutil/avutil.h b/libavutil/avutil.h
index fa84eff..f0be5c1 100644
--- a/libavutil/avutil.h
+++ b/libavutil/avutil.h
@@ -154,7 +154,7 @@
  */
 
 #define LIBAVUTIL_VERSION_MAJOR 51
-#define LIBAVUTIL_VERSION_MINOR 20
+#define LIBAVUTIL_VERSION_MINOR 21
 #define LIBAVUTIL_VERSION_MICRO  0
 
 #define LIBAVUTIL_VERSION_INT   AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
diff --git a/libavutil/common.h b/libavutil/common.h
index 7e93a1a..c99d858 100644
--- a/libavutil/common.h
+++ b/libavutil/common.h
@@ -218,6 +218,16 @@ static av_always_inline av_const int av_popcount_c(uint32_t x)
     return (x + (x >> 16)) & 0x3F;
 }
 
+/**
+ * Count number of bits set to one in x
+ * @param x value to count bits of
+ * @return the number of bits set to one in x
+ */
+static av_always_inline av_const int av_popcount64_c(uint64_t x)
+{
+    return av_popcount(x) + av_popcount(x >> 32);
+}
+
 #define MKTAG(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((unsigned)(d) << 24))
 #define MKBETAG(a,b,c,d) ((d) | ((c) << 8) | ((b) << 16) | ((unsigned)(a) << 24))
 
@@ -383,3 +393,6 @@ static av_always_inline av_const int av_popcount_c(uint32_t x)
 #ifndef av_popcount
 #   define av_popcount      av_popcount_c
 #endif
+#ifndef av_popcount64
+#   define av_popcount64    av_popcount64_c
+#endif
diff --git a/libavutil/timer.h b/libavutil/timer.h
index 6333cc6..78d2b5f 100644
--- a/libavutil/timer.h
+++ b/libavutil/timer.h
@@ -28,6 +28,7 @@
 
 #include <stdlib.h>
 #include <stdint.h>
+
 #include "config.h"
 
 #if   ARCH_ARM
@@ -45,29 +46,32 @@
 #endif
 
 #ifdef AV_READ_TIME
-#define START_TIMER \
-uint64_t tend;\
-uint64_t tstart= AV_READ_TIME();\
+#define START_TIMER                             \
+    uint64_t tend;                              \
+    uint64_t tstart = AV_READ_TIME();           \
 
-#define STOP_TIMER(id) \
-tend= AV_READ_TIME();\
-{\
-    static uint64_t tsum=0;\
-    static int tcount=0;\
-    static int tskip_count=0;\
-    if(tcount<2 || tend - tstart < 8*tsum/tcount || tend - tstart < 2000){\
-        tsum+= tend - tstart;\
-        tcount++;\
-    }else\
-        tskip_count++;\
-    if(((tcount+tskip_count)&(tcount+tskip_count-1))==0){\
-        av_log(NULL, AV_LOG_ERROR, "%"PRIu64" decicycles in %s, %d runs, %d skips\n",\
-               tsum*10/tcount, id, tcount, tskip_count);\
-    }\
-}
+#define STOP_TIMER(id)                                                    \
+    tend = AV_READ_TIME();                                                \
+    {                                                                     \
+        static uint64_t tsum   = 0;                                       \
+        static int tcount      = 0;                                       \
+        static int tskip_count = 0;                                       \
+        if (tcount < 2                        ||                          \
+            tend - tstart < 8 * tsum / tcount ||                          \
+            tend - tstart < 2000) {                                       \
+            tsum+= tend - tstart;                                         \
+            tcount++;                                                     \
+        } else                                                            \
+            tskip_count++;                                                \
+        if (((tcount + tskip_count) & (tcount + tskip_count - 1)) == 0) { \
+            av_log(NULL, AV_LOG_ERROR,                                    \
+                   "%"PRIu64" decicycles in %s, %d runs, %d skips\n",     \
+                   tsum * 10 / tcount, id, tcount, tskip_count);          \
+        }                                                                 \
+    }
 #else
 #define START_TIMER
-#define STOP_TIMER(id) {}
+#define STOP_TIMER(id) { }
 #endif
 
 #endif /* AVUTIL_TIMER_H */
diff --git a/libavutil/x86/x86inc.asm b/libavutil/x86/x86inc.asm
index 475e70e..6941c1a 100644
--- a/libavutil/x86/x86inc.asm
+++ b/libavutil/x86/x86inc.asm
@@ -916,6 +916,8 @@ AVX_INSTR minpd, 1, 0, 1
 AVX_INSTR minps, 1, 0, 1
 AVX_INSTR minsd, 1, 0, 1
 AVX_INSTR minss, 1, 0, 1
+AVX_INSTR movhlps, 1, 0, 0
+AVX_INSTR movlhps, 1, 0, 0
 AVX_INSTR movsd, 1, 0, 0
 AVX_INSTR movss, 1, 0, 0
 AVX_INSTR mpsadbw, 0, 1, 0
diff --git a/libpostproc/postprocess_template.c b/libpostproc/postprocess_template.c
index dd4c7a0..a609ce8 100644
--- a/libpostproc/postprocess_template.c
+++ b/libpostproc/postprocess_template.c
@@ -2472,7 +2472,7 @@ static av_always_inline void RENAME(do_a_deblock)(uint8_t *src, int step, int st
     int64_t dc_mask, eq_mask, both_masks;
     int64_t sums[10*8*2];
     src+= step*3; // src points to begin of the 8x8 Block
-//START_TIMER
+    //{ START_TIMER
     __asm__ volatile(
         "movq %0, %%mm7                         \n\t"
         "movq %1, %%mm6                         \n\t"
@@ -2998,7 +2998,8 @@ static av_always_inline void RENAME(do_a_deblock)(uint8_t *src, int step, int st
     STOP_TIMER("step16")
 }else{
     STOP_TIMER("stepX")
-}*/
+}
+    } */
 }
 #endif //HAVE_MMX
 
@@ -3372,14 +3373,14 @@ static void RENAME(postProcess)(const uint8_t src[], int srcStride, uint8_t dst[
             linecpy(tempSrc + srcStride*copyAhead, srcBlock + srcStride*copyAhead,
                     FFMAX(height-y-copyAhead, 0), srcStride);
 
-            /* duplicate last line of src to fill the void upto line (copyAhead+7) */
+            /* duplicate last line of src to fill the void up to line (copyAhead+7) */
             for(i=FFMAX(height-y, 8); i<copyAhead+8; i++)
                     memcpy(tempSrc + srcStride*i, src + srcStride*(height-1), FFABS(srcStride));
 
             /* copy up to (copyAhead+1) lines of dst (line -1 to (copyAhead-1))*/
             linecpy(tempDst, dstBlock - dstStride, FFMIN(height-y+1, copyAhead+1), dstStride);
 
-            /* duplicate last line of dst to fill the void upto line (copyAhead) */
+            /* duplicate last line of dst to fill the void up to line (copyAhead) */
             for(i=height-y+1; i<=copyAhead; i++)
                     memcpy(tempDst + dstStride*i, dst + dstStride*(height-1), FFABS(dstStride));
 
diff --git a/libswscale/Makefile b/libswscale/Makefile
index bb9b7d3..bef4200 100644
--- a/libswscale/Makefile
+++ b/libswscale/Makefile
@@ -17,7 +17,9 @@ OBJS-$(HAVE_MMX)           +=  x86/rgb2rgb.o            \
                                x86/swscale_mmx.o        \
                                x86/yuv2rgb_mmx.o
 OBJS-$(HAVE_VIS)           +=  sparc/yuv2rgb_vis.o
-OBJS-$(HAVE_YASM)          +=  x86/scale.o
+MMX-OBJS-$(HAVE_YASM)      +=  x86/input.o              \
+                               x86/output.o             \
+                               x86/scale.o
 
 TESTPROGS = colorspace swscale
 
diff --git a/libswscale/colorspace-test.c b/libswscale/colorspace-test.c
index 07c1cbd..10cee8a 100644
--- a/libswscale/colorspace-test.c
+++ b/libswscale/colorspace-test.c
@@ -27,19 +27,19 @@
 #include "swscale.h"
 #include "rgb2rgb.h"
 
-#define SIZE 1000
+#define SIZE    1000
 #define srcByte 0x55
 #define dstByte 0xBB
 
-#define FUNC(s,d,n) {s,d,#n,n}
+#define FUNC(s, d, n) { s, d, #n, n }
 
 int main(int argc, char **argv)
 {
     int i, funcNum;
-    uint8_t *srcBuffer= (uint8_t*)av_malloc(SIZE);
-    uint8_t *dstBuffer= (uint8_t*)av_malloc(SIZE);
-    int failedNum=0;
-    int passedNum=0;
+    uint8_t *srcBuffer = av_malloc(SIZE);
+    uint8_t *dstBuffer = av_malloc(SIZE);
+    int failedNum      = 0;
+    int passedNum      = 0;
 
     if (!srcBuffer || !dstBuffer)
         return -1;
@@ -47,7 +47,7 @@ int main(int argc, char **argv)
     av_log(NULL, AV_LOG_INFO, "memory corruption test ...\n");
     sws_rgb2rgb_init();
 
-    for(funcNum=0; ; funcNum++) {
+    for (funcNum = 0; ; funcNum++) {
         struct func_info_s {
             int src_bpp;
             int dst_bpp;
@@ -85,67 +85,78 @@ int main(int argc, char **argv)
             FUNC(0, 0, NULL)
         };
         int width;
-        int failed=0;
-        int srcBpp=0;
-        int dstBpp=0;
+        int failed = 0;
+        int srcBpp = 0;
+        int dstBpp = 0;
 
-        if (!func_info[funcNum].func) break;
+        if (!func_info[funcNum].func)
+            break;
 
-        av_log(NULL, AV_LOG_INFO,".");
+        av_log(NULL, AV_LOG_INFO, ".");
         memset(srcBuffer, srcByte, SIZE);
 
-        for(width=63; width>0; width--) {
+        for (width = 63; width > 0; width--) {
             int dstOffset;
-            for(dstOffset=128; dstOffset<196; dstOffset+=4) {
+            for (dstOffset = 128; dstOffset < 196; dstOffset += 4) {
                 int srcOffset;
                 memset(dstBuffer, dstByte, SIZE);
 
-                for(srcOffset=128; srcOffset<196; srcOffset+=4) {
-                    uint8_t *src= srcBuffer+srcOffset;
-                    uint8_t *dst= dstBuffer+dstOffset;
-                    const char *name=NULL;
+                for (srcOffset = 128; srcOffset < 196; srcOffset += 4) {
+                    uint8_t *src     = srcBuffer + srcOffset;
+                    uint8_t *dst     = dstBuffer + dstOffset;
+                    const char *name = NULL;
 
-                    if(failed) break; //don't fill the screen with shit ...
+                    // don't fill the screen with shit ...
+                    if (failed)
+                        break;
 
                     srcBpp = func_info[funcNum].src_bpp;
                     dstBpp = func_info[funcNum].dst_bpp;
                     name   = func_info[funcNum].name;
 
-                    func_info[funcNum].func(src, dst, width*srcBpp);
+                    func_info[funcNum].func(src, dst, width * srcBpp);
 
-                    if(!srcBpp) break;
+                    if (!srcBpp)
+                        break;
 
-                    for(i=0; i<SIZE; i++) {
-                        if(srcBuffer[i]!=srcByte) {
-                            av_log(NULL, AV_LOG_INFO, "src damaged at %d w:%d src:%d dst:%d %s\n",
+                    for (i = 0; i < SIZE; i++) {
+                        if (srcBuffer[i] != srcByte) {
+                            av_log(NULL, AV_LOG_INFO,
+                                   "src damaged at %d w:%d src:%d dst:%d %s\n",
                                    i, width, srcOffset, dstOffset, name);
-                            failed=1;
+                            failed = 1;
                             break;
                         }
                     }
-                    for(i=0; i<dstOffset; i++) {
-                        if(dstBuffer[i]!=dstByte) {
-                            av_log(NULL, AV_LOG_INFO, "dst damaged at %d w:%d src:%d dst:%d %s\n",
+                    for (i = 0; i < dstOffset; i++) {
+                        if (dstBuffer[i] != dstByte) {
+                            av_log(NULL, AV_LOG_INFO,
+                                   "dst damaged at %d w:%d src:%d dst:%d %s\n",
                                    i, width, srcOffset, dstOffset, name);
-                            failed=1;
+                            failed = 1;
                             break;
                         }
                     }
-                    for(i=dstOffset + width*dstBpp; i<SIZE; i++) {
-                        if(dstBuffer[i]!=dstByte) {
-                            av_log(NULL, AV_LOG_INFO, "dst damaged at %d w:%d src:%d dst:%d %s\n",
+                    for (i = dstOffset + width * dstBpp; i < SIZE; i++) {
+                        if (dstBuffer[i] != dstByte) {
+                            av_log(NULL, AV_LOG_INFO,
+                                   "dst damaged at %d w:%d src:%d dst:%d %s\n",
                                    i, width, srcOffset, dstOffset, name);
-                            failed=1;
+                            failed = 1;
                             break;
                         }
                     }
                 }
             }
         }
-        if(failed) failedNum++;
-        else if(srcBpp) passedNum++;
+        if (failed)
+            failedNum++;
+        else if (srcBpp)
+            passedNum++;
     }
 
-    av_log(NULL, AV_LOG_INFO, "\n%d converters passed, %d converters randomly overwrote memory\n", passedNum, failedNum);
+    av_log(NULL, AV_LOG_INFO,
+           "\n%d converters passed, %d converters randomly overwrote memory\n",
+           passedNum, failedNum);
     return failedNum;
 }
diff --git a/libswscale/ppc/yuv2rgb_altivec.h b/libswscale/ppc/yuv2rgb_altivec.h
index b809fe1..626d2b0 100644
--- a/libswscale/ppc/yuv2rgb_altivec.h
+++ b/libswscale/ppc/yuv2rgb_altivec.h
@@ -21,16 +21,21 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-#ifndef PPC_YUV2RGB_ALTIVEC_H
-#define PPC_YUV2RGB_ALTIVEC_H 1
+#ifndef SWSCALE_PPC_YUV2RGB_ALTIVEC_H
+#define SWSCALE_PPC_YUV2RGB_ALTIVEC_H
 
-#define YUV2PACKEDX_HEADER(suffix) \
-void ff_yuv2 ## suffix ## _X_altivec(SwsContext *c, const int16_t *lumFilter, \
-                            const int16_t **lumSrc, int lumFilterSize, \
-                            const int16_t *chrFilter, const int16_t **chrUSrc, \
-                            const int16_t **chrVSrc, int chrFilterSize, \
-                            const int16_t **alpSrc, uint8_t *dest, \
-                            int dstW, int dstY);
+#define YUV2PACKEDX_HEADER(suffix)                                  \
+    void ff_yuv2 ## suffix ## _X_altivec(SwsContext *c,             \
+                                         const int16_t *lumFilter,  \
+                                         const int16_t **lumSrc,    \
+                                         int lumFilterSize,         \
+                                         const int16_t *chrFilter,  \
+                                         const int16_t **chrUSrc,   \
+                                         const int16_t **chrVSrc,   \
+                                         int chrFilterSize,         \
+                                         const int16_t **alpSrc,    \
+                                         uint8_t *dest,             \
+                                         int dstW, int dstY);
 
 YUV2PACKEDX_HEADER(abgr);
 YUV2PACKEDX_HEADER(bgra);
@@ -39,4 +44,4 @@ YUV2PACKEDX_HEADER(rgba);
 YUV2PACKEDX_HEADER(rgb24);
 YUV2PACKEDX_HEADER(bgr24);
 
-#endif /* PPC_YUV2RGB_ALTIVEC_H */
+#endif /* SWSCALE_PPC_YUV2RGB_ALTIVEC_H */
diff --git a/libswscale/rgb2rgb.h b/libswscale/rgb2rgb.h
index 9d051de..833a984 100644
--- a/libswscale/rgb2rgb.h
+++ b/libswscale/rgb2rgb.h
@@ -36,32 +36,33 @@ extern void (*rgb24tobgr32)(const uint8_t *src, uint8_t *dst, int src_size);
 extern void (*rgb24tobgr16)(const uint8_t *src, uint8_t *dst, int src_size);
 extern void (*rgb24tobgr15)(const uint8_t *src, uint8_t *dst, int src_size);
 extern void (*rgb32tobgr24)(const uint8_t *src, uint8_t *dst, int src_size);
-extern void (*rgb32to16)   (const uint8_t *src, uint8_t *dst, int src_size);
-extern void (*rgb32to15)   (const uint8_t *src, uint8_t *dst, int src_size);
-extern void (*rgb15to16)   (const uint8_t *src, uint8_t *dst, int src_size);
+extern void    (*rgb32to16)(const uint8_t *src, uint8_t *dst, int src_size);
+extern void    (*rgb32to15)(const uint8_t *src, uint8_t *dst, int src_size);
+extern void    (*rgb15to16)(const uint8_t *src, uint8_t *dst, int src_size);
 extern void (*rgb15tobgr24)(const uint8_t *src, uint8_t *dst, int src_size);
-extern void (*rgb15to32)   (const uint8_t *src, uint8_t *dst, int src_size);
-extern void (*rgb16to15)   (const uint8_t *src, uint8_t *dst, int src_size);
+extern void    (*rgb15to32)(const uint8_t *src, uint8_t *dst, int src_size);
+extern void    (*rgb16to15)(const uint8_t *src, uint8_t *dst, int src_size);
 extern void (*rgb16tobgr24)(const uint8_t *src, uint8_t *dst, int src_size);
-extern void (*rgb16to32)   (const uint8_t *src, uint8_t *dst, int src_size);
+extern void    (*rgb16to32)(const uint8_t *src, uint8_t *dst, int src_size);
 extern void (*rgb24tobgr24)(const uint8_t *src, uint8_t *dst, int src_size);
-extern void (*rgb24to16)   (const uint8_t *src, uint8_t *dst, int src_size);
-extern void (*rgb24to15)   (const uint8_t *src, uint8_t *dst, int src_size);
-extern void (*shuffle_bytes_2103)(const uint8_t *src, uint8_t *dst, int src_size);
+extern void    (*rgb24to16)(const uint8_t *src, uint8_t *dst, int src_size);
+extern void    (*rgb24to15)(const uint8_t *src, uint8_t *dst, int src_size);
 extern void (*rgb32tobgr16)(const uint8_t *src, uint8_t *dst, int src_size);
 extern void (*rgb32tobgr15)(const uint8_t *src, uint8_t *dst, int src_size);
 
-void rgb24to32   (const uint8_t *src, uint8_t *dst, int src_size);
-void rgb32to24   (const uint8_t *src, uint8_t *dst, int src_size);
+extern void (*shuffle_bytes_2103)(const uint8_t *src, uint8_t *dst, int src_size);
+
+void    rgb24to32(const uint8_t *src, uint8_t *dst, int src_size);
+void    rgb32to24(const uint8_t *src, uint8_t *dst, int src_size);
 void rgb16tobgr32(const uint8_t *src, uint8_t *dst, int src_size);
-void rgb16to24   (const uint8_t *src, uint8_t *dst, int src_size);
+void    rgb16to24(const uint8_t *src, uint8_t *dst, int src_size);
 void rgb16tobgr16(const uint8_t *src, uint8_t *dst, int src_size);
 void rgb16tobgr15(const uint8_t *src, uint8_t *dst, int src_size);
 void rgb15tobgr32(const uint8_t *src, uint8_t *dst, int src_size);
-void rgb15to24   (const uint8_t *src, uint8_t *dst, int src_size);
+void    rgb15to24(const uint8_t *src, uint8_t *dst, int src_size);
 void rgb15tobgr16(const uint8_t *src, uint8_t *dst, int src_size);
 void rgb15tobgr15(const uint8_t *src, uint8_t *dst, int src_size);
-void bgr8torgb8  (const uint8_t *src, uint8_t *dst, int src_size);
+void   bgr8torgb8(const uint8_t *src, uint8_t *dst, int src_size);
 
 void shuffle_bytes_0321(const uint8_t *src, uint8_t *dst, int src_size);
 void shuffle_bytes_1230(const uint8_t *src, uint8_t *dst, int src_size);
@@ -138,7 +139,6 @@ extern void (*yvu9_to_yuy2)(const uint8_t *src1, const uint8_t *src2, const uint
                             int srcStride1, int srcStride2,
                             int srcStride3, int dstStride);
 
-
 extern void (*uyvytoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,
                             int width, int height,
                             int lumStride, int chromStride, int srcStride);
diff --git a/libswscale/swscale-test.c b/libswscale/swscale-test.c
index b5cf1d2..7ea01a6 100644
--- a/libswscale/swscale-test.c
+++ b/libswscale/swscale-test.c
@@ -35,33 +35,32 @@
 
 /* HACK Duplicated from swscale_internal.h.
  * Should be removed when a cleaner pixel format system exists. */
-#define isGray(x)       (           \
-           (x)==PIX_FMT_GRAY8       \
-        || (x)==PIX_FMT_GRAY16BE    \
-        || (x)==PIX_FMT_GRAY16LE    \
-    )
-#define hasChroma(x)   (!(          \
-            isGray(x)               \
-        || (x)==PIX_FMT_MONOBLACK   \
-        || (x)==PIX_FMT_MONOWHITE   \
-    ))
-#define isALPHA(x)      (           \
-           (x)==PIX_FMT_BGR32       \
-        || (x)==PIX_FMT_BGR32_1     \
-        || (x)==PIX_FMT_RGB32       \
-        || (x)==PIX_FMT_RGB32_1     \
-        || (x)==PIX_FMT_YUVA420P    \
-    )
-
-static uint64_t getSSD(uint8_t *src1, uint8_t *src2, int stride1, int stride2, int w, int h)
+#define isGray(x)                      \
+    ((x) == PIX_FMT_GRAY8       ||     \
+     (x) == PIX_FMT_Y400A       ||     \
+     (x) == PIX_FMT_GRAY16BE    ||     \
+     (x) == PIX_FMT_GRAY16LE)
+#define hasChroma(x)                   \
+    (!(isGray(x)                ||     \
+       (x) == PIX_FMT_MONOBLACK ||     \
+       (x) == PIX_FMT_MONOWHITE))
+#define isALPHA(x)                     \
+    ((x) == PIX_FMT_BGR32   ||         \
+     (x) == PIX_FMT_BGR32_1 ||         \
+     (x) == PIX_FMT_RGB32   ||         \
+     (x) == PIX_FMT_RGB32_1 ||         \
+     (x) == PIX_FMT_YUVA420P)
+
+static uint64_t getSSD(uint8_t *src1, uint8_t *src2, int stride1,
+                       int stride2, int w, int h)
 {
-    int x,y;
-    uint64_t ssd=0;
+    int x, y;
+    uint64_t ssd = 0;
 
-    for (y=0; y<h; y++) {
-        for (x=0; x<w; x++) {
-            int d= src1[x + y*stride1] - src2[x + y*stride2];
-            ssd+= d*d;
+    for (y = 0; y < h; y++) {
+        for (x = 0; x < w; x++) {
+            int d = src1[x + y * stride1] - src2[x + y * stride2];
+            ssd += d * d;
         }
     }
     return ssd;
@@ -86,14 +85,14 @@ static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
     static int cur_srcW, cur_srcH;
     static uint8_t *src[4];
     static int srcStride[4];
-    uint8_t *dst[4] = {0};
-    uint8_t *out[4] = {0};
+    uint8_t *dst[4] = { 0 };
+    uint8_t *out[4] = { 0 };
     int dstStride[4];
     int i;
-    uint64_t ssdY, ssdU=0, ssdV=0, ssdA=0;
+    uint64_t ssdY, ssdU = 0, ssdV = 0, ssdA = 0;
     struct SwsContext *dstContext = NULL, *outContext = NULL;
     uint32_t crc = 0;
-    int res = 0;
+    int res      = 0;
 
     if (cur_srcFormat != srcFormat || cur_srcW != srcW || cur_srcH != srcH) {
         struct SwsContext *srcContext = NULL;
@@ -105,11 +104,10 @@ static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
         av_image_fill_linesizes(srcStride, srcFormat, srcW);
         for (p = 0; p < 4; p++) {
             if (srcStride[p])
-                src[p] = av_mallocz(srcStride[p]*srcH+16);
+                src[p] = av_mallocz(srcStride[p] * srcH + 16);
             if (srcStride[p] && !src[p]) {
                 perror("Malloc");
                 res = -1;
-
                 goto end;
             }
         }
@@ -120,19 +118,18 @@ static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
                     av_pix_fmt_descriptors[PIX_FMT_YUVA420P].name,
                     av_pix_fmt_descriptors[srcFormat].name);
             res = -1;
-
             goto end;
         }
         sws_scale(srcContext, ref, refStride, 0, h, src, srcStride);
         sws_freeContext(srcContext);
 
         cur_srcFormat = srcFormat;
-        cur_srcW = srcW;
-        cur_srcH = srcH;
+        cur_srcW      = srcW;
+        cur_srcH      = srcH;
     }
 
     av_image_fill_linesizes(dstStride, dstFormat, dstW);
-    for (i=0; i<4; i++) {
+    for (i = 0; i < 4; i++) {
         /* Image buffers passed into libswscale can be allocated any way you
          * prefer, as long as they're aligned enough for the architecture, and
          * they're freed appropriately (such as using av_free for buffers
@@ -140,7 +137,7 @@ static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
         /* An extra 16 bytes is being allocated because some scalers may write
          * out of bounds. */
         if (dstStride[i])
-            dst[i]= av_mallocz(dstStride[i]*dstH+16);
+            dst[i] = av_mallocz(dstStride[i] * dstH + 16);
         if (dstStride[i] && !dst[i]) {
             perror("Malloc");
             res = -1;
@@ -149,13 +146,13 @@ static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
         }
     }
 
-    dstContext= sws_getContext(srcW, srcH, srcFormat, dstW, dstH, dstFormat, flags, NULL, NULL, NULL);
+    dstContext = sws_getContext(srcW, srcH, srcFormat, dstW, dstH, dstFormat,
+                                flags, NULL, NULL, NULL);
     if (!dstContext) {
         fprintf(stderr, "Failed to get %s ---> %s\n",
                 av_pix_fmt_descriptors[srcFormat].name,
                 av_pix_fmt_descriptors[dstFormat].name);
         res = -1;
-
         goto end;
     }
 
@@ -167,9 +164,9 @@ static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
 
     sws_scale(dstContext, src, srcStride, 0, srcH, dst, dstStride);
 
-    for (i = 0; i < 4 && dstStride[i]; i++) {
-        crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), crc, dst[i], dstStride[i] * dstH);
-    }
+    for (i = 0; i < 4 && dstStride[i]; i++)
+        crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), crc, dst[i],
+                     dstStride[i] * dstH);
 
     if (r && crc == r->crc) {
         ssdY = r->ssdY;
@@ -177,60 +174,59 @@ static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,
         ssdV = r->ssdV;
         ssdA = r->ssdA;
     } else {
-        for (i=0; i<4; i++) {
+        for (i = 0; i < 4; i++) {
             if (refStride[i])
-                out[i]= av_mallocz(refStride[i]*h);
+                out[i] = av_mallocz(refStride[i] * h);
             if (refStride[i] && !out[i]) {
                 perror("Malloc");
                 res = -1;
-
                 goto end;
             }
         }
-        outContext= sws_getContext(dstW, dstH, dstFormat, w, h, PIX_FMT_YUVA420P, SWS_BILINEAR, NULL, NULL, NULL);
+        outContext = sws_getContext(dstW, dstH, dstFormat, w, h,
+                                    PIX_FMT_YUVA420P, SWS_BILINEAR,
+                                    NULL, NULL, NULL);
         if (!outContext) {
             fprintf(stderr, "Failed to get %s ---> %s\n",
                     av_pix_fmt_descriptors[dstFormat].name,
                     av_pix_fmt_descriptors[PIX_FMT_YUVA420P].name);
             res = -1;
-
             goto end;
         }
         sws_scale(outContext, dst, dstStride, 0, dstH, out, refStride);
 
-        ssdY= getSSD(ref[0], out[0], refStride[0], refStride[0], w, h);
+        ssdY = getSSD(ref[0], out[0], refStride[0], refStride[0], w, h);
         if (hasChroma(srcFormat) && hasChroma(dstFormat)) {
             //FIXME check that output is really gray
-            ssdU= getSSD(ref[1], out[1], refStride[1], refStride[1], (w+1)>>1, (h+1)>>1);
-            ssdV= getSSD(ref[2], out[2], refStride[2], refStride[2], (w+1)>>1, (h+1)>>1);
+            ssdU = getSSD(ref[1], out[1], refStride[1], refStride[1],
+                          (w + 1) >> 1, (h + 1) >> 1);
+            ssdV = getSSD(ref[2], out[2], refStride[2], refStride[2],
+                          (w + 1) >> 1, (h + 1) >> 1);
         }
         if (isALPHA(srcFormat) && isALPHA(dstFormat))
-            ssdA= getSSD(ref[3], out[3], refStride[3], refStride[3], w, h);
+            ssdA = getSSD(ref[3], out[3], refStride[3], refStride[3], w, h);
 
-        ssdY/= w*h;
-        ssdU/= w*h/4;
-        ssdV/= w*h/4;
-        ssdA/= w*h;
+        ssdY /= w * h;
+        ssdU /= w * h / 4;
+        ssdV /= w * h / 4;
+        ssdA /= w * h;
 
         sws_freeContext(outContext);
 
-        for (i=0; i<4; i++) {
+        for (i = 0; i < 4; i++)
             if (refStride[i])
                 av_free(out[i]);
-        }
     }
 
-    printf(" CRC=%08x SSD=%5"PRId64",%5"PRId64",%5"PRId64",%5"PRId64"\n",
+    printf(" CRC=%08x SSD=%5"PRId64 ",%5"PRId64 ",%5"PRId64 ",%5"PRId64 "\n",
            crc, ssdY, ssdU, ssdV, ssdA);
 
 end:
-
     sws_freeContext(dstContext);
 
-    for (i=0; i<4; i++) {
+    for (i = 0; i < 4; i++)
         if (dstStride[i])
             av_free(dst[i]);
-    }
 
     return res;
 }
@@ -239,18 +235,18 @@ static void selfTest(uint8_t *ref[4], int refStride[4], int w, int h,
                      enum PixelFormat srcFormat_in,
                      enum PixelFormat dstFormat_in)
 {
-    const int flags[] = { SWS_FAST_BILINEAR,
-                          SWS_BILINEAR, SWS_BICUBIC,
-                          SWS_X       , SWS_POINT  , SWS_AREA, 0 };
-    const int srcW = w;
-    const int srcH = h;
-    const int dstW[] = { srcW - srcW/3, srcW, srcW + srcW/3, 0 };
-    const int dstH[] = { srcH - srcH/3, srcH, srcH + srcH/3, 0 };
+    const int flags[] = { SWS_FAST_BILINEAR, SWS_BILINEAR, SWS_BICUBIC,
+                          SWS_X, SWS_POINT, SWS_AREA, 0 };
+    const int srcW   = w;
+    const int srcH   = h;
+    const int dstW[] = { srcW - srcW / 3, srcW, srcW + srcW / 3, 0 };
+    const int dstH[] = { srcH - srcH / 3, srcH, srcH + srcH / 3, 0 };
     enum PixelFormat srcFormat, dstFormat;
 
     for (srcFormat = srcFormat_in != PIX_FMT_NONE ? srcFormat_in : 0;
          srcFormat < PIX_FMT_NB; srcFormat++) {
-        if (!sws_isSupportedInput(srcFormat) || !sws_isSupportedOutput(srcFormat))
+        if (!sws_isSupportedInput(srcFormat) ||
+            !sws_isSupportedOutput(srcFormat))
             continue;
 
         for (dstFormat = dstFormat_in != PIX_FMT_NONE ? dstFormat_in : 0;
@@ -258,7 +254,8 @@ static void selfTest(uint8_t *ref[4], int refStride[4], int w, int h,
             int i, j, k;
             int res = 0;
 
-            if (!sws_isSupportedInput(dstFormat) || !sws_isSupportedOutput(dstFormat))
+            if (!sws_isSupportedInput(dstFormat) ||
+                !sws_isSupportedOutput(dstFormat))
                 continue;
 
             printf("%s -> %s\n",
@@ -266,14 +263,13 @@ static void selfTest(uint8_t *ref[4], int refStride[4], int w, int h,
                    av_pix_fmt_descriptors[dstFormat].name);
             fflush(stdout);
 
-            for (k = 0; flags[k] && !res; k++) {
+            for (k = 0; flags[k] && !res; k++)
                 for (i = 0; dstW[i] && !res; i++)
                     for (j = 0; dstH[j] && !res; j++)
                         res = doTest(ref, refStride, w, h,
                                      srcFormat, dstFormat,
                                      srcW, srcH, dstW[i], dstH[j], flags[k],
                                      NULL);
-            }
             if (dstFormat_in != PIX_FMT_NONE)
                 break;
         }
@@ -299,13 +295,14 @@ static int fileTest(uint8_t *ref[4], int refStride[4], int w, int h, FILE *fp,
         int flags;
         int ret;
 
-        ret = sscanf(buf, " %12s %dx%d -> %12s %dx%d flags=%d CRC=%x"
-                          " SSD=%"PRId64", %"PRId64", %"PRId64", %"PRId64"\n",
-                          srcStr, &srcW, &srcH, dstStr, &dstW, &dstH,
-                          &flags, &r.crc, &r.ssdY, &r.ssdU, &r.ssdV, &r.ssdA);
+        ret = sscanf(buf,
+                     " %12s %dx%d -> %12s %dx%d flags=%d CRC=%x"
+                     " SSD=%"PRId64 ", %"PRId64 ", %"PRId64 ", %"PRId64 "\n",
+                     srcStr, &srcW, &srcH, dstStr, &dstW, &dstH,
+                     &flags, &r.crc, &r.ssdY, &r.ssdU, &r.ssdV, &r.ssdA);
         if (ret != 12) {
             srcStr[0] = dstStr[0] = 0;
-            ret = sscanf(buf, "%12s -> %12s\n", srcStr, dstStr);
+            ret       = sscanf(buf, "%12s -> %12s\n", srcStr, dstStr);
         }
 
         srcFormat = av_get_pix_fmt(srcStr);
@@ -339,12 +336,12 @@ int main(int argc, char **argv)
 {
     enum PixelFormat srcFormat = PIX_FMT_NONE;
     enum PixelFormat dstFormat = PIX_FMT_NONE;
-    uint8_t *rgb_data = av_malloc (W*H*4);
-    uint8_t *rgb_src[3]= {rgb_data, NULL, NULL};
-    int rgb_stride[3]={4*W, 0, 0};
-    uint8_t *data = av_malloc (4*W*H);
-    uint8_t *src[4]= {data, data+W*H, data+W*H*2, data+W*H*3};
-    int stride[4]={W, W, W, W};
+    uint8_t *rgb_data   = av_malloc(W * H * 4);
+    uint8_t *rgb_src[3] = { rgb_data, NULL, NULL };
+    int rgb_stride[3]   = { 4 * W, 0, 0 };
+    uint8_t *data       = av_malloc(4 * W * H);
+    uint8_t *src[4]     = { data, data + W * H, data + W * H * 2, data + W * H * 3 };
+    int stride[4]       = { W, W, W, W };
     int x, y;
     struct SwsContext *sws;
     AVLFG rand;
@@ -354,41 +351,40 @@ int main(int argc, char **argv)
     if (!rgb_data || !data)
         return -1;
 
-    sws= sws_getContext(W/12, H/12, PIX_FMT_RGB32, W, H, PIX_FMT_YUVA420P, SWS_BILINEAR, NULL, NULL, NULL);
+    sws = sws_getContext(W / 12, H / 12, PIX_FMT_RGB32, W, H,
+                         PIX_FMT_YUVA420P, SWS_BILINEAR, NULL, NULL, NULL);
 
     av_lfg_init(&rand, 1);
 
-    for (y=0; y<H; y++) {
-        for (x=0; x<W*4; x++) {
-            rgb_data[ x + y*4*W]= av_lfg_get(&rand);
-        }
-    }
+    for (y = 0; y < H; y++)
+        for (x = 0; x < W * 4; x++)
+            rgb_data[ x + y * 4 * W] = av_lfg_get(&rand);
     sws_scale(sws, rgb_src, rgb_stride, 0, H, src, stride);
     sws_freeContext(sws);
     av_free(rgb_data);
 
     for (i = 1; i < argc; i += 2) {
-        if (argv[i][0] != '-' || i+1 == argc)
+        if (argv[i][0] != '-' || i + 1 == argc)
             goto bad_option;
         if (!strcmp(argv[i], "-ref")) {
-            FILE *fp = fopen(argv[i+1], "r");
+            FILE *fp = fopen(argv[i + 1], "r");
             if (!fp) {
-                fprintf(stderr, "could not open '%s'\n", argv[i+1]);
+                fprintf(stderr, "could not open '%s'\n", argv[i + 1]);
                 goto error;
             }
             res = fileTest(src, stride, W, H, fp, srcFormat, dstFormat);
             fclose(fp);
             goto end;
         } else if (!strcmp(argv[i], "-src")) {
-            srcFormat = av_get_pix_fmt(argv[i+1]);
+            srcFormat = av_get_pix_fmt(argv[i + 1]);
             if (srcFormat == PIX_FMT_NONE) {
-                fprintf(stderr, "invalid pixel format %s\n", argv[i+1]);
+                fprintf(stderr, "invalid pixel format %s\n", argv[i + 1]);
                 return -1;
             }
         } else if (!strcmp(argv[i], "-dst")) {
-            dstFormat = av_get_pix_fmt(argv[i+1]);
+            dstFormat = av_get_pix_fmt(argv[i + 1]);
             if (dstFormat == PIX_FMT_NONE) {
-                fprintf(stderr, "invalid pixel format %s\n", argv[i+1]);
+                fprintf(stderr, "invalid pixel format %s\n", argv[i + 1]);
                 return -1;
             }
         } else {
diff --git a/libswscale/swscale.c b/libswscale/swscale.c
index f24561b..05ee8a4 100644
--- a/libswscale/swscale.c
+++ b/libswscale/swscale.c
@@ -18,39 +18,6 @@
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
-/*
-  supported Input formats: YV12, I420/IYUV, YUY2, UYVY, BGR32, BGR32_1, BGR24, BGR16, BGR15, RGB32, RGB32_1, RGB24, Y8/Y800, YVU9/IF09, PAL8
-  supported output formats: YV12, I420/IYUV, YUY2, UYVY, {BGR,RGB}{1,4,8,15,16,24,32}, Y8/Y800, YVU9/IF09
-  {BGR,RGB}{1,4,8,15,16} support dithering
-
-  unscaled special converters (YV12=I420=IYUV, Y800=Y8)
-  YV12 -> {BGR,RGB}{1,4,8,12,15,16,24,32}
-  x -> x
-  YUV9 -> YV12
-  YUV9/YV12 -> Y800
-  Y800 -> YUV9/YV12
-  BGR24 -> BGR32 & RGB24 -> RGB32
-  BGR32 -> BGR24 & RGB32 -> RGB24
-  BGR15 -> BGR16
-*/
-
-/*
-tested special converters (most are tested actually, but I did not write it down ...)
- YV12 -> BGR12/BGR16
- YV12 -> YV12
- BGR15 -> BGR16
- BGR16 -> BGR16
- YVU9 -> YV12
-
-untested special converters
-  YV12/I420 -> BGR15/BGR24/BGR32 (it is the yuv2rgb stuff, so it should be OK)
-  YV12/I420 -> YV12/I420
-  YUY2/BGR15/BGR24/BGR32/RGB24/RGB32 -> same format
-  BGR24 -> BGR32 & RGB24 -> RGB32
-  BGR32 -> BGR24 & RGB32 -> RGB24
-  BGR24 -> YV12
-*/
-
 #include <inttypes.h>
 #include <string.h>
 #include <math.h>
@@ -917,9 +884,17 @@ YUV2PACKED16WRAPPER(yuv2, rgb48, rgb48le, PIX_FMT_RGB48LE)
 YUV2PACKED16WRAPPER(yuv2, rgb48, bgr48be, PIX_FMT_BGR48BE)
 YUV2PACKED16WRAPPER(yuv2, rgb48, bgr48le, PIX_FMT_BGR48LE)
 
+/*
+ * Write out 2 RGB pixels in the target pixel format. This function takes a
+ * R/G/B LUT as generated by ff_yuv2rgb_c_init_tables(), which takes care of
+ * things like endianness conversion and shifting. The caller takes care of
+ * setting the correct offset in these tables from the chroma (U/V) values.
+ * This function then uses the luminance (Y1/Y2) values to write out the
+ * correct RGB values into the destination buffer.
+ */
 static av_always_inline void
 yuv2rgb_write(uint8_t *_dest, int i, unsigned Y1, unsigned Y2,
-              unsigned U, unsigned V, unsigned A1, unsigned A2,
+              unsigned A1, unsigned A2,
               const void *_r, const void *_g, const void *_b, int y,
               enum PixelFormat target, int hasAlpha)
 {
@@ -1086,7 +1061,7 @@ yuv2rgb_X_c_template(SwsContext *c, const int16_t *lumFilter,
         g = (c->table_gU[U] + c->table_gV[V]);
         b =  c->table_bU[U];
 
-        yuv2rgb_write(dest, i, Y1, Y2, U, V, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
+        yuv2rgb_write(dest, i, Y1, Y2, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
                       r, g, b, y, target, hasAlpha);
     }
 }
@@ -1122,7 +1097,7 @@ yuv2rgb_2_c_template(SwsContext *c, const int16_t *buf[2],
             A2 = (abuf0[i * 2 + 1] * yalpha1 + abuf1[i * 2 + 1] * yalpha) >> 19;
         }
 
-        yuv2rgb_write(dest, i, Y1, Y2, U, V, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
+        yuv2rgb_write(dest, i, Y1, Y2, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
                       r, g, b, y, target, hasAlpha);
     }
 }
@@ -1154,7 +1129,7 @@ yuv2rgb_1_c_template(SwsContext *c, const int16_t *buf0,
                 A2 = abuf0[i * 2 + 1] >> 7;
             }
 
-            yuv2rgb_write(dest, i, Y1, Y2, U, V, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
+            yuv2rgb_write(dest, i, Y1, Y2, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
                           r, g, b, y, target, hasAlpha);
         }
     } else {
@@ -1173,7 +1148,7 @@ yuv2rgb_1_c_template(SwsContext *c, const int16_t *buf0,
                 A2 = abuf0[i * 2 + 1] >> 7;
             }
 
-            yuv2rgb_write(dest, i, Y1, Y2, U, V, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
+            yuv2rgb_write(dest, i, Y1, Y2, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,
                           r, g, b, y, target, hasAlpha);
         }
     }
@@ -1562,12 +1537,16 @@ rgb16_32_wrapper(PIX_FMT_RGB32,    rgb32,   0, 0, 16, 0,   0x00FF, 0xFF00, 0xFF0
 rgb16_32_wrapper(PIX_FMT_RGB32_1,  rgb321,  0, 0, 16, 8,   0x00FF, 0xFF00, 0xFF0000,  8, 0,  8, RGB2YUV_SHIFT+8)
 rgb16_32_wrapper(PIX_FMT_BGR565LE, bgr16le, 0, 0,  0, 0,   0x001F, 0x07E0,   0xF800, 11, 5,  0, RGB2YUV_SHIFT+8)
 rgb16_32_wrapper(PIX_FMT_BGR555LE, bgr15le, 0, 0,  0, 0,   0x001F, 0x03E0,   0x7C00, 10, 5,  0, RGB2YUV_SHIFT+7)
+rgb16_32_wrapper(PIX_FMT_BGR444LE, bgr12le, 0, 0,  0, 0,   0x000F, 0x00F0,   0x0F00,  8, 4,  0, RGB2YUV_SHIFT+4)
 rgb16_32_wrapper(PIX_FMT_RGB565LE, rgb16le, 0, 0,  0, 0,   0xF800, 0x07E0,   0x001F,  0, 5, 11, RGB2YUV_SHIFT+8)
 rgb16_32_wrapper(PIX_FMT_RGB555LE, rgb15le, 0, 0,  0, 0,   0x7C00, 0x03E0,   0x001F,  0, 5, 10, RGB2YUV_SHIFT+7)
+rgb16_32_wrapper(PIX_FMT_RGB444LE, rgb12le, 0, 0,  0, 0,   0x0F00, 0x00F0,   0x000F,  0, 4,  8, RGB2YUV_SHIFT+4)
 rgb16_32_wrapper(PIX_FMT_BGR565BE, bgr16be, 0, 0,  0, 0,   0x001F, 0x07E0,   0xF800, 11, 5,  0, RGB2YUV_SHIFT+8)
 rgb16_32_wrapper(PIX_FMT_BGR555BE, bgr15be, 0, 0,  0, 0,   0x001F, 0x03E0,   0x7C00, 10, 5,  0, RGB2YUV_SHIFT+7)
+rgb16_32_wrapper(PIX_FMT_BGR444BE, bgr12be, 0, 0,  0, 0,   0x000F, 0x00F0,   0x0F00,  8, 4,  0, RGB2YUV_SHIFT+4)
 rgb16_32_wrapper(PIX_FMT_RGB565BE, rgb16be, 0, 0,  0, 0,   0xF800, 0x07E0,   0x001F,  0, 5, 11, RGB2YUV_SHIFT+8)
 rgb16_32_wrapper(PIX_FMT_RGB555BE, rgb15be, 0, 0,  0, 0,   0x7C00, 0x03E0,   0x001F,  0, 5, 10, RGB2YUV_SHIFT+7)
+rgb16_32_wrapper(PIX_FMT_RGB444BE, rgb12be, 0, 0,  0, 0,   0x0F00, 0x00F0,   0x000F,  0, 4,  8, RGB2YUV_SHIFT+4)
 
 static void abgrToA_c(uint8_t *dst, const uint8_t *src, int width, uint32_t *unused)
 {
@@ -2223,36 +2202,6 @@ find_c_packed_planar_out_funcs(SwsContext *c,
         }
     } else {
         switch (dstFormat) {
-        case PIX_FMT_GRAY16BE:
-            *yuv2packed1 = yuv2gray16BE_1_c;
-            *yuv2packed2 = yuv2gray16BE_2_c;
-            *yuv2packedX = yuv2gray16BE_X_c;
-            break;
-        case PIX_FMT_GRAY16LE:
-            *yuv2packed1 = yuv2gray16LE_1_c;
-            *yuv2packed2 = yuv2gray16LE_2_c;
-            *yuv2packedX = yuv2gray16LE_X_c;
-            break;
-        case PIX_FMT_MONOWHITE:
-            *yuv2packed1 = yuv2monowhite_1_c;
-            *yuv2packed2 = yuv2monowhite_2_c;
-            *yuv2packedX = yuv2monowhite_X_c;
-            break;
-        case PIX_FMT_MONOBLACK:
-            *yuv2packed1 = yuv2monoblack_1_c;
-            *yuv2packed2 = yuv2monoblack_2_c;
-            *yuv2packedX = yuv2monoblack_X_c;
-            break;
-        case PIX_FMT_YUYV422:
-            *yuv2packed1 = yuv2yuyv422_1_c;
-            *yuv2packed2 = yuv2yuyv422_2_c;
-            *yuv2packedX = yuv2yuyv422_X_c;
-            break;
-        case PIX_FMT_UYVY422:
-            *yuv2packed1 = yuv2uyvy422_1_c;
-            *yuv2packed2 = yuv2uyvy422_2_c;
-            *yuv2packedX = yuv2uyvy422_X_c;
-            break;
         case PIX_FMT_RGB48LE:
             *yuv2packed1 = yuv2rgb48le_1_c;
             *yuv2packed2 = yuv2rgb48le_2_c;
@@ -2369,6 +2318,38 @@ find_c_packed_planar_out_funcs(SwsContext *c,
             break;
         }
     }
+    switch (dstFormat) {
+    case PIX_FMT_GRAY16BE:
+        *yuv2packed1 = yuv2gray16BE_1_c;
+        *yuv2packed2 = yuv2gray16BE_2_c;
+        *yuv2packedX = yuv2gray16BE_X_c;
+        break;
+    case PIX_FMT_GRAY16LE:
+        *yuv2packed1 = yuv2gray16LE_1_c;
+        *yuv2packed2 = yuv2gray16LE_2_c;
+        *yuv2packedX = yuv2gray16LE_X_c;
+        break;
+    case PIX_FMT_MONOWHITE:
+        *yuv2packed1 = yuv2monowhite_1_c;
+        *yuv2packed2 = yuv2monowhite_2_c;
+        *yuv2packedX = yuv2monowhite_X_c;
+        break;
+    case PIX_FMT_MONOBLACK:
+        *yuv2packed1 = yuv2monoblack_1_c;
+        *yuv2packed2 = yuv2monoblack_2_c;
+        *yuv2packedX = yuv2monoblack_X_c;
+        break;
+    case PIX_FMT_YUYV422:
+        *yuv2packed1 = yuv2yuyv422_1_c;
+        *yuv2packed2 = yuv2yuyv422_2_c;
+        *yuv2packedX = yuv2yuyv422_X_c;
+        break;
+    case PIX_FMT_UYVY422:
+        *yuv2packed1 = yuv2uyvy422_1_c;
+        *yuv2packed2 = yuv2uyvy422_2_c;
+        *yuv2packedX = yuv2uyvy422_X_c;
+        break;
+    }
 }
 
 #define DEBUG_SWSCALE_BUFFERS 0
@@ -2771,6 +2752,8 @@ static av_cold void sws_init_swScale_c(SwsContext *c)
         case PIX_FMT_BGR565BE: c->chrToYV12 = bgr16beToUV_half_c; break;
         case PIX_FMT_BGR555LE: c->chrToYV12 = bgr15leToUV_half_c; break;
         case PIX_FMT_BGR555BE: c->chrToYV12 = bgr15beToUV_half_c; break;
+        case PIX_FMT_BGR444LE: c->chrToYV12 = bgr12leToUV_half_c; break;
+        case PIX_FMT_BGR444BE: c->chrToYV12 = bgr12beToUV_half_c; break;
         case PIX_FMT_BGR32   : c->chrToYV12 = rgb32ToUV_half_c;   break;
         case PIX_FMT_BGR32_1 : c->chrToYV12 = rgb321ToUV_half_c;  break;
         case PIX_FMT_RGB24   : c->chrToYV12 = rgb24ToUV_half_c;   break;
@@ -2778,6 +2761,8 @@ static av_cold void sws_init_swScale_c(SwsContext *c)
         case PIX_FMT_RGB565BE: c->chrToYV12 = rgb16beToUV_half_c; break;
         case PIX_FMT_RGB555LE: c->chrToYV12 = rgb15leToUV_half_c; break;
         case PIX_FMT_RGB555BE: c->chrToYV12 = rgb15beToUV_half_c; break;
+        case PIX_FMT_RGB444LE: c->chrToYV12 = rgb12leToUV_half_c; break;
+        case PIX_FMT_RGB444BE: c->chrToYV12 = rgb12beToUV_half_c; break;
         }
     } else {
         switch(srcFormat) {
@@ -2792,6 +2777,8 @@ static av_cold void sws_init_swScale_c(SwsContext *c)
         case PIX_FMT_BGR565BE: c->chrToYV12 = bgr16beToUV_c; break;
         case PIX_FMT_BGR555LE: c->chrToYV12 = bgr15leToUV_c; break;
         case PIX_FMT_BGR555BE: c->chrToYV12 = bgr15beToUV_c; break;
+        case PIX_FMT_BGR444LE: c->chrToYV12 = bgr12leToUV_c; break;
+        case PIX_FMT_BGR444BE: c->chrToYV12 = bgr12beToUV_c; break;
         case PIX_FMT_BGR32   : c->chrToYV12 = rgb32ToUV_c;   break;
         case PIX_FMT_BGR32_1 : c->chrToYV12 = rgb321ToUV_c;  break;
         case PIX_FMT_RGB24   : c->chrToYV12 = rgb24ToUV_c;   break;
@@ -2799,6 +2786,8 @@ static av_cold void sws_init_swScale_c(SwsContext *c)
         case PIX_FMT_RGB565BE: c->chrToYV12 = rgb16beToUV_c; break;
         case PIX_FMT_RGB555LE: c->chrToYV12 = rgb15leToUV_c; break;
         case PIX_FMT_RGB555BE: c->chrToYV12 = rgb15beToUV_c; break;
+        case PIX_FMT_RGB444LE: c->chrToYV12 = rgb12leToUV_c; break;
+        case PIX_FMT_RGB444BE: c->chrToYV12 = rgb12beToUV_c; break;
         }
     }
 
@@ -2843,11 +2832,15 @@ static av_cold void sws_init_swScale_c(SwsContext *c)
     case PIX_FMT_BGR565BE : c->lumToYV12 = bgr16beToY_c; break;
     case PIX_FMT_BGR555LE : c->lumToYV12 = bgr15leToY_c; break;
     case PIX_FMT_BGR555BE : c->lumToYV12 = bgr15beToY_c; break;
+    case PIX_FMT_BGR444LE : c->lumToYV12 = bgr12leToY_c; break;
+    case PIX_FMT_BGR444BE : c->lumToYV12 = bgr12beToY_c; break;
     case PIX_FMT_RGB24    : c->lumToYV12 = rgb24ToY_c;   break;
     case PIX_FMT_RGB565LE : c->lumToYV12 = rgb16leToY_c; break;
     case PIX_FMT_RGB565BE : c->lumToYV12 = rgb16beToY_c; break;
     case PIX_FMT_RGB555LE : c->lumToYV12 = rgb15leToY_c; break;
     case PIX_FMT_RGB555BE : c->lumToYV12 = rgb15beToY_c; break;
+    case PIX_FMT_RGB444LE : c->lumToYV12 = rgb12leToY_c; break;
+    case PIX_FMT_RGB444BE : c->lumToYV12 = rgb12beToY_c; break;
     case PIX_FMT_RGB8     :
     case PIX_FMT_BGR8     :
     case PIX_FMT_PAL8     :
diff --git a/libswscale/swscale.h b/libswscale/swscale.h
index 5cd55a7..b5a6a57 100644
--- a/libswscale/swscale.h
+++ b/libswscale/swscale.h
@@ -132,7 +132,6 @@ const char *swscale_license(void);
  */
 const int *sws_getCoefficients(int colorspace);
 
-
 // when used for filters they must have an odd number of elements
 // coeffs cannot be shared between vectors
 typedef struct {
@@ -232,9 +231,9 @@ struct SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat
  *                  the destination image
  * @return          the height of the output slice
  */
-int sws_scale(struct SwsContext *c, const uint8_t* const srcSlice[],
+int sws_scale(struct SwsContext *c, const uint8_t *const srcSlice[],
               const int srcStride[], int srcSliceY, int srcSliceH,
-              uint8_t* const dst[], const int dstStride[]);
+              uint8_t *const dst[], const int dstStride[]);
 
 /**
  * @param inv_table the yuv2rgb coefficients, normally ff_yuv2rgb_coeffs[x]
diff --git a/libswscale/swscale_internal.h b/libswscale/swscale_internal.h
index bb3b52d..3436b92 100644
--- a/libswscale/swscale_internal.h
+++ b/libswscale/swscale_internal.h
@@ -32,9 +32,9 @@
 #include "libavutil/pixfmt.h"
 #include "libavutil/pixdesc.h"
 
-#define STR(s)         AV_TOSTRING(s) //AV_STRINGIFY is too long
+#define STR(s) AV_TOSTRING(s) // AV_STRINGIFY is too long
 
-#define FAST_BGR2YV12 //use 7-bit instead of 15-bit coefficients
+#define FAST_BGR2YV12 // use 7-bit instead of 15-bit coefficients
 
 #define MAX_FILTER_SIZE 256
 
@@ -45,21 +45,20 @@
 #endif
 
 #if ARCH_X86_64
-#   define APCK_PTR2 8
+#   define APCK_PTR2  8
 #   define APCK_COEF 16
 #   define APCK_SIZE 24
 #else
-#   define APCK_PTR2 4
-#   define APCK_COEF 8
+#   define APCK_PTR2  4
+#   define APCK_COEF  8
 #   define APCK_SIZE 16
 #endif
 
 struct SwsContext;
 
-typedef int (*SwsFunc)(struct SwsContext *context, const uint8_t* src[],
+typedef int (*SwsFunc)(struct SwsContext *context, const uint8_t *src[],
                        int srcStride[], int srcSliceY, int srcSliceH,
-                       uint8_t* dst[], int dstStride[]);
-
+                       uint8_t *dst[], int dstStride[]);
 
 /**
  * Write one line of horizontally scaled data to planar output
@@ -73,8 +72,8 @@ typedef int (*SwsFunc)(struct SwsContext *context, const uint8_t* src[],
  * @param dither  ordered dither array of type int16_t and size 8
  * @param offset  Dither offset
  */
-typedef void (*yuv2planar1_fn) (const int16_t *src, uint8_t *dest, int dstW,
-                                const uint8_t *dither, int offset);
+typedef void (*yuv2planar1_fn)(const int16_t *src, uint8_t *dest, int dstW,
+                               const uint8_t *dither, int offset);
 
 /**
  * Write one line of horizontally scaled data to planar output
@@ -89,9 +88,9 @@ typedef void (*yuv2planar1_fn) (const int16_t *src, uint8_t *dest, int dstW,
  * @param dstW          width of destination pixels
  * @param offset        Dither offset
  */
-typedef void (*yuv2planarX_fn) (const int16_t *filter, int filterSize,
-                                const int16_t **src, uint8_t *dest, int dstW,
-                                const uint8_t *dither, int offset);
+typedef void (*yuv2planarX_fn)(const int16_t *filter, int filterSize,
+                               const int16_t **src, uint8_t *dest, int dstW,
+                               const uint8_t *dither, int offset);
 
 /**
  * Write one line of horizontally scaled chroma to interleaved output
@@ -108,9 +107,12 @@ typedef void (*yuv2planarX_fn) (const int16_t *filter, int filterSize,
  *                      output, this is in uint16_t
  * @param dstW          width of chroma planes
  */
-typedef void (*yuv2interleavedX_fn) (struct SwsContext *c, const int16_t *chrFilter, int chrFilterSize,
-                                     const int16_t **chrUSrc, const int16_t **chrVSrc,
-                                     uint8_t *dest, int dstW);
+typedef void (*yuv2interleavedX_fn)(struct SwsContext *c,
+                                    const int16_t *chrFilter,
+                                    int chrFilterSize,
+                                    const int16_t **chrUSrc,
+                                    const int16_t **chrVSrc,
+                                    uint8_t *dest, int dstW);
 
 /**
  * Write one line of horizontally scaled Y/U/V/A to packed-pixel YUV/RGB
@@ -141,10 +143,11 @@ typedef void (*yuv2interleavedX_fn) (struct SwsContext *c, const int16_t *chrFil
  *                but can be used to generate comfort noise using dithering
  *                for some output formats.
  */
-typedef void (*yuv2packed1_fn) (struct SwsContext *c,  const int16_t *lumSrc,
-                                const int16_t *chrUSrc[2], const int16_t *chrVSrc[2],
-                                const int16_t *alpSrc,  uint8_t *dest,
-                                int dstW, int uvalpha, int y);
+typedef void (*yuv2packed1_fn)(struct SwsContext *c, const int16_t *lumSrc,
+                               const int16_t *chrUSrc[2],
+                               const int16_t *chrVSrc[2],
+                               const int16_t *alpSrc, uint8_t *dest,
+                               int dstW, int uvalpha, int y);
 /**
  * Write one line of horizontally scaled Y/U/V/A to packed-pixel YUV/RGB
  * output by doing bilinear scaling between two input lines.
@@ -173,10 +176,12 @@ typedef void (*yuv2packed1_fn) (struct SwsContext *c,  const int16_t *lumSrc,
  *                but can be used to generate comfort noise using dithering
  *                for some output formats.
  */
-typedef void (*yuv2packed2_fn) (struct SwsContext *c,  const int16_t *lumSrc[2],
-                                const int16_t *chrUSrc[2], const int16_t *chrVSrc[2],
-                                const int16_t *alpSrc[2], uint8_t *dest,
-                                int dstW, int yalpha, int uvalpha, int y);
+typedef void (*yuv2packed2_fn)(struct SwsContext *c, const int16_t *lumSrc[2],
+                               const int16_t *chrUSrc[2],
+                               const int16_t *chrVSrc[2],
+                               const int16_t *alpSrc[2],
+                               uint8_t *dest,
+                               int dstW, int yalpha, int uvalpha, int y);
 /**
  * Write one line of horizontally scaled Y/U/V/A to packed-pixel YUV/RGB
  * output by doing multi-point vertical scaling between input pixels.
@@ -203,12 +208,13 @@ typedef void (*yuv2packed2_fn) (struct SwsContext *c,  const int16_t *lumSrc[2],
  *                      but can be used to generate comfort noise using dithering
  *                      or some output formats.
  */
-typedef void (*yuv2packedX_fn) (struct SwsContext *c, const int16_t *lumFilter,
-                                const int16_t **lumSrc, int lumFilterSize,
-                                const int16_t *chrFilter, const int16_t **chrUSrc,
-                                const int16_t **chrVSrc, int chrFilterSize,
-                                const int16_t **alpSrc, uint8_t *dest,
-                                int dstW, int y);
+typedef void (*yuv2packedX_fn)(struct SwsContext *c, const int16_t *lumFilter,
+                               const int16_t **lumSrc, int lumFilterSize,
+                               const int16_t *chrFilter,
+                               const int16_t **chrUSrc,
+                               const int16_t **chrVSrc, int chrFilterSize,
+                               const int16_t **alpSrc, uint8_t *dest,
+                               int dstW, int y);
 
 /* This struct should be aligned on at least a 32-byte boundary. */
 typedef struct SwsContext {
@@ -261,12 +267,12 @@ typedef struct SwsContext {
     int16_t **chrUPixBuf;         ///< Ring buffer for scaled horizontal chroma plane lines to be fed to the vertical scaler.
     int16_t **chrVPixBuf;         ///< Ring buffer for scaled horizontal chroma plane lines to be fed to the vertical scaler.
     int16_t **alpPixBuf;          ///< Ring buffer for scaled horizontal alpha  plane lines to be fed to the vertical scaler.
-    int       vLumBufSize;        ///< Number of vertical luma/alpha lines allocated in the ring buffer.
-    int       vChrBufSize;        ///< Number of vertical chroma     lines allocated in the ring buffer.
-    int       lastInLumBuf;       ///< Last scaled horizontal luma/alpha line from source in the ring buffer.
-    int       lastInChrBuf;       ///< Last scaled horizontal chroma     line from source in the ring buffer.
-    int       lumBufIndex;        ///< Index in ring buffer of the last scaled horizontal luma/alpha line from source.
-    int       chrBufIndex;        ///< Index in ring buffer of the last scaled horizontal chroma     line from source.
+    int vLumBufSize;              ///< Number of vertical luma/alpha lines allocated in the ring buffer.
+    int vChrBufSize;              ///< Number of vertical chroma     lines allocated in the ring buffer.
+    int lastInLumBuf;             ///< Last scaled horizontal luma/alpha line from source in the ring buffer.
+    int lastInChrBuf;             ///< Last scaled horizontal chroma     line from source in the ring buffer.
+    int lumBufIndex;              ///< Index in ring buffer of the last scaled horizontal luma/alpha line from source.
+    int chrBufIndex;              ///< Index in ring buffer of the last scaled horizontal chroma     line from source.
     //@}
 
     uint8_t *formatConvBuffer;
@@ -293,10 +299,10 @@ typedef struct SwsContext {
     int16_t *hChrFilterPos;       ///< Array of horizontal filter starting positions for each dst[i] for chroma     planes.
     int16_t *vLumFilterPos;       ///< Array of vertical   filter starting positions for each dst[i] for luma/alpha planes.
     int16_t *vChrFilterPos;       ///< Array of vertical   filter starting positions for each dst[i] for chroma     planes.
-    int      hLumFilterSize;      ///< Horizontal filter size for luma/alpha pixels.
-    int      hChrFilterSize;      ///< Horizontal filter size for chroma     pixels.
-    int      vLumFilterSize;      ///< Vertical   filter size for luma/alpha pixels.
-    int      vChrFilterSize;      ///< Vertical   filter size for chroma     pixels.
+    int hLumFilterSize;           ///< Horizontal filter size for luma/alpha pixels.
+    int hChrFilterSize;           ///< Horizontal filter size for chroma     pixels.
+    int vLumFilterSize;           ///< Vertical   filter size for luma/alpha pixels.
+    int vChrFilterSize;           ///< Vertical   filter size for chroma     pixels.
     //@}
 
     int lumMmx2FilterCodeSize;    ///< Runtime-generated MMX2 horizontal fast bilinear scaler code size for luma/alpha planes.
@@ -308,11 +314,11 @@ typedef struct SwsContext {
 
     int dstY;                     ///< Last destination vertical line output from last slice.
     int flags;                    ///< Flags passed by the user to select scaler algorithm, optimizations, subsampling, etc...
-    void * yuvTable;            // pointer to the yuv->rgb table start so it can be freed()
-    uint8_t * table_rV[256];
-    uint8_t * table_gU[256];
-    int    table_gV[256];
-    uint8_t * table_bU[256];
+    void *yuvTable;             // pointer to the yuv->rgb table start so it can be freed()
+    uint8_t *table_rV[256];
+    uint8_t *table_gU[256];
+    int table_gV[256];
+    uint8_t *table_bU[256];
 
     //Colorspace stuff
     int contrast, brightness, saturation;    // for sws_getColorspaceDetails
@@ -364,15 +370,15 @@ typedef struct SwsContext {
     DECLARE_ALIGNED(8, uint64_t, yOffset);
     DECLARE_ALIGNED(8, uint64_t, uOffset);
     DECLARE_ALIGNED(8, uint64_t, vOffset);
-    int32_t  lumMmxFilter[4*MAX_FILTER_SIZE];
-    int32_t  chrMmxFilter[4*MAX_FILTER_SIZE];
+    int32_t lumMmxFilter[4 * MAX_FILTER_SIZE];
+    int32_t chrMmxFilter[4 * MAX_FILTER_SIZE];
     int dstW;                     ///< Width  of destination luma/alpha planes.
     DECLARE_ALIGNED(8, uint64_t, esp);
     DECLARE_ALIGNED(8, uint64_t, vRounder);
     DECLARE_ALIGNED(8, uint64_t, u_temp);
     DECLARE_ALIGNED(8, uint64_t, v_temp);
     DECLARE_ALIGNED(8, uint64_t, y_temp);
-    int32_t  alpMmxFilter[4*MAX_FILTER_SIZE];
+    int32_t alpMmxFilter[4 * MAX_FILTER_SIZE];
     // alignment of these values is not necessary, but merely here
     // to maintain the same offset across x8632 and x86-64. Once we
     // use proper offset macros in the asm, they can be removed.
@@ -391,7 +397,7 @@ typedef struct SwsContext {
     vector signed short   CGV;
     vector signed short   OY;
     vector unsigned short CSHIFT;
-    vector signed short   *vYCoeffsBank, *vCCoeffsBank;
+    vector signed short  *vYCoeffsBank, *vCCoeffsBank;
 #endif
 
 #if ARCH_BFIN
@@ -420,21 +426,25 @@ typedef struct SwsContext {
     yuv2packed2_fn yuv2packed2;
     yuv2packedX_fn yuv2packedX;
 
+    /// Unscaled conversion of luma plane to YV12 for horizontal scaler.
     void (*lumToYV12)(uint8_t *dst, const uint8_t *src,
-                      int width, uint32_t *pal); ///< Unscaled conversion of luma plane to YV12 for horizontal scaler.
+                      int width, uint32_t *pal);
+    /// Unscaled conversion of alpha plane to YV12 for horizontal scaler.
     void (*alpToYV12)(uint8_t *dst, const uint8_t *src,
-                      int width, uint32_t *pal); ///< Unscaled conversion of alpha plane to YV12 for horizontal scaler.
+                      int width, uint32_t *pal);
+    /// Unscaled conversion of chroma planes to YV12 for horizontal scaler.
     void (*chrToYV12)(uint8_t *dstU, uint8_t *dstV,
                       const uint8_t *src1, const uint8_t *src2,
-                      int width, uint32_t *pal); ///< Unscaled conversion of chroma planes to YV12 for horizontal scaler.
+                      int width, uint32_t *pal);
 
     /**
-      * Functions to read planar input, such as planar RGB, and convert
-      * internally to Y/UV.
-      */
+     * Functions to read planar input, such as planar RGB, and convert
+     * internally to Y/UV.
+     */
     /** @{ */
     void (*readLumPlanar)(uint8_t *dst, const uint8_t *src[4], int width);
-    void (*readChrPlanar)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src[4], int width);
+    void (*readChrPlanar)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src[4],
+                          int width);
     /** @} */
 
     /**
@@ -496,19 +506,20 @@ typedef struct SwsContext {
      *                   to simplify creating SIMD code.
      */
     /** @{ */
-    void (*hyScale)(struct SwsContext *c, int16_t *dst, int dstW, const uint8_t *src,
-                    const int16_t *filter, const int16_t *filterPos,
-                    int filterSize);
-    void (*hcScale)(struct SwsContext *c, int16_t *dst, int dstW, const uint8_t *src,
-                    const int16_t *filter, const int16_t *filterPos,
-                    int filterSize);
+    void (*hyScale)(struct SwsContext *c, int16_t *dst, int dstW,
+                    const uint8_t *src, const int16_t *filter,
+                    const int16_t *filterPos, int filterSize);
+    void (*hcScale)(struct SwsContext *c, int16_t *dst, int dstW,
+                    const uint8_t *src, const int16_t *filter,
+                    const int16_t *filterPos, int filterSize);
     /** @} */
 
-    void (*lumConvertRange)(int16_t *dst, int width); ///< Color range conversion function for luma plane if needed.
-    void (*chrConvertRange)(int16_t *dst1, int16_t *dst2, int width); ///< Color range conversion function for chroma planes if needed.
+    /// Color range conversion function for luma plane if needed.
+    void (*lumConvertRange)(int16_t *dst, int width);
+    /// Color range conversion function for chroma planes if needed.
+    void (*chrConvertRange)(int16_t *dst1, int16_t *dst2, int width);
 
     int needs_hcscale; ///< Set if there are chroma planes to be converted.
-
 } SwsContext;
 //FIXME check init (where 0)
 
@@ -557,66 +568,64 @@ const char *sws_format_name(enum PixelFormat format);
     (!(av_pix_fmt_descriptors[x].flags & PIX_FMT_PAL) && \
      av_pix_fmt_descriptors[x].nb_components <= 2)
 #else
-#define isGray(x)       (           \
-           (x)==PIX_FMT_GRAY8       \
-        || (x)==PIX_FMT_Y400A      \
-        || (x)==PIX_FMT_GRAY16BE    \
-        || (x)==PIX_FMT_GRAY16LE    \
-    )
+#define isGray(x)                      \
+    ((x) == PIX_FMT_GRAY8       ||     \
+     (x) == PIX_FMT_Y400A       ||     \
+     (x) == PIX_FMT_GRAY16BE    ||     \
+     (x) == PIX_FMT_GRAY16LE)
 #endif
 
-#define isRGBinInt(x)   (           \
-           (x)==PIX_FMT_RGB48BE     \
-        || (x)==PIX_FMT_RGB48LE     \
-        || (x)==PIX_FMT_RGB32       \
-        || (x)==PIX_FMT_RGB32_1     \
-        || (x)==PIX_FMT_RGB24       \
-        || (x)==PIX_FMT_RGB565BE    \
-        || (x)==PIX_FMT_RGB565LE    \
-        || (x)==PIX_FMT_RGB555BE    \
-        || (x)==PIX_FMT_RGB555LE    \
-        || (x)==PIX_FMT_RGB444BE    \
-        || (x)==PIX_FMT_RGB444LE    \
-        || (x)==PIX_FMT_RGB8        \
-        || (x)==PIX_FMT_RGB4        \
-        || (x)==PIX_FMT_RGB4_BYTE   \
-        || (x)==PIX_FMT_MONOBLACK   \
-        || (x)==PIX_FMT_MONOWHITE   \
-    )
-#define isBGRinInt(x)   (           \
-           (x)==PIX_FMT_BGR48BE     \
-        || (x)==PIX_FMT_BGR48LE     \
-        || (x)==PIX_FMT_BGR32       \
-        || (x)==PIX_FMT_BGR32_1     \
-        || (x)==PIX_FMT_BGR24       \
-        || (x)==PIX_FMT_BGR565BE    \
-        || (x)==PIX_FMT_BGR565LE    \
-        || (x)==PIX_FMT_BGR555BE    \
-        || (x)==PIX_FMT_BGR555LE    \
-        || (x)==PIX_FMT_BGR444BE    \
-        || (x)==PIX_FMT_BGR444LE    \
-        || (x)==PIX_FMT_BGR8        \
-        || (x)==PIX_FMT_BGR4        \
-        || (x)==PIX_FMT_BGR4_BYTE   \
-        || (x)==PIX_FMT_MONOBLACK   \
-        || (x)==PIX_FMT_MONOWHITE   \
-    )
-#define isAnyRGB(x)     (           \
-            isRGBinInt(x)           \
-        ||  isBGRinInt(x)           \
-    )
-#define isALPHA(x) \
-    (av_pix_fmt_descriptors[x].nb_components == 2 || \
+#define isRGBinInt(x)                  \
+    ((x) == PIX_FMT_RGB48BE     ||     \
+     (x) == PIX_FMT_RGB48LE     ||     \
+     (x) == PIX_FMT_RGB32       ||     \
+     (x) == PIX_FMT_RGB32_1     ||     \
+     (x) == PIX_FMT_RGB24       ||     \
+     (x) == PIX_FMT_RGB565BE    ||     \
+     (x) == PIX_FMT_RGB565LE    ||     \
+     (x) == PIX_FMT_RGB555BE    ||     \
+     (x) == PIX_FMT_RGB555LE    ||     \
+     (x) == PIX_FMT_RGB444BE    ||     \
+     (x) == PIX_FMT_RGB444LE    ||     \
+     (x) == PIX_FMT_RGB8        ||     \
+     (x) == PIX_FMT_RGB4        ||     \
+     (x) == PIX_FMT_RGB4_BYTE   ||     \
+     (x) == PIX_FMT_MONOBLACK   ||     \
+     (x) == PIX_FMT_MONOWHITE)
+
+#define isBGRinInt(x)                  \
+    ((x) == PIX_FMT_BGR48BE     ||     \
+     (x) == PIX_FMT_BGR48LE     ||     \
+     (x) == PIX_FMT_BGR32       ||     \
+     (x) == PIX_FMT_BGR32_1     ||     \
+     (x) == PIX_FMT_BGR24       ||     \
+     (x) == PIX_FMT_BGR565BE    ||     \
+     (x) == PIX_FMT_BGR565LE    ||     \
+     (x) == PIX_FMT_BGR555BE    ||     \
+     (x) == PIX_FMT_BGR555LE    ||     \
+     (x) == PIX_FMT_BGR444BE    ||     \
+     (x) == PIX_FMT_BGR444LE    ||     \
+     (x) == PIX_FMT_BGR8        ||     \
+     (x) == PIX_FMT_BGR4        ||     \
+     (x) == PIX_FMT_BGR4_BYTE   ||     \
+     (x) == PIX_FMT_MONOBLACK   ||     \
+     (x) == PIX_FMT_MONOWHITE)
+
+#define isAnyRGB(x)                    \
+    (isRGBinInt(x)              ||     \
+     isBGRinInt(x))
+
+#define isALPHA(x)                                            \
+    (av_pix_fmt_descriptors[x].nb_components == 2          || \
      av_pix_fmt_descriptors[x].nb_components == 4)
 
-#define isPacked(x) (\
-    (av_pix_fmt_descriptors[x].nb_components >= 2 && \
-     !(av_pix_fmt_descriptors[x].flags & PIX_FMT_PLANAR)) || \
-    (x) == PIX_FMT_PAL8\
-    )
+#define isPacked(x)                                            \
+    ((av_pix_fmt_descriptors[x].nb_components >= 2         &&  \
+      !(av_pix_fmt_descriptors[x].flags & PIX_FMT_PLANAR)) ||  \
+     (x) == PIX_FMT_PAL8)
 
 #define isPlanar(x) \
-    (av_pix_fmt_descriptors[x].nb_components >= 2 && \
+    (av_pix_fmt_descriptors[x].nb_components >= 2          &&  \
      (av_pix_fmt_descriptors[x].flags & PIX_FMT_PLANAR))
 
 #define usePal(x) ((av_pix_fmt_descriptors[x].flags & PIX_FMT_PAL) || (x) == PIX_FMT_Y400A)
diff --git a/libswscale/swscale_unscaled.c b/libswscale/swscale_unscaled.c
index 7c339b6..5769548 100644
--- a/libswscale/swscale_unscaled.c
+++ b/libswscale/swscale_unscaled.c
@@ -360,8 +360,8 @@ static int rgbToRgbWrapper(SwsContext *c, const uint8_t *src[], int srcStride[],
     const enum PixelFormat dstFormat = c->dstFormat;
     const int srcBpp = (c->srcFormatBpp + 7) >> 3;
     const int dstBpp = (c->dstFormatBpp + 7) >> 3;
-    const int srcId = c->srcFormatBpp >> 2; /* 1:0, 4:1, 8:2, 15:3, 16:4, 24:6, 32:8 */
-    const int dstId = c->dstFormatBpp >> 2;
+    const int srcId = c->srcFormatBpp;
+    const int dstId = c->dstFormatBpp;
     void (*conv)(const uint8_t *src, uint8_t *dst, int src_size) = NULL;
 
 #define CONV_IS(src, dst) (srcFormat == PIX_FMT_##src && dstFormat == PIX_FMT_##dst)
@@ -383,38 +383,38 @@ static int rgbToRgbWrapper(SwsContext *c, const uint8_t *src[], int srcStride[],
     /* BGR -> BGR */
     if ((isBGRinInt(srcFormat) && isBGRinInt(dstFormat)) ||
         (isRGBinInt(srcFormat) && isRGBinInt(dstFormat))) {
-        switch (srcId | (dstId << 4)) {
-        case 0x34: conv = rgb16to15; break;
-        case 0x36: conv = rgb24to15; break;
-        case 0x38: conv = rgb32to15; break;
-        case 0x43: conv = rgb15to16; break;
-        case 0x46: conv = rgb24to16; break;
-        case 0x48: conv = rgb32to16; break;
-        case 0x63: conv = rgb15to24; break;
-        case 0x64: conv = rgb16to24; break;
-        case 0x68: conv = rgb32to24; break;
-        case 0x83: conv = rgb15to32; break;
-        case 0x84: conv = rgb16to32; break;
-        case 0x86: conv = rgb24to32; break;
+        switch (srcId | (dstId << 16)) {
+        case 0x000F0010: conv = rgb16to15; break;
+        case 0x000F0018: conv = rgb24to15; break;
+        case 0x000F0020: conv = rgb32to15; break;
+        case 0x0010000F: conv = rgb15to16; break;
+        case 0x00100018: conv = rgb24to16; break;
+        case 0x00100020: conv = rgb32to16; break;
+        case 0x0018000F: conv = rgb15to24; break;
+        case 0x00180010: conv = rgb16to24; break;
+        case 0x00180020: conv = rgb32to24; break;
+        case 0x0020000F: conv = rgb15to32; break;
+        case 0x00200010: conv = rgb16to32; break;
+        case 0x00200018: conv = rgb24to32; break;
         }
     } else if ((isBGRinInt(srcFormat) && isRGBinInt(dstFormat)) ||
                (isRGBinInt(srcFormat) && isBGRinInt(dstFormat))) {
-        switch (srcId | (dstId << 4)) {
-        case 0x33: conv = rgb15tobgr15; break;
-        case 0x34: conv = rgb16tobgr15; break;
-        case 0x36: conv = rgb24tobgr15; break;
-        case 0x38: conv = rgb32tobgr15; break;
-        case 0x43: conv = rgb15tobgr16; break;
-        case 0x44: conv = rgb16tobgr16; break;
-        case 0x46: conv = rgb24tobgr16; break;
-        case 0x48: conv = rgb32tobgr16; break;
-        case 0x63: conv = rgb15tobgr24; break;
-        case 0x64: conv = rgb16tobgr24; break;
-        case 0x66: conv = rgb24tobgr24; break;
-        case 0x68: conv = rgb32tobgr24; break;
-        case 0x83: conv = rgb15tobgr32; break;
-        case 0x84: conv = rgb16tobgr32; break;
-        case 0x86: conv = rgb24tobgr32; break;
+        switch (srcId | (dstId << 16)) {
+        case 0x000F000F: conv = rgb15tobgr15; break;
+        case 0x000F0010: conv = rgb16tobgr15; break;
+        case 0x000F0018: conv = rgb24tobgr15; break;
+        case 0x000F0020: conv = rgb32tobgr15; break;
+        case 0x0010000F: conv = rgb15tobgr16; break;
+        case 0x00100010: conv = rgb16tobgr16; break;
+        case 0x00100018: conv = rgb24tobgr16; break;
+        case 0x00100020: conv = rgb32tobgr16; break;
+        case 0x0018000F: conv = rgb15tobgr24; break;
+        case 0x00180010: conv = rgb16tobgr24; break;
+        case 0x00180018: conv = rgb24tobgr24; break;
+        case 0x00180020: conv = rgb32tobgr24; break;
+        case 0x0020000F: conv = rgb15tobgr32; break;
+        case 0x00200010: conv = rgb16tobgr32; break;
+        case 0x00200018: conv = rgb24tobgr32; break;
         }
     }
 
diff --git a/libswscale/utils.c b/libswscale/utils.c
index 12b3202..d252f2e 100644
--- a/libswscale/utils.c
+++ b/libswscale/utils.c
@@ -120,10 +120,10 @@ const static FormatEntry format_entries[PIX_FMT_NB] = {
     [PIX_FMT_YUV422P16BE] = { 1 , 1 },
     [PIX_FMT_YUV444P16LE] = { 1 , 1 },
     [PIX_FMT_YUV444P16BE] = { 1 , 1 },
-    [PIX_FMT_RGB444LE]    = { 0 , 1 },
-    [PIX_FMT_RGB444BE]    = { 0 , 1 },
-    [PIX_FMT_BGR444LE]    = { 0 , 1 },
-    [PIX_FMT_BGR444BE]    = { 0 , 1 },
+    [PIX_FMT_RGB444LE]    = { 1 , 1 },
+    [PIX_FMT_RGB444BE]    = { 1 , 1 },
+    [PIX_FMT_BGR444LE]    = { 1 , 1 },
+    [PIX_FMT_BGR444BE]    = { 1 , 1 },
     [PIX_FMT_Y400A]       = { 1 , 0 },
     [PIX_FMT_BGR48BE]     = { 1 , 1 },
     [PIX_FMT_BGR48LE]     = { 1 , 1 },
@@ -829,6 +829,7 @@ int sws_init_context(SwsContext *c, SwsFilter *srcFilter, SwsFilter *dstFilter)
 
     // reuse chroma for 2 pixels RGB/BGR unless user wants full chroma interpolation
     if (flags & SWS_FULL_CHR_H_INT &&
+        isAnyRGB(dstFormat)       &&
         dstFormat != PIX_FMT_RGBA &&
         dstFormat != PIX_FMT_ARGB &&
         dstFormat != PIX_FMT_BGRA &&
diff --git a/libswscale/x86/input.asm b/libswscale/x86/input.asm
new file mode 100644
index 0000000..a23cf05
--- /dev/null
+++ b/libswscale/x86/input.asm
@@ -0,0 +1,242 @@
+;******************************************************************************
+;* x86-optimized input routines; does shuffling of packed
+;* YUV formats into individual planes, and converts RGB
+;* into YUV planes also.
+;* Copyright (c) 2012 Ronald S. Bultje <rsbultje at gmail.com>
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+SECTION_RODATA
+
+SECTION .text
+
+;-----------------------------------------------------------------------------
+; YUYV/UYVY/NV12/NV21 packed pixel shuffling.
+;
+; void <fmt>ToY_<opt>(uint8_t *dst, const uint8_t *src, int w);
+; and
+; void <fmt>toUV_<opt>(uint8_t *dstU, uint8_t *dstV, const uint8_t *src,
+;                      const uint8_t *unused, int w);
+;-----------------------------------------------------------------------------
+
+; %1 = a (aligned) or u (unaligned)
+; %2 = yuyv or uyvy
+%macro LOOP_YUYV_TO_Y 2
+.loop_%1:
+    mov%1          m0, [srcq+wq*2]        ; (byte) { Y0, U0, Y1, V0, ... }
+    mov%1          m1, [srcq+wq*2+mmsize] ; (byte) { Y8, U4, Y9, V4, ... }
+%ifidn %2, yuyv
+    pand           m0, m2                 ; (word) { Y0, Y1, ..., Y7 }
+    pand           m1, m2                 ; (word) { Y8, Y9, ..., Y15 }
+%else ; uyvy
+    psrlw          m0, 8                  ; (word) { Y0, Y1, ..., Y7 }
+    psrlw          m1, 8                  ; (word) { Y8, Y9, ..., Y15 }
+%endif ; yuyv/uyvy
+    packuswb       m0, m1                 ; (byte) { Y0, ..., Y15 }
+    mova    [dstq+wq], m0
+    add            wq, mmsize
+    jl .loop_%1
+    REP_RET
+%endmacro
+
+; %1 = nr. of XMM registers
+; %2 = yuyv or uyvy
+; %3 = if specified, it means that unaligned and aligned code in loop
+;      will be the same (i.e. YUYV+AVX), and thus we don't need to
+;      split the loop in an aligned and unaligned case
+%macro YUYV_TO_Y_FN 2-3
+cglobal %2ToY, 3, 3, %1, dst, src, w
+%ifdef ARCH_X86_64
+    movsxd         wq, wd
+%endif
+    add          dstq, wq
+%if mmsize == 16
+    test         srcq, 15
+%endif
+    lea          srcq, [srcq+wq*2]
+%ifidn %2, yuyv
+    pcmpeqb        m2, m2                 ; (byte) { 0xff } x 16
+    psrlw          m2, 8                  ; (word) { 0x00ff } x 8
+%endif ; yuyv
+%if mmsize == 16
+    jnz .loop_u_start
+    neg            wq
+    LOOP_YUYV_TO_Y  a, %2
+.loop_u_start:
+    neg            wq
+    LOOP_YUYV_TO_Y  u, %2
+%else ; mmsize == 8
+    neg            wq
+    LOOP_YUYV_TO_Y  a, %2
+%endif ; mmsize == 8/16
+%endmacro
+
+; %1 = a (aligned) or u (unaligned)
+; %2 = yuyv or uyvy
+%macro LOOP_YUYV_TO_UV 2
+.loop_%1:
+%ifidn %2, yuyv
+    mov%1          m0, [srcq+wq*4]        ; (byte) { Y0, U0, Y1, V0, ... }
+    mov%1          m1, [srcq+wq*4+mmsize] ; (byte) { Y8, U4, Y9, V4, ... }
+    psrlw          m0, 8                  ; (word) { U0, V0, ..., U3, V3 }
+    psrlw          m1, 8                  ; (word) { U4, V4, ..., U7, V7 }
+%else ; uyvy
+%if cpuflag(avx)
+    vpand          m0, m2, [srcq+wq*4]        ; (word) { U0, V0, ..., U3, V3 }
+    vpand          m1, m2, [srcq+wq*4+mmsize] ; (word) { U4, V4, ..., U7, V7 }
+%else
+    mov%1          m0, [srcq+wq*4]        ; (byte) { Y0, U0, Y1, V0, ... }
+    mov%1          m1, [srcq+wq*4+mmsize] ; (byte) { Y8, U4, Y9, V4, ... }
+    pand           m0, m2                 ; (word) { U0, V0, ..., U3, V3 }
+    pand           m1, m2                 ; (word) { U4, V4, ..., U7, V7 }
+%endif
+%endif ; yuyv/uyvy
+    packuswb       m0, m1                 ; (byte) { U0, V0, ..., U7, V7 }
+    pand           m1, m0, m2             ; (word) { U0, U1, ..., U7 }
+    psrlw          m0, 8                  ; (word) { V0, V1, ..., V7 }
+%if mmsize == 16
+    packuswb       m1, m0                 ; (byte) { U0, ... U7, V1, ... V7 }
+    movh   [dstUq+wq], m1
+    movhps [dstVq+wq], m1
+%else ; mmsize == 8
+    packuswb       m1, m1                 ; (byte) { U0, ... U3 }
+    packuswb       m0, m0                 ; (byte) { V0, ... V3 }
+    movh   [dstUq+wq], m1
+    movh   [dstVq+wq], m0
+%endif ; mmsize == 8/16
+    add            wq, mmsize / 2
+    jl .loop_%1
+    REP_RET
+%endmacro
+
+; %1 = nr. of XMM registers
+; %2 = yuyv or uyvy
+; %3 = if specified, it means that unaligned and aligned code in loop
+;      will be the same (i.e. UYVY+AVX), and thus we don't need to
+;      split the loop in an aligned and unaligned case
+%macro YUYV_TO_UV_FN 2-3
+cglobal %2ToUV, 3, 4, %1, dstU, dstV, src, w
+%ifdef ARCH_X86_64
+    movsxd         wq, dword r4m
+%else ; x86-32
+    mov            wq, r4m
+%endif
+    add         dstUq, wq
+    add         dstVq, wq
+%if mmsize == 16 && %0 == 2
+    test         srcq, 15
+%endif
+    lea          srcq, [srcq+wq*4]
+    pcmpeqb        m2, m2                 ; (byte) { 0xff } x 16
+    psrlw          m2, 8                  ; (word) { 0x00ff } x 8
+    ; NOTE: if uyvy+avx, u/a are identical
+%if mmsize == 16 && %0 == 2
+    jnz .loop_u_start
+    neg            wq
+    LOOP_YUYV_TO_UV a, %2
+.loop_u_start:
+    neg            wq
+    LOOP_YUYV_TO_UV u, %2
+%else ; mmsize == 8
+    neg            wq
+    LOOP_YUYV_TO_UV a, %2
+%endif ; mmsize == 8/16
+%endmacro
+
+; %1 = a (aligned) or u (unaligned)
+; %2 = nv12 or nv21
+%macro LOOP_NVXX_TO_UV 2
+.loop_%1:
+    mov%1          m0, [srcq+wq*2]        ; (byte) { U0, V0, U1, V1, ... }
+    mov%1          m1, [srcq+wq*2+mmsize] ; (byte) { U8, V8, U9, V9, ... }
+    pand           m2, m0, m4             ; (word) { U0, U1, ..., U7 }
+    pand           m3, m1, m4             ; (word) { U8, U9, ..., U15 }
+    psrlw          m0, 8                  ; (word) { V0, V1, ..., V7 }
+    psrlw          m1, 8                  ; (word) { V8, V9, ..., V15 }
+    packuswb       m2, m3                 ; (byte) { U0, ..., U15 }
+    packuswb       m0, m1                 ; (byte) { V0, ..., V15 }
+%ifidn %2, nv12
+    mova   [dstUq+wq], m2
+    mova   [dstVq+wq], m0
+%else ; nv21
+    mova   [dstVq+wq], m2
+    mova   [dstUq+wq], m0
+%endif ; nv12/21
+    add            wq, mmsize
+    jl .loop_%1
+    REP_RET
+%endmacro
+
+; %1 = nr. of XMM registers
+; %2 = nv12 or nv21
+%macro NVXX_TO_UV_FN 2
+cglobal %2ToUV, 3, 4, %1, dstU, dstV, src, w
+%ifdef ARCH_X86_64
+    movsxd         wq, dword r4m
+%else ; x86-32
+    mov            wq, r4m
+%endif
+    add         dstUq, wq
+    add         dstVq, wq
+%if mmsize == 16
+    test         srcq, 15
+%endif
+    lea          srcq, [srcq+wq*2]
+    pcmpeqb        m4, m4                 ; (byte) { 0xff } x 16
+    psrlw          m4, 8                  ; (word) { 0x00ff } x 8
+%if mmsize == 16
+    jnz .loop_u_start
+    neg            wq
+    LOOP_NVXX_TO_UV a, %2
+.loop_u_start:
+    neg            wq
+    LOOP_NVXX_TO_UV u, %2
+%else ; mmsize == 8
+    neg            wq
+    LOOP_NVXX_TO_UV a, %2
+%endif ; mmsize == 8/16
+%endmacro
+
+%ifdef ARCH_X86_32
+INIT_MMX mmx
+YUYV_TO_Y_FN  0, yuyv
+YUYV_TO_Y_FN  0, uyvy
+YUYV_TO_UV_FN 0, yuyv
+YUYV_TO_UV_FN 0, uyvy
+NVXX_TO_UV_FN 0, nv12
+NVXX_TO_UV_FN 0, nv21
+%endif
+
+INIT_XMM sse2
+YUYV_TO_Y_FN  3, yuyv
+YUYV_TO_Y_FN  2, uyvy
+YUYV_TO_UV_FN 3, yuyv
+YUYV_TO_UV_FN 3, uyvy
+NVXX_TO_UV_FN 5, nv12
+NVXX_TO_UV_FN 5, nv21
+
+INIT_XMM avx
+; in theory, we could write a yuy2-to-y using vpand (i.e. AVX), but
+; that's not faster in practice
+YUYV_TO_UV_FN 3, yuyv
+YUYV_TO_UV_FN 3, uyvy, 1
+NVXX_TO_UV_FN 5, nv12
+NVXX_TO_UV_FN 5, nv21
diff --git a/libswscale/x86/output.asm b/libswscale/x86/output.asm
new file mode 100644
index 0000000..0ec2038
--- /dev/null
+++ b/libswscale/x86/output.asm
@@ -0,0 +1,409 @@
+;******************************************************************************
+;* x86-optimized vertical line scaling functions
+;* Copyright (c) 2011 Ronald S. Bultje <rsbultje at gmail.com>
+;*                    Kieran Kunhya <kieran at kunhya.com>
+;*
+;* This file is part of Libav.
+;*
+;* Libav is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* Libav is distributed in the hope that it will be useful,
+;* but WITHOUT ANY WARRANTY; without even the implied warranty of
+;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with Libav; if not, write to the Free Software
+;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "x86inc.asm"
+%include "x86util.asm"
+
+SECTION_RODATA
+
+minshort:      times 8 dw 0x8000
+yuv2yuvX_16_start:  times 4 dd 0x4000 - 0x40000000
+yuv2yuvX_10_start:  times 4 dd 0x10000
+yuv2yuvX_9_start:   times 4 dd 0x20000
+yuv2yuvX_10_upper:  times 8 dw 0x3ff
+yuv2yuvX_9_upper:   times 8 dw 0x1ff
+pd_4:          times 4 dd 4
+pd_4min0x40000:times 4 dd 4 - (0x40000)
+pw_16:         times 8 dw 16
+pw_32:         times 8 dw 32
+pw_512:        times 8 dw 512
+pw_1024:       times 8 dw 1024
+
+SECTION .text
+
+;-----------------------------------------------------------------------------
+; vertical line scaling
+;
+; void yuv2plane1_<output_size>_<opt>(const int16_t *src, uint8_t *dst, int dstW,
+;                                     const uint8_t *dither, int offset)
+; and
+; void yuv2planeX_<output_size>_<opt>(const int16_t *filter, int filterSize,
+;                                     const int16_t **src, uint8_t *dst, int dstW,
+;                                     const uint8_t *dither, int offset)
+;
+; Scale one or $filterSize lines of source data to generate one line of output
+; data. The input is 15-bit in int16_t if $output_size is [8,10] and 19-bit in
+; int32_t if $output_size is 16. $filter is 12-bits. $filterSize is a multiple
+; of 2. $offset is either 0 or 3. $dither holds 8 values.
+;-----------------------------------------------------------------------------
+
+%macro yuv2planeX_fn 4
+
+%ifdef ARCH_X86_32
+%define cntr_reg r1
+%define movsx mov
+%else
+%define cntr_reg r11
+%define movsx movsxd
+%endif
+
+cglobal yuv2planeX_%2_%1, %4, 7, %3
+%if %2 == 8 || %2 == 9 || %2 == 10
+    pxor            m6,  m6
+%endif ; %2 == 8/9/10
+
+%if %2 == 8
+%ifdef ARCH_X86_32
+%assign pad 0x2c - (stack_offset & 15)
+    SUB             rsp, pad
+%define m_dith m7
+%else ; x86-64
+%define m_dith m9
+%endif ; x86-32
+
+    ; create registers holding dither
+    movq        m_dith, [r5]             ; dither
+    test            r6d, r6d
+    jz              .no_rot
+%if mmsize == 16
+    punpcklqdq  m_dith,  m_dith
+%endif ; mmsize == 16
+    PALIGNR     m_dith,  m_dith,  3,  m0
+.no_rot:
+%if mmsize == 16
+    punpcklbw   m_dith,  m6
+%ifdef ARCH_X86_64
+    punpcklwd       m8,  m_dith,  m6
+    pslld           m8,  12
+%else ; x86-32
+    punpcklwd       m5,  m_dith,  m6
+    pslld           m5,  12
+%endif ; x86-32/64
+    punpckhwd   m_dith,  m6
+    pslld       m_dith,  12
+%ifdef ARCH_X86_32
+    mova      [rsp+ 0],  m5
+    mova      [rsp+16],  m_dith
+%endif
+%else ; mmsize == 8
+    punpcklbw       m5,  m_dith,  m6
+    punpckhbw   m_dith,  m6
+    punpcklwd       m4,  m5,  m6
+    punpckhwd       m5,  m6
+    punpcklwd       m3,  m_dith,  m6
+    punpckhwd   m_dith,  m6
+    pslld           m4,  12
+    pslld           m5,  12
+    pslld           m3,  12
+    pslld       m_dith,  12
+    mova      [rsp+ 0],  m4
+    mova      [rsp+ 8],  m5
+    mova      [rsp+16],  m3
+    mova      [rsp+24],  m_dith
+%endif ; mmsize == 8/16
+%endif ; %2 == 8
+
+    xor             r5,  r5
+
+.pixelloop:
+%assign %%i 0
+    ; the rep here is for the 8bit output mmx case, where dither covers
+    ; 8 pixels but we can only handle 2 pixels per register, and thus 4
+    ; pixels per iteration. In order to not have to keep track of where
+    ; we are w.r.t. dithering, we unroll the mmx/8bit loop x2.
+%if %2 == 8
+%rep 16/mmsize
+%endif ; %2 == 8
+
+%if %2 == 8
+%ifdef ARCH_X86_32
+    mova            m2, [rsp+mmsize*(0+%%i)]
+    mova            m1, [rsp+mmsize*(1+%%i)]
+%else ; x86-64
+    mova            m2,  m8
+    mova            m1,  m_dith
+%endif ; x86-32/64
+%else ; %2 == 9/10/16
+    mova            m1, [yuv2yuvX_%2_start]
+    mova            m2,  m1
+%endif ; %2 == 8/9/10/16
+    movsx     cntr_reg,  r1m
+.filterloop_ %+ %%i:
+    ; input pixels
+    mov             r6, [r2+gprsize*cntr_reg-2*gprsize]
+%if %2 == 16
+    mova            m3, [r6+r5*4]
+    mova            m5, [r6+r5*4+mmsize]
+%else ; %2 == 8/9/10
+    mova            m3, [r6+r5*2]
+%endif ; %2 == 8/9/10/16
+    mov             r6, [r2+gprsize*cntr_reg-gprsize]
+%if %2 == 16
+    mova            m4, [r6+r5*4]
+    mova            m6, [r6+r5*4+mmsize]
+%else ; %2 == 8/9/10
+    mova            m4, [r6+r5*2]
+%endif ; %2 == 8/9/10/16
+
+    ; coefficients
+    movd            m0, [r0+2*cntr_reg-4]; coeff[0], coeff[1]
+%if %2 == 16
+    pshuflw         m7,  m0,  0          ; coeff[0]
+    pshuflw         m0,  m0,  0x55       ; coeff[1]
+    pmovsxwd        m7,  m7              ; word -> dword
+    pmovsxwd        m0,  m0              ; word -> dword
+
+    pmulld          m3,  m7
+    pmulld          m5,  m7
+    pmulld          m4,  m0
+    pmulld          m6,  m0
+
+    paddd           m2,  m3
+    paddd           m1,  m5
+    paddd           m2,  m4
+    paddd           m1,  m6
+%else ; %2 == 10/9/8
+    punpcklwd       m5,  m3,  m4
+    punpckhwd       m3,  m4
+    SPLATD          m0,  m0
+
+    pmaddwd         m5,  m0
+    pmaddwd         m3,  m0
+
+    paddd           m2,  m5
+    paddd           m1,  m3
+%endif ; %2 == 8/9/10/16
+
+    sub       cntr_reg,  2
+    jg .filterloop_ %+ %%i
+
+%if %2 == 16
+    psrad           m2,  31 - %2
+    psrad           m1,  31 - %2
+%else ; %2 == 10/9/8
+    psrad           m2,  27 - %2
+    psrad           m1,  27 - %2
+%endif ; %2 == 8/9/10/16
+
+%if %2 == 8
+    packssdw        m2,  m1
+    packuswb        m2,  m2
+    movh     [r3+r5*1],  m2
+%else ; %2 == 9/10/16
+%if %2 == 16
+    packssdw        m2,  m1
+    paddw           m2, [minshort]
+%else ; %2 == 9/10
+%ifidn %1, sse4
+    packusdw        m2,  m1
+%elifidn %1, avx
+    packusdw        m2,  m1
+%else ; mmx2/sse2
+    packssdw        m2,  m1
+    pmaxsw          m2,  m6
+%endif ; mmx2/sse2/sse4/avx
+    pminsw          m2, [yuv2yuvX_%2_upper]
+%endif ; %2 == 9/10/16
+    mova     [r3+r5*2],  m2
+%endif ; %2 == 8/9/10/16
+
+    add             r5,  mmsize/2
+    sub             r4d, mmsize/2
+%if %2 == 8
+%assign %%i %%i+2
+%endrep
+%endif ; %2 == 8
+    jg .pixelloop
+
+%if %2 == 8
+%ifdef ARCH_X86_32
+    ADD             rsp, pad
+    RET
+%else ; x86-64
+    REP_RET
+%endif ; x86-32/64
+%else ; %2 == 9/10/16
+    REP_RET
+%endif ; %2 == 8/9/10/16
+%endmacro
+
+%define PALIGNR PALIGNR_MMX
+%ifdef ARCH_X86_32
+INIT_MMX
+yuv2planeX_fn mmx2,  8,  0, 7
+yuv2planeX_fn mmx2,  9,  0, 5
+yuv2planeX_fn mmx2, 10,  0, 5
+%endif
+
+INIT_XMM
+yuv2planeX_fn sse2,  8, 10, 7
+yuv2planeX_fn sse2,  9,  7, 5
+yuv2planeX_fn sse2, 10,  7, 5
+
+%define PALIGNR PALIGNR_SSSE3
+yuv2planeX_fn sse4,  8, 10, 7
+yuv2planeX_fn sse4,  9,  7, 5
+yuv2planeX_fn sse4, 10,  7, 5
+yuv2planeX_fn sse4, 16,  8, 5
+
+INIT_AVX
+yuv2planeX_fn avx,   8, 10, 7
+yuv2planeX_fn avx,   9,  7, 5
+yuv2planeX_fn avx,  10,  7, 5
+
+; %1=outout-bpc, %2=alignment (u/a)
+%macro yuv2plane1_mainloop 2
+.loop_%2:
+%if %1 == 8
+    paddsw          m0, m2, [r0+r2*2+mmsize*0]
+    paddsw          m1, m3, [r0+r2*2+mmsize*1]
+    psraw           m0, 7
+    psraw           m1, 7
+    packuswb        m0, m1
+    mov%2      [r1+r2], m0
+%elif %1 == 16
+    paddd           m0, m4, [r0+r2*4+mmsize*0]
+    paddd           m1, m4, [r0+r2*4+mmsize*1]
+    paddd           m2, m4, [r0+r2*4+mmsize*2]
+    paddd           m3, m4, [r0+r2*4+mmsize*3]
+    psrad           m0, 3
+    psrad           m1, 3
+    psrad           m2, 3
+    psrad           m3, 3
+%if cpuflag(sse4) ; avx/sse4
+    packusdw        m0, m1
+    packusdw        m2, m3
+%else ; mmx/sse2
+    packssdw        m0, m1
+    packssdw        m2, m3
+    paddw           m0, m5
+    paddw           m2, m5
+%endif ; mmx/sse2/sse4/avx
+    mov%2    [r1+r2*2], m0
+    mov%2    [r1+r2*2+mmsize], m2
+%else
+    paddsw          m0, m2, [r0+r2*2+mmsize*0]
+    paddsw          m1, m2, [r0+r2*2+mmsize*1]
+    psraw           m0, 15 - %1
+    psraw           m1, 15 - %1
+    pmaxsw          m0, m4
+    pmaxsw          m1, m4
+    pminsw          m0, m3
+    pminsw          m1, m3
+    mov%2    [r1+r2*2], m0
+    mov%2    [r1+r2*2+mmsize], m1
+%endif
+    add             r2, mmsize
+    jl .loop_%2
+%endmacro
+
+%macro yuv2plane1_fn 3
+cglobal yuv2plane1_%1, %3, %3, %2
+    add             r2, mmsize - 1
+    and             r2, ~(mmsize - 1)
+%if %1 == 8
+    add             r1, r2
+%else ; %1 != 8
+    lea             r1, [r1+r2*2]
+%endif ; %1 == 8
+%if %1 == 16
+    lea             r0, [r0+r2*4]
+%else ; %1 != 16
+    lea             r0, [r0+r2*2]
+%endif ; %1 == 16
+    neg             r2
+
+%if %1 == 8
+    pxor            m4, m4               ; zero
+
+    ; create registers holding dither
+    movq            m3, [r3]             ; dither
+    test           r4d, r4d
+    jz              .no_rot
+%if mmsize == 16
+    punpcklqdq      m3, m3
+%endif ; mmsize == 16
+    PALIGNR_MMX     m3, m3, 3, m2
+.no_rot:
+%if mmsize == 8
+    mova            m2, m3
+    punpckhbw       m3, m4               ; byte->word
+    punpcklbw       m2, m4               ; byte->word
+%else
+    punpcklbw       m3, m4
+    mova            m2, m3
+%endif
+%elif %1 == 9
+    pxor            m4, m4
+    mova            m3, [pw_512]
+    mova            m2, [pw_32]
+%elif %1 == 10
+    pxor            m4, m4
+    mova            m3, [pw_1024]
+    mova            m2, [pw_16]
+%else ; %1 == 16
+%if cpuflag(sse4) ; sse4/avx
+    mova            m4, [pd_4]
+%else ; mmx/sse2
+    mova            m4, [pd_4min0x40000]
+    mova            m5, [minshort]
+%endif ; mmx/sse2/sse4/avx
+%endif ; %1 == ..
+
+    ; actual pixel scaling
+%if mmsize == 8
+    yuv2plane1_mainloop %1, a
+%else ; mmsize == 16
+    test            r1, 15
+    jnz .unaligned
+    yuv2plane1_mainloop %1, a
+    REP_RET
+.unaligned:
+    yuv2plane1_mainloop %1, u
+%endif ; mmsize == 8/16
+    REP_RET
+%endmacro
+
+%ifdef ARCH_X86_32
+INIT_MMX mmx
+yuv2plane1_fn  8, 0, 5
+yuv2plane1_fn 16, 0, 3
+
+INIT_MMX mmx2
+yuv2plane1_fn  9, 0, 3
+yuv2plane1_fn 10, 0, 3
+%endif
+
+INIT_XMM sse2
+yuv2plane1_fn  8, 5, 5
+yuv2plane1_fn  9, 5, 3
+yuv2plane1_fn 10, 5, 3
+yuv2plane1_fn 16, 6, 3
+
+INIT_XMM sse4
+yuv2plane1_fn 16, 5, 3
+
+INIT_XMM avx
+yuv2plane1_fn  8, 5, 5
+yuv2plane1_fn  9, 5, 3
+yuv2plane1_fn 10, 5, 3
+yuv2plane1_fn 16, 5, 3
diff --git a/libswscale/x86/scale.asm b/libswscale/x86/scale.asm
index 1f5e1db..d355894 100644
--- a/libswscale/x86/scale.asm
+++ b/libswscale/x86/scale.asm
@@ -1,7 +1,6 @@
 ;******************************************************************************
-;* x86-optimized horizontal/vertical line scaling functions
+;* x86-optimized horizontal line scaling functions
 ;* Copyright (c) 2011 Ronald S. Bultje <rsbultje at gmail.com>
-;*                    Kieran Kunhya <kieran at kunhya.com>
 ;*
 ;* This file is part of Libav.
 ;*
@@ -29,17 +28,6 @@ max_19bit_int: times 4 dd 0x7ffff
 max_19bit_flt: times 4 dd 524287.0
 minshort:      times 8 dw 0x8000
 unicoeff:      times 4 dd 0x20000000
-yuv2yuvX_16_start:  times 4 dd 0x4000 - 0x40000000
-yuv2yuvX_10_start:  times 4 dd 0x10000
-yuv2yuvX_9_start:   times 4 dd 0x20000
-yuv2yuvX_10_upper:  times 8 dw 0x3ff
-yuv2yuvX_9_upper:   times 8 dw 0x1ff
-pd_4:          times 4 dd 4
-pd_4min0x40000:times 4 dd 4 - (0x40000)
-pw_16:         times 8 dw 16
-pw_32:         times 8 dw 32
-pw_512:        times 8 dw 512
-pw_1024:       times 8 dw 1024
 
 SECTION .text
 
@@ -439,371 +427,3 @@ INIT_XMM
 SCALE_FUNCS2 sse2,  6, 7, 8
 SCALE_FUNCS2 ssse3, 6, 6, 8
 SCALE_FUNCS2 sse4,  6, 6, 8
-
-;-----------------------------------------------------------------------------
-; vertical line scaling
-;
-; void yuv2plane1_<output_size>_<opt>(const int16_t *src, uint8_t *dst, int dstW,
-;                                     const uint8_t *dither, int offset)
-; and
-; void yuv2planeX_<output_size>_<opt>(const int16_t *filter, int filterSize,
-;                                     const int16_t **src, uint8_t *dst, int dstW,
-;                                     const uint8_t *dither, int offset)
-;
-; Scale one or $filterSize lines of source data to generate one line of output
-; data. The input is 15-bit in int16_t if $output_size is [8,10] and 19-bit in
-; int32_t if $output_size is 16. $filter is 12-bits. $filterSize is a multiple
-; of 2. $offset is either 0 or 3. $dither holds 8 values.
-;-----------------------------------------------------------------------------
-
-%macro yuv2planeX_fn 4
-
-%ifdef ARCH_X86_32
-%define cntr_reg r1
-%define movsx mov
-%else
-%define cntr_reg r11
-%define movsx movsxd
-%endif
-
-cglobal yuv2planeX_%2_%1, %4, 7, %3
-%if %2 == 8 || %2 == 9 || %2 == 10
-    pxor            m6,  m6
-%endif ; %2 == 8/9/10
-
-%if %2 == 8
-%ifdef ARCH_X86_32
-%assign pad 0x2c - (stack_offset & 15)
-    SUB             rsp, pad
-%define m_dith m7
-%else ; x86-64
-%define m_dith m9
-%endif ; x86-32
-
-    ; create registers holding dither
-    movq        m_dith, [r5]             ; dither
-    test            r6d, r6d
-    jz              .no_rot
-%if mmsize == 16
-    punpcklqdq  m_dith,  m_dith
-%endif ; mmsize == 16
-    PALIGNR     m_dith,  m_dith,  3,  m0
-.no_rot:
-%if mmsize == 16
-    punpcklbw   m_dith,  m6
-%ifdef ARCH_X86_64
-    punpcklwd       m8,  m_dith,  m6
-    pslld           m8,  12
-%else ; x86-32
-    punpcklwd       m5,  m_dith,  m6
-    pslld           m5,  12
-%endif ; x86-32/64
-    punpckhwd   m_dith,  m6
-    pslld       m_dith,  12
-%ifdef ARCH_X86_32
-    mova      [rsp+ 0],  m5
-    mova      [rsp+16],  m_dith
-%endif
-%else ; mmsize == 8
-    punpcklbw       m5,  m_dith,  m6
-    punpckhbw   m_dith,  m6
-    punpcklwd       m4,  m5,  m6
-    punpckhwd       m5,  m6
-    punpcklwd       m3,  m_dith,  m6
-    punpckhwd   m_dith,  m6
-    pslld           m4,  12
-    pslld           m5,  12
-    pslld           m3,  12
-    pslld       m_dith,  12
-    mova      [rsp+ 0],  m4
-    mova      [rsp+ 8],  m5
-    mova      [rsp+16],  m3
-    mova      [rsp+24],  m_dith
-%endif ; mmsize == 8/16
-%endif ; %2 == 8
-
-    xor             r5,  r5
-
-.pixelloop:
-%assign %%i 0
-    ; the rep here is for the 8bit output mmx case, where dither covers
-    ; 8 pixels but we can only handle 2 pixels per register, and thus 4
-    ; pixels per iteration. In order to not have to keep track of where
-    ; we are w.r.t. dithering, we unroll the mmx/8bit loop x2.
-%if %2 == 8
-%rep 16/mmsize
-%endif ; %2 == 8
-
-%if %2 == 8
-%ifdef ARCH_X86_32
-    mova            m2, [rsp+mmsize*(0+%%i)]
-    mova            m1, [rsp+mmsize*(1+%%i)]
-%else ; x86-64
-    mova            m2,  m8
-    mova            m1,  m_dith
-%endif ; x86-32/64
-%else ; %2 == 9/10/16
-    mova            m1, [yuv2yuvX_%2_start]
-    mova            m2,  m1
-%endif ; %2 == 8/9/10/16
-    movsx     cntr_reg,  r1m
-.filterloop_ %+ %%i:
-    ; input pixels
-    mov             r6, [r2+gprsize*cntr_reg-2*gprsize]
-%if %2 == 16
-    mova            m3, [r6+r5*4]
-    mova            m5, [r6+r5*4+mmsize]
-%else ; %2 == 8/9/10
-    mova            m3, [r6+r5*2]
-%endif ; %2 == 8/9/10/16
-    mov             r6, [r2+gprsize*cntr_reg-gprsize]
-%if %2 == 16
-    mova            m4, [r6+r5*4]
-    mova            m6, [r6+r5*4+mmsize]
-%else ; %2 == 8/9/10
-    mova            m4, [r6+r5*2]
-%endif ; %2 == 8/9/10/16
-
-    ; coefficients
-    movd            m0, [r0+2*cntr_reg-4]; coeff[0], coeff[1]
-%if %2 == 16
-    pshuflw         m7,  m0,  0          ; coeff[0]
-    pshuflw         m0,  m0,  0x55       ; coeff[1]
-    pmovsxwd        m7,  m7              ; word -> dword
-    pmovsxwd        m0,  m0              ; word -> dword
-
-    pmulld          m3,  m7
-    pmulld          m5,  m7
-    pmulld          m4,  m0
-    pmulld          m6,  m0
-
-    paddd           m2,  m3
-    paddd           m1,  m5
-    paddd           m2,  m4
-    paddd           m1,  m6
-%else ; %2 == 10/9/8
-    punpcklwd       m5,  m3,  m4
-    punpckhwd       m3,  m4
-    SPLATD          m0,  m0
-
-    pmaddwd         m5,  m0
-    pmaddwd         m3,  m0
-
-    paddd           m2,  m5
-    paddd           m1,  m3
-%endif ; %2 == 8/9/10/16
-
-    sub       cntr_reg,  2
-    jg .filterloop_ %+ %%i
-
-%if %2 == 16
-    psrad           m2,  31 - %2
-    psrad           m1,  31 - %2
-%else ; %2 == 10/9/8
-    psrad           m2,  27 - %2
-    psrad           m1,  27 - %2
-%endif ; %2 == 8/9/10/16
-
-%if %2 == 8
-    packssdw        m2,  m1
-    packuswb        m2,  m2
-    movh     [r3+r5*1],  m2
-%else ; %2 == 9/10/16
-%if %2 == 16
-    packssdw        m2,  m1
-    paddw           m2, [minshort]
-%else ; %2 == 9/10
-%ifidn %1, sse4
-    packusdw        m2,  m1
-%elifidn %1, avx
-    packusdw        m2,  m1
-%else ; mmx2/sse2
-    packssdw        m2,  m1
-    pmaxsw          m2,  m6
-%endif ; mmx2/sse2/sse4/avx
-    pminsw          m2, [yuv2yuvX_%2_upper]
-%endif ; %2 == 9/10/16
-    mova     [r3+r5*2],  m2
-%endif ; %2 == 8/9/10/16
-
-    add             r5,  mmsize/2
-    sub             r4d, mmsize/2
-%if %2 == 8
-%assign %%i %%i+2
-%endrep
-%endif ; %2 == 8
-    jg .pixelloop
-
-%if %2 == 8
-%ifdef ARCH_X86_32
-    ADD             rsp, pad
-    RET
-%else ; x86-64
-    REP_RET
-%endif ; x86-32/64
-%else ; %2 == 9/10/16
-    REP_RET
-%endif ; %2 == 8/9/10/16
-%endmacro
-
-%define PALIGNR PALIGNR_MMX
-%ifdef ARCH_X86_32
-INIT_MMX
-yuv2planeX_fn mmx2,  8,  0, 7
-yuv2planeX_fn mmx2,  9,  0, 5
-yuv2planeX_fn mmx2, 10,  0, 5
-%endif
-
-INIT_XMM
-yuv2planeX_fn sse2,  8, 10, 7
-yuv2planeX_fn sse2,  9,  7, 5
-yuv2planeX_fn sse2, 10,  7, 5
-
-%define PALIGNR PALIGNR_SSSE3
-yuv2planeX_fn sse4,  8, 10, 7
-yuv2planeX_fn sse4,  9,  7, 5
-yuv2planeX_fn sse4, 10,  7, 5
-yuv2planeX_fn sse4, 16,  8, 5
-
-INIT_AVX
-yuv2planeX_fn avx,   8, 10, 7
-yuv2planeX_fn avx,   9,  7, 5
-yuv2planeX_fn avx,  10,  7, 5
-
-; %1=outout-bpc, %2=alignment (u/a)
-%macro yuv2plane1_mainloop 2
-.loop_%2:
-%if %1 == 8
-    paddsw          m0, m2, [r0+r2*2+mmsize*0]
-    paddsw          m1, m3, [r0+r2*2+mmsize*1]
-    psraw           m0, 7
-    psraw           m1, 7
-    packuswb        m0, m1
-    mov%2      [r1+r2], m0
-%elif %1 == 16
-    paddd           m0, m4, [r0+r2*4+mmsize*0]
-    paddd           m1, m4, [r0+r2*4+mmsize*1]
-    paddd           m2, m4, [r0+r2*4+mmsize*2]
-    paddd           m3, m4, [r0+r2*4+mmsize*3]
-    psrad           m0, 3
-    psrad           m1, 3
-    psrad           m2, 3
-    psrad           m3, 3
-%if cpuflag(sse4) ; avx/sse4
-    packusdw        m0, m1
-    packusdw        m2, m3
-%else ; mmx/sse2
-    packssdw        m0, m1
-    packssdw        m2, m3
-    paddw           m0, m5
-    paddw           m2, m5
-%endif ; mmx/sse2/sse4/avx
-    mov%2    [r1+r2*2], m0
-    mov%2    [r1+r2*2+mmsize], m2
-%else
-    paddsw          m0, m2, [r0+r2*2+mmsize*0]
-    paddsw          m1, m2, [r0+r2*2+mmsize*1]
-    psraw           m0, 15 - %1
-    psraw           m1, 15 - %1
-    pmaxsw          m0, m4
-    pmaxsw          m1, m4
-    pminsw          m0, m3
-    pminsw          m1, m3
-    mov%2    [r1+r2*2], m0
-    mov%2    [r1+r2*2+mmsize], m1
-%endif
-    add             r2, mmsize
-    jl .loop_%2
-%endmacro
-
-%macro yuv2plane1_fn 3
-cglobal yuv2plane1_%1, %3, %3, %2
-    add             r2, mmsize - 1
-    and             r2, ~(mmsize - 1)
-%if %1 == 8
-    add             r1, r2
-%else ; %1 != 8
-    lea             r1, [r1+r2*2]
-%endif ; %1 == 8
-%if %1 == 16
-    lea             r0, [r0+r2*4]
-%else ; %1 != 16
-    lea             r0, [r0+r2*2]
-%endif ; %1 == 16
-    neg             r2
-
-%if %1 == 8
-    pxor            m4, m4               ; zero
-
-    ; create registers holding dither
-    movq            m3, [r3]             ; dither
-    test           r4d, r4d
-    jz              .no_rot
-%if mmsize == 16
-    punpcklqdq      m3, m3
-%endif ; mmsize == 16
-    PALIGNR_MMX     m3, m3, 3, m2
-.no_rot:
-%if mmsize == 8
-    mova            m2, m3
-    punpckhbw       m3, m4               ; byte->word
-    punpcklbw       m2, m4               ; byte->word
-%else
-    punpcklbw       m3, m4
-    mova            m2, m3
-%endif
-%elif %1 == 9
-    pxor            m4, m4
-    mova            m3, [pw_512]
-    mova            m2, [pw_32]
-%elif %1 == 10
-    pxor            m4, m4
-    mova            m3, [pw_1024]
-    mova            m2, [pw_16]
-%else ; %1 == 16
-%if cpuflag(sse4) ; sse4/avx
-    mova            m4, [pd_4]
-%else ; mmx/sse2
-    mova            m4, [pd_4min0x40000]
-    mova            m5, [minshort]
-%endif ; mmx/sse2/sse4/avx
-%endif ; %1 == ..
-
-    ; actual pixel scaling
-%if mmsize == 8
-    yuv2plane1_mainloop %1, a
-%else ; mmsize == 16
-    test            r1, 15
-    jnz .unaligned
-    yuv2plane1_mainloop %1, a
-    REP_RET
-.unaligned:
-    yuv2plane1_mainloop %1, u
-%endif ; mmsize == 8/16
-    REP_RET
-%endmacro
-
-%ifdef ARCH_X86_32
-INIT_MMX mmx
-yuv2plane1_fn  8, 0, 5
-yuv2plane1_fn 16, 0, 3
-
-INIT_MMX mmx2
-yuv2plane1_fn  9, 0, 3
-yuv2plane1_fn 10, 0, 3
-%endif
-
-INIT_XMM sse2
-yuv2plane1_fn  8, 5, 5
-yuv2plane1_fn  9, 5, 3
-yuv2plane1_fn 10, 5, 3
-yuv2plane1_fn 16, 6, 3
-
-INIT_XMM sse4
-yuv2plane1_fn 16, 5, 3
-
-INIT_XMM avx
-yuv2plane1_fn  8, 5, 5
-yuv2plane1_fn  9, 5, 3
-yuv2plane1_fn 10, 5, 3
-yuv2plane1_fn 16, 5, 3
diff --git a/libswscale/x86/swscale_mmx.c b/libswscale/x86/swscale_mmx.c
index 4305cef..867a9f1 100644
--- a/libswscale/x86/swscale_mmx.c
+++ b/libswscale/x86/swscale_mmx.c
@@ -244,6 +244,26 @@ VSCALE_FUNCS(sse2, sse2);
 VSCALE_FUNC(16, sse4);
 VSCALE_FUNCS(avx, avx);
 
+#define INPUT_UV_FUNC(fmt, opt) \
+extern void ff_ ## fmt ## ToUV_ ## opt(uint8_t *dstU, uint8_t *dstV, \
+                                       const uint8_t *src, const uint8_t *unused1, \
+                                       int w, uint32_t *unused2)
+#define INPUT_FUNC(fmt, opt) \
+extern void ff_ ## fmt ## ToY_  ## opt(uint8_t *dst, const uint8_t *src, \
+                                       int w, uint32_t *unused); \
+    INPUT_UV_FUNC(fmt, opt)
+#define INPUT_FUNCS(opt) \
+    INPUT_FUNC(uyvy, opt); \
+    INPUT_FUNC(yuyv, opt); \
+    INPUT_UV_FUNC(nv12, opt); \
+    INPUT_UV_FUNC(nv21, opt)
+
+#if ARCH_X86_32
+INPUT_FUNCS(mmx);
+#endif
+INPUT_FUNCS(sse2);
+INPUT_FUNCS(avx);
+
 void ff_sws_init_swScale_mmx(SwsContext *c)
 {
     int cpu_flags = av_get_cpu_flags();
@@ -296,6 +316,30 @@ switch(c->dstBpc){ \
         ASSIGN_MMX_SCALE_FUNC(c->hyScale, c->hLumFilterSize, mmx, mmx);
         ASSIGN_MMX_SCALE_FUNC(c->hcScale, c->hChrFilterSize, mmx, mmx);
         ASSIGN_VSCALE_FUNC(c->yuv2plane1, mmx, mmx2, cpu_flags & AV_CPU_FLAG_MMX2);
+
+        switch (c->srcFormat) {
+        case PIX_FMT_Y400A:
+            c->lumToYV12 = ff_yuyvToY_mmx;
+            if (c->alpPixBuf)
+                c->alpToYV12 = ff_uyvyToY_mmx;
+            break;
+        case PIX_FMT_YUYV422:
+            c->lumToYV12 = ff_yuyvToY_mmx;
+            c->chrToYV12 = ff_yuyvToUV_mmx;
+            break;
+        case PIX_FMT_UYVY422:
+            c->lumToYV12 = ff_uyvyToY_mmx;
+            c->chrToYV12 = ff_uyvyToUV_mmx;
+            break;
+        case PIX_FMT_NV12:
+            c->chrToYV12 = ff_nv12ToUV_mmx;
+            break;
+        case PIX_FMT_NV21:
+            c->chrToYV12 = ff_nv21ToUV_mmx;
+            break;
+        default:
+            break;
+        }
     }
     if (cpu_flags & AV_CPU_FLAG_MMX2) {
         ASSIGN_VSCALEX_FUNC(c->yuv2planeX, mmx2,);
@@ -314,6 +358,28 @@ switch(c->dstBpc){ \
         ASSIGN_SSE_SCALE_FUNC(c->hcScale, c->hChrFilterSize, sse2, sse2);
         ASSIGN_VSCALEX_FUNC(c->yuv2planeX, sse2,);
         ASSIGN_VSCALE_FUNC(c->yuv2plane1, sse2, sse2, 1);
+
+        switch (c->srcFormat) {
+        case PIX_FMT_Y400A:
+            c->lumToYV12 = ff_yuyvToY_sse2;
+            if (c->alpPixBuf)
+                c->alpToYV12 = ff_uyvyToY_sse2;
+            break;
+        case PIX_FMT_YUYV422:
+            c->lumToYV12 = ff_yuyvToY_sse2;
+            c->chrToYV12 = ff_yuyvToUV_sse2;
+            break;
+        case PIX_FMT_UYVY422:
+            c->lumToYV12 = ff_uyvyToY_sse2;
+            c->chrToYV12 = ff_uyvyToUV_sse2;
+            break;
+        case PIX_FMT_NV12:
+            c->chrToYV12 = ff_nv12ToUV_sse2;
+            break;
+        case PIX_FMT_NV21:
+            c->chrToYV12 = ff_nv21ToUV_sse2;
+            break;
+        }
     }
     if (cpu_flags & AV_CPU_FLAG_SSSE3) {
         ASSIGN_SSE_SCALE_FUNC(c->hyScale, c->hLumFilterSize, ssse3, ssse3);
@@ -332,6 +398,23 @@ switch(c->dstBpc){ \
     if (cpu_flags & AV_CPU_FLAG_AVX) {
         ASSIGN_VSCALEX_FUNC(c->yuv2planeX, avx,);
         ASSIGN_VSCALE_FUNC(c->yuv2plane1, avx, avx, 1);
+
+        switch (c->srcFormat) {
+        case PIX_FMT_YUYV422:
+            c->chrToYV12 = ff_yuyvToUV_avx;
+            break;
+        case PIX_FMT_UYVY422:
+            c->chrToYV12 = ff_uyvyToUV_avx;
+            break;
+        case PIX_FMT_NV12:
+            c->chrToYV12 = ff_nv12ToUV_avx;
+            break;
+        case PIX_FMT_NV21:
+            c->chrToYV12 = ff_nv21ToUV_avx;
+            break;
+        default:
+            break;
+        }
     }
 #endif
 }
diff --git a/libswscale/x86/swscale_template.c b/libswscale/x86/swscale_template.c
index 5e7df5c..e38f58b 100644
--- a/libswscale/x86/swscale_template.c
+++ b/libswscale/x86/swscale_template.c
@@ -1361,147 +1361,6 @@ static void RENAME(yuv2yuyv422_1)(SwsContext *c, const int16_t *buf0,
     }
 }
 
-#if !COMPILE_TEMPLATE_MMX2
-//FIXME yuy2* can read up to 7 samples too much
-
-static void RENAME(yuy2ToY)(uint8_t *dst, const uint8_t *src,
-                            int width, uint32_t *unused)
-{
-    __asm__ volatile(
-        "movq "MANGLE(bm01010101)", %%mm2           \n\t"
-        "mov                    %0, %%"REG_a"       \n\t"
-        "1:                                         \n\t"
-        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"
-        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"
-        "pand                %%mm2, %%mm0           \n\t"
-        "pand                %%mm2, %%mm1           \n\t"
-        "packuswb            %%mm1, %%mm0           \n\t"
-        "movq                %%mm0, (%2, %%"REG_a") \n\t"
-        "add                    $8, %%"REG_a"       \n\t"
-        " js                    1b                  \n\t"
-        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst+width)
-        : "%"REG_a
-    );
-}
-
-static void RENAME(yuy2ToUV)(uint8_t *dstU, uint8_t *dstV,
-                             const uint8_t *src1, const uint8_t *src2,
-                             int width, uint32_t *unused)
-{
-    __asm__ volatile(
-        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
-        "mov                    %0, %%"REG_a"       \n\t"
-        "1:                                         \n\t"
-        "movq    (%1, %%"REG_a",4), %%mm0           \n\t"
-        "movq   8(%1, %%"REG_a",4), %%mm1           \n\t"
-        "psrlw                  $8, %%mm0           \n\t"
-        "psrlw                  $8, %%mm1           \n\t"
-        "packuswb            %%mm1, %%mm0           \n\t"
-        "movq                %%mm0, %%mm1           \n\t"
-        "psrlw                  $8, %%mm0           \n\t"
-        "pand                %%mm4, %%mm1           \n\t"
-        "packuswb            %%mm0, %%mm0           \n\t"
-        "packuswb            %%mm1, %%mm1           \n\t"
-        "movd                %%mm0, (%3, %%"REG_a") \n\t"
-        "movd                %%mm1, (%2, %%"REG_a") \n\t"
-        "add                    $4, %%"REG_a"       \n\t"
-        " js                    1b                  \n\t"
-        : : "g" ((x86_reg)-width), "r" (src1+width*4), "r" (dstU+width), "r" (dstV+width)
-        : "%"REG_a
-    );
-    assert(src1 == src2);
-}
-
-/* This is almost identical to the previous, end exists only because
- * yuy2ToY/UV)(dst, src+1, ...) would have 100% unaligned accesses. */
-static void RENAME(uyvyToY)(uint8_t *dst, const uint8_t *src,
-                            int width, uint32_t *unused)
-{
-    __asm__ volatile(
-        "mov                  %0, %%"REG_a"         \n\t"
-        "1:                                         \n\t"
-        "movq  (%1, %%"REG_a",2), %%mm0             \n\t"
-        "movq 8(%1, %%"REG_a",2), %%mm1             \n\t"
-        "psrlw                $8, %%mm0             \n\t"
-        "psrlw                $8, %%mm1             \n\t"
-        "packuswb          %%mm1, %%mm0             \n\t"
-        "movq              %%mm0, (%2, %%"REG_a")   \n\t"
-        "add                  $8, %%"REG_a"         \n\t"
-        " js                  1b                    \n\t"
-        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst+width)
-        : "%"REG_a
-    );
-}
-
-static void RENAME(uyvyToUV)(uint8_t *dstU, uint8_t *dstV,
-                             const uint8_t *src1, const uint8_t *src2,
-                             int width, uint32_t *unused)
-{
-    __asm__ volatile(
-        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
-        "mov                    %0, %%"REG_a"       \n\t"
-        "1:                                         \n\t"
-        "movq    (%1, %%"REG_a",4), %%mm0           \n\t"
-        "movq   8(%1, %%"REG_a",4), %%mm1           \n\t"
-        "pand                %%mm4, %%mm0           \n\t"
-        "pand                %%mm4, %%mm1           \n\t"
-        "packuswb            %%mm1, %%mm0           \n\t"
-        "movq                %%mm0, %%mm1           \n\t"
-        "psrlw                  $8, %%mm0           \n\t"
-        "pand                %%mm4, %%mm1           \n\t"
-        "packuswb            %%mm0, %%mm0           \n\t"
-        "packuswb            %%mm1, %%mm1           \n\t"
-        "movd                %%mm0, (%3, %%"REG_a") \n\t"
-        "movd                %%mm1, (%2, %%"REG_a") \n\t"
-        "add                    $4, %%"REG_a"       \n\t"
-        " js                    1b                  \n\t"
-        : : "g" ((x86_reg)-width), "r" (src1+width*4), "r" (dstU+width), "r" (dstV+width)
-        : "%"REG_a
-    );
-    assert(src1 == src2);
-}
-
-static av_always_inline void RENAME(nvXXtoUV)(uint8_t *dst1, uint8_t *dst2,
-                                              const uint8_t *src, int width)
-{
-    __asm__ volatile(
-        "movq "MANGLE(bm01010101)", %%mm4           \n\t"
-        "mov                    %0, %%"REG_a"       \n\t"
-        "1:                                         \n\t"
-        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"
-        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"
-        "movq                %%mm0, %%mm2           \n\t"
-        "movq                %%mm1, %%mm3           \n\t"
-        "pand                %%mm4, %%mm0           \n\t"
-        "pand                %%mm4, %%mm1           \n\t"
-        "psrlw                  $8, %%mm2           \n\t"
-        "psrlw                  $8, %%mm3           \n\t"
-        "packuswb            %%mm1, %%mm0           \n\t"
-        "packuswb            %%mm3, %%mm2           \n\t"
-        "movq                %%mm0, (%2, %%"REG_a") \n\t"
-        "movq                %%mm2, (%3, %%"REG_a") \n\t"
-        "add                    $8, %%"REG_a"       \n\t"
-        " js                    1b                  \n\t"
-        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst1+width), "r" (dst2+width)
-        : "%"REG_a
-    );
-}
-
-static void RENAME(nv12ToUV)(uint8_t *dstU, uint8_t *dstV,
-                             const uint8_t *src1, const uint8_t *src2,
-                             int width, uint32_t *unused)
-{
-    RENAME(nvXXtoUV)(dstU, dstV, src1, width);
-}
-
-static void RENAME(nv21ToUV)(uint8_t *dstU, uint8_t *dstV,
-                             const uint8_t *src1, const uint8_t *src2,
-                             int width, uint32_t *unused)
-{
-    RENAME(nvXXtoUV)(dstV, dstU, src1, width);
-}
-#endif /* !COMPILE_TEMPLATE_MMX2 */
-
 static av_always_inline void RENAME(bgr24ToY_mmx)(uint8_t *dst, const uint8_t *src,
                                                   int width, enum PixelFormat srcFormat)
 {
@@ -1654,12 +1513,24 @@ static void RENAME(hyscale_fast)(SwsContext *c, int16_t *dst,
     void    *mmx2FilterCode= c->lumMmx2FilterCode;
     int i;
 #if defined(PIC)
-    DECLARE_ALIGNED(8, uint64_t, ebxsave);
+    uint64_t ebxsave;
+#endif
+#if ARCH_X86_64
+    uint64_t retsave;
 #endif
 
     __asm__ volatile(
 #if defined(PIC)
         "mov               %%"REG_b", %5        \n\t"
+#if ARCH_X86_64
+        "mov               -8(%%rsp), %%"REG_a" \n\t"
+        "mov               %%"REG_a", %6        \n\t"
+#endif
+#else
+#if ARCH_X86_64
+        "mov               -8(%%rsp), %%"REG_a" \n\t"
+        "mov               %%"REG_a", %5        \n\t"
+#endif
 #endif
         "pxor                  %%mm7, %%mm7     \n\t"
         "mov                      %0, %%"REG_c" \n\t"
@@ -1701,12 +1572,24 @@ static void RENAME(hyscale_fast)(SwsContext *c, int16_t *dst,
 
 #if defined(PIC)
         "mov                      %5, %%"REG_b" \n\t"
+#if ARCH_X86_64
+        "mov                      %6, %%"REG_a" \n\t"
+        "mov               %%"REG_a", -8(%%rsp) \n\t"
+#endif
+#else
+#if ARCH_X86_64
+        "mov                      %5, %%"REG_a" \n\t"
+        "mov               %%"REG_a", -8(%%rsp) \n\t"
+#endif
 #endif
         :: "m" (src), "m" (dst), "m" (filter), "m" (filterPos),
            "m" (mmx2FilterCode)
 #if defined(PIC)
           ,"m" (ebxsave)
 #endif
+#if ARCH_X86_64
+          ,"m"(retsave)
+#endif
         : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D
 #if !defined(PIC)
          ,"%"REG_b
@@ -1728,10 +1611,22 @@ static void RENAME(hcscale_fast)(SwsContext *c, int16_t *dst1, int16_t *dst2,
 #if defined(PIC)
     DECLARE_ALIGNED(8, uint64_t, ebxsave);
 #endif
+#if ARCH_X86_64
+    DECLARE_ALIGNED(8, uint64_t, retsave);
+#endif
 
     __asm__ volatile(
 #if defined(PIC)
         "mov          %%"REG_b", %7         \n\t"
+#if ARCH_X86_64
+        "mov          -8(%%rsp), %%"REG_a"  \n\t"
+        "mov          %%"REG_a", %8         \n\t"
+#endif
+#else
+#if ARCH_X86_64
+        "mov          -8(%%rsp), %%"REG_a"  \n\t"
+        "mov          %%"REG_a", %7         \n\t"
+#endif
 #endif
         "pxor             %%mm7, %%mm7      \n\t"
         "mov                 %0, %%"REG_c"  \n\t"
@@ -1761,12 +1656,24 @@ static void RENAME(hcscale_fast)(SwsContext *c, int16_t *dst1, int16_t *dst2,
 
 #if defined(PIC)
         "mov %7, %%"REG_b"    \n\t"
+#if ARCH_X86_64
+        "mov                 %8, %%"REG_a"  \n\t"
+        "mov          %%"REG_a", -8(%%rsp)  \n\t"
+#endif
+#else
+#if ARCH_X86_64
+        "mov                 %7, %%"REG_a"  \n\t"
+        "mov          %%"REG_a", -8(%%rsp)  \n\t"
+#endif
 #endif
         :: "m" (src1), "m" (dst1), "m" (filter), "m" (filterPos),
            "m" (mmx2FilterCode), "m" (src2), "m"(dst2)
 #if defined(PIC)
           ,"m" (ebxsave)
 #endif
+#if ARCH_X86_64
+          ,"m"(retsave)
+#endif
         : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D
 #if !defined(PIC)
          ,"%"REG_b
@@ -1856,15 +1763,6 @@ static av_cold void RENAME(sws_init_swScale)(SwsContext *c)
 #endif /* COMPILE_TEMPLATE_MMX2 */
     }
 
-#if !COMPILE_TEMPLATE_MMX2
-    switch(srcFormat) {
-        case PIX_FMT_YUYV422  : c->chrToYV12 = RENAME(yuy2ToUV); break;
-        case PIX_FMT_UYVY422  : c->chrToYV12 = RENAME(uyvyToUV); break;
-        case PIX_FMT_NV12     : c->chrToYV12 = RENAME(nv12ToUV); break;
-        case PIX_FMT_NV21     : c->chrToYV12 = RENAME(nv21ToUV); break;
-        default: break;
-    }
-#endif /* !COMPILE_TEMPLATE_MMX2 */
     if (!c->chrSrcHSubSample) {
         switch(srcFormat) {
         case PIX_FMT_BGR24  : c->chrToYV12 = RENAME(bgr24ToUV); break;
@@ -1874,21 +1772,8 @@ static av_cold void RENAME(sws_init_swScale)(SwsContext *c)
     }
 
     switch (srcFormat) {
-#if !COMPILE_TEMPLATE_MMX2
-    case PIX_FMT_YUYV422  :
-    case PIX_FMT_Y400A    : c->lumToYV12 = RENAME(yuy2ToY); break;
-    case PIX_FMT_UYVY422  : c->lumToYV12 = RENAME(uyvyToY); break;
-#endif /* !COMPILE_TEMPLATE_MMX2 */
     case PIX_FMT_BGR24    : c->lumToYV12 = RENAME(bgr24ToY); break;
     case PIX_FMT_RGB24    : c->lumToYV12 = RENAME(rgb24ToY); break;
     default: break;
     }
-#if !COMPILE_TEMPLATE_MMX2
-    if (c->alpPixBuf) {
-        switch (srcFormat) {
-        case PIX_FMT_Y400A  : c->alpToYV12 = RENAME(yuy2ToY); break;
-        default: break;
-        }
-    }
-#endif /* !COMPILE_TEMPLATE_MMX2 */
 }
diff --git a/tests/Makefile b/tests/Makefile
index d36fa5c..43024eb 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -23,17 +23,18 @@ tests/data/asynth-16000-1.sw: tests/audiogen$(HOSTEXESUF)
 
 tests/data/asynth%.sw tests/vsynth%/00.pgm: TAG = GEN
 
-include $(SRC_PATH)/tests/fate.mak
-include $(SRC_PATH)/tests/fate2.mak
-
 include $(SRC_PATH)/tests/fate/aac.mak
 include $(SRC_PATH)/tests/fate/ac3.mak
 include $(SRC_PATH)/tests/fate/als.mak
 include $(SRC_PATH)/tests/fate/amrnb.mak
 include $(SRC_PATH)/tests/fate/amrwb.mak
 include $(SRC_PATH)/tests/fate/atrac.mak
+include $(SRC_PATH)/tests/fate/audio.mak
 include $(SRC_PATH)/tests/fate/dct.mak
+include $(SRC_PATH)/tests/fate/demux.mak
+include $(SRC_PATH)/tests/fate/dfa.mak
 include $(SRC_PATH)/tests/fate/dpcm.mak
+include $(SRC_PATH)/tests/fate/ea.mak
 include $(SRC_PATH)/tests/fate/fft.mak
 include $(SRC_PATH)/tests/fate/h264.mak
 include $(SRC_PATH)/tests/fate/image.mak
@@ -47,10 +48,13 @@ include $(SRC_PATH)/tests/fate/mp3.mak
 include $(SRC_PATH)/tests/fate/mpc.mak
 include $(SRC_PATH)/tests/fate/pcm.mak
 include $(SRC_PATH)/tests/fate/prores.mak
+include $(SRC_PATH)/tests/fate/qt.mak
 include $(SRC_PATH)/tests/fate/qtrle.mak
 include $(SRC_PATH)/tests/fate/real.mak
 include $(SRC_PATH)/tests/fate/screen.mak
 include $(SRC_PATH)/tests/fate/utvideo.mak
+include $(SRC_PATH)/tests/fate/video.mak
+include $(SRC_PATH)/tests/fate/voice.mak
 include $(SRC_PATH)/tests/fate/vorbis.mak
 include $(SRC_PATH)/tests/fate/vpx.mak
 include $(SRC_PATH)/tests/fate/vqf.mak
diff --git a/tests/codec-regression.sh b/tests/codec-regression.sh
index e20bf64..5fd90f5 100755
--- a/tests/codec-regression.sh
+++ b/tests/codec-regression.sh
@@ -62,13 +62,13 @@ fi
 
 if [ -n "$do_mpeg2thread" ] ; then
 # mpeg2 encoding interlaced
-do_video_encoding mpeg2thread.mpg "-qscale 10 -vcodec mpeg2video -f mpeg1video -bf 2 -flags +ildct+ilme -threads 2"
+do_video_encoding mpeg2thread.mpg "-qscale 10 -vcodec mpeg2video -f mpeg1video -bf 2 -flags +ildct+ilme -threads 2 -slices 2"
 do_video_decoding
 fi
 
 if [ -n "$do_mpeg2thread_ilace" ]; then
 # mpeg2 encoding interlaced using intra vlc
-do_video_encoding mpeg2threadivlc.mpg "-qscale 10 -vcodec mpeg2video -f mpeg1video -bf 2 -flags +ildct+ilme -flags2 +ivlc -threads 2"
+do_video_encoding mpeg2threadivlc.mpg "-qscale 10 -vcodec mpeg2video -f mpeg1video -bf 2 -flags +ildct+ilme -flags2 +ivlc -threads 2 -slices 2"
 do_video_decoding
 fi
 
@@ -143,7 +143,7 @@ do_video_decoding
 fi
 
 if [ -n "$do_mpeg4thread" ] ; then
-do_video_encoding mpeg4-thread.avi "-b 500k -flags +mv4+part+aic -trellis 1 -mbd bits -ps 200 -bf 2 -an -vcodec mpeg4 -threads 2"
+do_video_encoding mpeg4-thread.avi "-b 500k -flags +mv4+part+aic -trellis 1 -mbd bits -ps 200 -bf 2 -an -vcodec mpeg4 -threads 2 -slices 2"
 do_video_decoding
 fi
 
@@ -311,6 +311,11 @@ do_audio_encoding g726.wav "-b 32k -ac 1 -ar 8000 -acodec g726"
 do_audio_decoding
 fi
 
+if [ -n "$do_adpcm_adx" ] ; then
+do_audio_encoding adpcm_adx.adx "-acodec adpcm_adx"
+do_audio_decoding
+fi
+
 if [ -n "$do_adpcm_ima_wav" ] ; then
 do_audio_encoding adpcm_ima.wav "-acodec adpcm_ima_wav"
 do_audio_decoding
diff --git a/tests/fate.mak b/tests/fate.mak
deleted file mode 100644
index 89bbb9f..0000000
--- a/tests/fate.mak
+++ /dev/null
@@ -1,200 +0,0 @@
-FATE_TESTS += fate-4xm-1
-fate-4xm-1: CMD = framecrc -i $(SAMPLES)/4xm/version1.4xm -pix_fmt rgb24 -an
-FATE_TESTS += fate-4xm-2
-fate-4xm-2: CMD = framecrc -i $(SAMPLES)/4xm/version2.4xm -pix_fmt rgb24 -an
-FATE_TESTS += fate-8bps
-fate-8bps: CMD = framecrc  -i $(SAMPLES)/8bps/full9iron-partial.mov -pix_fmt rgb24
-FATE_TESTS += fate-aasc
-fate-aasc: CMD = framecrc  -i $(SAMPLES)/aasc/AASC-1.5MB.AVI -pix_fmt rgb24
-FATE_TESTS += fate-adts-demux
-fate-adts-demux: CMD = crc  -i $(SAMPLES)/aac/ct_faac-adts.aac -acodec copy
-FATE_TESTS += fate-aea-demux
-fate-aea-demux: CMD = crc  -i $(SAMPLES)/aea/chirp.aea -acodec copy
-FATE_TESTS += fate-alg-mm
-fate-alg-mm: CMD = framecrc  -i $(SAMPLES)/alg-mm/ibmlogo.mm -an -pix_fmt rgb24
-FATE_TESTS += fate-amv
-fate-amv: CMD = framecrc  -idct simple -i $(SAMPLES)/amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv -t 10
-FATE_TESTS += fate-armovie-escape124
-fate-armovie-escape124: CMD = framecrc  -i $(SAMPLES)/rpl/ESCAPE.RPL -pix_fmt rgb24
-FATE_TESTS += fate-auravision
-fate-auravision: CMD = framecrc  -i $(SAMPLES)/auravision/SOUVIDEO.AVI -an
-FATE_TESTS += fate-auravision-v2
-fate-auravision-v2: CMD = framecrc  -i $(SAMPLES)/auravision/salma-hayek-in-ugly-betty-partial-avi -an
-FATE_TESTS += fate-bethsoft-vid
-fate-bethsoft-vid: CMD = framecrc  -i $(SAMPLES)/bethsoft-vid/ANIM0001.VID -vsync 0 -t 5 -pix_fmt rgb24
-FATE_TESTS += fate-bfi
-fate-bfi: CMD = framecrc  -i $(SAMPLES)/bfi/2287.bfi -pix_fmt rgb24
-FATE_TESTS += fate-bink-demux
-fate-bink-demux: CMD = crc  -i $(SAMPLES)/bink/Snd0a7d9b58.dee -vn -acodec copy
-FATE_TESTS += fate-bink-demux-video
-fate-bink-demux-video: CMD = framecrc  -i $(SAMPLES)/bink/hol2br.bik
-FATE_TESTS += fate-caf
-fate-caf: CMD = crc  -i $(SAMPLES)/caf/caf-pcm16.caf
-FATE_TESTS += fate-cdgraphics
-fate-cdgraphics: CMD = framecrc  -i $(SAMPLES)/cdgraphics/BrotherJohn.cdg -pix_fmt rgb24 -t 1
-FATE_TESTS += fate-cljr
-fate-cljr: CMD = framecrc  -i $(SAMPLES)/cljr/testcljr-partial.avi
-FATE_TESTS += fate-corepng
-fate-corepng: CMD = framecrc  -i $(SAMPLES)/png1/corepng-partial.avi
-FATE_TESTS += fate-creatureshock-avs
-fate-creatureshock-avs: CMD = framecrc  -i $(SAMPLES)/creatureshock-avs/OUTATIME.AVS -pix_fmt rgb24
-FATE_TESTS += fate-cryo-apc
-fate-cryo-apc: CMD = md5  -i $(SAMPLES)/cryo-apc/cine007.APC -f s16le
-FATE_TESTS += fate-cvid
-fate-cvid: CMD = framecrc  -i $(SAMPLES)/cvid/laracroft-cinepak-partial.avi -an
-FATE_TESTS += fate-cvid-palette
-fate-cvid-palette: CMD = framecrc  -i $(SAMPLES)/cvid/catfight-cvid-pal8-partial.mov -pix_fmt rgb24 -an
-FATE_TESTS += fate-cyberia-c93
-fate-cyberia-c93: CMD = framecrc  -i $(SAMPLES)/cyberia-c93/intro1.c93 -t 3 -pix_fmt rgb24
-FATE_TESTS += fate-cyuv
-fate-cyuv: CMD = framecrc  -i $(SAMPLES)/cyuv/cyuv.avi
-FATE_TESTS += fate-d-cinema-demux
-fate-d-cinema-demux: CMD = framecrc  -i $(SAMPLES)/d-cinema/THX_Science_FLT_1920-partial.302 -acodec copy -pix_fmt rgb24
-FATE_TESTS += fate-delphine-cin
-fate-delphine-cin: CMD = framecrc  -i $(SAMPLES)/delphine-cin/LOGO-partial.CIN -pix_fmt rgb24 -vsync 0
-FATE_TESTS += fate-deluxepaint-anm
-fate-deluxepaint-anm: CMD = framecrc  -i $(SAMPLES)/deluxepaint-anm/INTRO1.ANM -pix_fmt rgb24
-FATE_TESTS += fate-duck-tm2
-fate-duck-tm2: CMD = framecrc  -i $(SAMPLES)/duck/tm20.avi
-FATE_TESTS += fate-ea-cdata
-fate-ea-cdata: CMD = md5  -i $(SAMPLES)/ea-cdata/166b084d.46410f77.0009b440.24be960c.cdata -f s16le
-FATE_TESTS += fate-ea-cmv
-fate-ea-cmv: CMD = framecrc  -i $(SAMPLES)/ea-cmv/TITLE.CMV -vsync 0 -pix_fmt rgb24
-FATE_TESTS += fate-ea-dct
-fate-ea-dct: CMD = framecrc  -idct simple -i $(SAMPLES)/ea-dct/NFS2Esprit-partial.dct
-FATE_TESTS += fate-ea-tgq
-fate-ea-tgq: CMD = framecrc  -i $(SAMPLES)/ea-tgq/v27.tgq -an
-FATE_TESTS += fate-ea-tgv-ima-ea-eacs
-fate-ea-tgv-ima-ea-eacs: CMD = framecrc  -i $(SAMPLES)/ea-tgv/INTRO8K-partial.TGV -pix_fmt rgb24
-FATE_TESTS += fate-ea-tgv-ima-ea-sead
-fate-ea-tgv-ima-ea-sead: CMD = framecrc  -i $(SAMPLES)/ea-tgv/INTEL_S.TGV -pix_fmt rgb24
-FATE_TESTS += fate-feeble-dxa
-fate-feeble-dxa: CMD = framecrc  -i $(SAMPLES)/dxa/meetsquid.dxa -t 2 -pix_fmt rgb24
-FATE_TESTS += fate-flic-af11-palette-change
-fate-flic-af11-palette-change: CMD = framecrc  -i $(SAMPLES)/fli/fli-engines.fli -t 3.3 -pix_fmt rgb24
-FATE_TESTS += fate-flic-af12
-fate-flic-af12: CMD = framecrc  -i $(SAMPLES)/fli/jj00c2.fli -pix_fmt rgb24
-FATE_TESTS += fate-flic-magiccarpet
-fate-flic-magiccarpet: CMD = framecrc  -i $(SAMPLES)/fli/intel.dat -pix_fmt rgb24
-FATE_TESTS += fate-frwu
-fate-frwu: CMD = framecrc  -i $(SAMPLES)/frwu/frwu.avi
-FATE_TESTS += fate-funcom-iss
-fate-funcom-iss: CMD = md5  -i $(SAMPLES)/funcom-iss/0004010100.iss -f s16le
-FATE_TESTS += fate-id-cin-video
-fate-id-cin-video: CMD = framecrc  -i $(SAMPLES)/idcin/idlog-2MB.cin -pix_fmt rgb24
-FATE_TESTS-$(CONFIG_AVFILTER) += fate-idroq-video-encode
-fate-idroq-video-encode: CMD = md5  -f image2 -vcodec pgmyuv -i $(SAMPLES)/ffmpeg-synthetic/vsynth1/%02d.pgm -sws_flags +bitexact -vf pad=512:512:80:112 -f RoQ -t 0.2
-FATE_TESTS += fate-iff-byterun1
-fate-iff-byterun1: CMD = framecrc  -i $(SAMPLES)/iff/ASH.LBM -pix_fmt rgb24
-FATE_TESTS += fate-iff-fibonacci
-fate-iff-fibonacci: CMD = md5  -i $(SAMPLES)/iff/dasboot-in-compressed -f s16le
-FATE_TESTS += fate-iff-ilbm
-fate-iff-ilbm: CMD = framecrc  -i $(SAMPLES)/iff/lms-matriks.ilbm -pix_fmt rgb24
-FATE_TESTS += fate-interplay-mve-16bit
-fate-interplay-mve-16bit: CMD = framecrc  -i $(SAMPLES)/interplay-mve/descent3-level5-16bit-partial.mve -pix_fmt rgb24
-FATE_TESTS += fate-interplay-mve-8bit
-fate-interplay-mve-8bit: CMD = framecrc  -i $(SAMPLES)/interplay-mve/interplay-logo-2MB.mve -pix_fmt rgb24
-FATE_TESTS += fate-iv8-demux
-fate-iv8-demux: CMD = framecrc  -i $(SAMPLES)/iv8/zzz-partial.mpg -vsync 0 -vcodec copy
-FATE_TESTS += fate-kmvc
-fate-kmvc: CMD = framecrc  -i $(SAMPLES)/KMVC/LOGO1.AVI -an -t 3 -pix_fmt rgb24
-FATE_TESTS += fate-lmlm4-demux
-fate-lmlm4-demux: CMD = framecrc  -i $(SAMPLES)/lmlm4/LMLM4_CIFat30fps.divx -t 3 -acodec copy -vcodec copy
-FATE_TESTS += fate-maxis-xa
-fate-maxis-xa: CMD = md5  -i $(SAMPLES)/maxis-xa/SC2KBUG.XA -f s16le
-FATE_TESTS += fate-mimic
-fate-mimic: CMD = framecrc  -idct simple -i $(SAMPLES)/mimic/mimic2-womanloveffmpeg.cam -vsync 0
-FATE_TESTS += fate-motionpixels
-fate-motionpixels: CMD = framecrc  -i $(SAMPLES)/motion-pixels/INTRO-partial.MVI -an -pix_fmt rgb24 -vframes 111
-FATE_TESTS += fate-mtv
-fate-mtv: CMD = framecrc  -i $(SAMPLES)/mtv/comedian_auto-partial.mtv -acodec copy -pix_fmt rgb24
-FATE_TESTS += fate-mxf-demux
-fate-mxf-demux: CMD = framecrc  -i $(SAMPLES)/mxf/C0023S01.mxf -acodec copy -vcodec copy
-FATE_TESTS += fate-nc-demux
-fate-nc-demux: CMD = framecrc  -i $(SAMPLES)/nc-camera/nc-sample-partial -vcodec copy
-FATE_TESTS += fate-nsv-demux
-fate-nsv-demux: CMD = framecrc  -i $(SAMPLES)/nsv/witchblade-51kbps.nsv -t 6 -vcodec copy -acodec copy
-FATE_TESTS += fate-nuv
-fate-nuv: CMD = framecrc  -idct simple -i $(SAMPLES)/nuv/Today.nuv -vsync 0
-FATE_TESTS += fate-oma-demux
-fate-oma-demux: CMD = crc  -i $(SAMPLES)/oma/01-Untitled-partial.oma -acodec copy
-FATE_TESTS += fate-psx-str
-fate-psx-str: CMD = framecrc  -i $(SAMPLES)/psx-str/descent-partial.str
-FATE_TESTS += fate-psx-str-v3-mdec
-fate-psx-str-v3-mdec: CMD = framecrc  -i $(SAMPLES)/psx-str/abc000_cut.str -an
-FATE_TESTS += fate-pva-demux
-fate-pva-demux: CMD = framecrc  -idct simple -i $(SAMPLES)/pva/PVA_test-partial.pva -t 0.6 -acodec copy
-FATE_TESTS += fate-qcp-demux
-fate-qcp-demux: CMD = crc  -i $(SAMPLES)/qcp/0036580847.QCP -acodec copy
-FATE_TESTS += fate-qpeg
-fate-qpeg: CMD = framecrc  -i $(SAMPLES)/qpeg/Clock.avi -an -pix_fmt rgb24
-FATE_TESTS += fate-qt-alaw-mono
-fate-qt-alaw-mono: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-alaw.mov -f s16le
-FATE_TESTS += fate-qt-alaw-stereo
-fate-qt-alaw-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-alaw.mov -f s16le
-FATE_TESTS += fate-qt-ima4-mono
-fate-qt-ima4-mono: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-ima4.mov -f s16le
-FATE_TESTS += fate-qt-ima4-stereo
-fate-qt-ima4-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-ima4.mov -f s16le
-FATE_TESTS += fate-qt-mac3-mono
-fate-qt-mac3-mono: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-8-MAC3.mov -f s16le
-FATE_TESTS += fate-qt-mac3-stereo
-fate-qt-mac3-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-8-MAC3.mov -f s16le
-FATE_TESTS += fate-qt-mac6-mono
-fate-qt-mac6-mono: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-8-MAC6.mov -f s16le
-FATE_TESTS += fate-qt-mac6-stereo
-fate-qt-mac6-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-8-MAC6.mov -f s16le
-FATE_TESTS += fate-qt-ulaw-mono
-fate-qt-ulaw-mono: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-ulaw.mov -f s16le
-FATE_TESTS += fate-qt-ulaw-stereo
-fate-qt-ulaw-stereo: CMD = md5  -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-ulaw.mov -f s16le
-FATE_TESTS += fate-quickdraw
-fate-quickdraw: CMD = framecrc  -i $(SAMPLES)/quickdraw/Airplane.mov -pix_fmt rgb24
-FATE_TESTS += fate-redcode-demux
-fate-redcode-demux: CMD = framecrc  -i $(SAMPLES)/r3d/4MB-sample.r3d -vcodec copy -acodec copy
-FATE_TESTS += fate-rl2
-fate-rl2: CMD = framecrc  -i $(SAMPLES)/rl2/Z4915300.RL2 -pix_fmt rgb24 -an -vsync 0
-FATE_TESTS += fate-rpza
-fate-rpza: CMD = framecrc  -i $(SAMPLES)/rpza/rpza2.mov -t 2 -pix_fmt rgb24
-FATE_TESTS += fate-sierra-audio
-fate-sierra-audio: CMD = md5  -i $(SAMPLES)/sol/lsl7sample.sol -f s16le
-FATE_TESTS += fate-sierra-vmd
-fate-sierra-vmd: CMD = framecrc  -i $(SAMPLES)/vmd/12.vmd -vsync 0 -pix_fmt rgb24
-FATE_TESTS += fate-siff
-fate-siff: CMD = framecrc  -i $(SAMPLES)/SIFF/INTRO_B.VB -t 3 -pix_fmt rgb24
-FATE_TESTS += fate-smacker
-fate-smacker: CMD = framecrc  -i $(SAMPLES)/smacker/wetlogo.smk -pix_fmt rgb24
-FATE_TESTS += fate-smc
-fate-smc: CMD = framecrc  -i $(SAMPLES)/smc/cass_schi.qt -vsync 0 -pix_fmt rgb24
-FATE_TESTS += fate-sp5x
-fate-sp5x: CMD = framecrc  -idct simple -i $(SAMPLES)/sp5x/sp5x_problem.avi
-FATE_TESTS += fate-sub-srt
-fate-sub-srt: CMD = md5  -i $(SAMPLES)/sub/SubRip_capability_tester.srt -f ass
-FATE_TESTS += fate-svq1
-fate-svq1: CMD = framecrc  -i $(SAMPLES)/svq1/marymary-shackles.mov -an -t 10
-FATE_TESTS += fate-svq3
-fate-svq3: CMD = framecrc  -i $(SAMPLES)/svq3/Vertical400kbit.sorenson3.mov -t 6 -an
-FATE_TESTS += fate-tiertex-seq
-fate-tiertex-seq: CMD = framecrc  -i $(SAMPLES)/tiertex-seq/Gameover.seq -pix_fmt rgb24
-FATE_TESTS += fate-tmv
-fate-tmv: CMD = framecrc  -i $(SAMPLES)/tmv/pop-partial.tmv -pix_fmt rgb24
-FATE_TESTS += fate-truemotion1-15
-fate-truemotion1-15: CMD = framecrc -i $(SAMPLES)/duck/phant2-940.duk -pix_fmt rgb24
-FATE_TESTS += fate-truemotion1-24
-fate-truemotion1-24: CMD = framecrc -i $(SAMPLES)/duck/sonic3dblast_intro-partial.avi -pix_fmt rgb24
-FATE_TESTS += fate-ulti
-fate-ulti: CMD = framecrc  -i $(SAMPLES)/ulti/hit12w.avi -an
-FATE_TESTS += fate-v210
-fate-v210: CMD = framecrc  -i $(SAMPLES)/v210/v210_720p-partial.avi -pix_fmt yuv422p16be -an
-FATE_TESTS += fate-vcr1
-fate-vcr1: CMD = framecrc  -i $(SAMPLES)/vcr1/VCR1test.avi -an
-FATE_TESTS += fate-video-xl
-fate-video-xl: CMD = framecrc  -i $(SAMPLES)/vixl/pig-vixl.avi
-FATE_TESTS += fate-vqa-cc
-fate-vqa-cc: CMD = framecrc  -i $(SAMPLES)/vqa/cc-demo1-partial.vqa -pix_fmt rgb24
-FATE_TESTS += fate-wc3movie-xan
-fate-wc3movie-xan: CMD = framecrc  -i $(SAMPLES)/wc3movie/SC_32-part.MVE -pix_fmt rgb24
-FATE_TESTS += fate-westwood-aud
-fate-westwood-aud: CMD = md5  -i $(SAMPLES)/westwood-aud/excellent.aud -f s16le
-FATE_TESTS += fate-wnv1
-fate-wnv1: CMD = framecrc  -i $(SAMPLES)/wnv1/wnv1-codec.avi -an
diff --git a/tests/fate/aac.mak b/tests/fate/aac.mak
index f17c914..ea87436 100644
--- a/tests/fate/aac.mak
+++ b/tests/fate/aac.mak
@@ -14,18 +14,34 @@ FATE_AAC += fate-aac-al07_96
 fate-aac-al07_96: CMD = pcm -i $(SAMPLES)/aac/al07_96.mp4
 fate-aac-al07_96: REF = $(SAMPLES)/aac/al07_96.s16
 
+FATE_AAC += fate-aac-al15_44
+fate-aac-al15_44: CMD = pcm -i $(SAMPLES)/aac/al15_44.mp4
+fate-aac-al15_44: REF = $(SAMPLES)/aac/al15_44.s16
+
 FATE_AAC += fate-aac-al17_44
 fate-aac-al17_44: CMD = pcm -i $(SAMPLES)/aac/al17_44.mp4
 fate-aac-al17_44: REF = $(SAMPLES)/aac/al17_44.s16
 
+FATE_AAC += fate-aac-al18_44
+fate-aac-al18_44: CMD = pcm -i $(SAMPLES)/aac/al18_44.mp4
+fate-aac-al18_44: REF = $(SAMPLES)/aac/al18_44.s16
+
 FATE_AAC += fate-aac-am00_88
 fate-aac-am00_88: CMD = pcm -i $(SAMPLES)/aac/am00_88.mp4
 fate-aac-am00_88: REF = $(SAMPLES)/aac/am00_88.s16
 
+FATE_AAC += fate-aac-am05_44
+fate-aac-am05_44: CMD = pcm -i $(SAMPLES)/aac/am05_44.mp4
+fate-aac-am05_44: REF = $(SAMPLES)/aac/am05_44.s16
+
 FATE_AAC += fate-aac-al_sbr_hq_cm_48_2
 fate-aac-al_sbr_hq_cm_48_2: CMD = pcm -i $(SAMPLES)/aac/al_sbr_cm_48_2.mp4
 fate-aac-al_sbr_hq_cm_48_2: REF = $(SAMPLES)/aac/al_sbr_hq_cm_48_2.s16
 
+FATE_AAC += fate-aac-al_sbr_hq_cm_48_5.1
+fate-aac-al_sbr_hq_cm_48_5.1: CMD = pcm -i $(SAMPLES)/aac/al_sbr_cm_48_5.1.mp4
+fate-aac-al_sbr_hq_cm_48_5.1: REF = $(SAMPLES)/aac/al_sbr_hq_cm_48_5.1.s16
+
 FATE_AAC += fate-aac-al_sbr_ps_06_ur
 fate-aac-al_sbr_ps_06_ur: CMD = pcm -i $(SAMPLES)/aac/al_sbr_ps_06_new.mp4
 fate-aac-al_sbr_ps_06_ur: REF = $(SAMPLES)/aac/al_sbr_ps_06_ur.s16
diff --git a/tests/fate/audio.mak b/tests/fate/audio.mak
new file mode 100644
index 0000000..9c9a6ff
--- /dev/null
+++ b/tests/fate/audio.mak
@@ -0,0 +1,30 @@
+FATE_TESTS += fate-binkaudio-dct
+fate-binkaudio-dct: CMD = pcm -i $(SAMPLES)/bink/binkaudio_dct.bik
+fate-binkaudio-dct: CMP = oneoff
+fate-binkaudio-dct: REF = $(SAMPLES)/bink/binkaudio_dct.pcm
+fate-binkaudio-dct: FUZZ = 2
+
+FATE_TESTS += fate-binkaudio-rdft
+fate-binkaudio-rdft: CMD = pcm -i $(SAMPLES)/bink/binkaudio_rdft.bik
+fate-binkaudio-rdft: CMP = oneoff
+fate-binkaudio-rdft: REF = $(SAMPLES)/bink/binkaudio_rdft.pcm
+fate-binkaudio-rdft: FUZZ = 2
+
+FATE_TESTS += fate-dts
+fate-dts: CMD = pcm -i $(SAMPLES)/dts/dts.ts
+fate-dts: CMP = oneoff
+fate-dts: REF = $(SAMPLES)/dts/dts.pcm
+
+FATE_TESTS += fate-imc
+fate-imc: CMD = pcm -i $(SAMPLES)/imc/imc.avi
+fate-imc: CMP = oneoff
+fate-imc: REF = $(SAMPLES)/imc/imc.pcm
+
+FATE_TESTS += fate-nellymoser
+fate-nellymoser: CMD = pcm -i $(SAMPLES)/nellymoser/nellymoser.flv
+fate-nellymoser: CMP = oneoff
+fate-nellymoser: REF = $(SAMPLES)/nellymoser/nellymoser.pcm
+
+FATE_TESTS += fate-ws_snd
+fate-ws_snd: CMD = md5 -i $(SAMPLES)/vqa/ws_snd.vqa -f s16le
+
diff --git a/tests/fate/demux.mak b/tests/fate/demux.mak
new file mode 100644
index 0000000..4dd953e
--- /dev/null
+++ b/tests/fate/demux.mak
@@ -0,0 +1,95 @@
+FATE_TESTS += fate-adts-demux
+fate-adts-demux: CMD = crc -i $(SAMPLES)/aac/ct_faac-adts.aac -acodec copy
+
+FATE_TESTS += fate-aea-demux
+fate-aea-demux: CMD = crc -i $(SAMPLES)/aea/chirp.aea -acodec copy
+
+FATE_TESTS += fate-bink-demux
+fate-bink-demux: CMD = crc -i $(SAMPLES)/bink/Snd0a7d9b58.dee -vn -acodec copy
+
+FATE_TESTS += fate-bink-demux-video
+fate-bink-demux-video: CMD = framecrc -i $(SAMPLES)/bink/hol2br.bik
+
+FATE_TESTS += fate-bmv
+fate-bmv: CMD = framecrc -i $(SAMPLES)/bmv/SURFING-partial.BMV -pix_fmt rgb24
+
+FATE_TESTS += fate-caf
+fate-caf: CMD = crc -i $(SAMPLES)/caf/caf-pcm16.caf
+
+FATE_TESTS += fate-cryo-apc
+fate-cryo-apc: CMD = md5 -i $(SAMPLES)/cryo-apc/cine007.APC -f s16le
+
+FATE_TESTS += fate-d-cinema-demux
+fate-d-cinema-demux: CMD = framecrc -i $(SAMPLES)/d-cinema/THX_Science_FLT_1920-partial.302 -acodec copy -pix_fmt rgb24
+
+FATE_TESTS += fate-funcom-iss
+fate-funcom-iss: CMD = md5 -i $(SAMPLES)/funcom-iss/0004010100.iss -f s16le
+
+FATE_TESTS += fate-interplay-mve-16bit
+fate-interplay-mve-16bit: CMD = framecrc -i $(SAMPLES)/interplay-mve/descent3-level5-16bit-partial.mve -pix_fmt rgb24
+
+FATE_TESTS += fate-interplay-mve-8bit
+fate-interplay-mve-8bit: CMD = framecrc -i $(SAMPLES)/interplay-mve/interplay-logo-2MB.mve -pix_fmt rgb24
+
+FATE_TESTS += fate-iv8-demux
+fate-iv8-demux: CMD = framecrc -i $(SAMPLES)/iv8/zzz-partial.mpg -vsync 0 -vcodec copy
+
+FATE_TESTS += fate-lmlm4-demux
+fate-lmlm4-demux: CMD = framecrc -i $(SAMPLES)/lmlm4/LMLM4_CIFat30fps.divx -t 3 -acodec copy -vcodec copy
+
+FATE_TESTS += fate-maxis-xa
+fate-maxis-xa: CMD = md5 -i $(SAMPLES)/maxis-xa/SC2KBUG.XA -f s16le
+
+FATE_TESTS += fate-mtv
+fate-mtv: CMD = framecrc -i $(SAMPLES)/mtv/comedian_auto-partial.mtv -acodec copy -pix_fmt rgb24
+
+FATE_TESTS += fate-mxf-demux
+fate-mxf-demux: CMD = framecrc -i $(SAMPLES)/mxf/C0023S01.mxf -acodec copy -vcodec copy
+
+FATE_TESTS += fate-nc-demux
+fate-nc-demux: CMD = framecrc -i $(SAMPLES)/nc-camera/nc-sample-partial -vcodec copy
+
+FATE_TESTS += fate-nsv-demux
+fate-nsv-demux: CMD = framecrc -i $(SAMPLES)/nsv/witchblade-51kbps.nsv -t 6 -vcodec copy -acodec copy
+
+FATE_TESTS += fate-oma-demux
+fate-oma-demux: CMD = crc -i $(SAMPLES)/oma/01-Untitled-partial.oma -acodec copy
+
+FATE_TESTS += fate-psx-str
+fate-psx-str: CMD = framecrc -i $(SAMPLES)/psx-str/descent-partial.str
+
+FATE_TESTS += fate-psx-str-v3-mdec
+fate-psx-str-v3-mdec: CMD = framecrc -i $(SAMPLES)/psx-str/abc000_cut.str -an
+
+FATE_TESTS += fate-pva-demux
+fate-pva-demux: CMD = framecrc -idct simple -i $(SAMPLES)/pva/PVA_test-partial.pva -t 0.6 -acodec copy
+
+FATE_TESTS += fate-qcp-demux
+fate-qcp-demux: CMD = crc -i $(SAMPLES)/qcp/0036580847.QCP -acodec copy
+
+FATE_TESTS += fate-redcode-demux
+fate-redcode-demux: CMD = framecrc -i $(SAMPLES)/r3d/4MB-sample.r3d -vcodec copy -acodec copy
+
+FATE_TESTS += fate-sierra-audio
+fate-sierra-audio: CMD = md5 -i $(SAMPLES)/sol/lsl7sample.sol -f s16le
+
+FATE_TESTS += fate-sierra-vmd
+fate-sierra-vmd: CMD = framecrc -i $(SAMPLES)/vmd/12.vmd -vsync 0 -pix_fmt rgb24
+
+FATE_TESTS += fate-siff
+fate-siff: CMD = framecrc -i $(SAMPLES)/SIFF/INTRO_B.VB -t 3 -pix_fmt rgb24
+
+FATE_TESTS += fate-smjpeg
+fate-smjpeg: CMD = framecrc -i $(SAMPLES)/smjpeg/scenwin.mjpg -vcodec copy
+
+FATE_TESTS += fate-westwood-aud
+fate-westwood-aud: CMD = md5 -i $(SAMPLES)/westwood-aud/excellent.aud -f s16le
+
+FATE_TESTS += fate-wtv-demux
+fate-wtv-demux: CMD = framecrc -i $(SAMPLES)/wtv/law-and-order-partial.wtv -vcodec copy -acodec copy
+
+FATE_TESTS += fate-xmv-demux
+fate-xmv-demux: CMD = framecrc -i $(SAMPLES)/xmv/logos1p.fmv -vcodec copy -acodec copy
+
+FATE_TESTS += fate-xwma-demux
+fate-xwma-demux: CMD = crc -i $(SAMPLES)/xwma/ergon.xwma -acodec copy
diff --git a/tests/fate/dfa.mak b/tests/fate/dfa.mak
new file mode 100644
index 0000000..6220c07
--- /dev/null
+++ b/tests/fate/dfa.mak
@@ -0,0 +1,35 @@
+FATE_DFA += fate-dfa1
+fate-dfa1: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0000.dfa -pix_fmt rgb24
+
+FATE_DFA += fate-dfa2
+fate-dfa2: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0001.dfa -pix_fmt rgb24
+
+FATE_DFA += fate-dfa3
+fate-dfa3: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0002.dfa -pix_fmt rgb24
+
+FATE_DFA += fate-dfa4
+fate-dfa4: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0003.dfa -pix_fmt rgb24
+
+FATE_DFA += fate-dfa5
+fate-dfa5: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0004.dfa -pix_fmt rgb24
+
+FATE_DFA += fate-dfa6
+fate-dfa6: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0005.dfa -pix_fmt rgb24
+
+FATE_DFA += fate-dfa7
+fate-dfa7: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0006.dfa -pix_fmt rgb24
+
+FATE_DFA += fate-dfa8
+fate-dfa8: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0007.dfa -pix_fmt rgb24
+
+FATE_DFA += fate-dfa9
+fate-dfa9: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0008.dfa -pix_fmt rgb24
+
+FATE_DFA += fate-dfa10
+fate-dfa10: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0009.dfa -pix_fmt rgb24
+
+FATE_DFA += fate-dfa11
+fate-dfa11: CMD = framecrc -i $(SAMPLES)/chronomaster-dfa/0010.dfa -pix_fmt rgb24
+
+FATE_TESTS += $(FATE_DFA)
+fate-dfa: $(FATE_DFA)
diff --git a/tests/fate/dpcm.mak b/tests/fate/dpcm.mak
index 7144518..606a524 100644
--- a/tests/fate/dpcm.mak
+++ b/tests/fate/dpcm.mak
@@ -38,5 +38,5 @@ FATE_TESTS += fate-thp-mjpeg-adpcm
 fate-thp-mjpeg-adpcm: CMD = framecrc -idct simple -i $(SAMPLES)/thp/pikmin2-opening1-partial.thp
 
 FATE_TESTS += fate-dpcm-xan
-fate-dpcm-xan: CMD = md5  -i $(SAMPLES)/wc4-xan/wc4_2.avi -vn -f s16le
+fate-dpcm-xan: CMD = md5 -i $(SAMPLES)/wc4-xan/wc4_2.avi -vn -f s16le
 
diff --git a/tests/fate/ea.mak b/tests/fate/ea.mak
new file mode 100644
index 0000000..1e628f4
--- /dev/null
+++ b/tests/fate/ea.mak
@@ -0,0 +1,17 @@
+FATE_TESTS += fate-ea-cdata
+fate-ea-cdata: CMD = md5 -i $(SAMPLES)/ea-cdata/166b084d.46410f77.0009b440.24be960c.cdata -f s16le
+
+FATE_TESTS += fate-ea-cmv
+fate-ea-cmv: CMD = framecrc -i $(SAMPLES)/ea-cmv/TITLE.CMV -vsync 0 -pix_fmt rgb24
+
+FATE_TESTS += fate-ea-dct
+fate-ea-dct: CMD = framecrc -idct simple -i $(SAMPLES)/ea-dct/NFS2Esprit-partial.dct
+
+FATE_TESTS += fate-ea-tgq
+fate-ea-tgq: CMD = framecrc -i $(SAMPLES)/ea-tgq/v27.tgq -an
+
+FATE_TESTS += fate-ea-tgv-ima-ea-eacs
+fate-ea-tgv-ima-ea-eacs: CMD = framecrc -i $(SAMPLES)/ea-tgv/INTRO8K-partial.TGV -pix_fmt rgb24
+
+FATE_TESTS += fate-ea-tgv-ima-ea-sead
+fate-ea-tgv-ima-ea-sead: CMD = framecrc -i $(SAMPLES)/ea-tgv/INTEL_S.TGV -pix_fmt rgb24
diff --git a/tests/fate/h264.mak b/tests/fate/h264.mak
index 20bfda2..e33ffa5 100644
--- a/tests/fate/h264.mak
+++ b/tests/fate/h264.mak
@@ -184,7 +184,7 @@ fate-h264-conformance-aud_mw_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-confo
 fate-h264-conformance-ba1_ft_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/BA1_FT_C.264
 fate-h264-conformance-ba1_sony_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/BA1_Sony_D.jsv
 fate-h264-conformance-ba2_sony_f: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/BA2_Sony_F.jsv
-fate-h264-conformance-ba3_sva_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/BA3_SVA_C.264
+fate-h264-conformance-ba3_sva_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/BA3_SVA_C.264
 fate-h264-conformance-ba_mw_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/BA_MW_D.264
 fate-h264-conformance-bamq1_jvc_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/BAMQ1_JVC_C.264
 fate-h264-conformance-bamq2_jvc_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/BAMQ2_JVC_C.264
@@ -194,81 +194,81 @@ fate-h264-conformance-caba1_sony_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-c
 fate-h264-conformance-caba1_sva_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CABA1_SVA_B.264
 fate-h264-conformance-caba2_sony_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CABA2_Sony_E.jsv
 fate-h264-conformance-caba2_sva_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CABA2_SVA_B.264
-fate-h264-conformance-caba3_sony_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CABA3_Sony_C.jsv
-fate-h264-conformance-caba3_sva_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CABA3_SVA_B.264
+fate-h264-conformance-caba3_sony_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CABA3_Sony_C.jsv
+fate-h264-conformance-caba3_sva_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CABA3_SVA_B.264
 fate-h264-conformance-caba3_toshiba_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CABA3_TOSHIBA_E.264
-fate-h264-conformance-cabac_mot_fld0_full: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/camp_mot_fld0_full.26l
-fate-h264-conformance-cabac_mot_frm0_full: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/camp_mot_frm0_full.26l
-fate-h264-conformance-cabac_mot_mbaff0_full: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/camp_mot_mbaff0_full.26l
-fate-h264-conformance-cabac_mot_picaff0_full: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/camp_mot_picaff0_full.26l
-fate-h264-conformance-cabaci3_sony_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CABACI3_Sony_B.jsv
-fate-h264-conformance-cabast3_sony_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CABAST3_Sony_E.jsv
-fate-h264-conformance-cabastbr3_sony_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CABASTBR3_Sony_B.jsv
-fate-h264-conformance-cabref3_sand_d: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CABREF3_Sand_D.264
-fate-h264-conformance-cacqp3_sony_d: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CACQP3_Sony_D.jsv
-fate-h264-conformance-cafi1_sva_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAFI1_SVA_C.264
+fate-h264-conformance-cabac_mot_fld0_full: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/camp_mot_fld0_full.26l
+fate-h264-conformance-cabac_mot_frm0_full: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/camp_mot_frm0_full.26l
+fate-h264-conformance-cabac_mot_mbaff0_full: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/camp_mot_mbaff0_full.26l
+fate-h264-conformance-cabac_mot_picaff0_full: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/camp_mot_picaff0_full.26l
+fate-h264-conformance-cabaci3_sony_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CABACI3_Sony_B.jsv
+fate-h264-conformance-cabast3_sony_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CABAST3_Sony_E.jsv
+fate-h264-conformance-cabastbr3_sony_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CABASTBR3_Sony_B.jsv
+fate-h264-conformance-cabref3_sand_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CABREF3_Sand_D.264
+fate-h264-conformance-cacqp3_sony_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CACQP3_Sony_D.jsv
+fate-h264-conformance-cafi1_sva_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAFI1_SVA_C.264
 fate-h264-conformance-cama1_sony_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAMA1_Sony_C.jsv
-fate-h264-conformance-cama1_toshiba_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAMA1_TOSHIBA_B.264
-fate-h264-conformance-cama1_vtc_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/cama1_vtc_c.avc
-fate-h264-conformance-cama2_vtc_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/cama2_vtc_b.avc
-fate-h264-conformance-cama3_sand_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAMA3_Sand_E.264
-fate-h264-conformance-cama3_vtc_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/cama3_vtc_b.avc
-fate-h264-conformance-camaci3_sony_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAMACI3_Sony_C.jsv
-fate-h264-conformance-camanl1_toshiba_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAMANL1_TOSHIBA_B.264
-fate-h264-conformance-camanl2_toshiba_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAMANL2_TOSHIBA_B.264
-fate-h264-conformance-camanl3_sand_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAMANL3_Sand_E.264
-fate-h264-conformance-camasl3_sony_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAMASL3_Sony_B.jsv
-fate-h264-conformance-camp_mot_mbaff_l30: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAMP_MOT_MBAFF_L30.26l
-fate-h264-conformance-camp_mot_mbaff_l31: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAMP_MOT_MBAFF_L31.26l
+fate-h264-conformance-cama1_toshiba_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAMA1_TOSHIBA_B.264
+fate-h264-conformance-cama1_vtc_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/cama1_vtc_c.avc
+fate-h264-conformance-cama2_vtc_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/cama2_vtc_b.avc
+fate-h264-conformance-cama3_sand_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAMA3_Sand_E.264
+fate-h264-conformance-cama3_vtc_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/cama3_vtc_b.avc
+fate-h264-conformance-camaci3_sony_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAMACI3_Sony_C.jsv
+fate-h264-conformance-camanl1_toshiba_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAMANL1_TOSHIBA_B.264
+fate-h264-conformance-camanl2_toshiba_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAMANL2_TOSHIBA_B.264
+fate-h264-conformance-camanl3_sand_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAMANL3_Sand_E.264
+fate-h264-conformance-camasl3_sony_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAMASL3_Sony_B.jsv
+fate-h264-conformance-camp_mot_mbaff_l30: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAMP_MOT_MBAFF_L30.26l
+fate-h264-conformance-camp_mot_mbaff_l31: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAMP_MOT_MBAFF_L31.26l
 fate-h264-conformance-canl1_sony_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CANL1_Sony_E.jsv
 fate-h264-conformance-canl1_sva_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CANL1_SVA_B.264
 fate-h264-conformance-canl1_toshiba_g: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CANL1_TOSHIBA_G.264
 fate-h264-conformance-canl2_sony_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CANL2_Sony_E.jsv
 fate-h264-conformance-canl2_sva_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CANL2_SVA_B.264
-fate-h264-conformance-canl3_sony_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CANL3_Sony_C.jsv
+fate-h264-conformance-canl3_sony_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CANL3_Sony_C.jsv
 fate-h264-conformance-canl3_sva_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CANL3_SVA_B.264
 fate-h264-conformance-canl4_sva_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CANL4_SVA_B.264
 fate-h264-conformance-canlma2_sony_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CANLMA2_Sony_C.jsv
 fate-h264-conformance-canlma3_sony_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CANLMA3_Sony_C.jsv
-fate-h264-conformance-capa1_toshiba_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAPA1_TOSHIBA_B.264
-fate-h264-conformance-capama3_sand_f: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAPAMA3_Sand_F.264
+fate-h264-conformance-capa1_toshiba_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAPA1_TOSHIBA_B.264
+fate-h264-conformance-capama3_sand_f: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAPAMA3_Sand_F.264
 fate-h264-conformance-capcm1_sand_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAPCM1_Sand_E.264
 fate-h264-conformance-capcmnl1_sand_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAPCMNL1_Sand_E.264
-fate-h264-conformance-capm3_sony_d: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAPM3_Sony_D.jsv
+fate-h264-conformance-capm3_sony_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAPM3_Sony_D.jsv
 fate-h264-conformance-caqp1_sony_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAQP1_Sony_B.jsv
-fate-h264-conformance-cavlc_mot_fld0_full_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/cvmp_mot_fld0_full_B.26l
-fate-h264-conformance-cavlc_mot_frm0_full_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/cvmp_mot_frm0_full_B.26l
-fate-h264-conformance-cavlc_mot_mbaff0_full_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/cvmp_mot_mbaff0_full_B.26l
-fate-h264-conformance-cavlc_mot_picaff0_full_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/cvmp_mot_picaff0_full_B.26l
+fate-h264-conformance-cavlc_mot_fld0_full_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/cvmp_mot_fld0_full_B.26l
+fate-h264-conformance-cavlc_mot_frm0_full_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/cvmp_mot_frm0_full_B.26l
+fate-h264-conformance-cavlc_mot_mbaff0_full_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/cvmp_mot_mbaff0_full_B.26l
+fate-h264-conformance-cavlc_mot_picaff0_full_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/cvmp_mot_picaff0_full_B.26l
 fate-h264-conformance-cawp1_toshiba_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAWP1_TOSHIBA_E.264
-fate-h264-conformance-cawp5_toshiba_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CAWP5_TOSHIBA_E.264
+fate-h264-conformance-cawp5_toshiba_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CAWP5_TOSHIBA_E.264
 fate-h264-conformance-ci1_ft_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CI1_FT_B.264
 fate-h264-conformance-ci_mw_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CI_MW_D.264
-fate-h264-conformance-cvbs3_sony_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVBS3_Sony_C.jsv
+fate-h264-conformance-cvbs3_sony_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVBS3_Sony_C.jsv
 fate-h264-conformance-cvcanlma2_sony_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVCANLMA2_Sony_C.jsv
-fate-h264-conformance-cvfi1_sony_d: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVFI1_Sony_D.jsv
-fate-h264-conformance-cvfi1_sva_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVFI1_SVA_C.264
-fate-h264-conformance-cvfi2_sony_h: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVFI2_Sony_H.jsv
-fate-h264-conformance-cvfi2_sva_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVFI2_SVA_C.264
+fate-h264-conformance-cvfi1_sony_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVFI1_Sony_D.jsv
+fate-h264-conformance-cvfi1_sva_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVFI1_SVA_C.264
+fate-h264-conformance-cvfi2_sony_h: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVFI2_Sony_H.jsv
+fate-h264-conformance-cvfi2_sva_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVFI2_SVA_C.264
 fate-h264-conformance-cvma1_sony_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVMA1_Sony_D.jsv
-fate-h264-conformance-cvma1_toshiba_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVMA1_TOSHIBA_B.264
-fate-h264-conformance-cvmanl1_toshiba_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVMANL1_TOSHIBA_B.264
-fate-h264-conformance-cvmanl2_toshiba_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVMANL2_TOSHIBA_B.264
-fate-h264-conformance-cvmapaqp3_sony_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVMAPAQP3_Sony_E.jsv
-fate-h264-conformance-cvmaqp2_sony_g: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVMAQP2_Sony_G.jsv
-fate-h264-conformance-cvmaqp3_sony_d: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVMAQP3_Sony_D.jsv
-fate-h264-conformance-cvmp_mot_fld_l30_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVMP_MOT_FLD_L30_B.26l
-fate-h264-conformance-cvmp_mot_frm_l31_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVMP_MOT_FRM_L31_B.26l
-fate-h264-conformance-cvnlfi1_sony_c: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVNLFI1_Sony_C.jsv
-fate-h264-conformance-cvnlfi2_sony_h: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVNLFI2_Sony_H.jsv
-fate-h264-conformance-cvpa1_toshiba_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVPA1_TOSHIBA_B.264
+fate-h264-conformance-cvma1_toshiba_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVMA1_TOSHIBA_B.264
+fate-h264-conformance-cvmanl1_toshiba_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVMANL1_TOSHIBA_B.264
+fate-h264-conformance-cvmanl2_toshiba_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVMANL2_TOSHIBA_B.264
+fate-h264-conformance-cvmapaqp3_sony_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVMAPAQP3_Sony_E.jsv
+fate-h264-conformance-cvmaqp2_sony_g: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVMAQP2_Sony_G.jsv
+fate-h264-conformance-cvmaqp3_sony_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVMAQP3_Sony_D.jsv
+fate-h264-conformance-cvmp_mot_fld_l30_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVMP_MOT_FLD_L30_B.26l
+fate-h264-conformance-cvmp_mot_frm_l31_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVMP_MOT_FRM_L31_B.26l
+fate-h264-conformance-cvnlfi1_sony_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVNLFI1_Sony_C.jsv
+fate-h264-conformance-cvnlfi2_sony_h: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVNLFI2_Sony_H.jsv
+fate-h264-conformance-cvpa1_toshiba_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVPA1_TOSHIBA_B.264
 fate-h264-conformance-cvpcmnl1_sva_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVPCMNL1_SVA_C.264
 fate-h264-conformance-cvpcmnl2_sva_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVPCMNL2_SVA_C.264
 fate-h264-conformance-cvwp1_toshiba_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVWP1_TOSHIBA_E.264
-fate-h264-conformance-cvwp2_toshiba_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVWP2_TOSHIBA_E.264
-fate-h264-conformance-cvwp3_toshiba_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVWP3_TOSHIBA_E.264
-fate-h264-conformance-cvwp5_toshiba_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/CVWP5_TOSHIBA_E.264
-fate-h264-conformance-fi1_sony_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/FI1_Sony_E.jsv
+fate-h264-conformance-cvwp2_toshiba_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVWP2_TOSHIBA_E.264
+fate-h264-conformance-cvwp3_toshiba_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVWP3_TOSHIBA_E.264
+fate-h264-conformance-cvwp5_toshiba_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/CVWP5_TOSHIBA_E.264
+fate-h264-conformance-fi1_sony_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FI1_Sony_E.jsv
 fate-h264-conformance-frext-alphaconformanceg: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/test8b43.264
 fate-h264-conformance-frext-bcrm_freh10: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/freh10.264 -vsync 0
 fate-h264-conformance-frext-brcm_freh11: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/freh11.264 -vsync 0
@@ -288,7 +288,7 @@ fate-h264-conformance-frext-frext1_panasonic_c: CMD = framecrc -vsync 0 -i $(SAM
 fate-h264-conformance-frext-frext2_panasonic_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/FRExt2_Panasonic.avc -vsync 0
 fate-h264-conformance-frext-frext3_panasonic_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/FRExt3_Panasonic.avc
 fate-h264-conformance-frext-frext4_panasonic_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/FRExt4_Panasonic.avc
-fate-h264-conformance-frext-frext_mmco4_sony_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/FRExt_MMCO4_Sony_B.264
+fate-h264-conformance-frext-frext_mmco4_sony_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/FRExt_MMCO4_Sony_B.264
 fate-h264-conformance-frext-hcaff1_hhi_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/HCAFF1_HHI.264
 fate-h264-conformance-frext-hcafr1_hhi_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/HCAFR1_HHI.264
 fate-h264-conformance-frext-hcafr2_hhi_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/HCAFR2_HHI.264
@@ -316,35 +316,35 @@ fate-h264-conformance-frext-pph10i4_panasonic_a: CMD = framecrc -vsync 0 -i $(SA
 fate-h264-conformance-frext-pph10i5_panasonic_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/PPH10I5_Panasonic_A.264 -pix_fmt yuv420p10le
 fate-h264-conformance-frext-pph10i6_panasonic_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/PPH10I6_Panasonic_A.264 -pix_fmt yuv420p10le
 fate-h264-conformance-frext-pph10i7_panasonic_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/FRext/PPH10I7_Panasonic_A.264 -pix_fmt yuv420p10le
-fate-h264-conformance-hcbp2_hhi_a: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/HCBP2_HHI_A.264
-fate-h264-conformance-hcmp1_hhi_a: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/HCMP1_HHI_A.264
+fate-h264-conformance-hcbp2_hhi_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/HCBP2_HHI_A.264
+fate-h264-conformance-hcmp1_hhi_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/HCMP1_HHI_A.264
 fate-h264-conformance-ls_sva_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/LS_SVA_D.264
 fate-h264-conformance-midr_mw_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MIDR_MW_D.264
 fate-h264-conformance-mps_mw_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MPS_MW_A.264
 fate-h264-conformance-mr1_bt_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MR1_BT_A.h264
 fate-h264-conformance-mr1_mw_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MR1_MW_A.264
 fate-h264-conformance-mr2_mw_a: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MR2_MW_A.264
-fate-h264-conformance-mr2_tandberg_e: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/MR2_TANDBERG_E.264
-fate-h264-conformance-mr3_tandberg_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/MR3_TANDBERG_B.264
-fate-h264-conformance-mr4_tandberg_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR4_TANDBERG_C.264
-fate-h264-conformance-mr5_tandberg_c: CMD = framecrc  -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR5_TANDBERG_C.264
-fate-h264-conformance-mr6_bt_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/MR6_BT_B.h264
-fate-h264-conformance-mr7_bt_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/MR7_BT_B.h264
-fate-h264-conformance-mr8_bt_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/MR8_BT_B.h264
-fate-h264-conformance-mr9_bt_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/MR9_BT_B.h264
-fate-h264-conformance-mv1_brcm_d: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/src19td.IBP.264
+fate-h264-conformance-mr2_tandberg_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MR2_TANDBERG_E.264
+fate-h264-conformance-mr3_tandberg_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MR3_TANDBERG_B.264
+fate-h264-conformance-mr4_tandberg_c: CMD = framecrc -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR4_TANDBERG_C.264
+fate-h264-conformance-mr5_tandberg_c: CMD = framecrc -vsync 0 -strict 1 -i $(SAMPLES)/h264-conformance/MR5_TANDBERG_C.264
+fate-h264-conformance-mr6_bt_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MR6_BT_B.h264
+fate-h264-conformance-mr7_bt_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MR7_BT_B.h264
+fate-h264-conformance-mr8_bt_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MR8_BT_B.h264
+fate-h264-conformance-mr9_bt_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/MR9_BT_B.h264
+fate-h264-conformance-mv1_brcm_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/src19td.IBP.264
 fate-h264-conformance-nl1_sony_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/NL1_Sony_D.jsv
 fate-h264-conformance-nl2_sony_h: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/NL2_Sony_H.jsv
 fate-h264-conformance-nl3_sva_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/NL3_SVA_E.264
 fate-h264-conformance-nlmq1_jvc_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/NLMQ1_JVC_C.264
 fate-h264-conformance-nlmq2_jvc_c: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/NLMQ2_JVC_C.264
 fate-h264-conformance-nrf_mw_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/NRF_MW_E.264
-fate-h264-conformance-sharp_mp_field_1_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_Field_1_B.jvt
-fate-h264-conformance-sharp_mp_field_2_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_Field_2_B.jvt
-fate-h264-conformance-sharp_mp_field_3_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_Field_3_B.jvt
-fate-h264-conformance-sharp_mp_paff_1r2: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_PAFF_1r2.jvt
-fate-h264-conformance-sharp_mp_paff_2r: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_PAFF_2.jvt
-fate-h264-conformance-sl1_sva_b: CMD = framecrc  -vsync 0 -i $(SAMPLES)/h264-conformance/SL1_SVA_B.264
+fate-h264-conformance-sharp_mp_field_1_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_Field_1_B.jvt
+fate-h264-conformance-sharp_mp_field_2_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_Field_2_B.jvt
+fate-h264-conformance-sharp_mp_field_3_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_Field_3_B.jvt
+fate-h264-conformance-sharp_mp_paff_1r2: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_PAFF_1r2.jvt
+fate-h264-conformance-sharp_mp_paff_2r: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/Sharp_MP_PAFF_2.jvt
+fate-h264-conformance-sl1_sva_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/SL1_SVA_B.264
 fate-h264-conformance-sva_ba1_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/SVA_BA1_B.264
 fate-h264-conformance-sva_ba2_d: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/SVA_BA2_D.264
 fate-h264-conformance-sva_base_b: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conformance/SVA_Base_B.264
@@ -356,4 +356,4 @@ fate-h264-conformance-sva_nl2_e: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264-conf
 fate-h264-interlace-crop: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264/interlaced_crop.mp4 -vframes 3
 fate-h264-lossless: CMD = framecrc -vsync 0 -i $(SAMPLES)/h264/lossless.h264
 fate-h264-extreme-plane-pred: CMD = framemd5 -vsync 0 -i $(SAMPLES)/h264/extreme-plane-pred.h264
-fate-h264-bsf-mp4toannexb: CMD = md5 -i $(SAMPLES)/h264/interlaced_crop.mp4 -vcodec copy -bsf h264_mp4toannexb -f mpeg
+fate-h264-bsf-mp4toannexb: CMD = md5 -i $(SAMPLES)/h264/interlaced_crop.mp4 -vcodec copy -bsf h264_mp4toannexb -f h264
diff --git a/tests/fate/image.mak b/tests/fate/image.mak
index db52bd2..9c5106f 100644
--- a/tests/fate/image.mak
+++ b/tests/fate/image.mak
@@ -1,5 +1,5 @@
 FATE_TESTS += fate-dpx
-fate-dpx: CMD = framecrc  -i $(SAMPLES)/dpx/lighthouse_rgb48.dpx
+fate-dpx: CMD = framecrc -i $(SAMPLES)/dpx/lighthouse_rgb48.dpx
 
 FATE_TESTS += fate-fax-g3
 fate-fax-g3: CMD = framecrc -i $(SAMPLES)/CCITT_fax/G31D.TIF
@@ -11,22 +11,22 @@ FATE_TESTS += fate-pictor
 fate-pictor: CMD = framecrc -i $(SAMPLES)/pictor/MFISH.PIC -pix_fmt rgb24
 
 FATE_TESTS += fate-ptx
-fate-ptx: CMD = framecrc  -i $(SAMPLES)/ptx/_113kw_pic.ptx -pix_fmt rgb24
+fate-ptx: CMD = framecrc -i $(SAMPLES)/ptx/_113kw_pic.ptx -pix_fmt rgb24
 
 FATE_TESTS += fate-sunraster-1bit-raw
-fate-sunraster-1bit-raw: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-1bit-raw.sun
+fate-sunraster-1bit-raw: CMD = framecrc -i $(SAMPLES)/sunraster/lena-1bit-raw.sun
 
 FATE_TESTS += fate-sunraster-1bit-rle
-fate-sunraster-1bit-rle: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-1bit-rle.sun
+fate-sunraster-1bit-rle: CMD = framecrc -i $(SAMPLES)/sunraster/lena-1bit-rle.sun
 
 FATE_TESTS += fate-sunraster-8bit-raw
-fate-sunraster-8bit-raw: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-8bit-raw.sun -pix_fmt rgb24
+fate-sunraster-8bit-raw: CMD = framecrc -i $(SAMPLES)/sunraster/lena-8bit-raw.sun -pix_fmt rgb24
 
 FATE_TESTS += fate-sunraster-8bit-rle
-fate-sunraster-8bit-rle: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-8bit-rle.sun -pix_fmt rgb24
+fate-sunraster-8bit-rle: CMD = framecrc -i $(SAMPLES)/sunraster/lena-8bit-rle.sun -pix_fmt rgb24
 
 FATE_TESTS += fate-sunraster-24bit-raw
-fate-sunraster-24bit-raw: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-24bit-raw.sun
+fate-sunraster-24bit-raw: CMD = framecrc -i $(SAMPLES)/sunraster/lena-24bit-raw.sun
 
 FATE_TESTS += fate-sunraster-24bit-rle
-fate-sunraster-24bit-rle: CMD = framecrc  -i $(SAMPLES)/sunraster/lena-24bit-rle.sun
+fate-sunraster-24bit-rle: CMD = framecrc -i $(SAMPLES)/sunraster/lena-24bit-rle.sun
diff --git a/tests/fate/indeo.mak b/tests/fate/indeo.mak
index df07392..36bf21b 100644
--- a/tests/fate/indeo.mak
+++ b/tests/fate/indeo.mak
@@ -4,5 +4,8 @@ fate-indeo2: CMD = framecrc -i $(SAMPLES)/rt21/VPAR0026.AVI
 FATE_TESTS += fate-indeo3
 fate-indeo3: CMD = framecrc -i $(SAMPLES)/iv32/cubes.mov
 
+FATE_TESTS += fate-indeo4
+fate-indeo4: CMD = framecrc -i $(SAMPLES)/iv41/indeo41-partial.avi -an
+
 FATE_TESTS += fate-indeo5
 fate-indeo5: CMD = framecrc -i $(SAMPLES)/iv50/Educ_Movie_DeadlyForce.avi -an
diff --git a/tests/fate/lossless-audio.mak b/tests/fate/lossless-audio.mak
index e735597..93e4678 100644
--- a/tests/fate/lossless-audio.mak
+++ b/tests/fate/lossless-audio.mak
@@ -1,17 +1,17 @@
 FATE_TESTS += fate-lossless-appleaudio
-fate-lossless-appleaudio: CMD = md5  -i $(SAMPLES)/lossless-audio/inside.m4a -f s16le
+fate-lossless-appleaudio: CMD = md5 -i $(SAMPLES)/lossless-audio/inside.m4a -f s16le
 
 FATE_TESTS += fate-lossless-meridianaudio
-fate-lossless-meridianaudio: CMD = md5  -i $(SAMPLES)/lossless-audio/luckynight-partial.mlp -f s16le
+fate-lossless-meridianaudio: CMD = md5 -i $(SAMPLES)/lossless-audio/luckynight-partial.mlp -f s16le
 
 FATE_TESTS += fate-lossless-monkeysaudio
-fate-lossless-monkeysaudio: CMD = md5  -i $(SAMPLES)/lossless-audio/luckynight-partial.ape -f s16le
+fate-lossless-monkeysaudio: CMD = md5 -i $(SAMPLES)/lossless-audio/luckynight-partial.ape -f s16le
 
 FATE_TESTS += fate-lossless-shortenaudio
-fate-lossless-shortenaudio: CMD = md5  -i $(SAMPLES)/lossless-audio/luckynight-partial.shn -f s16le
+fate-lossless-shortenaudio: CMD = md5 -i $(SAMPLES)/lossless-audio/luckynight-partial.shn -f s16le
 
 FATE_TESTS += fate-lossless-tta
-fate-lossless-tta: CMD = crc  -i $(SAMPLES)/lossless-audio/inside.tta
+fate-lossless-tta: CMD = crc -i $(SAMPLES)/lossless-audio/inside.tta
 
 FATE_TESTS += fate-lossless-wavpackaudio
-fate-lossless-wavpackaudio: CMD = md5  -i $(SAMPLES)/lossless-audio/luckynight-partial.wv -f s16le
+fate-lossless-wavpackaudio: CMD = md5 -i $(SAMPLES)/lossless-audio/luckynight-partial.wv -f s16le
diff --git a/tests/fate/lossless-video.mak b/tests/fate/lossless-video.mak
index 0d1e2b8..0c2b669 100644
--- a/tests/fate/lossless-video.mak
+++ b/tests/fate/lossless-video.mak
@@ -1,17 +1,17 @@
 FATE_TESTS += fate-loco-rgb
-fate-loco-rgb: CMD = framecrc  -i $(SAMPLES)/loco/pig-loco-rgb.avi
+fate-loco-rgb: CMD = framecrc -i $(SAMPLES)/loco/pig-loco-rgb.avi
 
 FATE_TESTS += fate-loco-yuy2
-fate-loco-yuy2: CMD = framecrc  -i $(SAMPLES)/loco/pig-loco-0.avi
+fate-loco-yuy2: CMD = framecrc -i $(SAMPLES)/loco/pig-loco-0.avi
 
 FATE_TESTS += fate-msrle-8bit
-fate-msrle-8bit: CMD = framecrc  -i $(SAMPLES)/msrle/Search-RLE.avi -pix_fmt rgb24
+fate-msrle-8bit: CMD = framecrc -i $(SAMPLES)/msrle/Search-RLE.avi -pix_fmt rgb24
 
 FATE_TESTS += fate-mszh
-fate-mszh: CMD = framecrc  -i $(SAMPLES)/lcl/mszh-1frame.avi
+fate-mszh: CMD = framecrc -i $(SAMPLES)/lcl/mszh-1frame.avi
 
 FATE_TESTS += fate-vble
 fate-vble: CMD = framecrc -i $(SAMPLES)/vble/flowers-partial-2MB.avi
 
 FATE_TESTS += fate-zlib
-fate-zlib: CMD = framecrc  -i $(SAMPLES)/lcl/zlib-1frame.avi
+fate-zlib: CMD = framecrc -i $(SAMPLES)/lcl/zlib-1frame.avi
diff --git a/tests/fate/microsoft.mak b/tests/fate/microsoft.mak
index bb7e701..b36f854 100644
--- a/tests/fate/microsoft.mak
+++ b/tests/fate/microsoft.mak
@@ -25,3 +25,6 @@ fate-vc1_sa10091: CMD = framecrc -i $(SAMPLES)/vc1/SA10091.vc1
 
 FATE_TESTS += fate-vc1_sa20021
 fate-vc1_sa20021: CMD = framecrc -i $(SAMPLES)/vc1/SA20021.vc1
+
+FATE_TESTS += fate-vc1-ism
+fate-vc1-ism: CMD = framecrc -i $(SAMPLES)/isom/vc1-wmapro.ism -an
diff --git a/tests/fate/mpc.mak b/tests/fate/mpc.mak
index d7f8c47..a5f1b30 100644
--- a/tests/fate/mpc.mak
+++ b/tests/fate/mpc.mak
@@ -1,8 +1,8 @@
 FATE_TESTS += fate-mpc7-demux
-fate-mpc7-demux: CMD = crc  -i $(SAMPLES)/musepack/inside-mp7.mpc -acodec copy
+fate-mpc7-demux: CMD = crc -i $(SAMPLES)/musepack/inside-mp7.mpc -acodec copy
 
 FATE_TESTS += fate-mpc8-demux
-fate-mpc8-demux: CMD = crc  -i $(SAMPLES)/musepack/inside-mp8.mpc -acodec copy
+fate-mpc8-demux: CMD = crc -i $(SAMPLES)/musepack/inside-mp8.mpc -acodec copy
 
 FATE_TESTS += fate-musepack7
 fate-musepack7: CMD = pcm -i $(SAMPLES)/musepack/inside-mp7.mpc
diff --git a/tests/fate/pcm.mak b/tests/fate/pcm.mak
index f8ee34a..2c4b8e4 100644
--- a/tests/fate/pcm.mak
+++ b/tests/fate/pcm.mak
@@ -1,8 +1,8 @@
 FATE_TESTS += fate-duck-dk3
-fate-duck-dk3: CMD = md5  -i $(SAMPLES)/duck/sop-audio-only.avi -f s16le
+fate-duck-dk3: CMD = md5 -i $(SAMPLES)/duck/sop-audio-only.avi -f s16le
 
 FATE_TESTS += fate-duck-dk4
-fate-duck-dk4: CMD = md5  -i $(SAMPLES)/duck/salsa-audio-only.avi -f s16le
+fate-duck-dk4: CMD = md5 -i $(SAMPLES)/duck/salsa-audio-only.avi -f s16le
 
 FATE_TESTS += fate-ea-mad-pcm-planar
 fate-ea-mad-pcm-planar: CMD = framecrc -i $(SAMPLES)/ea-mad/xeasport.mad
diff --git a/tests/fate/qt.mak b/tests/fate/qt.mak
new file mode 100644
index 0000000..9b25306
--- /dev/null
+++ b/tests/fate/qt.mak
@@ -0,0 +1,50 @@
+FATE_TESTS += fate-8bps
+fate-8bps: CMD = framecrc -i $(SAMPLES)/8bps/full9iron-partial.mov -pix_fmt rgb24
+
+FATE_TESTS += fate-qdm2
+fate-qdm2: CMD = pcm -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-QDM2.mov
+fate-qdm2: CMP = oneoff
+fate-qdm2: REF = $(SAMPLES)/qt-surge-suite/surge-2-16-B-QDM2.pcm
+fate-qdm2: FUZZ = 2
+
+FATE_TESTS += fate-qt-alaw-mono
+fate-qt-alaw-mono: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-alaw.mov -f s16le
+
+FATE_TESTS += fate-qt-alaw-stereo
+fate-qt-alaw-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-alaw.mov -f s16le
+
+FATE_TESTS += fate-qt-ima4-mono
+fate-qt-ima4-mono: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-ima4.mov -f s16le
+
+FATE_TESTS += fate-qt-ima4-stereo
+fate-qt-ima4-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-ima4.mov -f s16le
+
+FATE_TESTS += fate-qt-mac3-mono
+fate-qt-mac3-mono: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-1-8-MAC3.mov -f s16le
+
+FATE_TESTS += fate-qt-mac3-stereo
+fate-qt-mac3-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-8-MAC3.mov -f s16le
+
+FATE_TESTS += fate-qt-mac6-mono
+fate-qt-mac6-mono: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-1-8-MAC6.mov -f s16le
+
+FATE_TESTS += fate-qt-mac6-stereo
+fate-qt-mac6-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-8-MAC6.mov -f s16le
+
+FATE_TESTS += fate-qt-ulaw-mono
+fate-qt-ulaw-mono: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-1-16-B-ulaw.mov -f s16le
+
+FATE_TESTS += fate-qt-ulaw-stereo
+fate-qt-ulaw-stereo: CMD = md5 -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-ulaw.mov -f s16le
+
+FATE_TESTS += fate-quickdraw
+fate-quickdraw: CMD = framecrc -i $(SAMPLES)/quickdraw/Airplane.mov -pix_fmt rgb24
+
+FATE_TESTS += fate-rpza
+fate-rpza: CMD = framecrc -i $(SAMPLES)/rpza/rpza2.mov -t 2 -pix_fmt rgb24
+
+FATE_TESTS += fate-svq1
+fate-svq1: CMD = framecrc -i $(SAMPLES)/svq1/marymary-shackles.mov -an -t 10
+
+FATE_TESTS += fate-svq3
+fate-svq3: CMD = framecrc -i $(SAMPLES)/svq3/Vertical400kbit.sorenson3.mov -t 6 -an
diff --git a/tests/fate/qtrle.mak b/tests/fate/qtrle.mak
index 4856fe7..1fd393b 100644
--- a/tests/fate/qtrle.mak
+++ b/tests/fate/qtrle.mak
@@ -1,20 +1,20 @@
 FATE_TESTS += fate-qtrle-1bit
-fate-qtrle-1bit: CMD = framecrc  -i $(SAMPLES)/qtrle/Animation-Monochrome.mov
+fate-qtrle-1bit: CMD = framecrc -i $(SAMPLES)/qtrle/Animation-Monochrome.mov
 
 FATE_TESTS += fate-qtrle-2bit
-fate-qtrle-2bit: CMD = framecrc  -i $(SAMPLES)/qtrle/Animation-4Greys.mov -pix_fmt rgb24
+fate-qtrle-2bit: CMD = framecrc -i $(SAMPLES)/qtrle/Animation-4Greys.mov -pix_fmt rgb24
 
 FATE_TESTS += fate-qtrle-4bit
-fate-qtrle-4bit: CMD = framecrc  -i $(SAMPLES)/qtrle/Animation-16Greys.mov -pix_fmt rgb24 -an
+fate-qtrle-4bit: CMD = framecrc -i $(SAMPLES)/qtrle/Animation-16Greys.mov -pix_fmt rgb24 -an
 
 FATE_TESTS += fate-qtrle-8bit
-fate-qtrle-8bit: CMD = framecrc  -i $(SAMPLES)/qtrle/criticalpath-credits.mov -vsync 0 -pix_fmt rgb24 -an
+fate-qtrle-8bit: CMD = framecrc -i $(SAMPLES)/qtrle/criticalpath-credits.mov -vsync 0 -pix_fmt rgb24 -an
 
 FATE_TESTS += fate-qtrle-16bit
-fate-qtrle-16bit: CMD = framecrc  -i $(SAMPLES)/qtrle/mr-cork-rle.mov -pix_fmt rgb24
+fate-qtrle-16bit: CMD = framecrc -i $(SAMPLES)/qtrle/mr-cork-rle.mov -pix_fmt rgb24
 
 FATE_TESTS += fate-qtrle-24bit
-fate-qtrle-24bit: CMD = framecrc  -i $(SAMPLES)/qtrle/aletrek-rle.mov -vsync 0
+fate-qtrle-24bit: CMD = framecrc -i $(SAMPLES)/qtrle/aletrek-rle.mov -vsync 0
 
 FATE_TESTS += fate-qtrle-32bit
-fate-qtrle-32bit: CMD = framecrc  -i $(SAMPLES)/qtrle/ultra_demo_720_480_32bpp_rle.mov -pix_fmt rgb24
+fate-qtrle-32bit: CMD = framecrc -i $(SAMPLES)/qtrle/ultra_demo_720_480_32bpp_rle.mov -pix_fmt rgb24
diff --git a/tests/fate/real.mak b/tests/fate/real.mak
index b1ff507..4b88bbd 100644
--- a/tests/fate/real.mak
+++ b/tests/fate/real.mak
@@ -1,5 +1,5 @@
 FATE_TESTS += fate-real-14_4
-fate-real-14_4: CMD = md5  -i $(SAMPLES)/real/ra3_in_rm_file.rm -f s16le
+fate-real-14_4: CMD = md5 -i $(SAMPLES)/real/ra3_in_rm_file.rm -f s16le
 
 FATE_TESTS += fate-ra-288
 fate-ra-288: CMD = pcm -i $(SAMPLES)/real/ra_288.rm
@@ -16,7 +16,7 @@ FATE_TESTS += fate-rv30
 fate-rv30: CMD = framecrc -flags +bitexact -dct fastint -idct simple -i $(SAMPLES)/real/rv30.rm -an
 
 FATE_TESTS += fate-real-rv40
-fate-real-rv40: CMD = framecrc  -i $(SAMPLES)/real/spygames-2MB.rmvb -t 10 -an -vsync 0
+fate-real-rv40: CMD = framecrc -i $(SAMPLES)/real/spygames-2MB.rmvb -t 10 -an -vsync 0
 
 FATE_TESTS += fate-sipr-5k0
 fate-sipr-5k0: CMD = pcm -i $(SAMPLES)/sipr/sipr_5k0.rm
diff --git a/tests/fate/screen.mak b/tests/fate/screen.mak
index a296b00..7df7f3e 100644
--- a/tests/fate/screen.mak
+++ b/tests/fate/screen.mak
@@ -1,44 +1,47 @@
 FATE_TESTS += fate-cscd
-fate-cscd: CMD = framecrc  -i $(SAMPLES)/CSCD/sample_video.avi -an -vsync 0 -pix_fmt rgb24
+fate-cscd: CMD = framecrc -i $(SAMPLES)/CSCD/sample_video.avi -an -vsync 0 -pix_fmt rgb24
+
+FATE_TESTS += fate-dxtory
+fate-dxtory: CMD = framecrc -i $(SAMPLES)/dxtory/dxtory_mic.avi
 
 FATE_TESTS += fate-fraps-v0
-fate-fraps-v0: CMD = framecrc  -i $(SAMPLES)/fraps/Griffin_Ragdoll01-partial.avi
+fate-fraps-v0: CMD = framecrc -i $(SAMPLES)/fraps/Griffin_Ragdoll01-partial.avi
 
 FATE_TESTS += fate-fraps-v1
-fate-fraps-v1: CMD = framecrc  -i $(SAMPLES)/fraps/sample-v1.avi -an
+fate-fraps-v1: CMD = framecrc -i $(SAMPLES)/fraps/sample-v1.avi -an
 
 FATE_TESTS += fate-fraps-v2
-fate-fraps-v2: CMD = framecrc  -i $(SAMPLES)/fraps/test3-nosound-partial.avi
+fate-fraps-v2: CMD = framecrc -i $(SAMPLES)/fraps/test3-nosound-partial.avi
 
 FATE_TESTS += fate-fraps-v3
-fate-fraps-v3: CMD = framecrc  -i $(SAMPLES)/fraps/psclient-partial.avi -pix_fmt rgb24
+fate-fraps-v3: CMD = framecrc -i $(SAMPLES)/fraps/psclient-partial.avi -pix_fmt rgb24
 
 FATE_TESTS += fate-fraps-v4
-fate-fraps-v4: CMD = framecrc  -i $(SAMPLES)/fraps/WoW_2006-11-03_14-58-17-19-nosound-partial.avi
+fate-fraps-v4: CMD = framecrc -i $(SAMPLES)/fraps/WoW_2006-11-03_14-58-17-19-nosound-partial.avi
 
 FATE_TESTS += fate-fraps-v5
-fate-fraps-v5: CMD = framecrc  -i $(SAMPLES)/fraps/fraps-v5-bouncing-balls-partial.avi
+fate-fraps-v5: CMD = framecrc -i $(SAMPLES)/fraps/fraps-v5-bouncing-balls-partial.avi
 
 FATE_TESTS += fate-tscc-15bit
-fate-tscc-15bit: CMD = framecrc  -i $(SAMPLES)/tscc/oneminute.avi -t 15 -pix_fmt rgb24
+fate-tscc-15bit: CMD = framecrc -i $(SAMPLES)/tscc/oneminute.avi -t 15 -pix_fmt rgb24
 
 FATE_TESTS += fate-tscc-32bit
-fate-tscc-32bit: CMD = framecrc  -i $(SAMPLES)/tscc/2004-12-17-uebung9-partial.avi -pix_fmt rgb24 -an
+fate-tscc-32bit: CMD = framecrc -i $(SAMPLES)/tscc/2004-12-17-uebung9-partial.avi -pix_fmt rgb24 -an
 
 FATE_TESTS += fate-vmnc-16bit
-fate-vmnc-16bit: CMD = framecrc  -i $(SAMPLES)/VMnc/test.avi -pix_fmt rgb24
+fate-vmnc-16bit: CMD = framecrc -i $(SAMPLES)/VMnc/test.avi -pix_fmt rgb24
 
 FATE_TESTS += fate-vmnc-32bit
-fate-vmnc-32bit: CMD = framecrc  -i $(SAMPLES)/VMnc/VS2k5DebugDemo-01-partial.avi -pix_fmt rgb24
+fate-vmnc-32bit: CMD = framecrc -i $(SAMPLES)/VMnc/VS2k5DebugDemo-01-partial.avi -pix_fmt rgb24
 
 FATE_TESTS += fate-zmbv-8bit
-fate-zmbv-8bit: CMD = framecrc  -i $(SAMPLES)/zmbv/wc2_001-partial.avi -an -pix_fmt rgb24
+fate-zmbv-8bit: CMD = framecrc -i $(SAMPLES)/zmbv/wc2_001-partial.avi -an -pix_fmt rgb24
 
 FATE_TESTS += fate-zmbv-15bit
-fate-zmbv-15bit: CMD = framecrc  -i $(SAMPLES)/zmbv/zmbv_15bit.avi -pix_fmt rgb24 -t 25
+fate-zmbv-15bit: CMD = framecrc -i $(SAMPLES)/zmbv/zmbv_15bit.avi -pix_fmt rgb24 -t 25
 
 FATE_TESTS += fate-zmbv-16bit
-fate-zmbv-16bit: CMD = framecrc  -i $(SAMPLES)/zmbv/zmbv_16bit.avi -pix_fmt rgb24 -t 25
+fate-zmbv-16bit: CMD = framecrc -i $(SAMPLES)/zmbv/zmbv_16bit.avi -pix_fmt rgb24 -t 25
 
 FATE_TESTS += fate-zmbv-32bit
-fate-zmbv-32bit: CMD = framecrc  -i $(SAMPLES)/zmbv/zmbv_32bit.avi -pix_fmt rgb24 -t 25
+fate-zmbv-32bit: CMD = framecrc -i $(SAMPLES)/zmbv/zmbv_32bit.avi -pix_fmt rgb24 -t 25
diff --git a/tests/fate/video.mak b/tests/fate/video.mak
new file mode 100644
index 0000000..6d23134
--- /dev/null
+++ b/tests/fate/video.mak
@@ -0,0 +1,192 @@
+FATE_TESTS += fate-4xm-1
+fate-4xm-1: CMD = framecrc -i $(SAMPLES)/4xm/version1.4xm -pix_fmt rgb24 -an
+
+FATE_TESTS += fate-4xm-2
+fate-4xm-2: CMD = framecrc -i $(SAMPLES)/4xm/version2.4xm -pix_fmt rgb24 -an
+
+FATE_TESTS += fate-aasc
+fate-aasc: CMD = framecrc -i $(SAMPLES)/aasc/AASC-1.5MB.AVI -pix_fmt rgb24
+
+FATE_TESTS += fate-alg-mm
+fate-alg-mm: CMD = framecrc -i $(SAMPLES)/alg-mm/ibmlogo.mm -an -pix_fmt rgb24
+
+FATE_TESTS += fate-amv
+fate-amv: CMD = framecrc -idct simple -i $(SAMPLES)/amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv -t 10
+
+FATE_TESTS += fate-ansi
+fate-ansi: CMD = framecrc -chars_per_frame 44100 -i $(SAMPLES)/ansi/TRE-IOM5.ANS -pix_fmt rgb24
+
+FATE_TESTS += fate-armovie-escape124
+fate-armovie-escape124: CMD = framecrc -i $(SAMPLES)/rpl/ESCAPE.RPL -pix_fmt rgb24
+
+FATE_TESTS += fate-auravision
+fate-auravision: CMD = framecrc -i $(SAMPLES)/auravision/SOUVIDEO.AVI -an
+
+FATE_TESTS += fate-auravision-v2
+fate-auravision-v2: CMD = framecrc -i $(SAMPLES)/auravision/salma-hayek-in-ugly-betty-partial-avi -an
+
+FATE_TESTS += fate-bethsoft-vid
+fate-bethsoft-vid: CMD = framecrc -i $(SAMPLES)/bethsoft-vid/ANIM0001.VID -vsync 0 -t 5 -pix_fmt rgb24
+
+FATE_TESTS += fate-bfi
+fate-bfi: CMD = framecrc -i $(SAMPLES)/bfi/2287.bfi -pix_fmt rgb24
+
+FATE_TESTS += fate-cdgraphics
+fate-cdgraphics: CMD = framecrc -i $(SAMPLES)/cdgraphics/BrotherJohn.cdg -pix_fmt rgb24 -t 1
+
+FATE_TESTS += fate-cljr
+fate-cljr: CMD = framecrc -i $(SAMPLES)/cljr/testcljr-partial.avi
+
+FATE_TESTS += fate-corepng
+fate-corepng: CMD = framecrc -i $(SAMPLES)/png1/corepng-partial.avi
+
+FATE_TESTS += fate-creatureshock-avs
+fate-creatureshock-avs: CMD = framecrc -i $(SAMPLES)/creatureshock-avs/OUTATIME.AVS -pix_fmt rgb24
+
+FATE_TESTS += fate-cvid
+fate-cvid: CMD = framecrc -i $(SAMPLES)/cvid/laracroft-cinepak-partial.avi -an
+
+FATE_TESTS += fate-cvid-palette
+fate-cvid-palette: CMD = framecrc -i $(SAMPLES)/cvid/catfight-cvid-pal8-partial.mov -pix_fmt rgb24 -an
+
+FATE_TESTS += fate-cvid-grayscale
+fate-cvid-grayscale: CMD = framecrc -i $(SAMPLES)/cvid/pcitva15.avi -an
+
+FATE_TESTS += fate-cyberia-c93
+fate-cyberia-c93: CMD = framecrc -i $(SAMPLES)/cyberia-c93/intro1.c93 -t 3 -pix_fmt rgb24
+
+FATE_TESTS += fate-cyuv
+fate-cyuv: CMD = framecrc -i $(SAMPLES)/cyuv/cyuv.avi
+
+FATE_TESTS += fate-delphine-cin
+fate-delphine-cin: CMD = framecrc -i $(SAMPLES)/delphine-cin/LOGO-partial.CIN -pix_fmt rgb24 -vsync 0
+
+FATE_TESTS += fate-deluxepaint-anm
+fate-deluxepaint-anm: CMD = framecrc -i $(SAMPLES)/deluxepaint-anm/INTRO1.ANM -pix_fmt rgb24
+
+FATE_TESTS += fate-duck-tm2
+fate-duck-tm2: CMD = framecrc -i $(SAMPLES)/duck/tm20.avi
+
+FATE_TESTS += fate-dxa-scummvm
+fate-dxa-scummvm: CMD = framecrc -i $(SAMPLES)/dxa/scummvm.dxa -pix_fmt rgb24
+
+FATE_TESTS += fate-feeble-dxa
+fate-feeble-dxa: CMD = framecrc -i $(SAMPLES)/dxa/meetsquid.dxa -t 2 -pix_fmt rgb24
+
+FATE_TESTS += fate-flic-af11-palette-change
+fate-flic-af11-palette-change: CMD = framecrc -i $(SAMPLES)/fli/fli-engines.fli -t 3.3 -pix_fmt rgb24
+
+FATE_TESTS += fate-flic-af12
+fate-flic-af12: CMD = framecrc -i $(SAMPLES)/fli/jj00c2.fli -pix_fmt rgb24
+
+FATE_TESTS += fate-flic-magiccarpet
+fate-flic-magiccarpet: CMD = framecrc -i $(SAMPLES)/fli/intel.dat -pix_fmt rgb24
+
+FATE_TESTS += fate-frwu
+fate-frwu: CMD = framecrc -i $(SAMPLES)/frwu/frwu.avi
+
+FATE_TESTS += fate-id-cin-video
+fate-id-cin-video: CMD = framecrc -i $(SAMPLES)/idcin/idlog-2MB.cin -pix_fmt rgb24
+
+FATE_TESTS-$(CONFIG_AVFILTER) += fate-idroq-video-encode
+fate-idroq-video-encode: CMD = md5 -f image2 -vcodec pgmyuv -i $(SAMPLES)/ffmpeg-synthetic/vsynth1/%02d.pgm -sws_flags +bitexact -vf pad=512:512:80:112 -f RoQ -t 0.2
+
+FATE_TESTS += fate-iff-byterun1
+fate-iff-byterun1: CMD = framecrc -i $(SAMPLES)/iff/ASH.LBM -pix_fmt rgb24
+
+FATE_TESTS += fate-iff-fibonacci
+fate-iff-fibonacci: CMD = md5 -i $(SAMPLES)/iff/dasboot-in-compressed -f s16le
+
+FATE_TESTS += fate-iff-ilbm
+fate-iff-ilbm: CMD = framecrc -i $(SAMPLES)/iff/lms-matriks.ilbm -pix_fmt rgb24
+
+FATE_TESTS += fate-kmvc
+fate-kmvc: CMD = framecrc -i $(SAMPLES)/KMVC/LOGO1.AVI -an -t 3 -pix_fmt rgb24
+
+FATE_TESTS += fate-mimic
+fate-mimic: CMD = framecrc -idct simple -i $(SAMPLES)/mimic/mimic2-womanloveffmpeg.cam -vsync 0
+
+FATE_TESTS += fate-mjpegb
+fate-mjpegb: CMD = framecrc -idct simple -flags +bitexact -i $(SAMPLES)/mjpegb/mjpegb_part.mov -an
+
+FATE_TESTS += fate-motionpixels
+fate-motionpixels: CMD = framecrc -i $(SAMPLES)/motion-pixels/INTRO-partial.MVI -an -pix_fmt rgb24 -vframes 111
+
+FATE_TESTS += fate-mpeg2-field-enc
+fate-mpeg2-field-enc: CMD = framecrc -flags +bitexact -dct fastint -idct simple -i $(SAMPLES)/mpeg2/mpeg2_field_encoding.ts -an
+
+FATE_TESTS += fate-nuv
+fate-nuv: CMD = framecrc -idct simple -i $(SAMPLES)/nuv/Today.nuv -vsync 0
+
+FATE_TESTS += fate-qpeg
+fate-qpeg: CMD = framecrc -i $(SAMPLES)/qpeg/Clock.avi -an -pix_fmt rgb24
+
+FATE_TESTS += fate-r210
+fate-r210: CMD = framecrc -i $(SAMPLES)/r210/r210.avi -pix_fmt rgb48le
+
+FATE_TESTS += fate-rl2
+fate-rl2: CMD = framecrc -i $(SAMPLES)/rl2/Z4915300.RL2 -pix_fmt rgb24 -an -vsync 0
+
+FATE_TESTS += fate-smacker
+fate-smacker: CMD = framecrc -i $(SAMPLES)/smacker/wetlogo.smk -pix_fmt rgb24
+
+FATE_TESTS += fate-smc
+fate-smc: CMD = framecrc -i $(SAMPLES)/smc/cass_schi.qt -vsync 0 -pix_fmt rgb24
+
+FATE_TESTS += fate-sp5x
+fate-sp5x: CMD = framecrc -idct simple -i $(SAMPLES)/sp5x/sp5x_problem.avi
+
+FATE_TESTS += fate-sub-srt
+fate-sub-srt: CMD = md5 -i $(SAMPLES)/sub/SubRip_capability_tester.srt -f ass
+
+FATE_TESTS += fate-tiertex-seq
+fate-tiertex-seq: CMD = framecrc -i $(SAMPLES)/tiertex-seq/Gameover.seq -pix_fmt rgb24
+
+FATE_TESTS += fate-tmv
+fate-tmv: CMD = framecrc -i $(SAMPLES)/tmv/pop-partial.tmv -pix_fmt rgb24
+
+FATE_TESTS += fate-truemotion1-15
+fate-truemotion1-15: CMD = framecrc -i $(SAMPLES)/duck/phant2-940.duk -pix_fmt rgb24
+
+FATE_TESTS += fate-truemotion1-24
+fate-truemotion1-24: CMD = framecrc -i $(SAMPLES)/duck/sonic3dblast_intro-partial.avi -pix_fmt rgb24
+
+FATE_TESTS += fate-txd-16bpp
+fate-txd-16bpp: CMD = framecrc -i $(SAMPLES)/txd/misc.txd -pix_fmt bgra -an
+
+FATE_TESTS += fate-txd-pal8
+fate-txd-pal8: CMD = framecrc -i $(SAMPLES)/txd/outro.txd -pix_fmt rgb24 -an
+
+FATE_TESTS += fate-ulti
+fate-ulti: CMD = framecrc -i $(SAMPLES)/ulti/hit12w.avi -an
+
+FATE_TESTS += fate-v210
+fate-v210: CMD = framecrc -i $(SAMPLES)/v210/v210_720p-partial.avi -pix_fmt yuv422p16be -an
+
+FATE_TESTS += fate-v410dec
+fate-v410dec: CMD = framecrc -i $(SAMPLES)/v410/lenav410.mov -pix_fmt yuv444p10le
+
+FATE_TESTS += fate-v410enc
+fate-v410enc: tests/vsynth1/00.pgm
+fate-v410enc: CMD = md5 -f image2 -vcodec pgmyuv -i $(TARGET_PATH)/tests/vsynth1/%02d.pgm -flags +bitexact -vcodec v410 -f avi
+
+FATE_TESTS += fate-vcr1
+fate-vcr1: CMD = framecrc -i $(SAMPLES)/vcr1/VCR1test.avi -an
+
+FATE_TESTS += fate-video-xl
+fate-video-xl: CMD = framecrc -i $(SAMPLES)/vixl/pig-vixl.avi
+
+FATE_TESTS += fate-vqa-cc
+fate-vqa-cc: CMD = framecrc -i $(SAMPLES)/vqa/cc-demo1-partial.vqa -pix_fmt rgb24
+
+FATE_TESTS += fate-wc3movie-xan
+fate-wc3movie-xan: CMD = framecrc -i $(SAMPLES)/wc3movie/SC_32-part.MVE -pix_fmt rgb24
+
+FATE_TESTS += fate-wnv1
+fate-wnv1: CMD = framecrc -i $(SAMPLES)/wnv1/wnv1-codec.avi -an
+
+FATE_TESTS += fate-yop
+fate-yop: CMD = framecrc -i $(SAMPLES)/yop/test1.yop -pix_fmt rgb24 -an
+
+FATE_TESTS += fate-xxan-wc4
+fate-xxan-wc4: CMD = framecrc -i $(SAMPLES)/wc4-xan/wc4trailer-partial.avi -an
diff --git a/tests/fate/voice.mak b/tests/fate/voice.mak
new file mode 100644
index 0000000..51cc2ae
--- /dev/null
+++ b/tests/fate/voice.mak
@@ -0,0 +1,22 @@
+FATE_TESTS += fate-g722dec-1
+fate-g722dec-1: CMD = framecrc -i $(SAMPLES)/g722/conf-adminmenu-162.g722
+
+FATE_TESTS += fate-g722enc
+fate-g722enc: tests/data/asynth-16000-1.sw
+fate-g722enc: CMD = md5 -ar 16000 -ac 1 -f s16le -i $(TARGET_PATH)/tests/data/asynth-16000-1.sw -acodec g722 -ac 1 -f g722
+
+FATE_TESTS += fate-gsm
+fate-gsm: CMD = framecrc -i $(SAMPLES)/gsm/sample-gsm-8000.mov -t 10
+
+FATE_TESTS += fate-gsm-ms
+fate-gsm-ms: CMD = framecrc -i $(SAMPLES)/gsm/ciao.wav
+
+FATE_TESTS += fate-qcelp
+fate-qcelp: CMD = pcm -i $(SAMPLES)/qcp/0036580847.QCP
+fate-qcelp: CMP = oneoff
+fate-qcelp: REF = $(SAMPLES)/qcp/0036580847.pcm
+
+FATE_TESTS += fate-truespeech
+fate-truespeech: CMD = pcm -i $(SAMPLES)/truespeech/a6.wav
+fate-truespeech: CMP = oneoff
+fate-truespeech: REF = $(SAMPLES)/truespeech/a6.pcm
diff --git a/tests/fate/vpx.mak b/tests/fate/vpx.mak
index 66e9ced..2d1c8fd 100644
--- a/tests/fate/vpx.mak
+++ b/tests/fate/vpx.mak
@@ -1,20 +1,23 @@
 FATE_TESTS += fate-ea-vp60
-fate-ea-vp60: CMD = framecrc  -i $(SAMPLES)/ea-vp6/g36.vp6
+fate-ea-vp60: CMD = framecrc -i $(SAMPLES)/ea-vp6/g36.vp6
 
 FATE_TESTS += fate-ea-vp61
-fate-ea-vp61: CMD = framecrc  -i $(SAMPLES)/ea-vp6/MovieSkirmishGondor.vp6 -t 4
+fate-ea-vp61: CMD = framecrc -i $(SAMPLES)/ea-vp6/MovieSkirmishGondor.vp6 -t 4
 
 FATE_TESTS += fate-vp3
 fate-vp3: CMD = framecrc -i $(SAMPLES)/vp3/vp31.avi
 
+FATE_TESTS += fate-vp3-coeff-level64
+fate-vp3-coeff-level64: CMD = framecrc -i $(SAMPLES)/vp3/coeff_level64.mkv
+
 FATE_TESTS += fate-vp5
-fate-vp5: CMD = framecrc  -i $(SAMPLES)/vp5/potter512-400-partial.avi -an
+fate-vp5: CMD = framecrc -i $(SAMPLES)/vp5/potter512-400-partial.avi -an
 
 FATE_TESTS += fate-vp6a
-fate-vp6a: CMD = framecrc  -i $(SAMPLES)/flash-vp6/300x180-Scr-f8-056alpha.flv
+fate-vp6a: CMD = framecrc -i $(SAMPLES)/flash-vp6/300x180-Scr-f8-056alpha.flv
 
 FATE_TESTS += fate-vp6f
-fate-vp6f: CMD = framecrc  -i $(SAMPLES)/flash-vp6/clip1024.flv
+fate-vp6f: CMD = framecrc -i $(SAMPLES)/flash-vp6/clip1024.flv
 
 VP8_SUITE = 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017
 
diff --git a/tests/fate/vqf.mak b/tests/fate/vqf.mak
index 6860fad..846b140 100644
--- a/tests/fate/vqf.mak
+++ b/tests/fate/vqf.mak
@@ -4,4 +4,4 @@ fate-twinvq: CMP = oneoff
 fate-twinvq: REF = $(SAMPLES)/vqf/achterba.pcm
 
 FATE_TESTS += fate-vqf-demux
-fate-vqf-demux: CMD = md5  -i $(SAMPLES)/vqf/achterba.vqf -acodec copy -f framecrc
+fate-vqf-demux: CMD = md5 -i $(SAMPLES)/vqf/achterba.vqf -acodec copy -f framecrc
diff --git a/tests/fate/wma.mak b/tests/fate/wma.mak
index 25626f3..e448d76 100644
--- a/tests/fate/wma.mak
+++ b/tests/fate/wma.mak
@@ -8,6 +8,11 @@ fate-wmapro-5.1: CMD = pcm -i $(SAMPLES)/wmapro/latin_192_mulitchannel_cut.wma
 fate-wmapro-5.1: CMP = oneoff
 fate-wmapro-5.1: REF = $(SAMPLES)/wmapro/latin_192_mulitchannel_cut.pcm
 
+FATE_TESTS += fate-wmapro-ism
+fate-wmapro-ism: CMD = pcm -i $(SAMPLES)/isom/vc1-wmapro.ism -vn
+fate-wmapro-ism: CMP = oneoff
+fate-wmapro-ism: REF = $(SAMPLES)/isom/vc1-wmapro.pcm
+
 FATE_TESTS += fate-wmavoice-7k
 fate-wmavoice-7k: CMD = pcm -i $(SAMPLES)/wmavoice/streaming_CBR-7K.wma
 fate-wmavoice-7k: CMP = stddev
diff --git a/tests/fate2.mak b/tests/fate2.mak
deleted file mode 100644
index 40cebfe..0000000
--- a/tests/fate2.mak
+++ /dev/null
@@ -1,92 +0,0 @@
-FATE_TESTS += fate-mpeg2-field-enc
-fate-mpeg2-field-enc: CMD = framecrc -flags +bitexact -dct fastint -idct simple -i $(SAMPLES)/mpeg2/mpeg2_field_encoding.ts -an
-
-FATE_TESTS += fate-qcelp
-fate-qcelp: CMD = pcm -i $(SAMPLES)/qcp/0036580847.QCP
-fate-qcelp: CMP = oneoff
-fate-qcelp: REF = $(SAMPLES)/qcp/0036580847.pcm
-
-FATE_TESTS += fate-qdm2
-fate-qdm2: CMD = pcm -i $(SAMPLES)/qt-surge-suite/surge-2-16-B-QDM2.mov
-fate-qdm2: CMP = oneoff
-fate-qdm2: REF = $(SAMPLES)/qt-surge-suite/surge-2-16-B-QDM2.pcm
-fate-qdm2: FUZZ = 2
-
-FATE_TESTS += fate-imc
-fate-imc: CMD = pcm -i $(SAMPLES)/imc/imc.avi
-fate-imc: CMP = oneoff
-fate-imc: REF = $(SAMPLES)/imc/imc.pcm
-
-FATE_TESTS += fate-yop
-fate-yop: CMD = framecrc -i $(SAMPLES)/yop/test1.yop -pix_fmt rgb24 -an
-
-FATE_TESTS += fate-dts
-fate-dts: CMD = pcm -i $(SAMPLES)/dts/dts.ts
-fate-dts: CMP = oneoff
-fate-dts: REF = $(SAMPLES)/dts/dts.pcm
-
-FATE_TESTS += fate-nellymoser
-fate-nellymoser: CMD = pcm -i $(SAMPLES)/nellymoser/nellymoser.flv
-fate-nellymoser: CMP = oneoff
-fate-nellymoser: REF = $(SAMPLES)/nellymoser/nellymoser.pcm
-
-FATE_TESTS += fate-truespeech
-fate-truespeech: CMD = pcm -i $(SAMPLES)/truespeech/a6.wav
-fate-truespeech: CMP = oneoff
-fate-truespeech: REF = $(SAMPLES)/truespeech/a6.pcm
-
-FATE_TESTS += fate-gsm
-fate-gsm: CMD = framecrc -i $(SAMPLES)/gsm/sample-gsm-8000.mov -t 10
-
-FATE_TESTS += fate-gsm-ms
-fate-gsm-ms: CMD = framecrc -i $(SAMPLES)/gsm/ciao.wav
-
-FATE_TESTS += fate-g722dec-1
-fate-g722dec-1: CMD = framecrc -i $(SAMPLES)/g722/conf-adminmenu-162.g722
-
-FATE_TESTS += fate-g722enc
-fate-g722enc: tests/data/asynth-16000-1.sw
-fate-g722enc: CMD = md5 -ar 16000 -ac 1 -f s16le -i $(TARGET_PATH)/tests/data/asynth-16000-1.sw -acodec g722 -ac 1 -f g722
-
-FATE_TESTS += fate-ansi
-fate-ansi: CMD = framecrc -chars_per_frame 44100 -i $(SAMPLES)/ansi/TRE-IOM5.ANS -pix_fmt rgb24
-
-FATE_TESTS += fate-binkaudio-dct
-fate-binkaudio-dct: CMD = pcm -i $(SAMPLES)/bink/binkaudio_dct.bik
-fate-binkaudio-dct: CMP = oneoff
-fate-binkaudio-dct: REF = $(SAMPLES)/bink/binkaudio_dct.pcm
-fate-binkaudio-dct: FUZZ = 2
-
-FATE_TESTS += fate-binkaudio-rdft
-fate-binkaudio-rdft: CMD = pcm -i $(SAMPLES)/bink/binkaudio_rdft.bik
-fate-binkaudio-rdft: CMP = oneoff
-fate-binkaudio-rdft: REF = $(SAMPLES)/bink/binkaudio_rdft.pcm
-fate-binkaudio-rdft: FUZZ = 2
-
-FATE_TESTS += fate-txd-pal8
-fate-txd-pal8: CMD = framecrc -i $(SAMPLES)/txd/outro.txd -pix_fmt rgb24 -an
-
-FATE_TESTS += fate-txd-16bpp
-fate-txd-16bpp: CMD = framecrc -i $(SAMPLES)/txd/misc.txd -pix_fmt bgra -an
-
-FATE_TESTS += fate-ws_snd
-fate-ws_snd: CMD = md5  -i $(SAMPLES)/vqa/ws_snd.vqa -f s16le
-
-FATE_TESTS += fate-dxa-scummvm
-fate-dxa-scummvm: CMD = framecrc -i $(SAMPLES)/dxa/scummvm.dxa -pix_fmt rgb24
-
-FATE_TESTS += fate-mjpegb
-fate-mjpegb: CMD = framecrc -idct simple -flags +bitexact -i $(SAMPLES)/mjpegb/mjpegb_part.mov -an
-
-FATE_TESTS += fate-v410dec
-fate-v410dec: CMD = framecrc -i $(SAMPLES)/v410/lenav410.mov -pix_fmt yuv444p10le
-
-FATE_TESTS += fate-v410enc
-fate-v410enc: tests/vsynth1/00.pgm
-fate-v410enc: CMD = md5 -f image2 -vcodec pgmyuv -i $(TARGET_PATH)/tests/vsynth1/%02d.pgm -flags +bitexact -vcodec v410 -f avi
-
-FATE_TESTS += fate-r210
-fate-r210: CMD = framecrc -i $(SAMPLES)/r210/r210.avi -pix_fmt rgb48le
-
-FATE_TESTS += fate-xxan-wc4
-fate-xxan-wc4: CMD = framecrc -i $(SAMPLES)/wc4-xan/wc4_2.avi -an -vframes 10
diff --git a/tests/ref/acodec/adpcm_adx b/tests/ref/acodec/adpcm_adx
new file mode 100644
index 0000000..8d86698
--- /dev/null
+++ b/tests/ref/acodec/adpcm_adx
@@ -0,0 +1,4 @@
+0a30509d9296b857e134b762b76dbc31 *./tests/data/acodec/adpcm_adx.adx
+297720 ./tests/data/acodec/adpcm_adx.adx
+2dbc601ed5259f4d74dc48ccd8da7eaf *./tests/data/adpcm_adx.acodec.out.wav
+stddev: 6989.46 PSNR: 19.44 MAXDIFF:65398 bytes:  1058432/  1058400
diff --git a/tests/ref/acodec/alac b/tests/ref/acodec/alac
index 15d1a1f..cef12d0 100644
--- a/tests/ref/acodec/alac
+++ b/tests/ref/acodec/alac
@@ -1,4 +1,4 @@
-8d9cb7f65c5b17c74e5f9bdc36f32b7d *./tests/data/acodec/alac.m4a
+db1806d9ffd85c168c2c71a28e6d9229 *./tests/data/acodec/alac.m4a
 389410 ./tests/data/acodec/alac.m4a
 64151e4bcc2b717aa5a8454d424d6a1f *./tests/data/alac.acodec.out.wav
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/g722 b/tests/ref/acodec/g722
index a1fc72a..6ea492a 100644
--- a/tests/ref/acodec/g722
+++ b/tests/ref/acodec/g722
@@ -1,4 +1,4 @@
-b380355e0360b4e50ee78f33fd60a0f5 *./tests/data/acodec/g722.wav
-47991 ./tests/data/acodec/g722.wav
-82fdd5bb059336e0550de7ba5947c5bb *./tests/data/g722.acodec.out.wav
-stddev: 8860.44 PSNR: 17.38 MAXDIFF:33814 bytes:   191732/  1058400
+1975cc4a3521e374b33ae042e182f6b6 *./tests/data/acodec/g722.wav
+48053 ./tests/data/acodec/g722.wav
+ade04cdcf249e6946395f109b077dd62 *./tests/data/g722.acodec.out.wav
+stddev: 8841.24 PSNR: 17.40 MAXDIFF:36225 bytes:   191980/  1058400
diff --git a/tests/ref/acodec/pcm_s16be b/tests/ref/acodec/pcm_s16be
index aea4c98..f766666 100644
--- a/tests/ref/acodec/pcm_s16be
+++ b/tests/ref/acodec/pcm_s16be
@@ -1,4 +1,4 @@
-dd832e23156643becce8e9d2c24cb31d *./tests/data/acodec/pcm_s16be.mov
+53c9eb319c778e7ce137667f62384994 *./tests/data/acodec/pcm_s16be.mov
 1060073 ./tests/data/acodec/pcm_s16be.mov
 64151e4bcc2b717aa5a8454d424d6a1f *./tests/data/pcm_s16be.acodec.out.wav
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm_s24be b/tests/ref/acodec/pcm_s24be
index 4407af3..b9fada7 100644
--- a/tests/ref/acodec/pcm_s24be
+++ b/tests/ref/acodec/pcm_s24be
@@ -1,4 +1,4 @@
-1b570c296bce03e36e1dfb369190ffb6 *./tests/data/acodec/pcm_s24be.mov
+af8acd2f08e4bbebe7f4bea4d6f59dd6 *./tests/data/acodec/pcm_s24be.mov
 1589273 ./tests/data/acodec/pcm_s24be.mov
 64151e4bcc2b717aa5a8454d424d6a1f *./tests/data/pcm_s24be.acodec.out.wav
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm_s32be b/tests/ref/acodec/pcm_s32be
index fc8fb5e..d6e5205 100644
--- a/tests/ref/acodec/pcm_s32be
+++ b/tests/ref/acodec/pcm_s32be
@@ -1,4 +1,4 @@
-249c2ca88e2d8cdaed345e3d446e5bc3 *./tests/data/acodec/pcm_s32be.mov
+63f0e22b4f7c5d61d75047d85f140d52 *./tests/data/acodec/pcm_s32be.mov
 2118473 ./tests/data/acodec/pcm_s32be.mov
 64151e4bcc2b717aa5a8454d424d6a1f *./tests/data/pcm_s32be.acodec.out.wav
 stddev:    0.00 PSNR:999.99 MAXDIFF:    0 bytes:  1058400/  1058400
diff --git a/tests/ref/acodec/pcm_s8 b/tests/ref/acodec/pcm_s8
index 01c2240..3b550d2 100644
--- a/tests/ref/acodec/pcm_s8
+++ b/tests/ref/acodec/pcm_s8
@@ -1,4 +1,4 @@
-f467f8899b2bd11c736d0f4e61efb1c4 *./tests/data/acodec/pcm_s8.mov
+4b3013a3f3c328ecdb617cd88b3fe836 *./tests/data/acodec/pcm_s8.mov
 530873 ./tests/data/acodec/pcm_s8.mov
 651d4eb8d98dfcdda96ae6c43d8f156b *./tests/data/pcm_s8.acodec.out.wav
 stddev:  147.89 PSNR: 52.93 MAXDIFF:  255 bytes:  1058400/  1058400
diff --git a/tests/ref/fate/bmv b/tests/ref/fate/bmv
new file mode 100644
index 0000000..4e46165
--- /dev/null
+++ b/tests/ref/fate/bmv
@@ -0,0 +1,42 @@
+0, 0, 823680, 0xddb8a306
+1, 0, 7424, 0x18540b36
+0, 7500, 823680, 0xa95375c8
+1, 7576, 7296, 0x5acd2484
+0, 15000, 823680, 0xa95375c8
+1, 15020, 7424, 0xa1bc5c5a
+0, 22500, 823680, 0xb6f78afe
+1, 22596, 7296, 0x71a02ad1
+0, 30000, 823680, 0xb6f78afe
+1, 30041, 7424, 0x09cc32f2
+0, 37500, 823680, 0x45b9c8f0
+1, 37616, 7296, 0xa3451726
+0, 45000, 823680, 0x45b9c8f0
+1, 45061, 7296, 0x1eb40a18
+0, 52500, 823680, 0x7653d8e9
+1, 52506, 7424, 0xc55a2acf
+0, 60000, 823680, 0x7653d8e9
+1, 60082, 7296, 0x5b9fad3f
+0, 67500, 823680, 0xf1e2fd73
+1, 67527, 7424, 0xea651ae7
+0, 75000, 823680, 0xf1e2fd73
+1, 75102, 7296, 0x2bd5ddb6
+0, 82500, 823680, 0x6d2deab3
+1, 82547, 7424, 0xde4243b4
+0, 90000, 823680, 0x6d2deab3
+1, 90122, 7296, 0x358806d3
+0, 97500, 823680, 0x37fd33ce
+1, 97567, 7296, 0x511a144e
+0, 105000, 823680, 0x37fd33ce
+1, 105012, 7424, 0x887a3e84
+0, 112500, 823680, 0x0a8e0ab9
+1, 112588, 7296, 0xfeae2a0c
+0, 120000, 823680, 0x0a8e0ab9
+1, 120033, 7424, 0xa4ea5d22
+0, 127500, 823680, 0x991bb2b0
+1, 127608, 7296, 0xb3adf7fa
+0, 135000, 823680, 0x991bb2b0
+1, 135053, 7424, 0xce995dcc
+0, 142500, 823680, 0xb8397c8c
+1, 142629, 7296, 0x5b4cf574
+0, 150000, 823680, 0xb8397c8c
+1, 150073, 7296, 0x8a70eaf0
diff --git a/tests/ref/fate/cvid-grayscale b/tests/ref/fate/cvid-grayscale
new file mode 100644
index 0000000..4e39571
--- /dev/null
+++ b/tests/ref/fate/cvid-grayscale
@@ -0,0 +1,152 @@
+0, 0, 11300, 0x46c78923
+0, 17921, 11300, 0x3f2a1175
+0, 35842, 11300, 0x722de221
+0, 53763, 11300, 0x01746b88
+0, 71684, 11300, 0x549587a7
+0, 89605, 11300, 0x843ab943
+0, 107526, 11300, 0x62fdee48
+0, 125447, 11300, 0x74a62867
+0, 143368, 11300, 0x35a20e2f
+0, 161289, 11300, 0x4e9ef54d
+0, 179210, 11300, 0xec7201f5
+0, 197131, 11300, 0x363bfe27
+0, 215052, 11300, 0x2aaab418
+0, 232973, 11300, 0x6a48ab3f
+0, 250894, 11300, 0x3fecea34
+0, 268815, 11300, 0xa371f55e
+0, 286736, 11300, 0xa86b147c
+0, 304657, 11300, 0x49e9206e
+0, 322578, 11300, 0x6c9a2155
+0, 340499, 11300, 0x2c8a4798
+0, 358420, 11300, 0x3485676c
+0, 376341, 11300, 0xb0b293f2
+0, 394262, 11300, 0xe4a9b068
+0, 412183, 11300, 0xd68d0556
+0, 430104, 11300, 0xc28e5193
+0, 448025, 11300, 0xf6948483
+0, 465945, 11300, 0xf21fbf57
+0, 483866, 11300, 0x8345eb44
+0, 501787, 11300, 0x8124f045
+0, 519708, 11300, 0x18e31f10
+0, 537629, 11300, 0xdb1943fc
+0, 555550, 11300, 0x8701699f
+0, 573471, 11300, 0xd7b18550
+0, 591392, 11300, 0xa56faccc
+0, 609313, 11300, 0xf8bcc17c
+0, 627234, 11300, 0x446acab9
+0, 645155, 11300, 0x755fd295
+0, 663076, 11300, 0x92e3d100
+0, 680997, 11300, 0x54895bb3
+0, 698918, 11300, 0xd18bffda
+0, 716839, 11300, 0x480dbe4f
+0, 734760, 11300, 0x49ea9dbe
+0, 752681, 11300, 0x00d3a003
+0, 770602, 11300, 0xda7bbfb2
+0, 788523, 11300, 0x9700d9c2
+0, 806444, 11300, 0xa0a9e490
+0, 824365, 11300, 0x00eb0979
+0, 842286, 11300, 0x32b04630
+0, 860207, 11300, 0xdfb73e51
+0, 878128, 11300, 0x3d8e4f96
+0, 896049, 11300, 0x2ca83271
+0, 913970, 11300, 0xb5b123c0
+0, 931891, 11300, 0x8a570e58
+0, 949812, 11300, 0xc6c805bc
+0, 967733, 11300, 0x27caf7a5
+0, 985654, 11300, 0x5319ecb0
+0, 1003575, 11300, 0x5471e3fd
+0, 1021496, 11300, 0x6d68a6f4
+0, 1039417, 11300, 0x872b7194
+0, 1057338, 11300, 0x007c36bd
+0, 1075259, 11300, 0x2714f1b5
+0, 1093180, 11300, 0x6c8eb50f
+0, 1111101, 11300, 0xf5d57be8
+0, 1129022, 11300, 0x981f412b
+0, 1146943, 11300, 0x1a9804a1
+0, 1164864, 11300, 0xf0c1d24a
+0, 1182785, 11300, 0xa70a9d9b
+0, 1200706, 11300, 0x8c466876
+0, 1218627, 11300, 0xcf2e32df
+0, 1236548, 11300, 0xcb8cfebf
+0, 1254469, 11300, 0xb961ca99
+0, 1272390, 11300, 0x666d9619
+0, 1290311, 11300, 0x84bf5b55
+0, 1308232, 11300, 0xbfa22ccc
+0, 1326153, 11300, 0xcde41849
+0, 1344074, 11300, 0x71372dcd
+0, 1361994, 11300, 0x13402cfd
+0, 1379915, 11300, 0xdebdd321
+0, 1397836, 11300, 0xdda66de1
+0, 1415757, 11300, 0x7f4bb682
+0, 1433678, 11300, 0xf67fd528
+0, 1451599, 11300, 0xe739ff8c
+0, 1469520, 11300, 0x2e131774
+0, 1487441, 11300, 0xfa942811
+0, 1505362, 11300, 0x0cd93ac2
+0, 1523283, 11300, 0xd0445e0e
+0, 1541204, 11300, 0x3f3497c7
+0, 1559125, 11300, 0x11b5bd2c
+0, 1577046, 11300, 0xccd5e62a
+0, 1594967, 11300, 0xa9d4fcb5
+0, 1612888, 11300, 0x34aa1a03
+0, 1630809, 11300, 0x1ce6299e
+0, 1648730, 11300, 0x661c2745
+0, 1666651, 11300, 0x27d8a8b3
+0, 1684572, 11300, 0x9eb07467
+0, 1702493, 11300, 0x128374d2
+0, 1720414, 11300, 0x05c36ff5
+0, 1738335, 11300, 0x8a136bde
+0, 1756256, 11300, 0x15c47c99
+0, 1774177, 11300, 0xcc4a93f4
+0, 1792098, 11300, 0x19529b2b
+0, 1810019, 11300, 0x9943c076
+0, 1827940, 11300, 0xf898e583
+0, 1845861, 11300, 0x40f71f94
+0, 1863782, 11300, 0x5b604afb
+0, 1881703, 11300, 0x8c176af4
+0, 1899624, 11300, 0x0f1a6216
+0, 1917545, 11300, 0x38bbd13d
+0, 1935466, 11300, 0x90c8d1fc
+0, 1953387, 11300, 0x253000d7
+0, 1971308, 11300, 0xb94b03b1
+0, 1989229, 11300, 0xbc872268
+0, 2007150, 11300, 0xe77adb8c
+0, 2025071, 11300, 0xa38936b7
+0, 2042992, 11300, 0xd6153632
+0, 2060913, 11300, 0x1ae633cc
+0, 2078834, 11300, 0xb90c286e
+0, 2096755, 11300, 0xbc7e333d
+0, 2114676, 11300, 0x1b5421f8
+0, 2132597, 11300, 0xdde6506d
+0, 2150518, 11300, 0xd3eb757e
+0, 2168439, 11300, 0x5ad1929c
+0, 2186360, 11300, 0x4f6aa47d
+0, 2204281, 11300, 0xab3caf55
+0, 2222202, 11300, 0x5ff9b39a
+0, 2240123, 11300, 0x1454e12e
+0, 2258043, 11300, 0xf18216e8
+0, 2275964, 11300, 0x62144880
+0, 2293885, 11300, 0x54284241
+0, 2311806, 11300, 0x8e8c7228
+0, 2329727, 11300, 0xb498d06e
+0, 2347648, 11300, 0x7b1e6be1
+0, 2365569, 11300, 0x5e5ea1f4
+0, 2383490, 11300, 0x41eda28e
+0, 2401411, 11300, 0x7ba6aa92
+0, 2419332, 11300, 0xa8a8b1c7
+0, 2437253, 11300, 0x0d30bd08
+0, 2455174, 11300, 0xc610bf16
+0, 2473095, 11300, 0xed57c075
+0, 2491016, 11300, 0xb86dbfea
+0, 2508937, 11300, 0x0970c03d
+0, 2526858, 11300, 0x743ac2ac
+0, 2544779, 11300, 0x0a44c816
+0, 2562700, 11300, 0xe32acd6b
+0, 2580621, 11300, 0x209bcdab
+0, 2598542, 11300, 0x3cd0d105
+0, 2616463, 11300, 0xc0bcd330
+0, 2634384, 11300, 0x4785d6dc
+0, 2652305, 11300, 0xe85f9c90
+0, 2670226, 11300, 0xd4a72850
+0, 2688147, 11300, 0x04766e41
+0, 2706068, 11300, 0x04766e41
diff --git a/tests/ref/fate/dfa1 b/tests/ref/fate/dfa1
new file mode 100644
index 0000000..43c9737
--- /dev/null
+++ b/tests/ref/fate/dfa1
@@ -0,0 +1,25 @@
+0, 0, 921600, 0x2e2b3ca4
+0, 11520, 921600, 0x0ff7a368
+0, 23040, 921600, 0xf5f0dc50
+0, 34560, 921600, 0x56cb0c9d
+0, 46080, 921600, 0xb253228f
+0, 57600, 921600, 0xefd3419e
+0, 69120, 921600, 0x708c0ce7
+0, 80640, 921600, 0x0b3a7f6d
+0, 92160, 921600, 0x72db4eac
+0, 103680, 921600, 0x94328111
+0, 115200, 921600, 0x95f7b2f0
+0, 126720, 921600, 0xdc3c9655
+0, 138240, 921600, 0xfe03dec6
+0, 149760, 921600, 0x2551dffb
+0, 161280, 921600, 0xe8b37d9e
+0, 172800, 921600, 0xad93508b
+0, 184320, 921600, 0x5a1c4890
+0, 195840, 921600, 0x6f972fb4
+0, 207360, 921600, 0xa1d5ff95
+0, 218880, 921600, 0x7bc5d07c
+0, 230400, 921600, 0xc0311e4e
+0, 241920, 921600, 0x5b02cc48
+0, 253440, 921600, 0x8db4d5fa
+0, 264960, 921600, 0x31aae769
+0, 276480, 921600, 0xab62b9a7
diff --git a/tests/ref/fate/dfa10 b/tests/ref/fate/dfa10
new file mode 100644
index 0000000..720704a
--- /dev/null
+++ b/tests/ref/fate/dfa10
@@ -0,0 +1,8 @@
+0, 0, 192000, 0xbabcbd55
+0, 6390, 192000, 0xf00a5683
+0, 12780, 192000, 0xcce90589
+0, 19170, 192000, 0x8545631f
+0, 25560, 192000, 0xd3ab654c
+0, 31950, 192000, 0x5e0dda12
+0, 38340, 192000, 0x7e94b053
+0, 44730, 192000, 0x8027e68b
diff --git a/tests/ref/fate/dfa11 b/tests/ref/fate/dfa11
new file mode 100644
index 0000000..f01fd13
--- /dev/null
+++ b/tests/ref/fate/dfa11
@@ -0,0 +1,9 @@
+0, 0, 192000, 0x8b8bd8de
+0, 6390, 192000, 0xdac26ec2
+0, 12780, 192000, 0x0fc01c28
+0, 19170, 192000, 0x1251eef7
+0, 25560, 192000, 0x89eced0e
+0, 31950, 192000, 0x4943d821
+0, 38340, 192000, 0x49258ec9
+0, 44730, 192000, 0x9afd5881
+0, 51120, 192000, 0xb322b901
diff --git a/tests/ref/fate/dfa2 b/tests/ref/fate/dfa2
new file mode 100644
index 0000000..98af733
--- /dev/null
+++ b/tests/ref/fate/dfa2
@@ -0,0 +1,17 @@
+0, 0, 921600, 0x713f2da1
+0, 6390, 921600, 0x9e772ec9
+0, 12780, 921600, 0x9420310f
+0, 19170, 921600, 0xd68f294f
+0, 25560, 921600, 0xe25a1bcf
+0, 31950, 921600, 0x32f903ec
+0, 38340, 921600, 0xdb290b1c
+0, 44730, 921600, 0x0b0d1b0f
+0, 51120, 921600, 0x58430921
+0, 57510, 921600, 0xe65dd39e
+0, 63900, 921600, 0x146b3068
+0, 70290, 921600, 0x6e1e7f78
+0, 76680, 921600, 0x0166e01c
+0, 83070, 921600, 0x83b86b56
+0, 89460, 921600, 0xd52a1697
+0, 95850, 921600, 0x5b38adc8
+0, 102240, 921600, 0x457f6cea
diff --git a/tests/ref/fate/dfa3 b/tests/ref/fate/dfa3
new file mode 100644
index 0000000..0452f2b
--- /dev/null
+++ b/tests/ref/fate/dfa3
@@ -0,0 +1,10 @@
+0, 0, 192000, 0x10380cf0
+0, 9000, 192000, 0x1d74af4c
+0, 18000, 192000, 0xd665492d
+0, 27000, 192000, 0xbf544565
+0, 36000, 192000, 0xf8a33b00
+0, 45000, 192000, 0x7d08bbad
+0, 54000, 192000, 0x10685a90
+0, 63000, 192000, 0x0a1a9ef6
+0, 72000, 192000, 0x3e967980
+0, 81000, 192000, 0x9849f751
diff --git a/tests/ref/fate/dfa4 b/tests/ref/fate/dfa4
new file mode 100644
index 0000000..f19061b
--- /dev/null
+++ b/tests/ref/fate/dfa4
@@ -0,0 +1,13 @@
+0, 0, 921600, 0xe6309638
+0, 12780, 921600, 0xa99a7665
+0, 25560, 921600, 0x172ccfbb
+0, 38340, 921600, 0xcf676571
+0, 51120, 921600, 0x6a5077f2
+0, 63900, 921600, 0x6a5077f2
+0, 76680, 921600, 0x6a5077f2
+0, 89460, 921600, 0x6a5077f2
+0, 102240, 921600, 0x6a5077f2
+0, 115020, 921600, 0x6a5077f2
+0, 127800, 921600, 0xb83db404
+0, 140580, 921600, 0x997ceb90
+0, 153360, 921600, 0xd707157c
diff --git a/tests/ref/fate/dfa5 b/tests/ref/fate/dfa5
new file mode 100644
index 0000000..65aa1bc
--- /dev/null
+++ b/tests/ref/fate/dfa5
@@ -0,0 +1,15 @@
+0, 0, 192000, 0xc0941c10
+0, 9000, 192000, 0xe2fe3ae5
+0, 18000, 192000, 0x4a352d98
+0, 27000, 192000, 0x7b78e0bb
+0, 36000, 192000, 0x855c6675
+0, 45000, 192000, 0xf443dad6
+0, 54000, 192000, 0xe7e2a2e1
+0, 63000, 192000, 0xa9009c58
+0, 72000, 192000, 0x551855ab
+0, 81000, 192000, 0x253908c7
+0, 90000, 192000, 0x616213c4
+0, 99000, 192000, 0xa381c3b1
+0, 108000, 192000, 0xa2d64152
+0, 117000, 192000, 0x34ed0f72
+0, 126000, 192000, 0x05be63b4
diff --git a/tests/ref/fate/dfa6 b/tests/ref/fate/dfa6
new file mode 100644
index 0000000..92fe427
--- /dev/null
+++ b/tests/ref/fate/dfa6
@@ -0,0 +1,12 @@
+0, 0, 192000, 0x69f6a5f6
+0, 6390, 192000, 0xc741d0a6
+0, 12780, 192000, 0xba31e7a4
+0, 19170, 192000, 0x7dc45080
+0, 25560, 192000, 0x1c91dad5
+0, 31950, 192000, 0x564b69b1
+0, 38340, 192000, 0xdd9d9ae8
+0, 44730, 192000, 0x605c05e1
+0, 51120, 192000, 0xa5341ddb
+0, 57510, 192000, 0x1ebff8ba
+0, 63900, 192000, 0x240df237
+0, 70290, 192000, 0xac641867
diff --git a/tests/ref/fate/dfa7 b/tests/ref/fate/dfa7
new file mode 100644
index 0000000..c9612f0
--- /dev/null
+++ b/tests/ref/fate/dfa7
@@ -0,0 +1,12 @@
+0, 0, 7866, 0xa0056fdb
+0, 6390, 7866, 0xed906c7a
+0, 12780, 7866, 0x1c6e6f7d
+0, 19170, 7866, 0xa2c460f7
+0, 25560, 7866, 0xcf2166d4
+0, 31950, 7866, 0xea545432
+0, 38340, 7866, 0x604a5a9e
+0, 44730, 7866, 0xbbc95c89
+0, 51120, 7866, 0x80b16b5b
+0, 57510, 7866, 0x9a1660ae
+0, 63900, 7866, 0x6f886b10
+0, 70290, 7866, 0xad8b5c99
diff --git a/tests/ref/fate/dfa8 b/tests/ref/fate/dfa8
new file mode 100644
index 0000000..ade21de
--- /dev/null
+++ b/tests/ref/fate/dfa8
@@ -0,0 +1,36 @@
+0, 0, 134724, 0x2ab217de
+0, 6390, 134724, 0xbf240f9a
+0, 12780, 134724, 0x020a6010
+0, 19170, 134724, 0x9a5f9374
+0, 25560, 134724, 0x1e93a7e9
+0, 31950, 134724, 0x9e4a4c55
+0, 38340, 134724, 0x8f9d1bab
+0, 44730, 134724, 0xb26ac45b
+0, 51120, 134724, 0xc08706d2
+0, 57510, 134724, 0x0806b031
+0, 63900, 134724, 0x234dbb33
+0, 70290, 134724, 0xe4cbfb2f
+0, 76680, 134724, 0xf603f3fd
+0, 83070, 134724, 0x205669d1
+0, 89460, 134724, 0x7ddbb5e3
+0, 95850, 134724, 0x8dfbb45a
+0, 102240, 134724, 0x9632f681
+0, 108630, 134724, 0x259e462c
+0, 115020, 134724, 0x14f2bac1
+0, 121410, 134724, 0xac3de7ed
+0, 127800, 134724, 0x6b8af396
+0, 134190, 134724, 0xd1e4bc1c
+0, 140580, 134724, 0x716d1c73
+0, 146970, 134724, 0x610956c8
+0, 153360, 134724, 0x89ff8e86
+0, 159750, 134724, 0xc3ea6b6f
+0, 166140, 134724, 0x886688ef
+0, 172530, 134724, 0xe60fc8c1
+0, 178920, 134724, 0x22bd3131
+0, 185310, 134724, 0xb1d74561
+0, 191700, 134724, 0x61b069bc
+0, 198090, 134724, 0x50b665c1
+0, 204480, 134724, 0x027e5144
+0, 210870, 134724, 0xfe0c31b4
+0, 217260, 134724, 0x1e7a1f2d
+0, 223650, 134724, 0x48bff03d
diff --git a/tests/ref/fate/dfa9 b/tests/ref/fate/dfa9
new file mode 100644
index 0000000..b33152a
--- /dev/null
+++ b/tests/ref/fate/dfa9
@@ -0,0 +1,6 @@
+0, 0, 228150, 0x188c6d9b
+0, 6390, 228150, 0x658dbf2f
+0, 12780, 228150, 0xc09a4b2e
+0, 19170, 228150, 0x8777bc7d
+0, 25560, 228150, 0xa388f0ce
+0, 31950, 228150, 0x4e06666e
diff --git a/tests/ref/fate/dxtory b/tests/ref/fate/dxtory
new file mode 100644
index 0000000..5fab200
--- /dev/null
+++ b/tests/ref/fate/dxtory
@@ -0,0 +1 @@
+0, 0, 1382400, 0x44373645
diff --git a/tests/ref/fate/h264-bsf-mp4toannexb b/tests/ref/fate/h264-bsf-mp4toannexb
index 6395f24..2049f39 100644
--- a/tests/ref/fate/h264-bsf-mp4toannexb
+++ b/tests/ref/fate/h264-bsf-mp4toannexb
@@ -1 +1 @@
-503d34ff458a86387ab349c31726f19a
+5f04c27cc6ee8625fe2405fb0f7da9a3
diff --git a/tests/ref/fate/indeo4 b/tests/ref/fate/indeo4
new file mode 100644
index 0000000..0f088ec
--- /dev/null
+++ b/tests/ref/fate/indeo4
@@ -0,0 +1,100 @@
+0, 0, 86400, 0x98f5e422
+0, 6000, 86400, 0x1864cb06
+0, 12000, 86400, 0xb09532ef
+0, 18000, 86400, 0x3cd3dcdc
+0, 24000, 86400, 0xe738847f
+0, 30000, 86400, 0xc9b13afb
+0, 36000, 86400, 0x5005d035
+0, 42000, 86400, 0x22f63e17
+0, 48000, 86400, 0x93391f02
+0, 54000, 86400, 0x264830fd
+0, 60000, 86400, 0x8fff9f5f
+0, 66000, 86400, 0x524997fe
+0, 72000, 86400, 0x54e330f9
+0, 78000, 86400, 0x1d766a22
+0, 84000, 86400, 0x683a70ac
+0, 90000, 86400, 0x553b7b3d
+0, 96000, 86400, 0x822c79bc
+0, 102000, 86400, 0xe1087a1c
+0, 108000, 86400, 0xff397595
+0, 114000, 86400, 0x1b6b7717
+0, 120000, 86400, 0x6c5275c1
+0, 126000, 86400, 0x4e6a7189
+0, 132000, 86400, 0x285c6eba
+0, 138000, 86400, 0xce647227
+0, 144000, 86400, 0xa0d07b1c
+0, 150000, 86400, 0x5b567861
+0, 156000, 86400, 0x105873ec
+0, 162000, 86400, 0x59267fa0
+0, 168000, 86400, 0xaeac839f
+0, 174000, 86400, 0x2faf7402
+0, 180000, 86400, 0xc8547a30
+0, 186000, 86400, 0x3d357d49
+0, 192000, 86400, 0x75db6d6c
+0, 198000, 86400, 0x9fbf68e9
+0, 204000, 86400, 0x56a64d26
+0, 210000, 86400, 0xce9e1f43
+0, 216000, 86400, 0xa4d7fddc
+0, 222000, 86400, 0x3e20d77c
+0, 228000, 86400, 0x4680661d
+0, 234000, 86400, 0xf1b20af3
+0, 240000, 86400, 0xb79d8045
+0, 246000, 86400, 0x9479fc8a
+0, 252000, 86400, 0x232965c3
+0, 258000, 86400, 0xd18bca17
+0, 264000, 86400, 0xb9064249
+0, 270000, 86400, 0xcc48ab34
+0, 276000, 86400, 0xe25018cd
+0, 282000, 86400, 0x8da489ee
+0, 288000, 86400, 0x90de0fc1
+0, 294000, 86400, 0x2428dcee
+0, 300000, 86400, 0x4316e1ae
+0, 306000, 86400, 0x2b25e54c
+0, 312000, 86400, 0x736ce020
+0, 318000, 86400, 0x9a6be09a
+0, 324000, 86400, 0x23bddbcd
+0, 330000, 86400, 0x9368e465
+0, 336000, 86400, 0x1ae9bb87
+0, 342000, 86400, 0x4e591f32
+0, 348000, 86400, 0xba1bf9dc
+0, 354000, 86400, 0x07f0aa60
+0, 360000, 86400, 0xf5a2cfa2
+0, 366000, 86400, 0xcba5fc18
+0, 372000, 86400, 0x858c0cfe
+0, 378000, 86400, 0xac73ecd4
+0, 384000, 86400, 0xf41bf03c
+0, 390000, 86400, 0x928ed146
+0, 396000, 86400, 0x9ff5990a
+0, 402000, 86400, 0xc2fabc3d
+0, 408000, 86400, 0x94af87a3
+0, 414000, 86400, 0x9bae514c
+0, 420000, 86400, 0xe0da267a
+0, 426000, 86400, 0x1d40f55c
+0, 432000, 86400, 0xe6173b68
+0, 438000, 86400, 0x1445490d
+0, 444000, 86400, 0x8d8753c1
+0, 450000, 86400, 0xe5a7779d
+0, 456000, 86400, 0x3cfc66ef
+0, 462000, 86400, 0xa5d45608
+0, 468000, 86400, 0x62f17be1
+0, 474000, 86400, 0xa64c84d3
+0, 480000, 86400, 0xf98162f0
+0, 486000, 86400, 0x0db77d9f
+0, 492000, 86400, 0x0f0cbac9
+0, 498000, 86400, 0xb9934e97
+0, 504000, 86400, 0x7f8fa248
+0, 510000, 86400, 0xdfd96768
+0, 516000, 86400, 0x81b07919
+0, 522000, 86400, 0x66c11e9f
+0, 528000, 86400, 0xd86eb114
+0, 534000, 86400, 0x67f20c1f
+0, 540000, 86400, 0x66915de5
+0, 546000, 86400, 0x2b8aa76f
+0, 552000, 86400, 0x85b5a3d2
+0, 558000, 86400, 0x80d29ed6
+0, 564000, 86400, 0x4d508e2c
+0, 570000, 86400, 0x0d407374
+0, 576000, 86400, 0xd4068016
+0, 582000, 86400, 0x6ffab98f
+0, 588000, 86400, 0x2360903d
+0, 594000, 86400, 0x470e04a0
diff --git a/tests/ref/fate/smjpeg b/tests/ref/fate/smjpeg
new file mode 100644
index 0000000..ec91959
--- /dev/null
+++ b/tests/ref/fate/smjpeg
@@ -0,0 +1,423 @@
+0, 0, 734, 0x5a042c2c
+1, 0, 1024, 0x00000000
+1, 2090, 1024, 0x00000000
+1, 4180, 1024, 0xd89a448e
+1, 6269, 1024, 0x695b369c
+1, 8359, 1024, 0xc8ba5707
+0, 9990, 763, 0xb5893f2f
+1, 10449, 1024, 0xdf241fc6
+1, 12539, 1024, 0x61cf4166
+1, 14629, 1024, 0x97cbc386
+1, 16718, 1024, 0x44899d04
+1, 18808, 1024, 0xa7cbaa62
+0, 19980, 3023, 0x0f3907d3
+1, 20898, 1024, 0xa7aea60c
+1, 22988, 1024, 0xd7b18a89
+1, 25078, 1024, 0x268e81f6
+1, 27167, 1024, 0x9cf83a2f
+1, 29257, 1024, 0x5559b508
+0, 29970, 4800, 0x22e6e18a
+1, 31347, 1024, 0xe1b9e71c
+1, 33437, 1024, 0xdcee733e
+1, 35527, 1024, 0xe5918f60
+1, 37616, 1024, 0x29dbd209
+1, 39706, 1024, 0x9bcbcf16
+0, 39960, 6417, 0x427adde5
+1, 41796, 1024, 0x86f5f458
+1, 43886, 1024, 0xabcbda86
+1, 45976, 1024, 0xc51f77b9
+1, 48065, 1024, 0xf6b3a504
+0, 49950, 6776, 0x7a74c6ad
+1, 50155, 1024, 0x1af3e40e
+1, 52245, 1024, 0x3866b03b
+1, 54335, 1024, 0xbc005403
+1, 56424, 1024, 0xe9dfcc51
+1, 58514, 1024, 0x83c837cb
+0, 59940, 6808, 0x1f6eb7c3
+1, 60604, 1024, 0xfa649580
+1, 62694, 1024, 0x519452ea
+1, 64784, 1024, 0xd4978774
+1, 66873, 1024, 0xe2a3b1cd
+1, 68963, 1024, 0x9a9472ad
+0, 69930, 6726, 0x452087e6
+1, 71053, 1024, 0xa12d4060
+1, 73143, 1024, 0x31fb0646
+1, 75233, 1024, 0xfc44343f
+1, 77322, 1024, 0x0847751a
+1, 79412, 1024, 0x227968a2
+0, 79920, 6829, 0xee82b109
+1, 81502, 1024, 0x7cce9f1c
+1, 83592, 1024, 0xb8356713
+1, 85682, 1024, 0xb29f6e6f
+1, 87771, 1024, 0x9e1430ab
+1, 89861, 1024, 0x26d85423
+0, 89910, 7055, 0xf41f1108
+1, 91951, 1024, 0x6496547d
+1, 94041, 1024, 0x316b1a86
+1, 96131, 1024, 0x3cd83afc
+1, 98220, 1024, 0x993ff633
+0, 99990, 6977, 0xf8fe1ede
+1, 100310, 1024, 0x0708d1a2
+1, 102400, 1024, 0xd7230db9
+1, 104490, 1024, 0xbb0779ca
+1, 106580, 1024, 0xc6094e1b
+1, 108669, 1024, 0x15a8b039
+0, 109980, 6942, 0x9ad105c6
+1, 110759, 1024, 0xd6dbe88c
+1, 112849, 1024, 0x7e8d1140
+1, 114939, 1024, 0xef88e525
+1, 117029, 1024, 0x44e21149
+1, 119118, 1024, 0x65b0f5f4
+0, 119970, 6926, 0xe239dad6
+1, 121208, 1024, 0xb955f687
+1, 123298, 1024, 0xc85fba9c
+1, 125388, 1024, 0xf59655ad
+1, 127478, 1024, 0x6de80bf1
+1, 129567, 1024, 0x2dcf6e41
+0, 129960, 6966, 0x81dcfab1
+1, 131657, 1024, 0xd0ddcf8a
+1, 133747, 1024, 0x00135c2d
+1, 135837, 1024, 0x697f8efd
+1, 137927, 1024, 0x7a9bada5
+0, 139950, 6896, 0x31e6cc02
+1, 140016, 1024, 0x0d22783c
+1, 142106, 1024, 0x7726d07d
+1, 144196, 1024, 0xa2f14f67
+1, 146286, 1024, 0x7f51060d
+1, 148376, 1024, 0xc4ec6aea
+0, 149940, 6889, 0x1cc1006e
+1, 150465, 1024, 0x9bb37ca4
+1, 152555, 1024, 0x9b085577
+1, 154645, 1024, 0x8812f8af
+1, 156735, 1024, 0x788f5221
+1, 158824, 1024, 0x3a2ce642
+0, 159930, 6933, 0xc303f87f
+1, 160914, 1024, 0x72415692
+1, 163004, 1024, 0xe3dcc105
+1, 165094, 1024, 0xb26c0599
+1, 167184, 1024, 0x5c9e55eb
+1, 169273, 1024, 0x8fe88707
+0, 169920, 7034, 0xb4970a20
+1, 171363, 1024, 0xc5d7beb6
+1, 173453, 1024, 0xe1d3a3b4
+1, 175543, 1024, 0x012da0c6
+1, 177633, 1024, 0x8d010922
+1, 179722, 1024, 0x3366eb0d
+0, 179910, 6961, 0xf064095d
+1, 181812, 1024, 0xc9381a27
+1, 183902, 1024, 0x0774f685
+1, 185992, 1024, 0xc5cae0a5
+1, 188082, 1024, 0xa6f4737c
+0, 189990, 7089, 0x5ba350f9
+1, 190171, 1024, 0x8fb6d0d1
+1, 192261, 1024, 0x05f579c2
+1, 194351, 1024, 0x56905d99
+1, 196441, 1024, 0x002ee18d
+1, 198531, 1024, 0xeb37ef51
+0, 199980, 7078, 0xa83f3e88
+1, 200620, 1024, 0x38025635
+1, 202710, 1024, 0x4fe643c8
+1, 204800, 1024, 0x11d66ab1
+1, 206890, 1024, 0xcc3051e9
+1, 208980, 1024, 0xcd93e854
+0, 209970, 7147, 0xcda66cfc
+1, 211069, 1024, 0x38f1196d
+1, 213159, 1024, 0x657a15fc
+1, 215249, 1024, 0x669ce2a9
+1, 217339, 1024, 0x95862dda
+1, 219429, 1024, 0x1726a7b2
+0, 219960, 7173, 0xb7455859
+1, 221518, 1024, 0xd6ece2a1
+1, 223608, 1024, 0x33ab9553
+1, 225698, 1024, 0xd50c73a6
+1, 227788, 1024, 0xfe25b63a
+1, 229878, 1024, 0x7e2959e3
+0, 229950, 7213, 0x97b89994
+1, 231967, 1024, 0xa4c07b34
+1, 234057, 1024, 0xd6d8f15c
+1, 236147, 1024, 0x1eccddd7
+1, 238237, 1024, 0x2b69f9cb
+0, 239940, 7170, 0xca8b2948
+1, 240327, 1024, 0x667b775f
+1, 242416, 1024, 0xad3b84e9
+1, 244506, 1024, 0x4f29fc67
+1, 246596, 1024, 0x8d611ab7
+1, 248686, 1024, 0x278966ea
+0, 249930, 7174, 0xc7cc6bbb
+1, 250776, 1024, 0xaf33812b
+1, 252865, 1024, 0xa55f4265
+1, 254955, 1024, 0x023cb51c
+1, 257045, 1024, 0x1d1f1005
+1, 259135, 1024, 0x874cccf7
+0, 259920, 7235, 0xc2e68d2b
+1, 261224, 1024, 0xda705428
+1, 263314, 1024, 0x48d9b440
+1, 265404, 1024, 0xa14e0712
+1, 267494, 1024, 0x7efbad1f
+1, 269584, 1024, 0xdb82c17f
+0, 270000, 7261, 0x8204a423
+1, 271673, 1024, 0xcbe87613
+1, 273763, 1024, 0x3a63df1d
+1, 275853, 1024, 0xd5636bba
+1, 277943, 1024, 0x9397af23
+0, 279990, 7353, 0xacc7e7c0
+1, 280033, 1024, 0x32a07c98
+1, 282122, 1024, 0x202ca667
+1, 284212, 1024, 0xdf969011
+1, 286302, 1024, 0xc434d238
+1, 288392, 1024, 0xe9ad7562
+0, 289980, 7065, 0x45035c5c
+1, 290482, 1024, 0xb51b6b50
+1, 292571, 1024, 0xe70aecd3
+1, 294661, 1024, 0x03c816b2
+1, 296751, 1024, 0x869fdf25
+1, 298841, 1024, 0xd40a0a62
+0, 299970, 7269, 0x72edbb76
+1, 300931, 1024, 0x5af7dd35
+1, 303020, 1024, 0x891ffc72
+1, 305110, 1024, 0x1ff68a08
+1, 307200, 1024, 0x5a7517a9
+1, 309290, 1024, 0x0f959f74
+0, 309960, 7220, 0xb926772f
+1, 311380, 1024, 0xe92a12a2
+1, 313469, 1024, 0x38000e55
+1, 315559, 1024, 0x39fbdd70
+1, 317649, 1024, 0xca3d9184
+1, 319739, 1024, 0x66c8995b
+0, 319950, 7326, 0x0a66c632
+1, 321829, 1024, 0xac25acea
+1, 323918, 1024, 0x3cd1046c
+1, 326008, 1024, 0x6a1df31c
+1, 328098, 1024, 0x21ca10a1
+0, 329940, 7225, 0xe39076ab
+1, 330188, 1024, 0x1aeccedc
+1, 332278, 1024, 0xddea1335
+1, 334367, 1024, 0x19f5ca9f
+1, 336457, 1024, 0x88e95e43
+1, 338547, 1024, 0x726284fe
+0, 339930, 7265, 0xe0209036
+1, 340637, 1024, 0x6b85b40e
+1, 342727, 1024, 0x111fee2a
+1, 344816, 1024, 0x3656b588
+1, 346906, 1024, 0xa5a2b552
+1, 348996, 1024, 0x38fb2467
+0, 349920, 7337, 0x7a5dc093
+1, 351086, 1024, 0xaa919ccc
+1, 353176, 1024, 0x15993dbc
+1, 355265, 1024, 0xbe01a7b9
+1, 357355, 1024, 0xefe93c09
+1, 359445, 1024, 0x1bb566e5
+0, 360000, 7246, 0x519a7a3c
+1, 361535, 1024, 0x15ce6237
+1, 363624, 1024, 0xa8552e66
+1, 365714, 1024, 0x9d80187e
+1, 367804, 1024, 0x5df3fc30
+1, 369894, 1024, 0x1a312aa5
+0, 369990, 7266, 0x352c8078
+1, 371984, 1024, 0x6bb8e302
+1, 374073, 1024, 0xbd9684bb
+1, 376163, 1024, 0x78b0b166
+1, 378253, 1024, 0xd9af5eae
+0, 379980, 7323, 0xcaf69d7c
+1, 380343, 1024, 0xdb90fe82
+1, 382433, 1024, 0x327614e9
+1, 384522, 1024, 0x1f19b7fe
+1, 386612, 1024, 0x46c53f96
+1, 388702, 1024, 0x921b2189
+0, 389970, 7309, 0x98c1e6f7
+1, 390792, 1024, 0xa8fbc85a
+1, 392882, 1024, 0xabfdaaae
+1, 394971, 1024, 0x6acc7387
+1, 397061, 1024, 0x0d9c27b5
+1, 399151, 1024, 0xba4dd809
+0, 399960, 7121, 0x913d5bd6
+1, 401241, 1024, 0x2a2ad521
+1, 403331, 1024, 0x892de38a
+1, 405420, 1024, 0xdc97a2eb
+1, 407510, 1024, 0x4f614ca4
+1, 409600, 1024, 0x9c8a77ea
+0, 409950, 7088, 0x56302362
+1, 411690, 1024, 0x2d30e646
+1, 413780, 1024, 0x74e800a7
+1, 415869, 1024, 0x1e01fb02
+1, 417959, 1024, 0x4ed2c1d8
+0, 419940, 7104, 0xc0d14f78
+1, 420049, 1024, 0xf2fdbe63
+1, 422139, 1024, 0x8d6f63a1
+1, 424229, 1024, 0xded468d9
+1, 426318, 1024, 0xccad839e
+1, 428408, 1024, 0xdde7c082
+0, 429930, 7169, 0xd03c825b
+1, 430498, 1024, 0x548613c5
+1, 432588, 1024, 0x383909bd
+1, 434678, 1024, 0xfd37627b
+1, 436767, 1024, 0x6d95a481
+1, 438857, 1024, 0x56aa87fa
+0, 439920, 7038, 0x1ecc201d
+1, 440947, 1024, 0x7b67258c
+1, 443037, 1024, 0x7dd99a92
+1, 445127, 1024, 0x4a66d102
+1, 447216, 1024, 0x7b3fce51
+1, 449306, 1024, 0xbbd968aa
+0, 450000, 7015, 0x83c94454
+1, 451396, 1024, 0x8283ec36
+1, 453486, 1024, 0x3c96493d
+1, 455576, 1024, 0xfa4f8cf8
+1, 457665, 1024, 0xe2cf872d
+1, 459755, 1024, 0x0a9e7aa6
+0, 459990, 6983, 0x9e51f54d
+1, 461845, 1024, 0x6e7a0550
+1, 463935, 1024, 0x3acfea2f
+1, 466024, 1024, 0x7111d0fa
+1, 468114, 1024, 0xe9a1eca9
+0, 469980, 7088, 0x70d33de1
+1, 470204, 1024, 0x24da6c46
+1, 472294, 1024, 0x117cff37
+1, 474384, 1024, 0x0f27cab6
+1, 476473, 1024, 0x69b6b4e6
+1, 478563, 1024, 0x1e6cc841
+0, 479970, 7096, 0x4d0f81b5
+1, 480653, 1024, 0xb01e2365
+1, 482743, 1024, 0x14e200d3
+1, 484833, 1024, 0xd1184c98
+1, 486922, 1024, 0xef9140e9
+1, 489012, 1024, 0x4cbb645e
+0, 489960, 7106, 0xd1a83ddc
+1, 491102, 1024, 0xe7fe2f06
+1, 493192, 1024, 0xf8c45028
+1, 495282, 1024, 0x561358f4
+1, 497371, 1024, 0xd0129b77
+1, 499461, 1024, 0xcc636e88
+0, 499950, 7219, 0x20f47fe4
+1, 501551, 1024, 0xe9406321
+1, 503641, 1024, 0x9f16a041
+1, 505731, 1024, 0x468bf409
+1, 507820, 1024, 0x3df70f7b
+1, 509910, 1024, 0xa880b11b
+0, 509940, 7184, 0x45dc6a0e
+1, 512000, 1024, 0x3286c489
+1, 514090, 1024, 0x39fe9ebc
+1, 516180, 1024, 0xc533d83b
+1, 518269, 1024, 0x153b195d
+0, 519930, 7222, 0x488c6499
+1, 520359, 1024, 0xd84786a1
+1, 522449, 1024, 0xdc295aaa
+1, 524539, 1024, 0xfb764d8c
+1, 526629, 1024, 0xeebc9db9
+1, 528718, 1024, 0x7ba9403e
+0, 529920, 7254, 0xbd097ba7
+1, 530808, 1024, 0x4e5571ec
+1, 532898, 1024, 0xd965fad4
+1, 534988, 1024, 0x87e259f2
+1, 537078, 1024, 0xae7e533b
+1, 539167, 1024, 0x313cf4d6
+0, 540000, 7189, 0x46e06d43
+1, 541257, 1024, 0xe1844c90
+1, 543347, 1024, 0xbb057b44
+1, 545437, 1024, 0xa5099687
+1, 547527, 1024, 0xbff10707
+1, 549616, 1024, 0x37c4ffc0
+0, 549990, 7283, 0x19dd7319
+1, 551706, 1024, 0xf9fb6caa
+1, 553796, 1024, 0x3b6a3a1f
+1, 555886, 1024, 0x83431edb
+1, 557976, 1024, 0x1eb713cf
+0, 559980, 7161, 0x23171d02
+1, 560065, 1024, 0xd7b07a6d
+1, 562155, 1024, 0x81ae3391
+1, 564245, 1024, 0xf150130a
+1, 566335, 1024, 0x09678eaa
+1, 568424, 1024, 0xb94e06f1
+0, 569970, 6976, 0xcc610c26
+1, 570514, 1024, 0x67b1dbc9
+1, 572604, 1024, 0xd6edc235
+1, 574694, 1024, 0x34e4c499
+1, 576784, 1024, 0xeefd89c0
+1, 578873, 1024, 0x38afdaf1
+0, 579960, 7056, 0x6cd917b0
+1, 580963, 1024, 0x29a60d76
+1, 583053, 1024, 0xe28a4372
+1, 585143, 1024, 0x7089454d
+1, 587233, 1024, 0x0c01bb7b
+1, 589322, 1024, 0xbd776a72
+0, 589950, 6736, 0x02b78951
+1, 591412, 1024, 0x86776fd0
+1, 593502, 1024, 0xb37c88f7
+1, 595592, 1024, 0x5f90aaf8
+1, 597682, 1024, 0x203d4222
+1, 599771, 1024, 0x382692a6
+0, 599940, 6540, 0x767e0854
+1, 601861, 1024, 0xf37c95fd
+1, 603951, 1024, 0x6c0b8877
+1, 606041, 1024, 0x2e54a8b6
+1, 608131, 1024, 0x7f266488
+0, 609930, 6170, 0xc84962fb
+1, 610220, 1024, 0xfbf20f9a
+1, 612310, 1024, 0xf2985cc0
+1, 614400, 1024, 0xc7075340
+1, 616490, 1024, 0xe4585695
+1, 618580, 1024, 0xbdffa380
+0, 619920, 6169, 0x27e06c03
+1, 620669, 1024, 0x2422a8a9
+1, 622759, 1024, 0x59cbd75f
+1, 624849, 1024, 0x04ad1a8c
+1, 626939, 1024, 0x33c09191
+1, 629029, 1024, 0x55efa6fd
+0, 630000, 5864, 0xd14db83f
+1, 631118, 1024, 0xf73d0e5d
+1, 633208, 1024, 0x6141ebae
+1, 635298, 1024, 0x7db17a68
+1, 637388, 1024, 0xa6c690b6
+1, 639478, 1024, 0xa6fd6725
+0, 639990, 5375, 0x4a21055d
+1, 641567, 1024, 0x50a90b9b
+1, 643657, 1024, 0xef990dc8
+1, 645747, 1024, 0x75adf6b5
+1, 647837, 1024, 0x61eac43e
+1, 649927, 1024, 0x67797a19
+0, 649980, 5206, 0x95ead3cb
+1, 652016, 1024, 0xf325277a
+1, 654106, 1024, 0x18bf254a
+1, 656196, 1024, 0x2ce6bee3
+1, 658286, 1024, 0x8d320860
+0, 659970, 5220, 0xcfdcc37e
+1, 660376, 1024, 0xc979b6e8
+1, 662465, 1024, 0xdb644b41
+1, 664555, 1024, 0xe1b368ba
+1, 666645, 1024, 0xacc53d15
+1, 668735, 1024, 0x42ea8c18
+0, 669960, 4946, 0x2d864a77
+1, 670824, 1024, 0xe52c99a4
+1, 672914, 1024, 0xd7db54a6
+1, 675004, 1024, 0x7f27a7e3
+1, 677094, 1024, 0xf7ffeaa9
+1, 679184, 1024, 0x792b6088
+0, 679950, 4390, 0x2ab9f462
+1, 681273, 1024, 0x61d99724
+1, 683363, 1024, 0x5213720e
+1, 685453, 1024, 0xac09dd30
+1, 687543, 1024, 0x960bf6bb
+1, 689633, 1024, 0xc90168e1
+0, 689940, 4051, 0x1d09592e
+1, 691722, 1024, 0x43b45768
+1, 693812, 1024, 0x935d60a1
+1, 695902, 1024, 0x9a342ef2
+1, 697992, 1024, 0xc894709f
+0, 699930, 3680, 0x39bd6a12
+1, 700082, 1024, 0x59b43b07
+1, 702171, 1024, 0x36a1a98d
+1, 704261, 1024, 0x9e1a121c
+1, 706351, 1024, 0x02208b78
+1, 708441, 1024, 0xd1d7b274
+0, 709920, 2910, 0x6337ece9
+1, 710531, 1024, 0xdacd5096
+1, 712620, 1024, 0x51b71ead
+1, 714710, 1024, 0xd009a7ca
+1, 716800, 1024, 0xb6d5a938
+1, 718890, 1024, 0xf3d45e47
+0, 720000, 2153, 0xf4e3bc17
+1, 720980, 1024, 0xea8e04fc
+1, 723069, 1024, 0x0b928bd8
+1, 725159, 1024, 0x0f02caec
+1, 727249, 1024, 0xe2b137a8
+1, 729339, 1024, 0xd5f94892
diff --git a/tests/ref/fate/vc1-ism b/tests/ref/fate/vc1-ism
new file mode 100644
index 0000000..886e583
--- /dev/null
+++ b/tests/ref/fate/vc1-ism
@@ -0,0 +1,120 @@
+0, 0, 37440, 0xd1bc5235
+0, 3750, 37440, 0x158e6167
+0, 7500, 37440, 0x0faa4481
+0, 11250, 37440, 0x427158c5
+0, 15000, 37440, 0x4eb53ac6
+0, 18750, 37440, 0x99304eea
+0, 22500, 37440, 0xcc554a6f
+0, 26250, 37440, 0xabeb6c35
+0, 30000, 37440, 0xddfc7e18
+0, 33750, 37440, 0xaa79b504
+0, 37500, 37440, 0x5cb1c839
+0, 41250, 37440, 0x7e36ecca
+0, 45000, 37440, 0xf486f425
+0, 48750, 37440, 0xf1b4138f
+0, 52500, 37440, 0x966f1a49
+0, 56250, 37440, 0x5eff21da
+0, 60000, 37440, 0x333f39b1
+0, 63750, 37440, 0x62e5963e
+0, 67500, 37440, 0x26930671
+0, 71250, 37440, 0x27b4bb6c
+0, 75000, 37440, 0xdbd07766
+0, 78750, 37440, 0x04260104
+0, 82500, 37440, 0x9b1e078b
+0, 86250, 37440, 0xdf4e2474
+0, 90000, 37440, 0x57d44986
+0, 93750, 37440, 0x8780e34c
+0, 97500, 37440, 0xf80c8bc0
+0, 101250, 37440, 0x630a7583
+0, 105000, 37440, 0x235ae089
+0, 108750, 37440, 0x984b8f0e
+0, 112500, 37440, 0x865cf592
+0, 116250, 37440, 0x70f376f2
+0, 120000, 37440, 0x8b30c035
+0, 123750, 37440, 0xde772d79
+0, 127500, 37440, 0x8e076be5
+0, 131250, 37440, 0x3dc2bd9f
+0, 135000, 37440, 0xb782eb67
+0, 138750, 37440, 0x02025d73
+0, 142500, 37440, 0x86bbbce8
+0, 146250, 37440, 0xd6554f62
+0, 150000, 37440, 0xb831b917
+0, 153750, 37440, 0x80643560
+0, 157500, 37440, 0x4ecf9afd
+0, 161250, 37440, 0x9ce51e0b
+0, 165000, 37440, 0x179466cd
+0, 168750, 37440, 0x145fc900
+0, 172500, 37440, 0xb1b50402
+0, 176250, 37440, 0x0a87552a
+0, 180000, 37440, 0x8f53821d
+0, 183750, 37440, 0x1c07c825
+0, 187500, 37440, 0x49dde82f
+0, 191250, 37440, 0xb1a32605
+0, 195000, 37440, 0x410f3cd5
+0, 198750, 37440, 0xff5e6696
+0, 202500, 37440, 0x96f678c9
+0, 206250, 37440, 0x6c9e9e68
+0, 210000, 37440, 0x79a2a655
+0, 213750, 37440, 0xf237bd6c
+0, 217500, 37440, 0x4051b611
+0, 221250, 37440, 0xc7ccc918
+0, 225000, 37440, 0xbd02c122
+0, 228750, 37440, 0xacb3c881
+0, 232500, 37440, 0x2abdb940
+0, 236250, 37440, 0x19d5be85
+0, 240000, 37440, 0xfa5fb1ba
+0, 243750, 37440, 0xdae7a7aa
+0, 247500, 37440, 0x6b0f9f69
+0, 251250, 37440, 0x353e8201
+0, 255000, 37440, 0xa21443aa
+0, 258750, 37440, 0x66c8d7e0
+0, 262500, 37440, 0xc332068e
+0, 266250, 37440, 0x71431b9b
+0, 270000, 37440, 0x392f15cb
+0, 273750, 37440, 0x95a146bb
+0, 277500, 37440, 0x7c51740a
+0, 281250, 37440, 0xa3bdd43c
+0, 285000, 37440, 0xa079f965
+0, 288750, 37440, 0xa95423ea
+0, 292500, 37440, 0xd1bd2c67
+0, 296250, 37440, 0x6cf82844
+0, 300000, 37440, 0xd401e128
+0, 303750, 37440, 0x1f7db118
+0, 307500, 37440, 0x2e0a65a9
+0, 311250, 37440, 0x321c1c40
+0, 315000, 37440, 0x95b2a127
+0, 318750, 37440, 0xa1471f4b
+0, 322500, 37440, 0x29d148c0
+0, 326250, 37440, 0x24c07107
+0, 330000, 37440, 0x0ead678d
+0, 333750, 37440, 0xd0ca6495
+0, 337500, 37440, 0x08f935ef
+0, 341250, 37440, 0xb5ec3c38
+0, 345000, 37440, 0xce371628
+0, 348750, 37440, 0x68170812
+0, 352500, 37440, 0xe222699e
+0, 356250, 37440, 0xd688706c
+0, 360000, 37440, 0x81a033f9
+0, 363750, 37440, 0x28bd0fbf
+0, 367500, 37440, 0xe36db7b2
+0, 371250, 37440, 0x30559121
+0, 375000, 37440, 0xbf2b5fc8
+0, 378750, 37440, 0x4b427672
+0, 382500, 37440, 0x0544b0b4
+0, 386250, 37440, 0x38a70b06
+0, 390000, 37440, 0x4ed62607
+0, 393750, 37440, 0x6efe8ea6
+0, 397500, 37440, 0x81197e11
+0, 401250, 37440, 0xf4060050
+0, 405000, 37440, 0xaf205f13
+0, 408750, 37440, 0x5fa21382
+0, 412500, 37440, 0x8627ad05
+0, 416250, 37440, 0xf7130133
+0, 420000, 37440, 0x76dea7ba
+0, 423750, 37440, 0x1dbae1be
+0, 427500, 37440, 0x74a933f7
+0, 431250, 37440, 0xbdcd41a3
+0, 435000, 37440, 0xf0fe8c1c
+0, 438750, 37440, 0xc0036222
+0, 442500, 37440, 0x3058385c
+0, 446250, 37440, 0x68141016
diff --git a/tests/ref/fate/vp3-coeff-level64 b/tests/ref/fate/vp3-coeff-level64
new file mode 100644
index 0000000..31a49aa
--- /dev/null
+++ b/tests/ref/fate/vp3-coeff-level64
@@ -0,0 +1,8 @@
+0, 0, 4617600, 0x4ba6df50
+0, 6000, 4617600, 0x419fdeaf
+0, 12000, 4617600, 0xeb2edced
+0, 18000, 4617600, 0xa2bb3a1a
+0, 24000, 4617600, 0x411cfb36
+0, 30000, 4617600, 0xb2dc22ed
+0, 36000, 4617600, 0x236d23b5
+0, 42000, 4617600, 0x7fef275e
diff --git a/tests/ref/fate/wtv-demux b/tests/ref/fate/wtv-demux
new file mode 100644
index 0000000..b3744ee
--- /dev/null
+++ b/tests/ref/fate/wtv-demux
@@ -0,0 +1,139 @@
+1, 0, 576, 0x9b6e1638
+1, 1620, 576, 0x0ca91183
+1, 3780, 576, 0xec6a180f
+1, 5940, 576, 0x478a2b9b
+1, 8100, 576, 0x00fa15b3
+1, 10260, 576, 0xfb551816
+1, 12960, 576, 0x422e12bd
+1, 15120, 576, 0xa7581b29
+1, 17280, 576, 0xd4b31a74
+1, 19440, 576, 0x11521b10
+1, 21600, 576, 0x3dcc1474
+1, 23760, 576, 0x66c31aab
+1, 25920, 576, 0x97f318a8
+1, 28080, 576, 0xd3fb1a30
+1, 30240, 576, 0xd2bd16af
+1, 32400, 576, 0x6c10146a
+1, 34560, 576, 0x10d81468
+1, 36720, 576, 0x3813162d
+1, 38880, 576, 0x89e71d95
+1, 41040, 576, 0xd1c717f9
+1, 43200, 576, 0x1a311e5f
+1, 45360, 576, 0x0ea80e05
+1, 47520, 576, 0x2f1718f2
+1, 49680, 576, 0xffe01e13
+1, 51840, 576, 0xa7b02296
+1, 54000, 576, 0x199f1597
+1, 56160, 576, 0xdea217ba
+1, 58320, 576, 0x8a790f01
+1, 60480, 576, 0x23e80038
+1, 62640, 576, 0x75dc048a
+1, 64800, 576, 0xeb4b0d93
+1, 66960, 576, 0xde1322f5
+1, 69120, 576, 0xc3131f35
+1, 71280, 576, 0x708f1381
+1, 73440, 576, 0x1f00137e
+0, 74578, 41980, 0xd4920915
+1, 75600, 576, 0x05131eb0
+1, 77760, 576, 0x78151c22
+0, 78178, 7228, 0x1b141fa3
+1, 79920, 576, 0x31771239
+0, 81777, 7492, 0x1a47f3e4
+1, 82080, 576, 0x3ce4097c
+1, 84240, 576, 0x180e15f4
+0, 85378, 25068, 0xcb70a744
+1, 86400, 576, 0x30db0604
+1, 88560, 576, 0x9b290284
+0, 88978, 7212, 0x0ab9f558
+1, 90720, 576, 0xcf340753
+0, 92578, 7612, 0xa93054f0
+1, 92880, 576, 0xdaa41457
+1, 95040, 576, 0x34d310a2
+0, 96177, 22868, 0xa77db64a
+1, 97200, 576, 0x58b31010
+1, 99360, 576, 0x19610f54
+0, 99778, 6260, 0x6cf76411
+1, 101520, 576, 0x17762352
+0, 103377, 6156, 0xe168394b
+1, 103680, 576, 0x1fea1448
+1, 105840, 576, 0x55840a01
+0, 106977, 23364, 0x53164f1e
+1, 108000, 576, 0x6c9c24ce
+1, 110160, 576, 0x955f1e97
+0, 110578, 6708, 0x89877269
+1, 112320, 576, 0x2827134f
+0, 114178, 6908, 0x8d62a249
+1, 114480, 576, 0x34a01c29
+1, 116640, 576, 0x7d351e52
+0, 117778, 38156, 0xec41f682
+1, 118800, 576, 0x00c91d9e
+1, 120960, 576, 0x57ea1a97
+0, 121377, 5764, 0xcc04534b
+1, 123120, 576, 0xef3a1c74
+0, 124977, 5388, 0xb8a1c3c5
+1, 125280, 576, 0x11fc217d
+1, 127440, 576, 0x59ce20e5
+0, 128578, 16764, 0x59460d96
+1, 129600, 576, 0xaafc1dbf
+1, 131760, 576, 0xdd941609
+0, 132177, 5548, 0x5c91e93d
+1, 133920, 576, 0x900420b0
+0, 135777, 5652, 0x5e321aed
+1, 136080, 576, 0x5f4f1aa1
+1, 138240, 576, 0x7d7e18de
+0, 139377, 15564, 0xefdf5080
+1, 140400, 576, 0x986c0d9d
+1, 142560, 576, 0xcb4c21c0
+0, 142977, 6492, 0xd1d5c5f8
+1, 144720, 576, 0xbcfb1e8b
+0, 146577, 5604, 0xf9472b44
+1, 146880, 576, 0xcb541b4c
+1, 149040, 576, 0x980426e9
+0, 150177, 17924, 0x45815b7b
+1, 151200, 576, 0x09d00aa0
+1, 153360, 576, 0xad591374
+0, 153778, 5020, 0x3cc5e554
+1, 155520, 576, 0x97bf1461
+0, 157378, 5276, 0xa0554c12
+1, 157680, 576, 0xdc871cc4
+1, 159840, 576, 0x56781896
+0, 160977, 31460, 0x5765eb5f
+1, 162000, 576, 0xc77714e3
+1, 164160, 576, 0x280e18d4
+0, 164577, 4972, 0x91adbab7
+1, 166320, 576, 0xbc0d2302
+0, 168178, 5580, 0xfea707cb
+1, 168480, 576, 0x79191384
+1, 170640, 576, 0x65481c97
+0, 171778, 17412, 0x0afe4d27
+1, 172800, 576, 0xc94d227d
+1, 174960, 576, 0xa68a1f14
+0, 175378, 5236, 0x03f55309
+1, 177120, 576, 0x6af11a5c
+0, 178977, 4924, 0x558e753c
+1, 179280, 576, 0x4d1019ef
+1, 181440, 576, 0x3b1b17b5
+0, 182577, 15396, 0xf145d121
+1, 183600, 576, 0xcdd8159f
+1, 185760, 576, 0x97cd1d06
+0, 186177, 4708, 0x43066a92
+1, 187920, 576, 0x5d1b1123
+0, 189778, 4332, 0x9e22bcba
+1, 190080, 576, 0x888d0cb0
+1, 192240, 576, 0x556e1dad
+0, 193377, 12876, 0x46ff9ef4
+1, 194400, 576, 0xf7af0bce
+1, 196560, 576, 0xb5da160a
+0, 196978, 5940, 0x27cba62e
+1, 198720, 576, 0x4a8d0e98
+0, 200578, 6124, 0x6bab0a6d
+1, 200880, 576, 0x183b1c7e
+1, 203040, 576, 0xc47120e6
+0, 204178, 36428, 0x942f9648
+1, 205200, 576, 0xb1f31346
+0, 207777, 6660, 0x545a0db7
+0, 211377, 6780, 0x2d1d4189
+0, 214978, 16460, 0x7c3b3ca4
+0, 218578, 6724, 0x8538cc6f
+0, 222178, 7068, 0x69574fd0
+0, 225777, 19552, 0xf230e854
diff --git a/tests/ref/fate/xmv-demux b/tests/ref/fate/xmv-demux
new file mode 100644
index 0000000..887b855
--- /dev/null
+++ b/tests/ref/fate/xmv-demux
@@ -0,0 +1,181 @@
+0, 0, 1508, 0xefceba48
+1, 0, 5976, 0xfa2c2db9
+1, 10841, 5976, 0x256b935c
+1, 21682, 5976, 0xa78a9563
+1, 32522, 5976, 0x4ea056f4
+1, 43363, 5976, 0xda772d8d
+1, 54204, 5976, 0xafacf7c9
+0, 57600, 108, 0x06713c96
+0, 61200, 952, 0xd306df7e
+0, 64800, 2312, 0xaf316585
+1, 65045, 5976, 0xdeb003f4
+0, 68400, 3872, 0xfc1c527c
+0, 72000, 20, 0xaffc0edd
+0, 75600, 6600, 0xe1b66c7f
+1, 75886, 2016, 0xa7380d36
+0, 79200, 6868, 0xd5b3f631
+1, 79543, 2016, 0xbc090bac
+0, 82800, 8420, 0xf70ee33b
+1, 83200, 2016, 0x6f8c164c
+0, 86400, 13144, 0x9a54ef39
+1, 86857, 2016, 0x13b80e28
+0, 90000, 6340, 0xe55bf555
+1, 90514, 2016, 0xd40ff863
+0, 93600, 3736, 0x0b23f89f
+1, 94171, 2016, 0x4d530ed7
+0, 97200, 2624, 0x79e2e451
+1, 97829, 2160, 0x0fbc37eb
+0, 100800, 1860, 0x63886f11
+1, 101747, 13824, 0x82fb2602
+0, 104400, 1244, 0x74594601
+0, 108000, 564, 0xf4561dfb
+0, 111600, 80, 0xbf8e2e30
+0, 115200, 20, 0xa0990c29
+1, 126824, 13824, 0x08771caf
+1, 151902, 13824, 0xdf7d4a65
+1, 176980, 13896, 0x24bf3f47
+1, 202188, 3600, 0x9ad26b9f
+1, 208718, 3600, 0x8c666fd6
+1, 215249, 3600, 0x305c6ca1
+1, 221780, 3600, 0x48b04e1e
+0, 223200, 104, 0x12413980
+0, 226800, 796, 0x2e698ed3
+1, 228310, 3600, 0x8c915935
+0, 230400, 1808, 0x8b3e6e5e
+0, 234000, 4712, 0xdbd51737
+1, 234841, 3600, 0xa8f45e01
+0, 237600, 5548, 0xee9c831c
+0, 241200, 6152, 0x9c18ccc1
+1, 241371, 3816, 0xc64cc5ed
+0, 244800, 6452, 0x7860462a
+1, 248294, 1944, 0x0ac2e3f1
+0, 248400, 6676, 0xe1b1c9e4
+1, 251820, 1944, 0x2197dccd
+0, 252000, 10904, 0x0bded7b7
+1, 255347, 1944, 0x0c02e77f
+0, 255600, 12844, 0xe6d16cff
+1, 258873, 1944, 0x675ee06a
+0, 259200, 10920, 0xe114c46b
+1, 262400, 2160, 0x0d803a8b
+0, 262800, 5952, 0xb7464634
+1, 266318, 6696, 0xa7a0dfea
+0, 266400, 4732, 0x2fa2e36d
+0, 270000, 2592, 0xf54ddd57
+0, 273600, 1516, 0x4a1cd4d5
+0, 277200, 864, 0x49889afc
+1, 278465, 6696, 0x59aa3145
+0, 280800, 468, 0x3932e6a4
+0, 284400, 116, 0x2b8341e6
+0, 288000, 16, 0x6a3109cf
+1, 290612, 6696, 0x69be4d78
+1, 302759, 6696, 0x64064c67
+1, 314906, 6696, 0xc8536f98
+1, 327053, 6696, 0xc0ce5199
+1, 339200, 6768, 0x3b275c58
+1, 351478, 8856, 0x90e5b37c
+0, 360000, 1508, 0xefceba48
+1, 367543, 8856, 0x86b33366
+1, 383608, 8856, 0x19e18797
+1, 399673, 8856, 0x0a0c7fbd
+1, 415739, 8928, 0x4a9b2d42
+0, 417600, 100, 0x45023894
+0, 421200, 948, 0xa65ed345
+0, 424800, 2808, 0xd7285746
+0, 428400, 5372, 0x05794175
+1, 431935, 1512, 0xed8b3f4b
+0, 432000, 11596, 0x8636eca7
+1, 434678, 1512, 0xa27d3891
+0, 435600, 11524, 0xe1f39be3
+1, 437420, 1512, 0xb0f13eb6
+0, 439200, 23392, 0xab053f05
+1, 440163, 1656, 0xe5a98324
+0, 442800, 4560, 0x03197d07
+1, 443167, 2232, 0x15445433
+0, 446400, 4440, 0x1cc361a2
+1, 447216, 2232, 0x5cb348a9
+0, 450000, 23688, 0x16030634
+1, 451265, 2232, 0xf10347da
+0, 453600, 16132, 0xf0eca799
+1, 455314, 2448, 0x3e16a175
+0, 457200, 29896, 0x0c0988ea
+1, 459755, 2520, 0x17e3ca2b
+0, 460800, 19956, 0x0093aa0b
+1, 464327, 1944, 0x35c2de84
+0, 464400, 16392, 0x8829a9ca
+1, 467853, 1944, 0x55b4db40
+0, 468000, 16772, 0x9a4a546d
+1, 471380, 2088, 0xdaae14b2
+0, 471600, 8920, 0xcd8ca203
+1, 475167, 1944, 0x92ccd37f
+0, 475200, 9632, 0x53c1d37b
+1, 478694, 1944, 0x70efede1
+0, 478800, 8976, 0xfe4da2cc
+1, 482220, 1944, 0x7601d304
+0, 482400, 6680, 0x35348fe0
+1, 485747, 1944, 0x3922ebc2
+0, 486000, 9228, 0xcbf62b0c
+1, 489273, 2160, 0xde462f2e
+0, 489600, 5108, 0xd1d88511
+1, 493192, 1872, 0x467ac1d2
+0, 493200, 10016, 0xaff4b2b2
+1, 496588, 1872, 0xa1e4cd43
+0, 496800, 7468, 0x23e81ab8
+1, 499984, 1872, 0x1dceccc6
+0, 500400, 4172, 0x253cd05b
+1, 503380, 1872, 0x2bbad2a5
+0, 504000, 8188, 0x7ede743f
+1, 506776, 1872, 0xc603d44d
+0, 507600, 2884, 0x2dec55a3
+1, 510171, 1872, 0x1b4cc261
+0, 511200, 3900, 0xd0666a18
+1, 513567, 1872, 0x10edd6cf
+0, 514800, 2996, 0x9cc99b8c
+1, 516963, 2376, 0xecdb9d61
+0, 518400, 2156, 0xae612776
+1, 521273, 2592, 0x5559eced
+0, 522000, 3988, 0x0d2c9992
+0, 525600, 1512, 0x6281fc00
+1, 525976, 2592, 0x8848dfc7
+0, 529200, 6544, 0xb75c2562
+1, 530678, 2592, 0x4ca2d7da
+0, 532800, 4108, 0xfb21efc9
+1, 535380, 2592, 0x285fd7e6
+0, 536400, 1096, 0x85922a37
+0, 540000, 9740, 0xe57d7647
+1, 540082, 2592, 0x2717e404
+0, 543600, 416, 0x61c2ea02
+1, 544784, 2592, 0xf106111a
+0, 547200, 336, 0x1dc5ac1c
+1, 549486, 2592, 0xd7d01119
+0, 550800, 204, 0x16f57017
+1, 554188, 2592, 0x550cfeda
+0, 554400, 112, 0x78374234
+0, 558000, 40, 0x6cb21985
+1, 558890, 2592, 0x47ad00c4
+1, 563592, 2592, 0x39bbf306
+1, 568294, 3240, 0x69addfce
+1, 574171, 21384, 0x254f63e0
+1, 612963, 21456, 0x2f7a9859
+0, 615600, 14420, 0x53324ca4
+0, 619200, 40, 0x10971420
+1, 651886, 37512, 0x6e962928
+1, 719935, 2736, 0x1dc91c69
+0, 720000, 24904, 0x15574f7e
+1, 724898, 2736, 0x023434fd
+1, 729861, 2736, 0x906f1541
+0, 734400, 1908, 0xccb2dd3c
+1, 734824, 2736, 0x85a31102
+0, 738000, 4676, 0xbfa42b7e
+1, 739788, 3024, 0x9296a5f3
+0, 741600, 3600, 0x87c9dc58
+0, 745200, 8184, 0x504a8e65
+1, 745273, 1944, 0x7bf4dedc
+0, 748800, 9636, 0x2efb3006
+1, 748800, 1944, 0x4196c404
+1, 752327, 1944, 0xcda97c7a
+0, 752400, 9580, 0x0fb6f4e8
+1, 755853, 1944, 0x5f4922b2
+0, 756000, 7840, 0xe996f564
+1, 759380, 2088, 0x37dfc157
+0, 759600, 4208, 0xe9c2fba2
+0, 763200, 556, 0x3f1e077c
diff --git a/tests/ref/fate/xwma-demux b/tests/ref/fate/xwma-demux
new file mode 100644
index 0000000..83a3b08
--- /dev/null
+++ b/tests/ref/fate/xwma-demux
@@ -0,0 +1 @@
+CRC=0x2ac2159e
diff --git a/tests/ref/fate/xxan-wc4 b/tests/ref/fate/xxan-wc4
index d31fbb6..7fede0a 100644
--- a/tests/ref/fate/xxan-wc4
+++ b/tests/ref/fate/xxan-wc4
@@ -1,10 +1,21 @@
-0, 0, 79360, 0x877eb3ed
-0, 6000, 79360, 0x9ff8707c
-0, 12000, 79360, 0x144dec86
-0, 18000, 79360, 0x56d59588
-0, 24000, 79360, 0x2d20f8ce
-0, 30000, 79360, 0x1a752c42
-0, 36000, 79360, 0x85705730
-0, 42000, 79360, 0xddea3741
-0, 48000, 79360, 0x46448efd
-0, 54000, 79360, 0x27186e2b
+0, 0, 79360, 0x3b0a7d1b
+0, 6000, 79360, 0x740842c3
+0, 12000, 79360, 0x85160167
+0, 18000, 79360, 0xaf510e92
+0, 24000, 79360, 0x8e290bec
+0, 30000, 79360, 0x51e981b0
+0, 36000, 79360, 0x16e52c60
+0, 42000, 79360, 0x66e1e60a
+0, 48000, 79360, 0x40fa58f6
+0, 54000, 79360, 0x00388edd
+0, 60000, 79360, 0xc74f95bf
+0, 66000, 79360, 0xf446a3fd
+0, 72000, 79360, 0x27b5eb60
+0, 78000, 79360, 0xea9266a2
+0, 84000, 79360, 0x7b6a7907
+0, 90000, 79360, 0x2be7d946
+0, 96000, 79360, 0x61881ee4
+0, 102000, 79360, 0x9214bd4f
+0, 108000, 79360, 0xeb294afe
+0, 114000, 79360, 0xc861ad55
+0, 120000, 79360, 0x3d3b6220
diff --git a/tests/ref/lavf/mov b/tests/ref/lavf/mov
index f51b42d..a4ae2d5 100644
--- a/tests/ref/lavf/mov
+++ b/tests/ref/lavf/mov
@@ -1,3 +1,3 @@
-8dc82a08a0abb47c822d03a6e408383b *./tests/data/lavf/lavf.mov
+6c5472152b46e070ae6da359838e1f86 *./tests/data/lavf/lavf.mov
 357717 ./tests/data/lavf/lavf.mov
 ./tests/data/lavf/lavf.mov CRC=0x2f6a9b26
diff --git a/tests/ref/lavfi/pixdesc b/tests/ref/lavfi/pixdesc
index a5016ee..5dfa270 100644
--- a/tests/ref/lavfi/pixdesc
+++ b/tests/ref/lavfi/pixdesc
@@ -1,6 +1,8 @@
 abgr                037bf9df6a765520ad6d490066bf4b89
 argb                c442a8261c2265a07212ef0f72e35f5a
 bgr24               0d0cb38ab3fa0b2ec0865c14f78b217b
+bgr444be            d9ea9307d21b162225b8b2c524cf9477
+bgr444le            88035350e9da3a8f67387890b956f0bc
 bgr48be             00624e6c7ec7ab19897ba2f0a3257fe8
 bgr48le             d02c235ebba7167881ca2d576497ff84
 bgr4_byte           50d23cc82d9dcef2fd12adb81fb9b806
@@ -18,6 +20,8 @@ monow               9251497f3b0634f1165d12d5a289d943
 nv12                e0af357888584d36eec5aa0f673793ef
 nv21                9a3297f3b34baa038b1f37cb202b512f
 rgb24               b41eba9651e1b5fe386289b506188105
+rgb444be            9e89db334568c6b2e3d5d0540f4ba960
+rgb444le            0a68cb6de8bf530aa30c5c1205c25155
 rgb48be             cc139ec1dd9451f0e049c0cb3a0c8aa2
 rgb48le             86c5608904f75360d492dbc5c9589969
 rgb4_byte           c93ba89b74c504e7f5ae9d9ab1546c73
diff --git a/tests/ref/lavfi/pixfmts_copy b/tests/ref/lavfi/pixfmts_copy
index a5016ee..5dfa270 100644
--- a/tests/ref/lavfi/pixfmts_copy
+++ b/tests/ref/lavfi/pixfmts_copy
@@ -1,6 +1,8 @@
 abgr                037bf9df6a765520ad6d490066bf4b89
 argb                c442a8261c2265a07212ef0f72e35f5a
 bgr24               0d0cb38ab3fa0b2ec0865c14f78b217b
+bgr444be            d9ea9307d21b162225b8b2c524cf9477
+bgr444le            88035350e9da3a8f67387890b956f0bc
 bgr48be             00624e6c7ec7ab19897ba2f0a3257fe8
 bgr48le             d02c235ebba7167881ca2d576497ff84
 bgr4_byte           50d23cc82d9dcef2fd12adb81fb9b806
@@ -18,6 +20,8 @@ monow               9251497f3b0634f1165d12d5a289d943
 nv12                e0af357888584d36eec5aa0f673793ef
 nv21                9a3297f3b34baa038b1f37cb202b512f
 rgb24               b41eba9651e1b5fe386289b506188105
+rgb444be            9e89db334568c6b2e3d5d0540f4ba960
+rgb444le            0a68cb6de8bf530aa30c5c1205c25155
 rgb48be             cc139ec1dd9451f0e049c0cb3a0c8aa2
 rgb48le             86c5608904f75360d492dbc5c9589969
 rgb4_byte           c93ba89b74c504e7f5ae9d9ab1546c73
diff --git a/tests/ref/lavfi/pixfmts_null b/tests/ref/lavfi/pixfmts_null
index a5016ee..5dfa270 100644
--- a/tests/ref/lavfi/pixfmts_null
+++ b/tests/ref/lavfi/pixfmts_null
@@ -1,6 +1,8 @@
 abgr                037bf9df6a765520ad6d490066bf4b89
 argb                c442a8261c2265a07212ef0f72e35f5a
 bgr24               0d0cb38ab3fa0b2ec0865c14f78b217b
+bgr444be            d9ea9307d21b162225b8b2c524cf9477
+bgr444le            88035350e9da3a8f67387890b956f0bc
 bgr48be             00624e6c7ec7ab19897ba2f0a3257fe8
 bgr48le             d02c235ebba7167881ca2d576497ff84
 bgr4_byte           50d23cc82d9dcef2fd12adb81fb9b806
@@ -18,6 +20,8 @@ monow               9251497f3b0634f1165d12d5a289d943
 nv12                e0af357888584d36eec5aa0f673793ef
 nv21                9a3297f3b34baa038b1f37cb202b512f
 rgb24               b41eba9651e1b5fe386289b506188105
+rgb444be            9e89db334568c6b2e3d5d0540f4ba960
+rgb444le            0a68cb6de8bf530aa30c5c1205c25155
 rgb48be             cc139ec1dd9451f0e049c0cb3a0c8aa2
 rgb48le             86c5608904f75360d492dbc5c9589969
 rgb4_byte           c93ba89b74c504e7f5ae9d9ab1546c73
diff --git a/tests/ref/lavfi/pixfmts_scale b/tests/ref/lavfi/pixfmts_scale
index 7abe0d7..4a5bf67 100644
--- a/tests/ref/lavfi/pixfmts_scale
+++ b/tests/ref/lavfi/pixfmts_scale
@@ -1,6 +1,8 @@
 abgr                d894cb97f6c80eb21bdbe8a4eea62d86
 argb                54346f2b2eef10919e0f247241df3b24
 bgr24               570f8d6b51a838aed022ef67535f6bdc
+bgr444be            25fe04f73a3bad4140d1c4f96ca5b670
+bgr444le            2fde227e6cea6dca5decdd0b7c0866f7
 bgr48be             390d3058a12a99c2b153ed7922508bea
 bgr48le             39fe06feb4ec1d9730dccc04a0cfac4c
 bgr4_byte           ee1d35a7baf8e9016891929a2f565c0b
@@ -18,6 +20,8 @@ monow               d31772ebaa877fc2a78565937f7f9673
 nv12                4676d59db43d657dc12841f6bc3ab452
 nv21                69c699510ff1fb777b118ebee1002f14
 rgb24               514692e28e8ff6860e415ce4fcf6eb8c
+rgb444be            12254053ae93373869fca18b2afcba31
+rgb444le            badbd68b59c87df6ae73248309637634
 rgb48be             8fac63787a711886030f8e056872b488
 rgb48le             ab92f2763a2eb264c3870cc758f97149
 rgb4_byte           d81ffd3add95842a618eec81024f0b5c
diff --git a/tests/ref/lavfi/pixfmts_vflip b/tests/ref/lavfi/pixfmts_vflip
index e834394..f21927b 100644
--- a/tests/ref/lavfi/pixfmts_vflip
+++ b/tests/ref/lavfi/pixfmts_vflip
@@ -1,6 +1,8 @@
 abgr                25e72e9dbd01ab00727c976d577f7be5
 argb                19869bf1a5ac0b6af4d8bbe2c104533c
 bgr24               89108a4ba00201f79b75b9305c42352d
+bgr444be            9ef12c42fb791948ca4423c452dc6b9a
+bgr444le            3650ecfc163abd1596c0cd29d130c4b0
 bgr48be             2f23931844f57641f3737348182d118c
 bgr48le             4242a026012b6c135a6aa138a6d67031
 bgr4_byte           407fcf564ed764c38e1d748f700ab921
@@ -18,6 +20,8 @@ monow               ff9869d067ecb94eb9d90c9750c31fea
 nv12                046f00f598ce14d9854a3534a5c99114
 nv21                01ea369dd2d0d3ed7451dc5c8d61497f
 rgb24               eaefabc168d0b14576bab45bc1e56e1e
+rgb444be            06722e03f8404e7d2226665ed2444a32
+rgb444le            185c9a5d9c2877484310d4196ef4cd6f
 rgb48be             62dd185862ed142283bd300eb6dbd216
 rgb48le             dcb76353268bc5862194d131762220da
 rgb4_byte           8c6ff02df0b06dd2d574836c3741b2a2
diff --git a/tests/ref/vsynth1/dnxhd_1080i b/tests/ref/vsynth1/dnxhd_1080i
index 80484b5..e989eae 100644
--- a/tests/ref/vsynth1/dnxhd_1080i
+++ b/tests/ref/vsynth1/dnxhd_1080i
@@ -1,4 +1,4 @@
-34949ea38da2cf6a8406ad600ad95cfa *./tests/data/vsynth1/dnxhd-1080i.mov
+3cfbe36a7dd5b48859b8a569d626ef77 *./tests/data/vsynth1/dnxhd-1080i.mov
 3031875 ./tests/data/vsynth1/dnxhd-1080i.mov
 0c651e840f860592f0d5b66030d9fa32 *./tests/data/dnxhd_1080i.vsynth1.out.yuv
 stddev:    6.29 PSNR: 32.15 MAXDIFF:   64 bytes:   760320/  7603200
diff --git a/tests/ref/vsynth1/mpeg4 b/tests/ref/vsynth1/mpeg4
index 133e228..b318e6f 100644
--- a/tests/ref/vsynth1/mpeg4
+++ b/tests/ref/vsynth1/mpeg4
@@ -1,4 +1,4 @@
-9251145d12150cb639098016d61fc75e *./tests/data/vsynth1/odivx.mp4
+59a9e2eed314abface66aaf1b45eb8f2 *./tests/data/vsynth1/odivx.mp4
 540180 ./tests/data/vsynth1/odivx.mp4
 8828a375448dc5c2215163ba70656f89 *./tests/data/mpeg4.vsynth1.out.yuv
 stddev:    7.97 PSNR: 30.10 MAXDIFF:  105 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/qtrle b/tests/ref/vsynth1/qtrle
index 9988897..002ee49 100644
--- a/tests/ref/vsynth1/qtrle
+++ b/tests/ref/vsynth1/qtrle
@@ -1,4 +1,4 @@
-d14041925ce5ec5001dc519276b1a1ab *./tests/data/vsynth1/qtrle.mov
+7d75328a17e04796a39fe9be3a322946 *./tests/data/vsynth1/qtrle.mov
 15263232 ./tests/data/vsynth1/qtrle.mov
 243325fb2cae1a9245efd49aff936327 *./tests/data/qtrle.vsynth1.out.yuv
 stddev:    3.42 PSNR: 37.43 MAXDIFF:   48 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth1/svq1 b/tests/ref/vsynth1/svq1
index 8c647c7..3137e3b 100644
--- a/tests/ref/vsynth1/svq1
+++ b/tests/ref/vsynth1/svq1
@@ -1,4 +1,4 @@
-595fc4e38734521356b60e67b813f0fa *./tests/data/vsynth1/svq1.mov
+5c9d8734693f3cab57f61e76b5b6da7d *./tests/data/vsynth1/svq1.mov
 1334367 ./tests/data/vsynth1/svq1.mov
 9cc35c54b2c77d36bd7e308b393c1f81 *./tests/data/svq1.vsynth1.out.yuv
 stddev:    9.58 PSNR: 28.50 MAXDIFF:  210 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/dnxhd_1080i b/tests/ref/vsynth2/dnxhd_1080i
index ae98846..b9a6fac 100644
--- a/tests/ref/vsynth2/dnxhd_1080i
+++ b/tests/ref/vsynth2/dnxhd_1080i
@@ -1,4 +1,4 @@
-995e433cd076e3c1534fa73181744a84 *./tests/data/vsynth2/dnxhd-1080i.mov
+19a91b7da35cecf41e5e3cb322485627 *./tests/data/vsynth2/dnxhd-1080i.mov
 3031875 ./tests/data/vsynth2/dnxhd-1080i.mov
 3c559af629ae0a8fb1a9a0e4b4da7733 *./tests/data/dnxhd_1080i.vsynth2.out.yuv
 stddev:    1.31 PSNR: 45.77 MAXDIFF:   23 bytes:   760320/  7603200
diff --git a/tests/ref/vsynth2/mpeg4 b/tests/ref/vsynth2/mpeg4
index b89a3ec..8ccab86 100644
--- a/tests/ref/vsynth2/mpeg4
+++ b/tests/ref/vsynth2/mpeg4
@@ -1,4 +1,4 @@
-c2ca709a0ed64833fd38f703b19e5e85 *./tests/data/vsynth2/odivx.mp4
+8c9afbf564008a8ce6719cc3546deae1 *./tests/data/vsynth2/odivx.mp4
 119833 ./tests/data/vsynth2/odivx.mp4
 90a3577850239083a9042bef33c50e85 *./tests/data/mpeg4.vsynth2.out.yuv
 stddev:    5.34 PSNR: 33.57 MAXDIFF:   83 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/qtrle b/tests/ref/vsynth2/qtrle
index 6b2a011..5dd0425 100644
--- a/tests/ref/vsynth2/qtrle
+++ b/tests/ref/vsynth2/qtrle
@@ -1,4 +1,4 @@
-d8c1604dc46d9aa4ec0385e6722c6989 *./tests/data/vsynth2/qtrle.mov
+4805f35ca6e03b9279cc18f3f7356366 *./tests/data/vsynth2/qtrle.mov
 14798419 ./tests/data/vsynth2/qtrle.mov
 b2418e0e3a9a8619b31219cbcf24dc82 *./tests/data/qtrle.vsynth2.out.yuv
 stddev:    1.26 PSNR: 46.06 MAXDIFF:   13 bytes:  7603200/  7603200
diff --git a/tests/ref/vsynth2/svq1 b/tests/ref/vsynth2/svq1
index 7c54c74..8adca64 100644
--- a/tests/ref/vsynth2/svq1
+++ b/tests/ref/vsynth2/svq1
@@ -1,4 +1,4 @@
-7f9fbe4890bc1df67867bf03803dca48 *./tests/data/vsynth2/svq1.mov
+138ad38281570f1a3b68d63ed896435d *./tests/data/vsynth2/svq1.mov
 766851 ./tests/data/vsynth2/svq1.mov
 aa03471dac3f49455a33a2b19fda1098 *./tests/data/svq1.vsynth2.out.yuv
 stddev:    3.23 PSNR: 37.93 MAXDIFF:   61 bytes:  7603200/  7603200
diff --git a/tools/patcheck b/tools/patcheck
index ae2c80b..3061716 100755
--- a/tools/patcheck
+++ b/tools/patcheck
@@ -67,7 +67,7 @@ $EGREP $OPT '^\+ *(const *|)static' $*| $EGREP --color=always '[^=]= *(0|NULL)[^
 cat $TMP
 hiegrep '# *ifdef * (HAVE|CONFIG)_' 'ifdefs that should be #if' $*
 
-hiegrep '\b(awnser|cant|dont|wont|usefull|successfull|occured|teh|alot|wether|skiped|heigth|informations|colums|loosy|loosing|seperate|preceed)\b' 'common typos' $*
+hiegrep '\b(awnser|cant|dont|wont|usefull|successfull|occured|teh|alot|wether|skiped|heigth|informations|colums|loosy|loosing|seperate|preceed|upto|paket)\b' 'common typos' $*
 
 hiegrep 'av_log\( *NULL' 'Missing context in av_log' $*
 hiegrep '[^sn]printf' 'Please use av_log' $*

-- 
Libav/FFmpeg packaging



More information about the pkg-multimedia-commits mailing list