]> git.sesse.net Git - ffmpeg/commitdiff
Merge commit 'd1dd0d404c085f4fce7b8358b4aea677761c5d88'
authorMichael Niedermayer <michaelni@gmx.at>
Wed, 10 Jun 2015 18:58:26 +0000 (20:58 +0200)
committerMichael Niedermayer <michaelni@gmx.at>
Wed, 10 Jun 2015 18:58:32 +0000 (20:58 +0200)
* commit 'd1dd0d404c085f4fce7b8358b4aea677761c5d88':
  mpegvideo: Move block permutation function where is used

Merged-by: Michael Niedermayer <michaelni@gmx.at>
1  2 
libavcodec/mpegvideo.c
libavcodec/mpegvideo.h
libavcodec/mpegvideo_enc.c

diff --combined libavcodec/mpegvideo.c
index b653d47530330e78aefcad9d53804e45d4f52526,68f95685d1e4790beede1584a50dd3fd781ab166..420d73f85e572080a1e7fbd6d9365850ec7feb22
@@@ -5,20 -5,20 +5,20 @@@
   *
   * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
  #include "libavutil/avassert.h"
  #include "libavutil/imgutils.h"
  #include "libavutil/internal.h"
 +#include "libavutil/motion_vector.h"
  #include "libavutil/timer.h"
  #include "avcodec.h"
  #include "blockdsp.h"
 +#include "h264chroma.h"
  #include "idctdsp.h"
  #include "internal.h"
  #include "mathops.h"
@@@ -45,6 -43,7 +45,6 @@@
  #include "mjpegenc.h"
  #include "msmpeg4.h"
  #include "qpeldsp.h"
 -#include "xvmc_internal.h"
  #include "thread.h"
  #include "wmv2.h"
  #include <limits.h>
@@@ -57,7 -56,10 +57,7 @@@ static void dct_unquantize_mpeg1_intra_
  
      nCoeffs= s->block_last_index[n];
  
 -    if (n < 4)
 -        block[0] = block[0] * s->y_dc_scale;
 -    else
 -        block[0] = block[0] * s->c_dc_scale;
 +    block[0] *= n < 4 ? s->y_dc_scale : s->c_dc_scale;
      /* XXX: only mpeg1 */
      quant_matrix = s->intra_matrix;
      for(i=1;i<=nCoeffs;i++) {
@@@ -116,7 -118,10 +116,7 @@@ static void dct_unquantize_mpeg2_intra_
      if(s->alternate_scan) nCoeffs= 63;
      else nCoeffs= s->block_last_index[n];
  
 -    if (n < 4)
 -        block[0] = block[0] * s->y_dc_scale;
 -    else
 -        block[0] = block[0] * s->c_dc_scale;
 +    block[0] *= n < 4 ? s->y_dc_scale : s->c_dc_scale;
      quant_matrix = s->intra_matrix;
      for(i=1;i<=nCoeffs;i++) {
          int j= s->intra_scantable.permutated[i];
@@@ -144,8 -149,10 +144,8 @@@ static void dct_unquantize_mpeg2_intra_
      if(s->alternate_scan) nCoeffs= 63;
      else nCoeffs= s->block_last_index[n];
  
 -    if (n < 4)
 -        block[0] = block[0] * s->y_dc_scale;
 -    else
 -        block[0] = block[0] * s->c_dc_scale;
 +    block[0] *= n < 4 ? s->y_dc_scale : s->c_dc_scale;
 +    sum += block[0];
      quant_matrix = s->intra_matrix;
      for(i=1;i<=nCoeffs;i++) {
          int j= s->intra_scantable.permutated[i];
@@@ -202,12 -209,15 +202,12 @@@ static void dct_unquantize_h263_intra_c
      int i, level, qmul, qadd;
      int nCoeffs;
  
 -    assert(s->block_last_index[n]>=0);
 +    av_assert2(s->block_last_index[n]>=0 || s->h263_aic);
  
      qmul = qscale << 1;
  
      if (!s->h263_aic) {
 -        if (n < 4)
 -            block[0] = block[0] * s->y_dc_scale;
 -        else
 -            block[0] = block[0] * s->c_dc_scale;
 +        block[0] *= n < 4 ? s->y_dc_scale : s->c_dc_scale;
          qadd = (qscale - 1) | 1;
      }else{
          qadd = 0;
@@@ -236,7 -246,7 +236,7 @@@ static void dct_unquantize_h263_inter_c
      int i, level, qmul, qadd;
      int nCoeffs;
  
 -    assert(s->block_last_index[n]>=0);
 +    av_assert2(s->block_last_index[n]>=0);
  
      qadd = (qscale - 1) | 1;
      qmul = qscale << 1;
@@@ -285,40 -295,14 +285,40 @@@ static void mpeg_er_decode_mb(void *opa
      ff_mpv_decode_mb(s, s->block);
  }
  
 +static void gray16(uint8_t *dst, const uint8_t *src, ptrdiff_t linesize, int h)
 +{
 +    while(h--)
 +        memset(dst + h*linesize, 128, 16);
 +}
 +
 +static void gray8(uint8_t *dst, const uint8_t *src, ptrdiff_t linesize, int h)
 +{
 +    while(h--)
 +        memset(dst + h*linesize, 128, 8);
 +}
 +
  /* init common dct for both encoder and decoder */
  static av_cold int dct_init(MpegEncContext *s)
  {
      ff_blockdsp_init(&s->bdsp, s->avctx);
 +    ff_h264chroma_init(&s->h264chroma, 8); //for lowres
      ff_hpeldsp_init(&s->hdsp, s->avctx->flags);
      ff_mpegvideodsp_init(&s->mdsp);
      ff_videodsp_init(&s->vdsp, s->avctx->bits_per_raw_sample);
  
 +    if (s->avctx->debug & FF_DEBUG_NOMC) {
 +        int i;
 +        for (i=0; i<4; i++) {
 +            s->hdsp.avg_pixels_tab[0][i] = gray16;
 +            s->hdsp.put_pixels_tab[0][i] = gray16;
 +            s->hdsp.put_no_rnd_pixels_tab[0][i] = gray16;
 +
 +            s->hdsp.avg_pixels_tab[1][i] = gray8;
 +            s->hdsp.put_pixels_tab[1][i] = gray8;
 +            s->hdsp.put_no_rnd_pixels_tab[1][i] = gray8;
 +        }
 +    }
 +
      s->dct_unquantize_h263_intra = dct_unquantize_h263_intra_c;
      s->dct_unquantize_h263_inter = dct_unquantize_h263_inter_c;
      s->dct_unquantize_mpeg1_intra = dct_unquantize_mpeg1_intra_c;
      if (HAVE_INTRINSICS_NEON)
          ff_mpv_common_init_neon(s);
  
 +    if (ARCH_ALPHA)
 +        ff_mpv_common_init_axp(s);
      if (ARCH_ARM)
          ff_mpv_common_init_arm(s);
      if (ARCH_PPC)
@@@ -365,7 -347,7 +365,7 @@@ static int alloc_picture(MpegEncContex
  {
      return ff_alloc_picture(s->avctx, pic, &s->me, &s->sc, shared, 0,
                              s->chroma_x_shift, s->chroma_y_shift, s->out_format,
 -                            s->mb_stride, s->mb_height, s->b8_stride,
 +                            s->mb_stride, s->mb_width, s->mb_height, s->b8_stride,
                              &s->linesize, &s->uvlinesize);
  }
  
@@@ -376,9 -358,6 +376,9 @@@ static int init_duplicate_context(MpegE
      int yc_size = y_size + 2 * c_size;
      int i;
  
 +    if (s->mb_height & 1)
 +        yc_size += 2*s->b8_stride + 2*s->mb_stride;
 +
      s->sc.edge_emu_buffer =
      s->me.scratchpad   =
      s->me.temp         =
      }
      if (s->avctx->codec_tag == AV_RL32("VCR2")) {
          // exchange uv
 -        int16_t (*tmp)[64];
 -        tmp           = s->pblocks[4];
 -        s->pblocks[4] = s->pblocks[5];
 -        s->pblocks[5] = tmp;
 +        FFSWAP(void *, s->pblocks[4], s->pblocks[5]);
      }
  
      if (s->out_format == FMT_H263) {
@@@ -482,7 -464,10 +482,7 @@@ int ff_update_duplicate_context(MpegEnc
      }
      if (dst->avctx->codec_tag == AV_RL32("VCR2")) {
          // exchange uv
 -        int16_t (*tmp)[64];
 -        tmp             = dst->pblocks[4];
 -        dst->pblocks[4] = dst->pblocks[5];
 -        dst->pblocks[5] = tmp;
 +        FFSWAP(void *, dst->pblocks[4], dst->pblocks[5]);
      }
      if (!dst->sc.edge_emu_buffer &&
          (ret = ff_mpeg_framesize_alloc(dst->avctx, &dst->me,
@@@ -502,11 -487,9 +502,11 @@@ int ff_mpeg_update_thread_context(AVCod
      int i, ret;
      MpegEncContext *s = dst->priv_data, *s1 = src->priv_data;
  
 -    if (dst == src || !s1->context_initialized)
 +    if (dst == src)
          return 0;
  
 +    av_assert0(s != s1);
 +
      // FIXME can parameters change on I-frames?
      // in that case dst may need a reinit
      if (!s->context_initialized) {
          s->bitstream_buffer      = NULL;
          s->bitstream_buffer_size = s->allocated_bitstream_buffer_size = 0;
  
 -        ff_mpv_idct_init(s);
 -        if ((err = ff_mpv_common_init(s)) < 0)
 -            return err;
 +        if (s1->context_initialized){
 +//             s->picture_range_start  += MAX_PICTURE_COUNT;
 +//             s->picture_range_end    += MAX_PICTURE_COUNT;
 +            ff_mpv_idct_init(s);
 +            if((err = ff_mpv_common_init(s)) < 0){
 +                memset(s, 0, sizeof(MpegEncContext));
 +                s->avctx = dst;
 +                return err;
 +            }
 +        }
      }
  
      if (s->height != s1->height || s->width != s1->width || s->context_reinit) {
 -        int err;
          s->context_reinit = 0;
          s->height = s1->height;
          s->width  = s1->width;
 -        if ((err = ff_mpv_common_frame_size_change(s)) < 0)
 -            return err;
 +        if ((ret = ff_mpv_common_frame_size_change(s)) < 0)
 +            return ret;
      }
  
      s->avctx->coded_height  = s1->avctx->coded_height;
      s->coded_picture_number = s1->coded_picture_number;
      s->picture_number       = s1->picture_number;
  
 +    av_assert0(!s->picture || s->picture != s1->picture);
 +    if(s->picture)
      for (i = 0; i < MAX_PICTURE_COUNT; i++) {
          ff_mpeg_unref_picture(s->avctx, &s->picture[i]);
          if (s1->picture[i].f->buf[0] &&
  #define UPDATE_PICTURE(pic)\
  do {\
      ff_mpeg_unref_picture(s->avctx, &s->pic);\
 -    if (s1->pic.f->buf[0])\
 +    if (s1->pic.f && s1->pic.f->buf[0])\
          ret = ff_mpeg_ref_picture(s->avctx, &s->pic, &s1->pic);\
      else\
          ret = ff_update_picture_tables(&s->pic, &s1->pic);\
      // Error/bug resilience
      s->next_p_frame_damaged = s1->next_p_frame_damaged;
      s->workaround_bugs      = s1->workaround_bugs;
 +    s->padding_bug_score    = s1->padding_bug_score;
  
      // MPEG4 timing info
      memcpy(&s->last_time_base, &s1->last_time_base,
  
      if (s1->bitstream_buffer) {
          if (s1->bitstream_buffer_size +
 -            FF_INPUT_BUFFER_PADDING_SIZE > s->allocated_bitstream_buffer_size)
 +            FF_INPUT_BUFFER_PADDING_SIZE > s->allocated_bitstream_buffer_size) {
              av_fast_malloc(&s->bitstream_buffer,
                             &s->allocated_bitstream_buffer_size,
                             s1->allocated_bitstream_buffer_size);
 -            s->bitstream_buffer_size = s1->bitstream_buffer_size;
 +            if (!s->bitstream_buffer) {
 +                s->bitstream_buffer_size = 0;
 +                return AVERROR(ENOMEM);
 +            }
 +        }
 +        s->bitstream_buffer_size = s1->bitstream_buffer_size;
          memcpy(s->bitstream_buffer, s1->bitstream_buffer,
                 s1->bitstream_buffer_size);
          memset(s->bitstream_buffer + s->bitstream_buffer_size, 0,
          } else {
              av_log(s->avctx, AV_LOG_ERROR, "Context scratch buffers could not "
                     "be allocated due to unknown size.\n");
 -            return AVERROR_BUG;
          }
  
      // MPEG2/interlacing info
@@@ -675,18 -645,6 +675,18 @@@ void ff_mpv_decode_defaults(MpegEncCont
      ff_mpv_common_defaults(s);
  }
  
 +void ff_mpv_decode_init(MpegEncContext *s, AVCodecContext *avctx)
 +{
 +    s->avctx           = avctx;
 +    s->width           = avctx->coded_width;
 +    s->height          = avctx->coded_height;
 +    s->codec_id        = avctx->codec->id;
 +    s->workaround_bugs = avctx->workaround_bugs;
 +
 +    /* convert fourcc to upper case */
 +    s->codec_tag          = avpriv_toupper4(avctx->codec_tag);
 +}
 +
  static int init_er(MpegEncContext *s)
  {
      ERContext *er = &s->er;
@@@ -736,7 -694,7 +736,7 @@@ static int init_context_frame(MpegEncCo
      mb_array_size = s->mb_height * s->mb_stride;
      mv_table_size = (s->mb_height + 2) * s->mb_stride + 1;
  
 -    /* set default edge pos, will be overriden
 +    /* set default edge pos, will be overridden
       * in decode_header if needed */
      s->h_edge_pos = s->mb_width * 16;
      s->v_edge_pos = s->mb_height * 16;
      c_size  = s->mb_stride * (s->mb_height + 1);
      yc_size = y_size + 2   * c_size;
  
 -    FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_index2xy, (s->mb_num + 1) * sizeof(int),
 -                      fail); // error ressilience code looks cleaner with this
 +    if (s->mb_height & 1)
 +        yc_size += 2*s->b8_stride + 2*s->mb_stride;
 +
 +    FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_index2xy, (s->mb_num + 1) * sizeof(int), fail); // error ressilience code looks cleaner with this
      for (y = 0; y < s->mb_height; y++)
          for (x = 0; x < s->mb_width; x++)
              s->mb_index2xy[x + y * s->mb_width] = x + y * s->mb_stride;
  
 -    s->mb_index2xy[s->mb_height * s->mb_width] =
 -        (s->mb_height - 1) * s->mb_stride + s->mb_width; // FIXME really needed?
 +    s->mb_index2xy[s->mb_height * s->mb_width] = (s->mb_height - 1) * s->mb_stride + s->mb_width; // FIXME really needed?
  
      if (s->encoding) {
          /* Allocate MV tables */
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->p_mv_table_base,
 -                          mv_table_size * 2 * sizeof(int16_t), fail);
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_forw_mv_table_base,
 -                          mv_table_size * 2 * sizeof(int16_t), fail);
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_back_mv_table_base,
 -                          mv_table_size * 2 * sizeof(int16_t), fail);
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_forw_mv_table_base,
 -                          mv_table_size * 2 * sizeof(int16_t), fail);
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_back_mv_table_base,
 -                          mv_table_size * 2 * sizeof(int16_t), fail);
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_direct_mv_table_base,
 -                          mv_table_size * 2 * sizeof(int16_t), fail);
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->p_mv_table_base,                 mv_table_size * 2 * sizeof(int16_t), fail)
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_forw_mv_table_base,            mv_table_size * 2 * sizeof(int16_t), fail)
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_back_mv_table_base,            mv_table_size * 2 * sizeof(int16_t), fail)
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_forw_mv_table_base,      mv_table_size * 2 * sizeof(int16_t), fail)
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_bidir_back_mv_table_base,      mv_table_size * 2 * sizeof(int16_t), fail)
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->b_direct_mv_table_base,          mv_table_size * 2 * sizeof(int16_t), fail)
          s->p_mv_table            = s->p_mv_table_base + s->mb_stride + 1;
          s->b_forw_mv_table       = s->b_forw_mv_table_base + s->mb_stride + 1;
          s->b_back_mv_table       = s->b_back_mv_table_base + s->mb_stride + 1;
 -        s->b_bidir_forw_mv_table = s->b_bidir_forw_mv_table_base +
 -                                   s->mb_stride + 1;
 -        s->b_bidir_back_mv_table = s->b_bidir_back_mv_table_base +
 -                                   s->mb_stride + 1;
 +        s->b_bidir_forw_mv_table = s->b_bidir_forw_mv_table_base + s->mb_stride + 1;
 +        s->b_bidir_back_mv_table = s->b_bidir_back_mv_table_base + s->mb_stride + 1;
          s->b_direct_mv_table     = s->b_direct_mv_table_base + s->mb_stride + 1;
  
          /* Allocate MB type table */
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_type, mb_array_size *
 -                          sizeof(uint16_t), fail); // needed for encoding
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->mb_type, mb_array_size * sizeof(uint16_t), fail) // needed for encoding
  
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->lambda_table, mb_array_size *
 -                          sizeof(int), fail);
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->lambda_table, mb_array_size * sizeof(int), fail)
  
          FF_ALLOC_OR_GOTO(s->avctx, s->cplx_tab,
                           mb_array_size * sizeof(float), fail);
                      s->b_field_mv_table[i][j][k] = s->b_field_mv_table_base[i][j][k] +
                                                     s->mb_stride + 1;
                  }
 -                FF_ALLOCZ_OR_GOTO(s->avctx, s->b_field_select_table [i][j],
 -                                  mb_array_size * 2 * sizeof(uint8_t), fail);
 -                FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_mv_table_base[i][j],
 -                                  mv_table_size * 2 * sizeof(int16_t), fail);
 -                s->p_field_mv_table[i][j] = s->p_field_mv_table_base[i][j]
 -                                            + s->mb_stride + 1;
 +                FF_ALLOCZ_OR_GOTO(s->avctx, s->b_field_select_table [i][j], mb_array_size * 2 * sizeof(uint8_t), fail)
 +                FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_mv_table_base[i][j], mv_table_size * 2 * sizeof(int16_t), fail)
 +                s->p_field_mv_table[i][j] = s->p_field_mv_table_base[i][j] + s->mb_stride + 1;
              }
 -            FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_select_table[i],
 -                              mb_array_size * 2 * sizeof(uint8_t), fail);
 +            FF_ALLOCZ_OR_GOTO(s->avctx, s->p_field_select_table[i], mb_array_size * 2 * sizeof(uint8_t), fail)
          }
      }
      if (s->out_format == FMT_H263) {
          /* cbp values */
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->coded_block_base, y_size, fail);
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->coded_block_base, y_size + (s->mb_height&1)*2*s->b8_stride, fail);
          s->coded_block = s->coded_block_base + s->b8_stride + 1;
  
          /* cbp, ac_pred, pred_dir */
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->cbp_table,
 -                          mb_array_size * sizeof(uint8_t), fail);
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->pred_dir_table,
 -                          mb_array_size * sizeof(uint8_t), fail);
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->cbp_table     , mb_array_size * sizeof(uint8_t), fail);
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->pred_dir_table, mb_array_size * sizeof(uint8_t), fail);
      }
  
      if (s->h263_pred || s->h263_plus || !s->encoding) {
          /* dc values */
          // MN: we need these for  error resilience of intra-frames
 -        FF_ALLOCZ_OR_GOTO(s->avctx, s->dc_val_base,
 -                          yc_size * sizeof(int16_t), fail);
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->dc_val_base, yc_size * sizeof(int16_t), fail);
          s->dc_val[0] = s->dc_val_base + s->b8_stride + 1;
          s->dc_val[1] = s->dc_val_base + y_size + s->mb_stride + 1;
          s->dc_val[2] = s->dc_val[1] + c_size;
@@@ -889,10 -863,12 +889,10 @@@ av_cold int ff_mpv_common_init(MpegEncC
      dct_init(s);
  
      /* set chroma shifts */
 -    av_pix_fmt_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);
  
 -    /* convert fourcc to upper case */
 -    s->codec_tag          = avpriv_toupper4(s->avctx->codec_tag);
  
      FF_ALLOCZ_OR_GOTO(s->avctx, s->picture,
                        MAX_PICTURE_COUNT * sizeof(Picture), fail);
      if (!s->new_picture.f)
          goto fail;
  
 -    if (s->width && s->height) {
          if (init_context_frame(s))
              goto fail;
  
          s->parse_context.state = -1;
 -    }
  
 -    s->context_initialized = 1;
 -    s->thread_context[0]   = s;
 +        s->context_initialized = 1;
 +        memset(s->thread_context, 0, sizeof(s->thread_context));
 +        s->thread_context[0]   = s;
  
 -    if (s->width && s->height) {
 +//     if (s->width && s->height) {
          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 < nb_slices; i++) {
 +                if (i) {
 +                    s->thread_context[i] = av_memdup(s, sizeof(MpegEncContext));
 +                    if (!s->thread_context[i])
 +                        goto fail;
 +                }
                  if (init_duplicate_context(s->thread_context[i]) < 0)
                      goto fail;
                      s->thread_context[i]->start_mb_y =
              s->end_mb_y   = s->mb_height;
          }
          s->slice_context_count = nb_slices;
 -    }
 +//     }
  
      return 0;
   fail:
@@@ -1004,7 -981,6 +1004,7 @@@ static void free_context_frame(MpegEncC
      av_freep(&s->er.er_temp_buffer);
      av_freep(&s->mb_index2xy);
      av_freep(&s->lambda_table);
 +
      av_freep(&s->cplx_tab);
      av_freep(&s->bits_tab);
  
@@@ -1015,9 -991,6 +1015,9 @@@ int ff_mpv_common_frame_size_change(Mpe
  {
      int i, err = 0;
  
 +    if (!s->context_initialized)
 +        return AVERROR(EINVAL);
 +
      if (s->slice_context_count > 1) {
          for (i = 0; i < s->slice_context_count; i++) {
              free_duplicate_context(s->thread_context[i]);
      if ((err = init_context_frame(s)))
          goto fail;
  
 +    memset(s->thread_context, 0, sizeof(s->thread_context));
      s->thread_context[0]   = s;
  
      if (s->width && s->height) {
          int nb_slices = s->slice_context_count;
          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 < nb_slices; i++) {
 +                if (i) {
 +                    s->thread_context[i] = av_memdup(s, sizeof(MpegEncContext));
 +                    if (!s->thread_context[i]) {
 +                        err = AVERROR(ENOMEM);
 +                        goto fail;
 +                    }
 +                }
                  if ((err = init_duplicate_context(s->thread_context[i])) < 0)
                      goto fail;
                      s->thread_context[i]->start_mb_y =
                          (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;
              }
          } else {
 -            if (init_duplicate_context(s) < 0)
 +            err = init_duplicate_context(s);
 +            if (err < 0)
                  goto fail;
              s->start_mb_y = 0;
              s->end_mb_y   = s->mb_height;
@@@ -1140,23 -1109,6 +1140,23 @@@ void ff_mpv_common_end(MpegEncContext *
      s->linesize = s->uvlinesize = 0;
  }
  
 +
 +static void gray_frame(AVFrame *frame)
 +{
 +    int i, h_chroma_shift, v_chroma_shift;
 +
 +    av_pix_fmt_get_chroma_sub_sample(frame->format, &h_chroma_shift, &v_chroma_shift);
 +
 +    for(i=0; i<frame->height; i++)
 +        memset(frame->data[0] + frame->linesize[0]*i, 0x80, frame->width);
 +    for(i=0; i<FF_CEIL_RSHIFT(frame->height, v_chroma_shift); i++) {
 +        memset(frame->data[1] + frame->linesize[1]*i,
 +               0x80, FF_CEIL_RSHIFT(frame->width, h_chroma_shift));
 +        memset(frame->data[2] + frame->linesize[2]*i,
 +               0x80, FF_CEIL_RSHIFT(frame->width, h_chroma_shift));
 +    }
 +}
 +
  /**
   * generic function called after decoding
   * the header and before a frame is decoded.
@@@ -1167,11 -1119,6 +1167,11 @@@ int ff_mpv_frame_start(MpegEncContext *
      Picture *pic;
      s->mb_skipped = 0;
  
 +    if (!ff_thread_can_start_frame(avctx)) {
 +        av_log(avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
 +        return -1;
 +    }
 +
      /* mark & release old frames */
      if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&
          s->last_picture_ptr != s->next_picture_ptr &&
          int h_chroma_shift, v_chroma_shift;
          av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,
                                           &h_chroma_shift, &v_chroma_shift);
 -        if (s->pict_type != AV_PICTURE_TYPE_I)
 +        if (s->pict_type == AV_PICTURE_TYPE_B && s->next_picture_ptr && s->next_picture_ptr->f->buf[0])
 +            av_log(avctx, AV_LOG_DEBUG,
 +                   "allocating dummy last picture for B frame\n");
 +        else if (s->pict_type != AV_PICTURE_TYPE_I)
              av_log(avctx, AV_LOG_ERROR,
                     "warning: first frame is no keyframe\n");
          else if (s->picture_structure != PICT_FRAME)
 -            av_log(avctx, AV_LOG_INFO,
 +            av_log(avctx, AV_LOG_DEBUG,
                     "allocate dummy last picture for field based first keyframe\n");
  
          /* Allocate a dummy frame */
          s->last_picture_ptr = &s->picture[i];
  
          s->last_picture_ptr->reference   = 3;
 -        s->last_picture_ptr->f->pict_type = AV_PICTURE_TYPE_I;
 +        s->last_picture_ptr->f->key_frame = 0;
 +        s->last_picture_ptr->f->pict_type = AV_PICTURE_TYPE_P;
  
          if (alloc_picture(s, s->last_picture_ptr, 0) < 0) {
              s->last_picture_ptr = NULL;
              return -1;
          }
  
 -        memset(s->last_picture_ptr->f->data[0], 0,
 -               avctx->height * s->last_picture_ptr->f->linesize[0]);
 -        memset(s->last_picture_ptr->f->data[1], 0x80,
 -               (avctx->height >> v_chroma_shift) *
 -               s->last_picture_ptr->f->linesize[1]);
 -        memset(s->last_picture_ptr->f->data[2], 0x80,
 -               (avctx->height >> v_chroma_shift) *
 -               s->last_picture_ptr->f->linesize[2]);
 +        if (!avctx->hwaccel && !(avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)) {
 +            for(i=0; i<avctx->height; i++)
 +                memset(s->last_picture_ptr->f->data[0] + s->last_picture_ptr->f->linesize[0]*i,
 +                       0x80, avctx->width);
 +            if (s->last_picture_ptr->f->data[2]) {
 +                for(i=0; i<FF_CEIL_RSHIFT(avctx->height, v_chroma_shift); i++) {
 +                    memset(s->last_picture_ptr->f->data[1] + s->last_picture_ptr->f->linesize[1]*i,
 +                        0x80, FF_CEIL_RSHIFT(avctx->width, h_chroma_shift));
 +                    memset(s->last_picture_ptr->f->data[2] + s->last_picture_ptr->f->linesize[2]*i,
 +                        0x80, FF_CEIL_RSHIFT(avctx->width, h_chroma_shift));
 +                }
 +            }
 +
 +            if(s->codec_id == AV_CODEC_ID_FLV1 || s->codec_id == AV_CODEC_ID_H263){
 +                for(i=0; i<avctx->height; i++)
 +                memset(s->last_picture_ptr->f->data[0] + s->last_picture_ptr->f->linesize[0]*i, 16, avctx->width);
 +            }
 +        }
  
          ff_thread_report_progress(&s->last_picture_ptr->tf, INT_MAX, 0);
          ff_thread_report_progress(&s->last_picture_ptr->tf, INT_MAX, 1);
          s->next_picture_ptr = &s->picture[i];
  
          s->next_picture_ptr->reference   = 3;
 -        s->next_picture_ptr->f->pict_type = AV_PICTURE_TYPE_I;
 +        s->next_picture_ptr->f->key_frame = 0;
 +        s->next_picture_ptr->f->pict_type = AV_PICTURE_TYPE_P;
  
          if (alloc_picture(s, s->next_picture_ptr, 0) < 0) {
              s->next_picture_ptr = NULL;
          ff_thread_report_progress(&s->next_picture_ptr->tf, INT_MAX, 1);
      }
  
 +#if 0 // BUFREF-FIXME
 +    memset(s->last_picture.f->data, 0, sizeof(s->last_picture.f->data));
 +    memset(s->next_picture.f->data, 0, sizeof(s->next_picture.f->data));
 +#endif
      if (s->last_picture_ptr) {
          ff_mpeg_unref_picture(s->avctx, &s->last_picture);
          if (s->last_picture_ptr->f->buf[0] &&
              return ret;
      }
  
 -    if (s->pict_type != AV_PICTURE_TYPE_I &&
 -        !(s->last_picture_ptr && s->last_picture_ptr->f->buf[0])) {
 -        av_log(s, AV_LOG_ERROR,
 -               "Non-reference picture received and no reference available\n");
 -        return AVERROR_INVALIDDATA;
 -    }
 +    av_assert0(s->pict_type == AV_PICTURE_TYPE_I || (s->last_picture_ptr &&
 +                                                 s->last_picture_ptr->f->buf[0]));
  
      if (s->picture_structure!= PICT_FRAME) {
          int i;
          s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;
      }
  
 -#if FF_API_XVMC
 -FF_DISABLE_DEPRECATION_WARNINGS
 -    if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)
 -        return ff_xvmc_field_start(s, avctx);
 -FF_ENABLE_DEPRECATION_WARNINGS
 -#endif /* FF_API_XVMC */
 +    if (s->avctx->debug & FF_DEBUG_NOMC) {
 +        gray_frame(s->current_picture_ptr->f);
 +    }
  
      return 0;
  }
  /* called after a frame has been decoded. */
  void ff_mpv_frame_end(MpegEncContext *s)
  {
 -#if FF_API_XVMC
 -FF_DISABLE_DEPRECATION_WARNINGS
 -    /* redraw edges for the frame if decoding didn't complete */
 -    // just to make sure that all data is rendered.
 -    if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration) {
 -        ff_xvmc_field_end(s);
 -    } else
 -FF_ENABLE_DEPRECATION_WARNINGS
 -#endif /* FF_API_XVMC */
 -
      emms_c();
  
      if (s->current_picture.reference)
          ff_thread_report_progress(&s->current_picture_ptr->tf, INT_MAX, 0);
  }
  
 +
 +#if FF_API_VISMV
 +static int clip_line(int *sx, int *sy, int *ex, int *ey, int maxx)
 +{
 +    if(*sx > *ex)
 +        return clip_line(ex, ey, sx, sy, maxx);
 +
 +    if (*sx < 0) {
 +        if (*ex < 0)
 +            return 1;
 +        *sy = *ey + (*sy - *ey) * (int64_t)*ex / (*ex - *sx);
 +        *sx = 0;
 +    }
 +
 +    if (*ex > maxx) {
 +        if (*sx > maxx)
 +            return 1;
 +        *ey = *sy + (*ey - *sy) * (int64_t)(maxx - *sx) / (*ex - *sx);
 +        *ex = maxx;
 +    }
 +    return 0;
 +}
 +
 +
 +/**
 + * Draw a line from (ex, ey) -> (sx, sy).
 + * @param w width of the image
 + * @param h height of the image
 + * @param stride stride/linesize of the image
 + * @param color color of the arrow
 + */
 +static void draw_line(uint8_t *buf, int sx, int sy, int ex, int ey,
 +                      int w, int h, int stride, int color)
 +{
 +    int x, y, fr, f;
 +
 +    if (clip_line(&sx, &sy, &ex, &ey, w - 1))
 +        return;
 +    if (clip_line(&sy, &sx, &ey, &ex, h - 1))
 +        return;
 +
 +    sx = av_clip(sx, 0, w - 1);
 +    sy = av_clip(sy, 0, h - 1);
 +    ex = av_clip(ex, 0, w - 1);
 +    ey = av_clip(ey, 0, h - 1);
 +
 +    buf[sy * stride + sx] += color;
 +
 +    if (FFABS(ex - sx) > FFABS(ey - sy)) {
 +        if (sx > ex) {
 +            FFSWAP(int, sx, ex);
 +            FFSWAP(int, sy, ey);
 +        }
 +        buf += sx + sy * stride;
 +        ex  -= sx;
 +        f    = ((ey - sy) << 16) / ex;
 +        for (x = 0; x <= ex; x++) {
 +            y  = (x * f) >> 16;
 +            fr = (x * f) & 0xFFFF;
 +            buf[y * stride + x]       += (color * (0x10000 - fr)) >> 16;
 +            if(fr) buf[(y + 1) * stride + x] += (color *            fr ) >> 16;
 +        }
 +    } else {
 +        if (sy > ey) {
 +            FFSWAP(int, sx, ex);
 +            FFSWAP(int, sy, ey);
 +        }
 +        buf += sx + sy * stride;
 +        ey  -= sy;
 +        if (ey)
 +            f = ((ex - sx) << 16) / ey;
 +        else
 +            f = 0;
 +        for(y= 0; y <= ey; y++){
 +            x  = (y*f) >> 16;
 +            fr = (y*f) & 0xFFFF;
 +            buf[y * stride + x]     += (color * (0x10000 - fr)) >> 16;
 +            if(fr) buf[y * stride + x + 1] += (color *            fr ) >> 16;
 +        }
 +    }
 +}
 +
 +/**
 + * Draw an arrow from (ex, ey) -> (sx, sy).
 + * @param w width of the image
 + * @param h height of the image
 + * @param stride stride/linesize of the image
 + * @param color color of the arrow
 + */
 +static void draw_arrow(uint8_t *buf, int sx, int sy, int ex,
 +                       int ey, int w, int h, int stride, int color, int tail, int direction)
 +{
 +    int dx,dy;
 +
 +    if (direction) {
 +        FFSWAP(int, sx, ex);
 +        FFSWAP(int, sy, ey);
 +    }
 +
 +    sx = av_clip(sx, -100, w + 100);
 +    sy = av_clip(sy, -100, h + 100);
 +    ex = av_clip(ex, -100, w + 100);
 +    ey = av_clip(ey, -100, h + 100);
 +
 +    dx = ex - sx;
 +    dy = ey - sy;
 +
 +    if (dx * dx + dy * dy > 3 * 3) {
 +        int rx =  dx + dy;
 +        int ry = -dx + dy;
 +        int length = ff_sqrt((rx * rx + ry * ry) << 8);
 +
 +        // FIXME subpixel accuracy
 +        rx = ROUNDED_DIV(rx * 3 << 4, length);
 +        ry = ROUNDED_DIV(ry * 3 << 4, length);
 +
 +        if (tail) {
 +            rx = -rx;
 +            ry = -ry;
 +        }
 +
 +        draw_line(buf, sx, sy, sx + rx, sy + ry, w, h, stride, color);
 +        draw_line(buf, sx, sy, sx - ry, sy + rx, w, h, stride, color);
 +    }
 +    draw_line(buf, sx, sy, ex, ey, w, h, stride, color);
 +}
 +#endif
 +
 +static int add_mb(AVMotionVector *mb, uint32_t mb_type,
 +                  int dst_x, int dst_y,
 +                  int src_x, int src_y,
 +                  int direction)
 +{
 +    mb->w = IS_8X8(mb_type) || IS_8X16(mb_type) ? 8 : 16;
 +    mb->h = IS_8X8(mb_type) || IS_16X8(mb_type) ? 8 : 16;
 +    mb->src_x = src_x;
 +    mb->src_y = src_y;
 +    mb->dst_x = dst_x;
 +    mb->dst_y = dst_y;
 +    mb->source = direction ? 1 : -1;
 +    mb->flags = 0; // XXX: does mb_type contain extra information that could be exported here?
 +    return 1;
 +}
 +
  /**
   * Print debugging info for the given picture.
   */
 -void ff_print_debug_info(MpegEncContext *s, Picture *p)
 +void ff_print_debug_info2(AVCodecContext *avctx, AVFrame *pict, uint8_t *mbskip_table,
 +                         uint32_t *mbtype_table, int8_t *qscale_table, int16_t (*motion_val[2])[2],
 +                         int *low_delay,
 +                         int mb_width, int mb_height, int mb_stride, int quarter_sample)
  {
 -    AVFrame *pict;
 -    if (s->avctx->hwaccel || !p || !p->mb_type)
 +    if ((avctx->flags2 & CODEC_FLAG2_EXPORT_MVS) && mbtype_table && motion_val[0]) {
 +        const int shift = 1 + quarter_sample;
 +        const int mv_sample_log2 = avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_SVQ3 ? 2 : 1;
 +        const int mv_stride      = (mb_width << mv_sample_log2) +
 +                                   (avctx->codec->id == AV_CODEC_ID_H264 ? 0 : 1);
 +        int mb_x, mb_y, mbcount = 0;
 +
 +        /* size is width * height * 2 * 4 where 2 is for directions and 4 is
 +         * for the maximum number of MB (4 MB in case of IS_8x8) */
 +        AVMotionVector *mvs = av_malloc_array(mb_width * mb_height, 2 * 4 * sizeof(AVMotionVector));
 +        if (!mvs)
 +            return;
 +
 +        for (mb_y = 0; mb_y < mb_height; mb_y++) {
 +            for (mb_x = 0; mb_x < mb_width; mb_x++) {
 +                int i, direction, mb_type = mbtype_table[mb_x + mb_y * mb_stride];
 +                for (direction = 0; direction < 2; direction++) {
 +                    if (!USES_LIST(mb_type, direction))
 +                        continue;
 +                    if (IS_8X8(mb_type)) {
 +                        for (i = 0; i < 4; i++) {
 +                            int sx = mb_x * 16 + 4 + 8 * (i & 1);
 +                            int sy = mb_y * 16 + 4 + 8 * (i >> 1);
 +                            int xy = (mb_x * 2 + (i & 1) +
 +                                      (mb_y * 2 + (i >> 1)) * mv_stride) << (mv_sample_log2 - 1);
 +                            int mx = (motion_val[direction][xy][0] >> shift) + sx;
 +                            int my = (motion_val[direction][xy][1] >> shift) + sy;
 +                            mbcount += add_mb(mvs + mbcount, mb_type, sx, sy, mx, my, direction);
 +                        }
 +                    } else if (IS_16X8(mb_type)) {
 +                        for (i = 0; i < 2; i++) {
 +                            int sx = mb_x * 16 + 8;
 +                            int sy = mb_y * 16 + 4 + 8 * i;
 +                            int xy = (mb_x * 2 + (mb_y * 2 + i) * mv_stride) << (mv_sample_log2 - 1);
 +                            int mx = (motion_val[direction][xy][0] >> shift);
 +                            int my = (motion_val[direction][xy][1] >> shift);
 +
 +                            if (IS_INTERLACED(mb_type))
 +                                my *= 2;
 +
 +                            mbcount += add_mb(mvs + mbcount, mb_type, sx, sy, mx + sx, my + sy, direction);
 +                        }
 +                    } else if (IS_8X16(mb_type)) {
 +                        for (i = 0; i < 2; i++) {
 +                            int sx = mb_x * 16 + 4 + 8 * i;
 +                            int sy = mb_y * 16 + 8;
 +                            int xy = (mb_x * 2 + i + mb_y * 2 * mv_stride) << (mv_sample_log2 - 1);
 +                            int mx = motion_val[direction][xy][0] >> shift;
 +                            int my = motion_val[direction][xy][1] >> shift;
 +
 +                            if (IS_INTERLACED(mb_type))
 +                                my *= 2;
 +
 +                            mbcount += add_mb(mvs + mbcount, mb_type, sx, sy, mx + sx, my + sy, direction);
 +                        }
 +                    } else {
 +                          int sx = mb_x * 16 + 8;
 +                          int sy = mb_y * 16 + 8;
 +                          int xy = (mb_x + mb_y * mv_stride) << mv_sample_log2;
 +                          int mx = (motion_val[direction][xy][0]>>shift) + sx;
 +                          int my = (motion_val[direction][xy][1]>>shift) + sy;
 +                          mbcount += add_mb(mvs + mbcount, mb_type, sx, sy, mx, my, direction);
 +                    }
 +                }
 +            }
 +        }
 +
 +        if (mbcount) {
 +            AVFrameSideData *sd;
 +
 +            av_log(avctx, AV_LOG_DEBUG, "Adding %d MVs info to frame %d\n", mbcount, avctx->frame_number);
 +            sd = av_frame_new_side_data(pict, AV_FRAME_DATA_MOTION_VECTORS, mbcount * sizeof(AVMotionVector));
 +            if (!sd) {
 +                av_freep(&mvs);
 +                return;
 +            }
 +            memcpy(sd->data, mvs, mbcount * sizeof(AVMotionVector));
 +        }
 +
 +        av_freep(&mvs);
 +    }
 +
 +    /* TODO: export all the following to make them accessible for users (and filters) */
 +    if (avctx->hwaccel || !mbtype_table
 +        || (avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU))
          return;
 -    pict = p->f;
  
 -    if (s->avctx->debug & (FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)) {
 +
 +    if (avctx->debug & (FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)) {
          int x,y;
  
 -        av_log(s->avctx,AV_LOG_DEBUG,"New frame, type: ");
 -        switch (pict->pict_type) {
 -        case AV_PICTURE_TYPE_I:
 -            av_log(s->avctx,AV_LOG_DEBUG,"I\n");
 -            break;
 -        case AV_PICTURE_TYPE_P:
 -            av_log(s->avctx,AV_LOG_DEBUG,"P\n");
 -            break;
 -        case AV_PICTURE_TYPE_B:
 -            av_log(s->avctx,AV_LOG_DEBUG,"B\n");
 -            break;
 -        case AV_PICTURE_TYPE_S:
 -            av_log(s->avctx,AV_LOG_DEBUG,"S\n");
 -            break;
 -        case AV_PICTURE_TYPE_SI:
 -            av_log(s->avctx,AV_LOG_DEBUG,"SI\n");
 -            break;
 -        case AV_PICTURE_TYPE_SP:
 -            av_log(s->avctx,AV_LOG_DEBUG,"SP\n");
 -            break;
 -        }
 -        for (y = 0; y < s->mb_height; y++) {
 -            for (x = 0; x < s->mb_width; x++) {
 -                if (s->avctx->debug & FF_DEBUG_SKIP) {
 -                    int count = s->mbskip_table[x + y * s->mb_stride];
 +        av_log(avctx, AV_LOG_DEBUG, "New frame, type: %c\n",
 +               av_get_picture_type_char(pict->pict_type));
 +        for (y = 0; y < mb_height; y++) {
 +            for (x = 0; x < mb_width; x++) {
 +                if (avctx->debug & FF_DEBUG_SKIP) {
 +                    int count = mbskip_table ? mbskip_table[x + y * mb_stride] : 0;
                      if (count > 9)
                          count = 9;
 -                    av_log(s->avctx, AV_LOG_DEBUG, "%1d", count);
 +                    av_log(avctx, AV_LOG_DEBUG, "%1d", count);
                  }
 -                if (s->avctx->debug & FF_DEBUG_QP) {
 -                    av_log(s->avctx, AV_LOG_DEBUG, "%2d",
 -                           p->qscale_table[x + y * s->mb_stride]);
 +                if (avctx->debug & FF_DEBUG_QP) {
 +                    av_log(avctx, AV_LOG_DEBUG, "%2d",
 +                           qscale_table[x + y * mb_stride]);
                  }
 -                if (s->avctx->debug & FF_DEBUG_MB_TYPE) {
 -                    int mb_type = p->mb_type[x + y * s->mb_stride];
 +                if (avctx->debug & FF_DEBUG_MB_TYPE) {
 +                    int mb_type = mbtype_table[x + y * mb_stride];
                      // Type & MV direction
                      if (IS_PCM(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "P");
 +                        av_log(avctx, AV_LOG_DEBUG, "P");
                      else if (IS_INTRA(mb_type) && IS_ACPRED(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "A");
 +                        av_log(avctx, AV_LOG_DEBUG, "A");
                      else if (IS_INTRA4x4(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "i");
 +                        av_log(avctx, AV_LOG_DEBUG, "i");
                      else if (IS_INTRA16x16(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "I");
 +                        av_log(avctx, AV_LOG_DEBUG, "I");
                      else if (IS_DIRECT(mb_type) && IS_SKIP(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "d");
 +                        av_log(avctx, AV_LOG_DEBUG, "d");
                      else if (IS_DIRECT(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "D");
 +                        av_log(avctx, AV_LOG_DEBUG, "D");
                      else if (IS_GMC(mb_type) && IS_SKIP(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "g");
 +                        av_log(avctx, AV_LOG_DEBUG, "g");
                      else if (IS_GMC(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "G");
 +                        av_log(avctx, AV_LOG_DEBUG, "G");
                      else if (IS_SKIP(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "S");
 +                        av_log(avctx, AV_LOG_DEBUG, "S");
                      else if (!USES_LIST(mb_type, 1))
 -                        av_log(s->avctx, AV_LOG_DEBUG, ">");
 +                        av_log(avctx, AV_LOG_DEBUG, ">");
                      else if (!USES_LIST(mb_type, 0))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "<");
 +                        av_log(avctx, AV_LOG_DEBUG, "<");
                      else {
 -                        assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
 -                        av_log(s->avctx, AV_LOG_DEBUG, "X");
 +                        av_assert2(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
 +                        av_log(avctx, AV_LOG_DEBUG, "X");
                      }
  
                      // segmentation
                      if (IS_8X8(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "+");
 +                        av_log(avctx, AV_LOG_DEBUG, "+");
                      else if (IS_16X8(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "-");
 +                        av_log(avctx, AV_LOG_DEBUG, "-");
                      else if (IS_8X16(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "|");
 +                        av_log(avctx, AV_LOG_DEBUG, "|");
                      else if (IS_INTRA(mb_type) || IS_16X16(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, " ");
 +                        av_log(avctx, AV_LOG_DEBUG, " ");
                      else
 -                        av_log(s->avctx, AV_LOG_DEBUG, "?");
 +                        av_log(avctx, AV_LOG_DEBUG, "?");
  
  
                      if (IS_INTERLACED(mb_type))
 -                        av_log(s->avctx, AV_LOG_DEBUG, "=");
 +                        av_log(avctx, AV_LOG_DEBUG, "=");
                      else
 -                        av_log(s->avctx, AV_LOG_DEBUG, " ");
 +                        av_log(avctx, AV_LOG_DEBUG, " ");
                  }
              }
 -            av_log(s->avctx, AV_LOG_DEBUG, "\n");
 +            av_log(avctx, AV_LOG_DEBUG, "\n");
          }
      }
 +
 +    if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) ||
 +        (avctx->debug_mv)) {
 +        int mb_y;
 +        int i;
 +        int h_chroma_shift, v_chroma_shift, block_height;
 +#if FF_API_VISMV
 +        const int shift = 1 + quarter_sample;
 +        uint8_t *ptr;
 +        const int width          = avctx->width;
 +        const int height         = avctx->height;
 +#endif
 +        const int mv_sample_log2 = avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_SVQ3 ? 2 : 1;
 +        const int mv_stride      = (mb_width << mv_sample_log2) +
 +                                   (avctx->codec->id == AV_CODEC_ID_H264 ? 0 : 1);
 +
 +        *low_delay = 0; // needed to see the vectors without trashing the buffers
 +
 +        avcodec_get_chroma_sub_sample(avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
 +
 +        av_frame_make_writable(pict);
 +
 +        pict->opaque = NULL;
 +#if FF_API_VISMV
 +        ptr          = pict->data[0];
 +#endif
 +        block_height = 16 >> v_chroma_shift;
 +
 +        for (mb_y = 0; mb_y < mb_height; mb_y++) {
 +            int mb_x;
 +            for (mb_x = 0; mb_x < mb_width; mb_x++) {
 +                const int mb_index = mb_x + mb_y * mb_stride;
 +#if FF_API_VISMV
 +                if ((avctx->debug_mv) && motion_val[0]) {
 +                    int type;
 +                    for (type = 0; type < 3; type++) {
 +                        int direction = 0;
 +                        switch (type) {
 +                        case 0:
 +                            if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_P_FOR)) ||
 +                                (pict->pict_type!= AV_PICTURE_TYPE_P))
 +                                continue;
 +                            direction = 0;
 +                            break;
 +                        case 1:
 +                            if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_B_FOR)) ||
 +                                (pict->pict_type!= AV_PICTURE_TYPE_B))
 +                                continue;
 +                            direction = 0;
 +                            break;
 +                        case 2:
 +                            if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_B_BACK)) ||
 +                                (pict->pict_type!= AV_PICTURE_TYPE_B))
 +                                continue;
 +                            direction = 1;
 +                            break;
 +                        }
 +                        if (!USES_LIST(mbtype_table[mb_index], direction))
 +                            continue;
 +
 +                        if (IS_8X8(mbtype_table[mb_index])) {
 +                            int i;
 +                            for (i = 0; i < 4; i++) {
 +                                int sx = mb_x * 16 + 4 + 8 * (i & 1);
 +                                int sy = mb_y * 16 + 4 + 8 * (i >> 1);
 +                                int xy = (mb_x * 2 + (i & 1) +
 +                                          (mb_y * 2 + (i >> 1)) * mv_stride) << (mv_sample_log2 - 1);
 +                                int mx = (motion_val[direction][xy][0] >> shift) + sx;
 +                                int my = (motion_val[direction][xy][1] >> shift) + sy;
 +                                draw_arrow(ptr, sx, sy, mx, my, width,
 +                                           height, pict->linesize[0], 100, 0, direction);
 +                            }
 +                        } else if (IS_16X8(mbtype_table[mb_index])) {
 +                            int i;
 +                            for (i = 0; i < 2; i++) {
 +                                int sx = mb_x * 16 + 8;
 +                                int sy = mb_y * 16 + 4 + 8 * i;
 +                                int xy = (mb_x * 2 + (mb_y * 2 + i) * mv_stride) << (mv_sample_log2 - 1);
 +                                int mx = (motion_val[direction][xy][0] >> shift);
 +                                int my = (motion_val[direction][xy][1] >> shift);
 +
 +                                if (IS_INTERLACED(mbtype_table[mb_index]))
 +                                    my *= 2;
 +
 +                                draw_arrow(ptr, sx, sy, mx + sx, my + sy, width,
 +                                           height, pict->linesize[0], 100, 0, direction);
 +                            }
 +                        } else if (IS_8X16(mbtype_table[mb_index])) {
 +                            int i;
 +                            for (i = 0; i < 2; i++) {
 +                                int sx = mb_x * 16 + 4 + 8 * i;
 +                                int sy = mb_y * 16 + 8;
 +                                int xy = (mb_x * 2 + i + mb_y * 2 * mv_stride) << (mv_sample_log2 - 1);
 +                                int mx = motion_val[direction][xy][0] >> shift;
 +                                int my = motion_val[direction][xy][1] >> shift;
 +
 +                                if (IS_INTERLACED(mbtype_table[mb_index]))
 +                                    my *= 2;
 +
 +                                draw_arrow(ptr, sx, sy, mx + sx, my + sy, width,
 +                                           height, pict->linesize[0], 100, 0, direction);
 +                            }
 +                        } else {
 +                              int sx= mb_x * 16 + 8;
 +                              int sy= mb_y * 16 + 8;
 +                              int xy= (mb_x + mb_y * mv_stride) << mv_sample_log2;
 +                              int mx= (motion_val[direction][xy][0]>>shift) + sx;
 +                              int my= (motion_val[direction][xy][1]>>shift) + sy;
 +                              draw_arrow(ptr, sx, sy, mx, my, width, height, pict->linesize[0], 100, 0, direction);
 +                        }
 +                    }
 +                }
 +#endif
 +                if ((avctx->debug & FF_DEBUG_VIS_QP)) {
 +                    uint64_t c = (qscale_table[mb_index] * 128 / 31) *
 +                                 0x0101010101010101ULL;
 +                    int y;
 +                    for (y = 0; y < block_height; y++) {
 +                        *(uint64_t *)(pict->data[1] + 8 * mb_x +
 +                                      (block_height * mb_y + y) *
 +                                      pict->linesize[1]) = c;
 +                        *(uint64_t *)(pict->data[2] + 8 * mb_x +
 +                                      (block_height * mb_y + y) *
 +                                      pict->linesize[2]) = c;
 +                    }
 +                }
 +                if ((avctx->debug & FF_DEBUG_VIS_MB_TYPE) &&
 +                    motion_val[0]) {
 +                    int mb_type = mbtype_table[mb_index];
 +                    uint64_t u,v;
 +                    int y;
 +#define COLOR(theta, r) \
 +    u = (int)(128 + r * cos(theta * 3.141592 / 180)); \
 +    v = (int)(128 + r * sin(theta * 3.141592 / 180));
 +
 +
 +                    u = v = 128;
 +                    if (IS_PCM(mb_type)) {
 +                        COLOR(120, 48)
 +                    } else if ((IS_INTRA(mb_type) && IS_ACPRED(mb_type)) ||
 +                               IS_INTRA16x16(mb_type)) {
 +                        COLOR(30, 48)
 +                    } else if (IS_INTRA4x4(mb_type)) {
 +                        COLOR(90, 48)
 +                    } else if (IS_DIRECT(mb_type) && IS_SKIP(mb_type)) {
 +                        // COLOR(120, 48)
 +                    } else if (IS_DIRECT(mb_type)) {
 +                        COLOR(150, 48)
 +                    } else if (IS_GMC(mb_type) && IS_SKIP(mb_type)) {
 +                        COLOR(170, 48)
 +                    } else if (IS_GMC(mb_type)) {
 +                        COLOR(190, 48)
 +                    } else if (IS_SKIP(mb_type)) {
 +                        // COLOR(180, 48)
 +                    } else if (!USES_LIST(mb_type, 1)) {
 +                        COLOR(240, 48)
 +                    } else if (!USES_LIST(mb_type, 0)) {
 +                        COLOR(0, 48)
 +                    } else {
 +                        av_assert2(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
 +                        COLOR(300,48)
 +                    }
 +
 +                    u *= 0x0101010101010101ULL;
 +                    v *= 0x0101010101010101ULL;
 +                    for (y = 0; y < block_height; y++) {
 +                        *(uint64_t *)(pict->data[1] + 8 * mb_x +
 +                                      (block_height * mb_y + y) * pict->linesize[1]) = u;
 +                        *(uint64_t *)(pict->data[2] + 8 * mb_x +
 +                                      (block_height * mb_y + y) * pict->linesize[2]) = v;
 +                    }
 +
 +                    // segmentation
 +                    if (IS_8X8(mb_type) || IS_16X8(mb_type)) {
 +                        *(uint64_t *)(pict->data[0] + 16 * mb_x + 0 +
 +                                      (16 * mb_y + 8) * pict->linesize[0]) ^= 0x8080808080808080ULL;
 +                        *(uint64_t *)(pict->data[0] + 16 * mb_x + 8 +
 +                                      (16 * mb_y + 8) * pict->linesize[0]) ^= 0x8080808080808080ULL;
 +                    }
 +                    if (IS_8X8(mb_type) || IS_8X16(mb_type)) {
 +                        for (y = 0; y < 16; y++)
 +                            pict->data[0][16 * mb_x + 8 + (16 * mb_y + y) *
 +                                          pict->linesize[0]] ^= 0x80;
 +                    }
 +                    if (IS_8X8(mb_type) && mv_sample_log2 >= 2) {
 +                        int dm = 1 << (mv_sample_log2 - 2);
 +                        for (i = 0; i < 4; i++) {
 +                            int sx = mb_x * 16 + 8 * (i & 1);
 +                            int sy = mb_y * 16 + 8 * (i >> 1);
 +                            int xy = (mb_x * 2 + (i & 1) +
 +                                     (mb_y * 2 + (i >> 1)) * mv_stride) << (mv_sample_log2 - 1);
 +                            // FIXME bidir
 +                            int32_t *mv = (int32_t *) &motion_val[0][xy];
 +                            if (mv[0] != mv[dm] ||
 +                                mv[dm * mv_stride] != mv[dm * (mv_stride + 1)])
 +                                for (y = 0; y < 8; y++)
 +                                    pict->data[0][sx + 4 + (sy + y) * pict->linesize[0]] ^= 0x80;
 +                            if (mv[0] != mv[dm * mv_stride] || mv[dm] != mv[dm * (mv_stride + 1)])
 +                                *(uint64_t *)(pict->data[0] + sx + (sy + 4) *
 +                                              pict->linesize[0]) ^= 0x8080808080808080ULL;
 +                        }
 +                    }
 +
 +                    if (IS_INTERLACED(mb_type) &&
 +                        avctx->codec->id == AV_CODEC_ID_H264) {
 +                        // hmm
 +                    }
 +                }
 +                if (mbskip_table)
 +                    mbskip_table[mb_index] = 0;
 +            }
 +        }
 +    }
 +}
 +
 +void ff_print_debug_info(MpegEncContext *s, Picture *p, AVFrame *pict)
 +{
 +    ff_print_debug_info2(s->avctx, pict, s->mbskip_table, p->mb_type,
 +                         p->qscale_table, p->motion_val, &s->low_delay,
 +                         s->mb_width, s->mb_height, s->mb_stride, s->quarter_sample);
 +}
 +
 +int ff_mpv_export_qp_table(MpegEncContext *s, AVFrame *f, Picture *p, int qp_type)
 +{
 +    AVBufferRef *ref = av_buffer_ref(p->qscale_table_buf);
 +    int offset = 2*s->mb_stride + 1;
 +    if(!ref)
 +        return AVERROR(ENOMEM);
 +    av_assert0(ref->size >= offset + s->mb_stride * ((f->height+15)/16));
 +    ref->size -= offset;
 +    ref->data += offset;
 +    return av_frame_set_qp_table(f, ref, s->mb_stride, qp_type);
 +}
 +
 +static inline int hpel_motion_lowres(MpegEncContext *s,
 +                                     uint8_t *dest, uint8_t *src,
 +                                     int field_based, int field_select,
 +                                     int src_x, int src_y,
 +                                     int width, int height, ptrdiff_t stride,
 +                                     int h_edge_pos, int v_edge_pos,
 +                                     int w, int h, h264_chroma_mc_func *pix_op,
 +                                     int motion_x, int motion_y)
 +{
 +    const int lowres   = s->avctx->lowres;
 +    const int op_index = FFMIN(lowres, 3);
 +    const int s_mask   = (2 << lowres) - 1;
 +    int emu = 0;
 +    int sx, sy;
 +
 +    if (s->quarter_sample) {
 +        motion_x /= 2;
 +        motion_y /= 2;
 +    }
 +
 +    sx = motion_x & s_mask;
 +    sy = motion_y & s_mask;
 +    src_x += motion_x >> lowres + 1;
 +    src_y += motion_y >> lowres + 1;
 +
 +    src   += src_y * stride + src_x;
 +
 +    if ((unsigned)src_x > FFMAX( h_edge_pos - (!!sx) - w,                 0) ||
 +        (unsigned)src_y > FFMAX((v_edge_pos >> field_based) - (!!sy) - h, 0)) {
 +        s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src,
 +                                 s->linesize, s->linesize,
 +                                 w + 1, (h + 1) << field_based,
 +                                 src_x, src_y   << field_based,
 +                                 h_edge_pos, v_edge_pos);
 +        src = s->sc.edge_emu_buffer;
 +        emu = 1;
 +    }
 +
 +    sx = (sx << 2) >> lowres;
 +    sy = (sy << 2) >> lowres;
 +    if (field_select)
 +        src += s->linesize;
 +    pix_op[op_index](dest, src, stride, h, sx, sy);
 +    return emu;
 +}
 +
 +/* apply one mpeg motion vector to the three components */
 +static av_always_inline void mpeg_motion_lowres(MpegEncContext *s,
 +                                                uint8_t *dest_y,
 +                                                uint8_t *dest_cb,
 +                                                uint8_t *dest_cr,
 +                                                int field_based,
 +                                                int bottom_field,
 +                                                int field_select,
 +                                                uint8_t **ref_picture,
 +                                                h264_chroma_mc_func *pix_op,
 +                                                int motion_x, int motion_y,
 +                                                int h, int mb_y)
 +{
 +    uint8_t *ptr_y, *ptr_cb, *ptr_cr;
 +    int mx, my, src_x, src_y, uvsrc_x, uvsrc_y, sx, sy, uvsx, uvsy;
 +    ptrdiff_t uvlinesize, linesize;
 +    const int lowres     = s->avctx->lowres;
 +    const int op_index   = FFMIN(lowres-1+s->chroma_x_shift, 3);
 +    const int block_s    = 8>>lowres;
 +    const int s_mask     = (2 << lowres) - 1;
 +    const int h_edge_pos = s->h_edge_pos >> lowres;
 +    const int v_edge_pos = s->v_edge_pos >> lowres;
 +    linesize   = s->current_picture.f->linesize[0] << field_based;
 +    uvlinesize = s->current_picture.f->linesize[1] << field_based;
 +
 +    // FIXME obviously not perfect but qpel will not work in lowres anyway
 +    if (s->quarter_sample) {
 +        motion_x /= 2;
 +        motion_y /= 2;
 +    }
 +
 +    if(field_based){
 +        motion_y += (bottom_field - field_select)*((1 << lowres)-1);
 +    }
 +
 +    sx = motion_x & s_mask;
 +    sy = motion_y & s_mask;
 +    src_x = s->mb_x * 2 * block_s + (motion_x >> lowres + 1);
 +    src_y = (mb_y * 2 * block_s >> field_based) + (motion_y >> lowres + 1);
 +
 +    if (s->out_format == FMT_H263) {
 +        uvsx    = ((motion_x >> 1) & s_mask) | (sx & 1);
 +        uvsy    = ((motion_y >> 1) & s_mask) | (sy & 1);
 +        uvsrc_x = src_x >> 1;
 +        uvsrc_y = src_y >> 1;
 +    } else if (s->out_format == FMT_H261) {
 +        // even chroma mv's are full pel in H261
 +        mx      = motion_x / 4;
 +        my      = motion_y / 4;
 +        uvsx    = (2 * mx) & s_mask;
 +        uvsy    = (2 * my) & s_mask;
 +        uvsrc_x = s->mb_x * block_s + (mx >> lowres);
 +        uvsrc_y =    mb_y * block_s + (my >> lowres);
 +    } else {
 +        if(s->chroma_y_shift){
 +            mx      = motion_x / 2;
 +            my      = motion_y / 2;
 +            uvsx    = mx & s_mask;
 +            uvsy    = my & s_mask;
 +            uvsrc_x = s->mb_x * block_s                 + (mx >> lowres + 1);
 +            uvsrc_y =   (mb_y * block_s >> field_based) + (my >> lowres + 1);
 +        } else {
 +            if(s->chroma_x_shift){
 +            //Chroma422
 +                mx = motion_x / 2;
 +                uvsx = mx & s_mask;
 +                uvsy = motion_y & s_mask;
 +                uvsrc_y = src_y;
 +                uvsrc_x = s->mb_x*block_s               + (mx >> (lowres+1));
 +            } else {
 +            //Chroma444
 +                uvsx = motion_x & s_mask;
 +                uvsy = motion_y & s_mask;
 +                uvsrc_x = src_x;
 +                uvsrc_y = src_y;
 +            }
 +        }
 +    }
 +
 +    ptr_y  = ref_picture[0] + src_y   * linesize   + src_x;
 +    ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;
 +    ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;
 +
 +    if ((unsigned) src_x > FFMAX( h_edge_pos - (!!sx) - 2 * block_s,       0) || uvsrc_y<0 ||
 +        (unsigned) src_y > FFMAX((v_edge_pos >> field_based) - (!!sy) - h, 0)) {
 +        s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, ptr_y,
 +                                 linesize >> field_based, linesize >> field_based,
 +                                 17, 17 + field_based,
 +                                src_x, src_y << field_based, h_edge_pos,
 +                                v_edge_pos);
 +        ptr_y = s->sc.edge_emu_buffer;
 +        if (!CONFIG_GRAY || !(s->avctx->flags & CODEC_FLAG_GRAY)) {
 +            uint8_t *ubuf = s->sc.edge_emu_buffer + 18 * s->linesize;
 +            uint8_t *vbuf =ubuf + 9 * s->uvlinesize;
 +            s->vdsp.emulated_edge_mc(ubuf,  ptr_cb,
 +                                     uvlinesize >> field_based, uvlinesize >> field_based,
 +                                     9, 9 + field_based,
 +                                    uvsrc_x, uvsrc_y << field_based,
 +                                    h_edge_pos >> 1, v_edge_pos >> 1);
 +            s->vdsp.emulated_edge_mc(vbuf,  ptr_cr,
 +                                     uvlinesize >> field_based,uvlinesize >> field_based,
 +                                     9, 9 + field_based,
 +                                    uvsrc_x, uvsrc_y << field_based,
 +                                    h_edge_pos >> 1, v_edge_pos >> 1);
 +            ptr_cb = ubuf;
 +            ptr_cr = vbuf;
 +        }
 +    }
 +
 +    // FIXME use this for field pix too instead of the obnoxious hack which changes picture.f->data
 +    if (bottom_field) {
 +        dest_y  += s->linesize;
 +        dest_cb += s->uvlinesize;
 +        dest_cr += s->uvlinesize;
 +    }
 +
 +    if (field_select) {
 +        ptr_y   += s->linesize;
 +        ptr_cb  += s->uvlinesize;
 +        ptr_cr  += s->uvlinesize;
 +    }
 +
 +    sx = (sx << 2) >> lowres;
 +    sy = (sy << 2) >> lowres;
 +    pix_op[lowres - 1](dest_y, ptr_y, linesize, h, sx, sy);
 +
 +    if (!CONFIG_GRAY || !(s->avctx->flags & CODEC_FLAG_GRAY)) {
 +        int hc = s->chroma_y_shift ? (h+1-bottom_field)>>1 : h;
 +        uvsx = (uvsx << 2) >> lowres;
 +        uvsy = (uvsy << 2) >> lowres;
 +        if (hc) {
 +            pix_op[op_index](dest_cb, ptr_cb, uvlinesize, hc, uvsx, uvsy);
 +            pix_op[op_index](dest_cr, ptr_cr, uvlinesize, hc, uvsx, uvsy);
 +        }
 +    }
 +    // FIXME h261 lowres loop filter
 +}
 +
 +static inline void chroma_4mv_motion_lowres(MpegEncContext *s,
 +                                            uint8_t *dest_cb, uint8_t *dest_cr,
 +                                            uint8_t **ref_picture,
 +                                            h264_chroma_mc_func * pix_op,
 +                                            int mx, int my)
 +{
 +    const int lowres     = s->avctx->lowres;
 +    const int op_index   = FFMIN(lowres, 3);
 +    const int block_s    = 8 >> lowres;
 +    const int s_mask     = (2 << lowres) - 1;
 +    const int h_edge_pos = s->h_edge_pos >> lowres + 1;
 +    const int v_edge_pos = s->v_edge_pos >> lowres + 1;
 +    int emu = 0, src_x, src_y, sx, sy;
 +    ptrdiff_t offset;
 +    uint8_t *ptr;
 +
 +    if (s->quarter_sample) {
 +        mx /= 2;
 +        my /= 2;
 +    }
 +
 +    /* In case of 8X8, we construct a single chroma motion vector
 +       with a special rounding */
 +    mx = ff_h263_round_chroma(mx);
 +    my = ff_h263_round_chroma(my);
 +
 +    sx = mx & s_mask;
 +    sy = my & s_mask;
 +    src_x = s->mb_x * block_s + (mx >> lowres + 1);
 +    src_y = s->mb_y * block_s + (my >> lowres + 1);
 +
 +    offset = src_y * s->uvlinesize + src_x;
 +    ptr = ref_picture[1] + offset;
 +    if ((unsigned) src_x > FFMAX(h_edge_pos - (!!sx) - block_s, 0) ||
 +        (unsigned) src_y > FFMAX(v_edge_pos - (!!sy) - block_s, 0)) {
 +        s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, ptr,
 +                                 s->uvlinesize, s->uvlinesize,
 +                                 9, 9,
 +                                 src_x, src_y, h_edge_pos, v_edge_pos);
 +        ptr = s->sc.edge_emu_buffer;
 +        emu = 1;
 +    }
 +    sx = (sx << 2) >> lowres;
 +    sy = (sy << 2) >> lowres;
 +    pix_op[op_index](dest_cb, ptr, s->uvlinesize, block_s, sx, sy);
 +
 +    ptr = ref_picture[2] + offset;
 +    if (emu) {
 +        s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, ptr,
 +                                 s->uvlinesize, s->uvlinesize,
 +                                 9, 9,
 +                                 src_x, src_y, h_edge_pos, v_edge_pos);
 +        ptr = s->sc.edge_emu_buffer;
 +    }
 +    pix_op[op_index](dest_cr, ptr, s->uvlinesize, block_s, sx, sy);
 +}
 +
 +/**
 + * motion compensation of a single macroblock
 + * @param s context
 + * @param dest_y luma destination pointer
 + * @param dest_cb chroma cb/u destination pointer
 + * @param dest_cr chroma cr/v destination pointer
 + * @param dir direction (0->forward, 1->backward)
 + * @param ref_picture array[3] of pointers to the 3 planes of the reference picture
 + * @param pix_op halfpel motion compensation function (average or put normally)
 + * the motion vectors are taken from s->mv and the MV type from s->mv_type
 + */
 +static inline void MPV_motion_lowres(MpegEncContext *s,
 +                                     uint8_t *dest_y, uint8_t *dest_cb,
 +                                     uint8_t *dest_cr,
 +                                     int dir, uint8_t **ref_picture,
 +                                     h264_chroma_mc_func *pix_op)
 +{
 +    int mx, my;
 +    int mb_x, mb_y, i;
 +    const int lowres  = s->avctx->lowres;
 +    const int block_s = 8 >>lowres;
 +
 +    mb_x = s->mb_x;
 +    mb_y = s->mb_y;
 +
 +    switch (s->mv_type) {
 +    case MV_TYPE_16X16:
 +        mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
 +                           0, 0, 0,
 +                           ref_picture, pix_op,
 +                           s->mv[dir][0][0], s->mv[dir][0][1],
 +                           2 * block_s, mb_y);
 +        break;
 +    case MV_TYPE_8X8:
 +        mx = 0;
 +        my = 0;
 +        for (i = 0; i < 4; i++) {
 +            hpel_motion_lowres(s, dest_y + ((i & 1) + (i >> 1) *
 +                               s->linesize) * block_s,
 +                               ref_picture[0], 0, 0,
 +                               (2 * mb_x + (i & 1)) * block_s,
 +                               (2 * mb_y + (i >> 1)) * block_s,
 +                               s->width, s->height, s->linesize,
 +                               s->h_edge_pos >> lowres, s->v_edge_pos >> lowres,
 +                               block_s, block_s, pix_op,
 +                               s->mv[dir][i][0], s->mv[dir][i][1]);
 +
 +            mx += s->mv[dir][i][0];
 +            my += s->mv[dir][i][1];
 +        }
 +
 +        if (!CONFIG_GRAY || !(s->avctx->flags & CODEC_FLAG_GRAY))
 +            chroma_4mv_motion_lowres(s, dest_cb, dest_cr, ref_picture,
 +                                     pix_op, mx, my);
 +        break;
 +    case MV_TYPE_FIELD:
 +        if (s->picture_structure == PICT_FRAME) {
 +            /* top field */
 +            mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
 +                               1, 0, s->field_select[dir][0],
 +                               ref_picture, pix_op,
 +                               s->mv[dir][0][0], s->mv[dir][0][1],
 +                               block_s, mb_y);
 +            /* bottom field */
 +            mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
 +                               1, 1, s->field_select[dir][1],
 +                               ref_picture, pix_op,
 +                               s->mv[dir][1][0], s->mv[dir][1][1],
 +                               block_s, mb_y);
 +        } else {
 +            if (s->picture_structure != s->field_select[dir][0] + 1 &&
 +                s->pict_type != AV_PICTURE_TYPE_B && !s->first_field) {
 +                ref_picture = s->current_picture_ptr->f->data;
 +
 +            }
 +            mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
 +                               0, 0, s->field_select[dir][0],
 +                               ref_picture, pix_op,
 +                               s->mv[dir][0][0],
 +                               s->mv[dir][0][1], 2 * block_s, mb_y >> 1);
 +            }
 +        break;
 +    case MV_TYPE_16X8:
 +        for (i = 0; i < 2; i++) {
 +            uint8_t **ref2picture;
 +
 +            if (s->picture_structure == s->field_select[dir][i] + 1 ||
 +                s->pict_type == AV_PICTURE_TYPE_B || s->first_field) {
 +                ref2picture = ref_picture;
 +            } else {
 +                ref2picture = s->current_picture_ptr->f->data;
 +            }
 +
 +            mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
 +                               0, 0, s->field_select[dir][i],
 +                               ref2picture, pix_op,
 +                               s->mv[dir][i][0], s->mv[dir][i][1] +
 +                               2 * block_s * i, block_s, mb_y >> 1);
 +
 +            dest_y  +=  2 * block_s *  s->linesize;
 +            dest_cb += (2 * block_s >> s->chroma_y_shift) * s->uvlinesize;
 +            dest_cr += (2 * block_s >> s->chroma_y_shift) * s->uvlinesize;
 +        }
 +        break;
 +    case MV_TYPE_DMV:
 +        if (s->picture_structure == PICT_FRAME) {
 +            for (i = 0; i < 2; i++) {
 +                int j;
 +                for (j = 0; j < 2; j++) {
 +                    mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
 +                                       1, j, j ^ i,
 +                                       ref_picture, pix_op,
 +                                       s->mv[dir][2 * i + j][0],
 +                                       s->mv[dir][2 * i + j][1],
 +                                       block_s, mb_y);
 +                }
 +                pix_op = s->h264chroma.avg_h264_chroma_pixels_tab;
 +            }
 +        } else {
 +            for (i = 0; i < 2; i++) {
 +                mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
 +                                   0, 0, s->picture_structure != i + 1,
 +                                   ref_picture, pix_op,
 +                                   s->mv[dir][2 * i][0],s->mv[dir][2 * i][1],
 +                                   2 * block_s, mb_y >> 1);
 +
 +                // after put we make avg of the same block
 +                pix_op = s->h264chroma.avg_h264_chroma_pixels_tab;
 +
 +                // opposite parity is always in the same
 +                // frame if this is second field
 +                if (!s->first_field) {
 +                    ref_picture = s->current_picture_ptr->f->data;
 +                }
 +            }
 +        }
 +        break;
 +    default:
 +        av_assert2(0);
 +    }
  }
  
  /**
@@@ -2352,14 -1471,14 +2352,14 @@@ int ff_mpv_lowest_referenced_row(MpegEn
      }
  
      for (i = 0; i < mvs; i++) {
 -        my = s->mv[dir][i][1]<<qpel_shift;
 +        my = s->mv[dir][i][1];
          my_max = FFMAX(my_max, my);
          my_min = FFMIN(my_min, my);
      }
  
 -    off = (FFMAX(-my_min, my_max) + 63) >> 6;
 +    off = ((FFMAX(-my_min, my_max)<<qpel_shift) + 63) >> 6;
  
 -    return FFMIN(FFMAX(s->mb_y + off, 0), s->mb_height-1);
 +    return av_clip(s->mb_y + off, 0, s->mb_height - 1);
  unhandled:
      return s->mb_height-1;
  }
@@@ -2436,15 -1555,18 +2436,15 @@@ void ff_clean_intra_table_entries(MpegE
   */
  static av_always_inline
  void mpv_decode_mb_internal(MpegEncContext *s, int16_t block[12][64],
 -                            int is_mpeg12)
 +                            int lowres_flag, int is_mpeg12)
  {
      const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
  
 -#if FF_API_XVMC
 -FF_DISABLE_DEPRECATION_WARNINGS
 -    if(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration){
 -        ff_xvmc_decode_mb(s);//xvmc uses pblocks
 +    if (CONFIG_XVMC &&
 +        s->avctx->hwaccel && s->avctx->hwaccel->decode_mb) {
 +        s->avctx->hwaccel->decode_mb(s);//xvmc uses pblocks
          return;
      }
 -FF_ENABLE_DEPRECATION_WARNINGS
 -#endif /* FF_API_XVMC */
  
      if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {
         /* print DCT coefficients */
      else if (!is_mpeg12 && (s->h263_pred || s->h263_aic))
          s->mbintra_table[mb_xy]=1;
  
 -    if ((s->avctx->flags & CODEC_FLAG_PSNR) ||
 +    if ((s->avctx->flags & CODEC_FLAG_PSNR) || s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor ||
          !(s->encoding && (s->intra_only || s->pict_type == AV_PICTURE_TYPE_B) &&
            s->avctx->mb_decision != FF_MB_DECISION_RD)) { // FIXME precalc
          uint8_t *dest_y, *dest_cb, *dest_cr;
          qpel_mc_func (*op_qpix)[16];
          const int linesize   = s->current_picture.f->linesize[0]; //not s->linesize as this would be wrong for field pics
          const int uvlinesize = s->current_picture.f->linesize[1];
 -        const int readable= s->pict_type != AV_PICTURE_TYPE_B || s->encoding || s->avctx->draw_horiz_band;
 -        const int block_size = 8;
 +        const int readable= s->pict_type != AV_PICTURE_TYPE_B || s->encoding || s->avctx->draw_horiz_band || lowres_flag;
 +        const int block_size= lowres_flag ? 8>>s->avctx->lowres : 8;
  
          /* avoid copy if macroblock skipped in last frame too */
          /* skip only during decoding as we might trash the buffers during encoding a bit */
  
              if (s->mb_skipped) {
                  s->mb_skipped= 0;
 -                assert(s->pict_type!=AV_PICTURE_TYPE_I);
 +                av_assert2(s->pict_type!=AV_PICTURE_TYPE_I);
                  *mbskip_ptr = 1;
              } else if(!s->current_picture.reference) {
                  *mbskip_ptr = 1;
                      }
                  }
  
 -                op_qpix= s->me.qpel_put;
 -                if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
 -                    op_pix = s->hdsp.put_pixels_tab;
 +                if(lowres_flag){
 +                    h264_chroma_mc_func *op_pix = s->h264chroma.put_h264_chroma_pixels_tab;
 +
 +                    if (s->mv_dir & MV_DIR_FORWARD) {
 +                        MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f->data, op_pix);
 +                        op_pix = s->h264chroma.avg_h264_chroma_pixels_tab;
 +                    }
 +                    if (s->mv_dir & MV_DIR_BACKWARD) {
 +                        MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f->data, op_pix);
 +                    }
                  }else{
 -                    op_pix = s->hdsp.put_no_rnd_pixels_tab;
 -                }
 -                if (s->mv_dir & MV_DIR_FORWARD) {
 -                    ff_mpv_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f->data, op_pix, op_qpix);
 -                    op_pix = s->hdsp.avg_pixels_tab;
 -                    op_qpix= s->me.qpel_avg;
 -                }
 -                if (s->mv_dir & MV_DIR_BACKWARD) {
 -                    ff_mpv_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f->data, op_pix, op_qpix);
 +                    op_qpix = s->me.qpel_put;
 +                    if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
 +                        op_pix = s->hdsp.put_pixels_tab;
 +                    }else{
 +                        op_pix = s->hdsp.put_no_rnd_pixels_tab;
 +                    }
 +                    if (s->mv_dir & MV_DIR_FORWARD) {
 +                        ff_mpv_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f->data, op_pix, op_qpix);
 +                        op_pix = s->hdsp.avg_pixels_tab;
 +                        op_qpix= s->me.qpel_avg;
 +                    }
 +                    if (s->mv_dir & MV_DIR_BACKWARD) {
 +                        ff_mpv_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f->data, op_pix, op_qpix);
 +                    }
                  }
              }
  
                      }else{
                          //chroma422
                          dct_linesize = uvlinesize << s->interlaced_dct;
 -                        dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize * 8;
 +                        dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize*block_size;
  
                          add_dct(s, block[4], 4, dest_cb, dct_linesize);
                          add_dct(s, block[5], 5, dest_cr, dct_linesize);
                          add_dct(s, block[6], 6, dest_cb+dct_offset, dct_linesize);
                          add_dct(s, block[7], 7, dest_cr+dct_offset, dct_linesize);
                          if(!s->chroma_x_shift){//Chroma444
 -                            add_dct(s, block[8], 8, dest_cb+8, dct_linesize);
 -                            add_dct(s, block[9], 9, dest_cr+8, dct_linesize);
 -                            add_dct(s, block[10], 10, dest_cb+8+dct_offset, dct_linesize);
 -                            add_dct(s, block[11], 11, dest_cr+8+dct_offset, dct_linesize);
 +                            add_dct(s, block[8], 8, dest_cb+block_size, dct_linesize);
 +                            add_dct(s, block[9], 9, dest_cr+block_size, dct_linesize);
 +                            add_dct(s, block[10], 10, dest_cb+block_size+dct_offset, dct_linesize);
 +                            add_dct(s, block[11], 11, dest_cr+block_size+dct_offset, dct_linesize);
                          }
                      }
                  }//fi gray
                      }else{
  
                          dct_linesize = uvlinesize << s->interlaced_dct;
 -                        dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize * 8;
 +                        dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize*block_size;
  
                          s->idsp.idct_put(dest_cb,              dct_linesize, block[4]);
                          s->idsp.idct_put(dest_cr,              dct_linesize, block[5]);
                          s->idsp.idct_put(dest_cb + dct_offset, dct_linesize, block[6]);
                          s->idsp.idct_put(dest_cr + dct_offset, dct_linesize, block[7]);
                          if(!s->chroma_x_shift){//Chroma444
 -                            s->idsp.idct_put(dest_cb + 8,              dct_linesize, block[8]);
 -                            s->idsp.idct_put(dest_cr + 8,              dct_linesize, block[9]);
 -                            s->idsp.idct_put(dest_cb + 8 + dct_offset, dct_linesize, block[10]);
 -                            s->idsp.idct_put(dest_cr + 8 + dct_offset, dct_linesize, block[11]);
 +                            s->idsp.idct_put(dest_cb + block_size,              dct_linesize, block[8]);
 +                            s->idsp.idct_put(dest_cr + block_size,              dct_linesize, block[9]);
 +                            s->idsp.idct_put(dest_cb + block_size + dct_offset, dct_linesize, block[10]);
 +                            s->idsp.idct_put(dest_cr + block_size + dct_offset, dct_linesize, block[11]);
                          }
                      }
                  }//gray
  skip_idct:
          if(!readable){
              s->hdsp.put_pixels_tab[0][0](s->dest[0], dest_y ,   linesize,16);
 -            s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[1], dest_cb, uvlinesize,16 >> s->chroma_y_shift);
 -            s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[2], dest_cr, uvlinesize,16 >> s->chroma_y_shift);
 +            if (!CONFIG_GRAY || !(s->avctx->flags & CODEC_FLAG_GRAY)) {
 +                s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[1], dest_cb, uvlinesize,16 >> s->chroma_y_shift);
 +                s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[2], dest_cr, uvlinesize,16 >> s->chroma_y_shift);
 +            }
          }
      }
  }
@@@ -2687,25 -1795,23 +2687,25 @@@ void ff_mpv_decode_mb(MpegEncContext *s
  {
  #if !CONFIG_SMALL
      if(s->out_format == FMT_MPEG1) {
 -        mpv_decode_mb_internal(s, block, 1);
 +        if(s->avctx->lowres) mpv_decode_mb_internal(s, block, 1, 1);
 +        else                 mpv_decode_mb_internal(s, block, 0, 1);
      } else
  #endif
 -        mpv_decode_mb_internal(s, block, 0);
 +    if(s->avctx->lowres) mpv_decode_mb_internal(s, block, 1, 0);
 +    else                  mpv_decode_mb_internal(s, block, 0, 0);
  }
  
  void ff_mpeg_draw_horiz_band(MpegEncContext *s, int y, int h)
  {
 -    ff_draw_horiz_band(s->avctx, s->current_picture.f,
 -                       s->last_picture.f, y, h, s->picture_structure,
 +    ff_draw_horiz_band(s->avctx, s->current_picture_ptr->f,
 +                       s->last_picture_ptr ? s->last_picture_ptr->f : NULL, y, h, s->picture_structure,
                         s->first_field, s->low_delay);
  }
  
  void ff_init_block_index(MpegEncContext *s){ //FIXME maybe rename
      const int linesize   = s->current_picture.f->linesize[0]; //not s->linesize as this would be wrong for field pics
      const int uvlinesize = s->current_picture.f->linesize[1];
 -    const int mb_size= 4;
 +    const int mb_size= 4 - s->avctx->lowres;
  
      s->block_index[0]= s->b8_stride*(s->mb_y*2    ) - 2 + s->mb_x*2;
      s->block_index[1]= s->b8_stride*(s->mb_y*2    ) - 1 + s->mb_x*2;
      s->block_index[5]= s->mb_stride*(s->mb_y + s->mb_height + 2) + s->b8_stride*s->mb_height*2 + s->mb_x - 1;
      //block_index is not used by mpeg2, so it is not affected by chroma_format
  
 -    s->dest[0] = s->current_picture.f->data[0] + ((s->mb_x - 1) <<  mb_size);
 -    s->dest[1] = s->current_picture.f->data[1] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
 -    s->dest[2] = s->current_picture.f->data[2] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
 +    s->dest[0] = s->current_picture.f->data[0] + (int)((s->mb_x - 1U) <<  mb_size);
 +    s->dest[1] = s->current_picture.f->data[1] + (int)((s->mb_x - 1U) << (mb_size - s->chroma_x_shift));
 +    s->dest[2] = s->current_picture.f->data[2] + (int)((s->mb_x - 1U) << (mb_size - s->chroma_x_shift));
  
      if(!(s->pict_type==AV_PICTURE_TYPE_B && s->avctx->draw_horiz_band && s->picture_structure==PICT_FRAME))
      {
              s->dest[0] += (s->mb_y>>1) *   linesize << mb_size;
              s->dest[1] += (s->mb_y>>1) * uvlinesize << (mb_size - s->chroma_y_shift);
              s->dest[2] += (s->mb_y>>1) * uvlinesize << (mb_size - s->chroma_y_shift);
 -            assert((s->mb_y&1) == (s->picture_structure == PICT_BOTTOM_FIELD));
 +            av_assert1((s->mb_y&1) == (s->picture_structure == PICT_BOTTOM_FIELD));
          }
      }
  }
  
- /**
-  * Permute an 8x8 block.
-  * @param block the block which will be permuted according to the given permutation vector
-  * @param permutation the permutation vector
-  * @param last the last non zero coefficient in scantable order, used to speed the permutation up
-  * @param scantable the used scantable, this is only used to speed the permutation up, the block is not
-  *                  (inverse) permutated to scantable order!
-  */
- void ff_block_permute(int16_t *block, uint8_t *permutation, const uint8_t *scantable, int last)
- {
-     int i;
-     int16_t temp[64];
-     if(last<=0) return;
-     //if(permutation[1]==1) return; //FIXME it is ok but not clean and might fail for some permutations
-     for(i=0; i<=last; i++){
-         const int j= scantable[i];
-         temp[j]= block[j];
-         block[j]=0;
-     }
-     for(i=0; i<=last; i++){
-         const int j= scantable[i];
-         const int perm_j= permutation[j];
-         block[perm_j]= temp[j];
-     }
- }
  void ff_mpeg_flush(AVCodecContext *avctx){
      int i;
      MpegEncContext *s = avctx->priv_data;
      ff_mpeg_unref_picture(s->avctx, &s->next_picture);
  
      s->mb_x= s->mb_y= 0;
 +    s->closed_gop= 0;
  
      s->parse_context.state= -1;
      s->parse_context.frame_start_found= 0;
diff --combined libavcodec/mpegvideo.h
index 95ddc0f6660de1b25d901592c99043b0de9442ed,1a6857dd425e2a5656ce75a6f0e65fc8e5c6a382..e538695a98b1db9c20ae8b6380b156fbb9a82600
@@@ -3,20 -3,20 +3,20 @@@
   * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
   * Copyright (c) 2002-2004 Michael Niedermayer
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
@@@ -35,7 -35,6 +35,7 @@@
  #include "error_resilience.h"
  #include "fdctdsp.h"
  #include "get_bits.h"
 +#include "h264chroma.h"
  #include "h263dsp.h"
  #include "hpeldsp.h"
  #include "idctdsp.h"
  #include "videodsp.h"
  
  #include "libavutil/opt.h"
 +#include "libavutil/timecode.h"
  
  #define FRAME_SKIPPED 100 ///< return value for header parsers if frame is not coded
  
  #define MAX_FCODE 7
  
 -#define MAX_THREADS 16
 +#define MAX_THREADS 32
  
  #define MAX_B_FRAMES 16
  
@@@ -197,7 -195,7 +197,7 @@@ typedef struct MpegEncContext 
      uint8_t *coded_block_base;
      uint8_t *coded_block;          ///< used for coded block pattern prediction (msmpeg4v3, wmv1)
      int16_t (*ac_val_base)[16];
 -    int16_t (*ac_val[3])[16];      ///< used for for mpeg4 AC prediction, all 3 arrays must be continuous
 +    int16_t (*ac_val[3])[16];      ///< used for mpeg4 AC prediction, all 3 arrays must be continuous
      int mb_skipped;                ///< MUST BE SET only during DECODING
      uint8_t *mbskip_table;        /**< used to avoid copy if macroblock skipped (for black regions for example)
                                     and used for b-frame encoding & decoding (contains skip table of next P Frame) */
      int *lambda_table;
      int adaptive_quant;         ///< use adaptive quantization
      int dquant;                 ///< qscale difference to prev qscale
 +    int closed_gop;             ///< MPEG1/2 GOP is closed
      int pict_type;              ///< AV_PICTURE_TYPE_I, AV_PICTURE_TYPE_P, AV_PICTURE_TYPE_B, ...
 +    int vbv_delay;
      int last_pict_type; //FIXME removes
      int last_non_b_pict_type;   ///< used for mpeg4 gmc b-frames & ratecontrol
      int droppable;
      int frame_rate_index;
 +    AVRational mpeg2_frame_rate_ext;
      int last_lambda_for[5];     ///< last lambda for a specific pict type
      int skipdct;                ///< skip dct and code zero residual
  
  
      BlockDSPContext bdsp;
      FDCTDSPContext fdsp;
 +    H264ChromaContext h264chroma;
      HpelDSPContext hdsp;
      IDCTDSPContext idsp;
      MECmpContext mecc;
      int ac_esc_length;       ///< num of bits needed to encode the longest esc
      uint8_t *intra_ac_vlc_length;
      uint8_t *intra_ac_vlc_last_length;
 +    uint8_t *intra_chroma_ac_vlc_length;
 +    uint8_t *intra_chroma_ac_vlc_last_length;
      uint8_t *inter_ac_vlc_length;
      uint8_t *inter_ac_vlc_last_length;
      uint8_t *luma_dc_vlc_length;
  #define UNI_AC_ENC_INDEX(run,level) ((run)*128 + (level))
  
 -    int coded_score[8];
 +    int coded_score[12];
  
      /** precomputed matrix (combine qscale and DCT renorm) */
      int (*q_intra_matrix)[64];
 +    int (*q_chroma_intra_matrix)[64];
      int (*q_inter_matrix)[64];
      /** identical to the above but for MMX & these are not permutated, second 64 entries are bias*/
      uint16_t (*q_intra_matrix16)[2][64];
 +    uint16_t (*q_chroma_intra_matrix16)[2][64];
      uint16_t (*q_inter_matrix16)[2][64];
  
      /* noise reduction */
      /* bit rate control */
      int64_t total_bits;
      int frame_bits;                ///< bits used for the current frame
 +    int stuffing_bits;             ///< bits used for stuffing
      int next_lambda;               ///< next lambda used for retrying to encode a frame
      RateControlContext rc_context; ///< contains stuff only accessed in ratecontrol.c
  
      int prev_mb_info, last_mb_info;
      uint8_t *mb_info_ptr;
      int mb_info_size;
 +    int ehc_mode;
  
      /* H.263+ specific */
      int umvplus;                    ///< == H263+ && unrestricted_mv
  
      /* MJPEG specific */
      struct MJpegContext *mjpeg_ctx;
 +    int esc_pos;
  
      /* MSMPEG4 specific */
      int mv_table_index;
      int q_scale_type;
      int intra_vlc_format;
      int alternate_scan;
 +    int seq_disp_ext;
      int repeat_first_field;
      int chroma_420_type;
      int chroma_format;
  #define CHROMA_420 1
  #define CHROMA_422 2
 +#define CHROMA_444 3
      int chroma_x_shift;//depend on pix_format, that depend on chroma_format
      int chroma_y_shift;
  
      /* RTP specific */
      int rtp_mode;
  
 +    char *tc_opt_str;        ///< timecode option string
 +    AVTimecode tc;           ///< timecode context
 +
      uint8_t *ptr_lastgob;
 +    int swap_uv;             //vcr2 codec is an MPEG-2 variant with U and V swapped
 +    int pack_pblocks;        //xvmc needs to keep blocks without gaps.
      int16_t (*pblocks[12])[64];
  
      int16_t (*block)[64]; ///< points to one of the following blocks
  
      /**
       * ratecontrol qmin qmax limiting method
 -     * 0-> clipping, 1-> use a nice continuous function to limit qscale wthin qmin/qmax.
 +     * 0-> clipping, 1-> use a nice continuous function to limit qscale within qmin/qmax.
       */
      float rc_qsquish;
      float rc_qmod_amp;
  #define FF_MPV_FLAG_NAQ          0x0010
  #define FF_MPV_FLAG_MV0          0x0020
  
 +#ifndef FF_MPV_OFFSET
  #define FF_MPV_OFFSET(x) offsetof(MpegEncContext, x)
 +#endif
  #define FF_MPV_OPT_FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  #define FF_MPV_COMMON_OPTS \
  { "mpv_flags",      "Flags common for all mpegvideo-based encoders.", FF_MPV_OFFSET(mpv_flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT_MIN, INT_MAX, FF_MPV_OPT_FLAGS, "mpv_flags" },\
@@@ -611,11 -589,8 +611,11 @@@ static const AVClass name ## _class = {
   */
  void ff_mpv_common_defaults(MpegEncContext *s);
  
 +void ff_dct_encode_init_x86(MpegEncContext *s);
 +
  int ff_mpv_common_init(MpegEncContext *s);
  void ff_mpv_common_init_arm(MpegEncContext *s);
 +void ff_mpv_common_init_axp(MpegEncContext *s);
  void ff_mpv_common_init_neon(MpegEncContext *s);
  void ff_mpv_common_init_ppc(MpegEncContext *s);
  void ff_mpv_common_init_x86(MpegEncContext *s);
@@@ -624,7 -599,6 +624,7 @@@ int ff_mpv_common_frame_size_change(Mpe
  void ff_mpv_common_end(MpegEncContext *s);
  
  void ff_mpv_decode_defaults(MpegEncContext *s);
 +void ff_mpv_decode_init(MpegEncContext *s, AVCodecContext *avctx);
  void ff_mpv_decode_mb(MpegEncContext *s, int16_t block[12][64]);
  void ff_mpv_report_decode_progress(MpegEncContext *s);
  
@@@ -639,20 -613,11 +639,20 @@@ void ff_mpv_encode_init_x86(MpegEncCont
  int ff_mpv_encode_end(AVCodecContext *avctx);
  int ff_mpv_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
                            const AVFrame *frame, int *got_packet);
 +int ff_mpv_reallocate_putbitbuffer(MpegEncContext *s, size_t threshold, size_t size_increase);
  
  void ff_clean_intra_table_entries(MpegEncContext *s);
  void ff_mpeg_draw_horiz_band(MpegEncContext *s, int y, int h);
  void ff_mpeg_flush(AVCodecContext *avctx);
 -void ff_print_debug_info(MpegEncContext *s, Picture *p);
 +
 +void ff_print_debug_info(MpegEncContext *s, Picture *p, AVFrame *pict);
 +void ff_print_debug_info2(AVCodecContext *avctx, AVFrame *pict, uint8_t *mbskip_table,
 +                         uint32_t *mbtype_table, int8_t *qscale_table, int16_t (*motion_val[2])[2],
 +                         int *low_delay,
 +                         int mb_width, int mb_height, int mb_stride, int quarter_sample);
 +
 +int ff_mpv_export_qp_table(MpegEncContext *s, AVFrame *f, Picture *p, int qp_type);
 +
  void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix);
  
  int ff_update_duplicate_context(MpegEncContext *dst, MpegEncContext *src);
@@@ -660,7 -625,6 +660,7 @@@ int ff_mpeg_update_thread_context(AVCod
  void ff_set_qscale(MpegEncContext * s, int qscale);
  
  void ff_mpv_idct_init(MpegEncContext *s);
 +int ff_dct_encode_init(MpegEncContext *s);
  void ff_convert_matrix(MpegEncContext *s, int (*qmat)[64], uint16_t (*qmat16)[2][64],
                         const uint16_t *quant_matrix, int bias, int qmin, int qmax, int intra);
  int ff_dct_quantize_c(MpegEncContext *s, int16_t *block, int n, int qscale, int *overflow);
@@@ -674,14 -638,8 +674,8 @@@ void ff_mpv_motion(MpegEncContext *s
                     op_pixels_func (*pix_op)[4],
                     qpel_mc_func (*qpix_op)[16]);
  
- /**
-  * permute block according to permuatation.
-  * @param last last non zero element in scantable order
-  */
- void ff_block_permute(int16_t *block, uint8_t *permutation, const uint8_t *scantable, int last);
  static inline void ff_update_block_index(MpegEncContext *s){
 -    const int block_size = 8;
 +    const int block_size= 8 >> s->avctx->lowres;
  
      s->block_index[0]+=2;
      s->block_index[1]+=2;
index 49fc083d3f423ec7b0958e1dceb4b12b4cf17d83,6fe34b57f89dae05dcf5a9e23f5c9051aa0c8cba..ee6496a60377fc4026f0238fa88b9a78d7f0e26b
@@@ -5,20 -5,20 +5,20 @@@
   *
   * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
   *
 - * This file is part of Libav.
 + * This file is part of FFmpeg.
   *
 - * Libav is free software; you can redistribute it and/or
 + * FFmpeg is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
 - * Libav is distributed in the hope that it will be useful,
 + * FFmpeg is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
 - * License along with Libav; if not, write to the Free Software
 + * License along with FFmpeg; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
   */
  
  #include "bytestream.h"
  #include "wmv2.h"
  #include <limits.h>
 +#include "sp5x.h"
  
  #define QUANT_BIAS_SHIFT 8
  
  #define QMAT_SHIFT_MMX 16
 -#define QMAT_SHIFT 22
 +#define QMAT_SHIFT 21
  
  static int encode_picture(MpegEncContext *s, int picture_number);
  static int dct_quantize_refine(MpegEncContext *s, int16_t *block, int16_t *weight, int16_t *orig, int n, int qscale);
@@@ -236,23 -235,6 +236,23 @@@ static void mpv_encode_defaults(MpegEnc
      s->picture_in_gop_number = 0;
  }
  
 +av_cold int ff_dct_encode_init(MpegEncContext *s) {
 +    if (ARCH_X86)
 +        ff_dct_encode_init_x86(s);
 +
 +    if (CONFIG_H263_ENCODER)
 +        ff_h263dsp_init(&s->h263dsp);
 +    if (!s->dct_quantize)
 +        s->dct_quantize = ff_dct_quantize_c;
 +    if (!s->denoise_dct)
 +        s->denoise_dct  = denoise_dct_c;
 +    s->fast_dct_quantize = s->dct_quantize;
 +    if (s->avctx->trellis)
 +        s->dct_quantize  = dct_quantize_trellis_c;
 +
 +    return 0;
 +}
 +
  /* init video encoder */
  av_cold int ff_mpv_encode_init(AVCodecContext *avctx)
  {
          }
          break;
      case AV_CODEC_ID_MJPEG:
 +    case AV_CODEC_ID_AMV:
          format_supported = 0;
          /* JPEG color space */
          if (avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||
              avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
 +            avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
              (avctx->color_range == AVCOL_RANGE_JPEG &&
               (avctx->pix_fmt == AV_PIX_FMT_YUV420P ||
 -              avctx->pix_fmt == AV_PIX_FMT_YUV422P)))
 +              avctx->pix_fmt == AV_PIX_FMT_YUV422P ||
 +              avctx->pix_fmt == AV_PIX_FMT_YUV444P)))
              format_supported = 1;
          /* MPEG color space */
          else if (avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL &&
                   (avctx->pix_fmt == AV_PIX_FMT_YUV420P ||
 -                  avctx->pix_fmt == AV_PIX_FMT_YUV422P))
 +                  avctx->pix_fmt == AV_PIX_FMT_YUV422P ||
 +                  avctx->pix_fmt == AV_PIX_FMT_YUV444P))
              format_supported = 1;
  
          if (!format_supported) {
      }
  
      switch (avctx->pix_fmt) {
 +    case AV_PIX_FMT_YUVJ444P:
 +    case AV_PIX_FMT_YUV444P:
 +        s->chroma_format = CHROMA_444;
 +        break;
      case AV_PIX_FMT_YUVJ422P:
      case AV_PIX_FMT_YUV422P:
          s->chroma_format = CHROMA_422;
      s->height   = avctx->height;
      if (avctx->gop_size > 600 &&
          avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
 -        av_log(avctx, AV_LOG_ERROR,
 -               "Warning keyframe interval too large! reducing it ...\n");
 +        av_log(avctx, AV_LOG_WARNING,
 +               "keyframe interval too large!, reducing it from %d to %d\n",
 +               avctx->gop_size, 600);
          avctx->gop_size = 600;
      }
      s->gop_size     = avctx->gop_size;
      if (avctx->max_b_frames > MAX_B_FRAMES) {
          av_log(avctx, AV_LOG_ERROR, "Too many B-frames requested, maximum "
                 "is %d.\n", MAX_B_FRAMES);
 +        avctx->max_b_frames = MAX_B_FRAMES;
      }
      s->max_b_frames = avctx->max_b_frames;
      s->codec_id     = avctx->codec->id;
      s->mpeg_quant         = avctx->mpeg_quant;
      s->rtp_mode           = !!avctx->rtp_payload_size;
      s->intra_dc_precision = avctx->intra_dc_precision;
 +
 +    // workaround some differences between how applications specify dc precision
 +    if (s->intra_dc_precision < 0) {
 +        s->intra_dc_precision += 8;
 +    } else if (s->intra_dc_precision >= 8)
 +        s->intra_dc_precision -= 8;
 +
 +    if (s->intra_dc_precision < 0) {
 +        av_log(avctx, AV_LOG_ERROR,
 +                "intra dc precision must be positive, note some applications use"
 +                " 0 and some 8 as base meaning 8bit, the value must not be smaller than that\n");
 +        return AVERROR(EINVAL);
 +    }
 +
 +    if (s->intra_dc_precision > (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO ? 3 : 0)) {
 +        av_log(avctx, AV_LOG_ERROR, "intra dc precision too large\n");
 +        return AVERROR(EINVAL);
 +    }
      s->user_specified_pts = AV_NOPTS_VALUE;
  
      if (s->gop_size <= 1) {
      s->loop_filter = !!(s->avctx->flags & CODEC_FLAG_LOOP_FILTER);
  
      if (avctx->rc_max_rate && !avctx->rc_buffer_size) {
 -        av_log(avctx, AV_LOG_ERROR,
 -               "a vbv buffer size is needed, "
 -               "for encoding with a maximum bitrate\n");
 +        switch(avctx->codec_id) {
 +        case AV_CODEC_ID_MPEG1VIDEO:
 +        case AV_CODEC_ID_MPEG2VIDEO:
 +            avctx->rc_buffer_size = FFMAX(avctx->rc_max_rate, 15000000) * 112LL / 15000000 * 16384;
 +            break;
 +        case AV_CODEC_ID_MPEG4:
 +        case AV_CODEC_ID_MSMPEG4V1:
 +        case AV_CODEC_ID_MSMPEG4V2:
 +        case AV_CODEC_ID_MSMPEG4V3:
 +            if       (avctx->rc_max_rate >= 15000000) {
 +                avctx->rc_buffer_size = 320 + (avctx->rc_max_rate - 15000000LL) * (760-320) / (38400000 - 15000000);
 +            } else if(avctx->rc_max_rate >=  2000000) {
 +                avctx->rc_buffer_size =  80 + (avctx->rc_max_rate -  2000000LL) * (320- 80) / (15000000 -  2000000);
 +            } else if(avctx->rc_max_rate >=   384000) {
 +                avctx->rc_buffer_size =  40 + (avctx->rc_max_rate -   384000LL) * ( 80- 40) / ( 2000000 -   384000);
 +            } else
 +                avctx->rc_buffer_size = 40;
 +            avctx->rc_buffer_size *= 16384;
 +            break;
 +        }
 +        if (avctx->rc_buffer_size) {
 +            av_log(avctx, AV_LOG_INFO, "Automatically choosing VBV buffer size of %d kbyte\n", avctx->rc_buffer_size/8192);
 +        }
 +    }
 +
 +    if ((!avctx->rc_max_rate) != (!avctx->rc_buffer_size)) {
 +        av_log(avctx, AV_LOG_ERROR, "Either both buffer size and max rate or neither must be specified\n");
          return -1;
      }
  
      }
  
      if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {
 -        av_log(avctx, AV_LOG_INFO, "bitrate above max bitrate\n");
 +        av_log(avctx, AV_LOG_ERROR, "bitrate above max bitrate\n");
          return -1;
      }
  
      if (!s->fixed_qscale &&
          avctx->bit_rate * av_q2d(avctx->time_base) >
              avctx->bit_rate_tolerance) {
 -        av_log(avctx, AV_LOG_ERROR,
 -               "bitrate tolerance too small for bitrate\n");
 -        return -1;
 +        av_log(avctx, AV_LOG_WARNING,
 +               "bitrate tolerance %d too small for bitrate %d, overriding\n", avctx->bit_rate_tolerance, avctx->bit_rate);
 +        avctx->bit_rate_tolerance = 5 * avctx->bit_rate * av_q2d(avctx->time_base);
      }
  
      if (s->avctx->rc_max_rate &&
          av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
          return -1;
      }
 +    if (s->max_b_frames < 0) {
 +        av_log(avctx, AV_LOG_ERROR,
 +               "max b frames must be 0 or positive for mpegvideo based encoders\n");
 +        return -1;
 +    }
  
      if ((s->codec_id == AV_CODEC_ID_MPEG4 ||
           s->codec_id == AV_CODEC_ID_H263  ||
           s->codec_id == AV_CODEC_ID_H263P) &&
          (avctx->sample_aspect_ratio.num > 255 ||
           avctx->sample_aspect_ratio.den > 255)) {
 -        av_log(avctx, AV_LOG_ERROR,
 -               "Invalid pixel aspect ratio %i/%i, limit is 255/255\n",
 +        av_log(avctx, AV_LOG_WARNING,
 +               "Invalid pixel aspect ratio %i/%i, limit is 255/255 reducing\n",
                 avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
 +        av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,
 +                   avctx->sample_aspect_ratio.num,  avctx->sample_aspect_ratio.den, 255);
 +    }
 +
 +    if ((s->codec_id == AV_CODEC_ID_H263  ||
 +         s->codec_id == AV_CODEC_ID_H263P) &&
 +        (avctx->width  > 2048 ||
 +         avctx->height > 1152 )) {
 +        av_log(avctx, AV_LOG_ERROR, "H.263 does not support resolutions above 2048x1152\n");
 +        return -1;
 +    }
 +    if ((s->codec_id == AV_CODEC_ID_H263  ||
 +         s->codec_id == AV_CODEC_ID_H263P) &&
 +        ((avctx->width &3) ||
 +         (avctx->height&3) )) {
 +        av_log(avctx, AV_LOG_ERROR, "w/h must be a multiple of 4\n");
 +        return -1;
 +    }
 +
 +    if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO &&
 +        (avctx->width  > 4095 ||
 +         avctx->height > 4095 )) {
 +        av_log(avctx, AV_LOG_ERROR, "MPEG-1 does not support resolutions above 4095x4095\n");
 +        return -1;
 +    }
 +
 +    if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
 +        (avctx->width  > 16383 ||
 +         avctx->height > 16383 )) {
 +        av_log(avctx, AV_LOG_ERROR, "MPEG-2 does not support resolutions above 16383x16383\n");
          return -1;
      }
  
 +    if (s->codec_id == AV_CODEC_ID_RV10 &&
 +        (avctx->width &15 ||
 +         avctx->height&15 )) {
 +        av_log(avctx, AV_LOG_ERROR, "width and height must be a multiple of 16\n");
 +        return AVERROR(EINVAL);
 +    }
 +
 +    if (s->codec_id == AV_CODEC_ID_RV20 &&
 +        (avctx->width &3 ||
 +         avctx->height&3 )) {
 +        av_log(avctx, AV_LOG_ERROR, "width and height must be a multiple of 4\n");
 +        return AVERROR(EINVAL);
 +    }
 +
 +    if ((s->codec_id == AV_CODEC_ID_WMV1 ||
 +         s->codec_id == AV_CODEC_ID_WMV2) &&
 +         avctx->width & 1) {
 +         av_log(avctx, AV_LOG_ERROR, "width must be multiple of 2\n");
 +         return -1;
 +    }
 +
      if ((s->avctx->flags & (CODEC_FLAG_INTERLACED_DCT | CODEC_FLAG_INTERLACED_ME)) &&
          s->codec_id != AV_CODEC_ID_MPEG4 && s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
          av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");
      }
  
      // FIXME mpeg2 uses that too
 -    if (s->mpeg_quant && s->codec_id != AV_CODEC_ID_MPEG4) {
 +    if (s->mpeg_quant && (   s->codec_id != AV_CODEC_ID_MPEG4
 +                          && s->codec_id != AV_CODEC_ID_MPEG2VIDEO)) {
          av_log(avctx, AV_LOG_ERROR,
                 "mpeg2 style quantization not supported by codec\n");
          return -1;
          s->codec_id != AV_CODEC_ID_MPEG4      &&
          s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&
          s->codec_id != AV_CODEC_ID_MPEG2VIDEO &&
 +        s->codec_id != AV_CODEC_ID_MJPEG      &&
          (s->codec_id != AV_CODEC_ID_H263P)) {
          av_log(avctx, AV_LOG_ERROR,
                 "multi threaded encoding not supported by codec\n");
  
      if (s->avctx->thread_count < 1) {
          av_log(avctx, AV_LOG_ERROR,
 -               "automatic thread number detection not supported by codec,"
 +               "automatic thread number detection not supported by codec, "
                 "patch welcome\n");
          return -1;
      }
  
 -    if (s->avctx->thread_count > 1)
 +    if (s->avctx->slices > 1 || s->avctx->thread_count > 1)
          s->rtp_mode = 1;
  
 +    if (s->avctx->thread_count > 1 && s->codec_id == AV_CODEC_ID_H263P)
 +        s->h263_slice_structured = 1;
 +
      if (!avctx->time_base.den || !avctx->time_base.num) {
          av_log(avctx, AV_LOG_ERROR, "framerate not set\n");
          return -1;
          //return -1;
      }
  
 -    if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
 -        s->codec_id == AV_CODEC_ID_MPEG2VIDEO || s->codec_id == AV_CODEC_ID_MJPEG) {
 +    if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG1VIDEO || s->codec_id == AV_CODEC_ID_MPEG2VIDEO || s->codec_id == AV_CODEC_ID_MJPEG || s->codec_id==AV_CODEC_ID_AMV) {
          // (a + x * 3 / 8) / x
          s->intra_quant_bias = 3 << (QUANT_BIAS_SHIFT - 3);
          s->inter_quant_bias = 0;
          s->inter_quant_bias = -(1 << (QUANT_BIAS_SHIFT - 2));
      }
  
 +    if (avctx->qmin > avctx->qmax || avctx->qmin <= 0) {
 +        av_log(avctx, AV_LOG_ERROR, "qmin and or qmax are invalid, they must be 0 < min <= max\n");
 +        return AVERROR(EINVAL);
 +    }
 +
      if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
          s->intra_quant_bias = avctx->intra_quant_bias;
      if (avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
          s->inter_quant_bias = avctx->inter_quant_bias;
  
 +    av_log(avctx, AV_LOG_DEBUG, "intra_quant_bias = %d inter_quant_bias = %d\n",s->intra_quant_bias,s->inter_quant_bias);
 +
      if (avctx->codec_id == AV_CODEC_ID_MPEG4 &&
          s->avctx->time_base.den > (1 << 16) - 1) {
          av_log(avctx, AV_LOG_ERROR,
          s->rtp_mode   = 1;
          break;
      case AV_CODEC_ID_MJPEG:
 +    case AV_CODEC_ID_AMV:
          s->out_format = FMT_MJPEG;
          s->intra_only = 1; /* force intra only for jpeg */
          if (!CONFIG_MJPEG_ENCODER ||
          break;
      case AV_CODEC_ID_H263:
          if (!CONFIG_H263_ENCODER)
 -        return -1;
 +            return -1;
          if (ff_match_2uint16(ff_h263_format, FF_ARRAY_ELEMS(ff_h263_format),
                               s->width, s->height) == 8) {
 -            av_log(avctx, AV_LOG_INFO,
 +            av_log(avctx, AV_LOG_ERROR,
                     "The specified picture size of %dx%d is not valid for "
                     "the H.263 codec.\nValid sizes are 128x96, 176x144, "
 -                   "352x288, 704x576, and 1408x1152."
 +                   "352x288, 704x576, and 1408x1152. "
                     "Try H.263+.\n", s->width, s->height);
              return -1;
          }
      if (ff_mpv_common_init(s) < 0)
          return -1;
  
 -    if (ARCH_X86)
 -        ff_mpv_encode_init_x86(s);
 -
      ff_fdctdsp_init(&s->fdsp, avctx);
      ff_me_cmp_init(&s->mecc, avctx);
      ff_mpegvideoencdsp_init(&s->mpvencdsp, avctx);
      FF_ALLOCZ_OR_GOTO(s->avctx, s->avctx->stats_out, 256, fail);
  
      FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix,   64 * 32 * sizeof(int), fail);
 +    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_chroma_intra_matrix, 64 * 32 * sizeof(int), fail);
      FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix,   64 * 32 * sizeof(int), fail);
      FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);
 +    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_chroma_intra_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);
      FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);
      FF_ALLOCZ_OR_GOTO(s->avctx, s->input_picture,
                        MAX_PICTURE_COUNT * sizeof(Picture *), fail);
                            2 * 64 * sizeof(uint16_t), fail);
      }
  
 -    if (CONFIG_H263_ENCODER)
 -        ff_h263dsp_init(&s->h263dsp);
 -    if (!s->dct_quantize)
 -        s->dct_quantize = ff_dct_quantize_c;
 -    if (!s->denoise_dct)
 -        s->denoise_dct  = denoise_dct_c;
 -    s->fast_dct_quantize = s->dct_quantize;
 -    if (avctx->trellis)
 -        s->dct_quantize  = dct_quantize_trellis_c;
 +    ff_dct_encode_init(s);
  
      if ((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)
          s->chroma_qscale_table = ff_h263_chroma_qscale_table;
              s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
          } else {
              /* mpeg1/2 */
 +            s->chroma_intra_matrix[j] =
              s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
              s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
          }
@@@ -1023,10 -893,6 +1023,10 @@@ av_cold int ff_mpv_encode_end(AVCodecCo
      av_freep(&s->avctx->stats_out);
      av_freep(&s->ac_stats);
  
 +    if(s->q_chroma_intra_matrix   != s->q_intra_matrix  ) av_freep(&s->q_chroma_intra_matrix);
 +    if(s->q_chroma_intra_matrix16 != s->q_intra_matrix16) av_freep(&s->q_chroma_intra_matrix16);
 +    s->q_chroma_intra_matrix=   NULL;
 +    s->q_chroma_intra_matrix16= NULL;
      av_freep(&s->q_intra_matrix);
      av_freep(&s->q_inter_matrix);
      av_freep(&s->q_intra_matrix16);
@@@ -1079,7 -945,7 +1079,7 @@@ static int alloc_picture(MpegEncContex
  {
      return ff_alloc_picture(s->avctx, pic, &s->me, &s->sc, shared, 1,
                              s->chroma_x_shift, s->chroma_y_shift, s->out_format,
 -                            s->mb_stride, s->mb_height, s->b8_stride,
 +                            s->mb_stride, s->mb_width, s->mb_height, s->b8_stride,
                              &s->linesize, &s->uvlinesize);
  }
  
@@@ -1098,17 -964,18 +1098,17 @@@ static int load_input_picture(MpegEncCo
  
          if (pts != AV_NOPTS_VALUE) {
              if (s->user_specified_pts != AV_NOPTS_VALUE) {
 -                int64_t time = pts;
                  int64_t last = s->user_specified_pts;
  
 -                if (time <= last) {
 +                if (pts <= last) {
                      av_log(s->avctx, AV_LOG_ERROR,
 -                           "Error, Invalid timestamp=%"PRId64", "
 -                           "last=%"PRId64"\n", pts, s->user_specified_pts);
 -                    return -1;
 +                           "Invalid pts (%"PRId64") <= last (%"PRId64")\n",
 +                           pts, last);
 +                    return AVERROR(EINVAL);
                  }
  
                  if (!s->low_delay && display_picture_number == 1)
 -                    s->dts_delta = time - last;
 +                    s->dts_delta = pts - last;
              }
              s->user_specified_pts = pts;
          } else {
              direct = 0;
          if ((s->width & 15) || (s->height & 15))
              direct = 0;
 +        if (((intptr_t)(pic_arg->data[0])) & (STRIDE_ALIGN-1))
 +            direct = 0;
 +        if (s->linesize & (STRIDE_ALIGN-1))
 +            direct = 0;
  
 -        ff_dlog(s->avctx, "%d %d %td %td\n", pic_arg->linesize[0],
 +        ff_dlog(s->avctx, "%d %d %"PTRDIFF_SPECIFIER" %"PTRDIFF_SPECIFIER"\n", pic_arg->linesize[0],
                  pic_arg->linesize[1], s->linesize, s->uvlinesize);
  
          i = ff_find_unused_picture(s->avctx, s->picture, direct);
                      int h = s->height >> v_shift;
                      uint8_t *src = pic_arg->data[i];
                      uint8_t *dst = pic->f->data[i];
 +                    int vpad = 16;
 +
 +                    if (   s->codec_id == AV_CODEC_ID_MPEG2VIDEO
 +                        && !s->progressive_sequence
 +                        && FFALIGN(s->height, 32) - s->height > 16)
 +                        vpad = 32;
  
                      if (!s->avctx->rc_buffer_size)
                          dst += INPLACE_OFFSET;
                              src += src_stride;
                          }
                      }
 -                    if ((s->width & 15) || (s->height & 15)) {
 +                    if ((s->width & 15) || (s->height & (vpad-1))) {
                          s->mpvencdsp.draw_edges(dst, dst_stride,
                                                  w, h,
                                                  16 >> h_shift,
 -                                                16 >> v_shift,
 +                                                vpad >> v_shift,
                                                  EDGE_BOTTOM);
                      }
                  }
@@@ -1239,23 -1096,19 +1239,23 @@@ static int skip_check(MpegEncContext *s
                  uint8_t *rptr = ref->f->data[plane] + 8 * (x + y * stride);
                  int v = s->mecc.frame_skip_cmp[1](s, dptr, rptr, stride, 8);
  
 -                switch (s->avctx->frame_skip_exp) {
 +                switch (FFABS(s->avctx->frame_skip_exp)) {
                  case 0: score    =  FFMAX(score, v);          break;
                  case 1: score   += FFABS(v);                  break;
 -                case 2: score   += v * v;                     break;
 -                case 3: score64 += FFABS(v * v * (int64_t)v); break;
 -                case 4: score64 += v * v * (int64_t)(v * v);  break;
 +                case 2: score64 += v * (int64_t)v;                       break;
 +                case 3: score64 += FFABS(v * (int64_t)v * v);            break;
 +                case 4: score64 += (v * (int64_t)v) * (v * (int64_t)v);  break;
                  }
              }
          }
      }
 +    emms_c();
  
      if (score)
          score64 = score;
 +    if (s->avctx->frame_skip_exp < 0)
 +        score64 = pow(score64 / (double)(s->mb_width * s->mb_height),
 +                      -1.0/s->avctx->frame_skip_exp);
  
      if (score64 < s->avctx->frame_skip_threshold)
          return 1;
@@@ -1290,7 -1143,7 +1290,7 @@@ static int estimate_best_b_count(MpegEn
  
      if (!c)
          return AVERROR(ENOMEM);
 -    assert(scale >= 0 && scale <= 3);
 +    av_assert0(scale >= 0 && scale <= 3);
  
      //emms_c();
      //s->next_picture_ptr->quality;
      for (i = 0; i < s->max_b_frames + 2; i++) {
          Picture pre_input, *pre_input_ptr = i ? s->input_picture[i - 1] :
                                                  s->next_picture_ptr;
 +        uint8_t *data[4];
  
          if (pre_input_ptr && (!i || s->input_picture[i - 1])) {
              pre_input = *pre_input_ptr;
 +            memcpy(data, pre_input_ptr->f->data, sizeof(data));
  
              if (!pre_input.shared && i) {
 -                pre_input.f->data[0] += INPLACE_OFFSET;
 -                pre_input.f->data[1] += INPLACE_OFFSET;
 -                pre_input.f->data[2] += INPLACE_OFFSET;
 +                data[0] += INPLACE_OFFSET;
 +                data[1] += INPLACE_OFFSET;
 +                data[2] += INPLACE_OFFSET;
              }
  
              s->mpvencdsp.shrink[scale](s->tmp_frames[i]->data[0],
                                         s->tmp_frames[i]->linesize[0],
 -                                       pre_input.f->data[0],
 +                                       data[0],
                                         pre_input.f->linesize[0],
                                         c->width, c->height);
              s->mpvencdsp.shrink[scale](s->tmp_frames[i]->data[1],
                                         s->tmp_frames[i]->linesize[1],
 -                                       pre_input.f->data[1],
 +                                       data[1],
                                         pre_input.f->linesize[1],
                                         c->width >> 1, c->height >> 1);
              s->mpvencdsp.shrink[scale](s->tmp_frames[i]->data[2],
                                         s->tmp_frames[i]->linesize[2],
 -                                       pre_input.f->data[2],
 +                                       data[2],
                                         pre_input.f->linesize[2],
                                         c->width >> 1, c->height >> 1);
          }
@@@ -1407,19 -1258,6 +1407,19 @@@ static int select_input_picture(MpegEnc
  
      /* set next picture type & ordering */
      if (!s->reordered_input_picture[0] && s->input_picture[0]) {
 +        if (s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor) {
 +            if (s->picture_in_gop_number < s->gop_size &&
 +                s->next_picture_ptr &&
 +                skip_check(s, s->input_picture[0], s->next_picture_ptr)) {
 +                // FIXME check that te gop check above is +-1 correct
 +                av_frame_unref(s->input_picture[0]->f);
 +
 +                ff_vbv_update(s, 0);
 +
 +                goto no_output_pic;
 +            }
 +        }
 +
          if (/*s->picture_in_gop_number >= s->gop_size ||*/
              !s->next_picture_ptr || s->intra_only) {
              s->reordered_input_picture[0] = s->input_picture[0];
          } else {
              int b_frames;
  
 -            if (s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor) {
 -                if (s->picture_in_gop_number < s->gop_size &&
 -                    skip_check(s, s->input_picture[0], s->next_picture_ptr)) {
 -                    // FIXME check that te gop check above is +-1 correct
 -                    av_frame_unref(s->input_picture[0]->f);
 -
 -                    emms_c();
 -                    ff_vbv_update(s, 0);
 -
 -                    goto no_output_pic;
 -                }
 -            }
 -
              if (s->avctx->flags & CODEC_FLAG_PASS2) {
                  for (i = 0; i < s->max_b_frames + 1; i++) {
                      int pict_num = s->input_picture[0]->f->display_picture_number + i;
@@@ -1577,26 -1428,25 +1577,26 @@@ no_output_pic
  
  static void frame_end(MpegEncContext *s)
  {
 -    int i;
 -
      if (s->unrestricted_mv &&
          s->current_picture.reference &&
          !s->intra_only) {
          const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
          int hshift = desc->log2_chroma_w;
          int vshift = desc->log2_chroma_h;
 -        s->mpvencdsp.draw_edges(s->current_picture.f->data[0], s->linesize,
 +        s->mpvencdsp.draw_edges(s->current_picture.f->data[0],
 +                                s->current_picture.f->linesize[0],
                                  s->h_edge_pos, s->v_edge_pos,
                                  EDGE_WIDTH, EDGE_WIDTH,
                                  EDGE_TOP | EDGE_BOTTOM);
 -        s->mpvencdsp.draw_edges(s->current_picture.f->data[1], s->uvlinesize,
 +        s->mpvencdsp.draw_edges(s->current_picture.f->data[1],
 +                                s->current_picture.f->linesize[1],
                                  s->h_edge_pos >> hshift,
                                  s->v_edge_pos >> vshift,
                                  EDGE_WIDTH >> hshift,
                                  EDGE_WIDTH >> vshift,
                                  EDGE_TOP | EDGE_BOTTOM);
 -        s->mpvencdsp.draw_edges(s->current_picture.f->data[2], s->uvlinesize,
 +        s->mpvencdsp.draw_edges(s->current_picture.f->data[2],
 +                                s->current_picture.f->linesize[2],
                                  s->h_edge_pos >> hshift,
                                  s->v_edge_pos >> vshift,
                                  EDGE_WIDTH >> hshift,
      if (s->pict_type!= AV_PICTURE_TYPE_B)
          s->last_non_b_pict_type = s->pict_type;
  
 -    if (s->encoding) {
 -        /* release non-reference frames */
 -        for (i = 0; i < MAX_PICTURE_COUNT; i++) {
 -            if (!s->picture[i].reference)
 -                ff_mpeg_unref_picture(s->avctx, &s->picture[i]);
 -        }
 -    }
 -
      s->avctx->coded_frame = s->current_picture_ptr->f;
  
  }
@@@ -1701,7 -1559,7 +1701,7 @@@ static int frame_start(MpegEncContext *
      }
  
      if (s->dct_error_sum) {
 -        assert(s->avctx->noise_reduction && s->encoding);
 +        av_assert2(s->avctx->noise_reduction && s->encoding);
          update_noise_reduction(s);
      }
  
@@@ -1726,11 -1584,8 +1726,11 @@@ int ff_mpv_encode_picture(AVCodecContex
  
      /* output? */
      if (s->new_picture.f->data[0]) {
 -        if (!pkt->data &&
 -            (ret = ff_alloc_packet(pkt, s->mb_width*s->mb_height*MAX_MB_BYTES)) < 0)
 +        int growing_buffer = context_count == 1 && !pkt->data && !s->data_partitioning;
 +        int pkt_size = growing_buffer ? FFMAX(s->mb_width*s->mb_height*64+10000, avctx->internal->byte_buffer_size) - FF_INPUT_BUFFER_PADDING_SIZE
 +                                              :
 +                                              s->mb_width*s->mb_height*(MAX_MB_BYTES+100)+10000;
 +        if ((ret = ff_alloc_packet2(avctx, pkt, pkt_size)) < 0)
              return ret;
          if (s->mb_info) {
              s->mb_info_ptr = av_packet_new_side_data(pkt,
          if (ret < 0)
              return ret;
  vbv_retry:
 -        if (encode_picture(s, s->picture_number) < 0)
 +        ret = encode_picture(s, s->picture_number);
 +        if (growing_buffer) {
 +            av_assert0(s->pb.buf == avctx->internal->byte_buffer);
 +            pkt->data = s->pb.buf;
 +            pkt->size = avctx->internal->byte_buffer_size;
 +        }
 +        if (ret < 0)
              return -1;
  
          avctx->header_bits = s->header_bits;
  
          if (avctx->rc_buffer_size) {
              RateControlContext *rcc = &s->rc_context;
 -            int max_size = rcc->buffer_index * avctx->rc_max_available_vbv_use;
 +            int max_size = FFMAX(rcc->buffer_index * avctx->rc_max_available_vbv_use, rcc->buffer_index - 500);
  
              if (put_bits_count(&s->pb) > max_size &&
                  s->lambda < s->lmax) {
                      PutBitContext *pb = &s->thread_context[i]->pb;
                      init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
                  }
 +                av_log(s->avctx, AV_LOG_VERBOSE, "reencoding frame due to VBV\n");
                  goto vbv_retry;
              }
  
 -            assert(s->avctx->rc_max_rate);
 +            av_assert0(s->avctx->rc_max_rate);
          }
  
          if (s->avctx->flags & CODEC_FLAG_PASS1)
              ff_write_pass1_stats(s);
  
          for (i = 0; i < 4; i++) {
 -            s->current_picture_ptr->f->error[i] = s->current_picture.f->error[i];
 +            s->current_picture_ptr->f->error[i] =
 +            s->current_picture.f->error[i] =
 +                s->current_picture.error[i];
              avctx->error[i] += s->current_picture_ptr->f->error[i];
          }
  
          s->frame_bits  = put_bits_count(&s->pb);
  
          stuffing_count = ff_vbv_update(s, s->frame_bits);
 +        s->stuffing_bits = 8*stuffing_count;
          if (stuffing_count) {
              if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) <
                      stuffing_count + 50) {
  
              vbv_delay = FFMAX(vbv_delay, min_delay);
  
 -            assert(vbv_delay < 0xFFFF);
 +            av_assert0(vbv_delay < 0xFFFF);
  
              s->vbv_delay_ptr[0] &= 0xF8;
              s->vbv_delay_ptr[0] |= vbv_delay >> 13;
      } else {
          s->frame_bits = 0;
      }
 -    assert((s->frame_bits & 7) == 0);
 +
 +    /* release non-reference frames */
 +    for (i = 0; i < MAX_PICTURE_COUNT; i++) {
 +        if (!s->picture[i].reference)
 +            ff_mpeg_unref_picture(s->avctx, &s->picture[i]);
 +    }
 +
 +    av_assert1((s->frame_bits & 7) == 0);
  
      pkt->size = s->frame_bits / 8;
      *got_packet = !!pkt->size;
@@@ -2050,17 -1888,15 +2050,17 @@@ static void get_visual_weight(int16_t *
  static av_always_inline void encode_mb_internal(MpegEncContext *s,
                                                  int motion_x, int motion_y,
                                                  int mb_block_height,
 +                                                int mb_block_width,
                                                  int mb_block_count)
  {
 -    int16_t weight[8][64];
 -    int16_t orig[8][64];
 +    int16_t weight[12][64];
 +    int16_t orig[12][64];
      const int mb_x = s->mb_x;
      const int mb_y = s->mb_y;
      int i;
 -    int skip_dct[8];
 +    int skip_dct[12];
      int dct_offset = s->linesize * 8; // default for progressive frames
 +    int uv_dct_offset = s->uvlinesize * 8;
      uint8_t *ptr_y, *ptr_cb, *ptr_cr;
      ptrdiff_t wrap_y, wrap_c;
  
      ptr_y  = s->new_picture.f->data[0] +
               (mb_y * 16 * wrap_y)              + mb_x * 16;
      ptr_cb = s->new_picture.f->data[1] +
 -             (mb_y * mb_block_height * wrap_c) + mb_x * 8;
 +             (mb_y * mb_block_height * wrap_c) + mb_x * mb_block_width;
      ptr_cr = s->new_picture.f->data[2] +
 -             (mb_y * mb_block_height * wrap_c) + mb_x * 8;
 +             (mb_y * mb_block_height * wrap_c) + mb_x * mb_block_width;
  
 -    if (mb_x * 16 + 16 > s->width || mb_y * 16 + 16 > s->height) {
 -        uint8_t *ebuf = s->sc.edge_emu_buffer + 32;
 +    if((mb_x * 16 + 16 > s->width || mb_y * 16 + 16 > s->height) && s->codec_id != AV_CODEC_ID_AMV){
 +        uint8_t *ebuf = s->sc.edge_emu_buffer + 36 * wrap_y;
 +        int cw = (s->width  + s->chroma_x_shift) >> s->chroma_x_shift;
 +        int ch = (s->height + s->chroma_y_shift) >> s->chroma_y_shift;
          s->vdsp.emulated_edge_mc(ebuf, ptr_y,
                                   wrap_y, wrap_y,
                                   16, 16, mb_x * 16, mb_y * 16,
                                   s->width, s->height);
          ptr_y = ebuf;
 -        s->vdsp.emulated_edge_mc(ebuf + 18 * wrap_y, ptr_cb,
 +        s->vdsp.emulated_edge_mc(ebuf + 16 * wrap_y, ptr_cb,
                                   wrap_c, wrap_c,
 -                                 8, mb_block_height, mb_x * 8, mb_y * 8,
 -                                 s->width >> 1, s->height >> 1);
 -        ptr_cb = ebuf + 18 * wrap_y;
 -        s->vdsp.emulated_edge_mc(ebuf + 18 * wrap_y + 8, ptr_cr,
 +                                 mb_block_width, mb_block_height,
 +                                 mb_x * mb_block_width, mb_y * mb_block_height,
 +                                 cw, ch);
 +        ptr_cb = ebuf + 16 * wrap_y;
 +        s->vdsp.emulated_edge_mc(ebuf + 16 * wrap_y + 16, ptr_cr,
                                   wrap_c, wrap_c,
 -                                 8, mb_block_height, mb_x * 8, mb_y * 8,
 -                                 s->width >> 1, s->height >> 1);
 -        ptr_cr = ebuf + 18 * wrap_y + 8;
 +                                 mb_block_width, mb_block_height,
 +                                 mb_x * mb_block_width, mb_y * mb_block_height,
 +                                 cw, ch);
 +        ptr_cr = ebuf + 16 * wrap_y + 16;
      }
  
      if (s->mb_intra) {
                      s->interlaced_dct = 1;
  
                      dct_offset = wrap_y;
 +                    uv_dct_offset = wrap_c;
                      wrap_y <<= 1;
 -                    if (s->chroma_format == CHROMA_422)
 +                    if (s->chroma_format == CHROMA_422 ||
 +                        s->chroma_format == CHROMA_444)
                          wrap_c <<= 1;
                  }
              }
          } else {
              s->pdsp.get_pixels(s->block[4], ptr_cb, wrap_c);
              s->pdsp.get_pixels(s->block[5], ptr_cr, wrap_c);
 -            if (!s->chroma_y_shift) { /* 422 */
 -                s->pdsp.get_pixels(s->block[6],
 -                                   ptr_cb + (dct_offset >> 1), wrap_c);
 -                s->pdsp.get_pixels(s->block[7],
 -                                   ptr_cr + (dct_offset >> 1), wrap_c);
 +            if (!s->chroma_y_shift && s->chroma_x_shift) { /* 422 */
 +                s->pdsp.get_pixels(s->block[6], ptr_cb + uv_dct_offset, wrap_c);
 +                s->pdsp.get_pixels(s->block[7], ptr_cr + uv_dct_offset, wrap_c);
 +            } else if (!s->chroma_y_shift && !s->chroma_x_shift) { /* 444 */
 +                s->pdsp.get_pixels(s->block[ 6], ptr_cb + 8, wrap_c);
 +                s->pdsp.get_pixels(s->block[ 7], ptr_cr + 8, wrap_c);
 +                s->pdsp.get_pixels(s->block[ 8], ptr_cb + uv_dct_offset, wrap_c);
 +                s->pdsp.get_pixels(s->block[ 9], ptr_cr + uv_dct_offset, wrap_c);
 +                s->pdsp.get_pixels(s->block[10], ptr_cb + uv_dct_offset + 8, wrap_c);
 +                s->pdsp.get_pixels(s->block[11], ptr_cr + uv_dct_offset + 8, wrap_c);
              }
          }
      } else {
                      s->interlaced_dct = 1;
  
                      dct_offset = wrap_y;
 +                    uv_dct_offset = wrap_c;
                      wrap_y <<= 1;
                      if (s->chroma_format == CHROMA_422)
                          wrap_c <<= 1;
              s->pdsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
              s->pdsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
              if (!s->chroma_y_shift) { /* 422 */
 -                s->pdsp.diff_pixels(s->block[6], ptr_cb + (dct_offset >> 1),
 -                                    dest_cb + (dct_offset >> 1), wrap_c);
 -                s->pdsp.diff_pixels(s->block[7], ptr_cr + (dct_offset >> 1),
 -                                    dest_cr + (dct_offset >> 1), wrap_c);
 +                s->pdsp.diff_pixels(s->block[6], ptr_cb + uv_dct_offset,
 +                                    dest_cb + uv_dct_offset, wrap_c);
 +                s->pdsp.diff_pixels(s->block[7], ptr_cr + uv_dct_offset,
 +                                    dest_cr + uv_dct_offset, wrap_c);
              }
          }
          /* pre quantization */
              if (s->mecc.sad[1](NULL, ptr_cr, dest_cr, wrap_c, 8) < 20 * s->qscale)
                  skip_dct[5] = 1;
              if (!s->chroma_y_shift) { /* 422 */
 -                if (s->mecc.sad[1](NULL, ptr_cb + (dct_offset >> 1),
 -                                   dest_cb + (dct_offset >> 1),
 +                if (s->mecc.sad[1](NULL, ptr_cb + uv_dct_offset,
 +                                   dest_cb + uv_dct_offset,
                                     wrap_c, 8) < 20 * s->qscale)
                      skip_dct[6] = 1;
 -                if (s->mecc.sad[1](NULL, ptr_cr + (dct_offset >> 1),
 -                                   dest_cr + (dct_offset >> 1),
 +                if (s->mecc.sad[1](NULL, ptr_cr + uv_dct_offset,
 +                                   dest_cr + uv_dct_offset,
                                     wrap_c, 8) < 20 * s->qscale)
                      skip_dct[7] = 1;
              }
              get_visual_weight(weight[5], ptr_cr                , wrap_c);
          if (!s->chroma_y_shift) { /* 422 */
              if (!skip_dct[6])
 -                get_visual_weight(weight[6], ptr_cb + (dct_offset >> 1),
 +                get_visual_weight(weight[6], ptr_cb + uv_dct_offset,
                                    wrap_c);
              if (!skip_dct[7])
 -                get_visual_weight(weight[7], ptr_cr + (dct_offset >> 1),
 +                get_visual_weight(weight[7], ptr_cr + uv_dct_offset,
                                    wrap_c);
          }
          memcpy(orig[0], s->block[0], sizeof(int16_t) * 64 * mb_block_count);
      }
  
      /* DCT & quantize */
 -    assert(s->out_format != FMT_MJPEG || s->qscale == 8);
 +    av_assert2(s->out_format != FMT_MJPEG || s->qscale == 8);
      {
          for (i = 0; i < mb_block_count; i++) {
              if (!skip_dct[i]) {
          s->block_last_index[5] = 0;
          s->block[4][0] =
          s->block[5][0] = (1024 + s->c_dc_scale / 2) / s->c_dc_scale;
 +        if (!s->chroma_y_shift) { /* 422 / 444 */
 +            for (i=6; i<12; i++) {
 +                s->block_last_index[i] = 0;
 +                s->block[i][0] = s->block[4][0];
 +            }
 +        }
      }
  
      // non c quantize code returns incorrect block_last_index FIXME
              ff_h263_encode_mb(s, s->block, motion_x, motion_y);
          break;
      case AV_CODEC_ID_MJPEG:
 +    case AV_CODEC_ID_AMV:
          if (CONFIG_MJPEG_ENCODER)
              ff_mjpeg_encode_mb(s, s->block);
          break;
      default:
 -        assert(0);
 +        av_assert1(0);
      }
  }
  
  static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
  {
 -    if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y,  8, 6);
 -    else                                encode_mb_internal(s, motion_x, motion_y, 16, 8);
 +    if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y,  8, 8, 6);
 +    else if (s->chroma_format == CHROMA_422) encode_mb_internal(s, motion_x, motion_y, 16, 8, 8);
 +    else encode_mb_internal(s, motion_x, motion_y, 16, 16, 12);
  }
  
  static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
@@@ -2522,7 -2338,7 +2522,7 @@@ static inline void encode_mb_hq(MpegEnc
          s->dest[0] = s->sc.rd_scratchpad;
          s->dest[1] = s->sc.rd_scratchpad + 16*s->linesize;
          s->dest[2] = s->sc.rd_scratchpad + 16*s->linesize + 8;
 -        assert(s->linesize >= 32); //FIXME
 +        av_assert0(s->linesize >= 32); //FIXME
      }
  
      encode_mb(s, motion_x, motion_y);
@@@ -2568,7 -2384,7 +2568,7 @@@ static int sse(MpegEncContext *s, uint8
          }
      }
  
 -    assert(acc>=0);
 +    av_assert2(acc>=0);
  
      return acc;
  }
@@@ -2618,8 -2434,6 +2618,8 @@@ static int pre_estimate_motion_thread(A
  static int estimate_motion_thread(AVCodecContext *c, void *arg){
      MpegEncContext *s= *(void**)arg;
  
 +    ff_check_alignment();
 +
      s->me.dia_size= s->avctx->dia_size;
      s->first_slice_line=1;
      for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
@@@ -2646,8 -2460,6 +2646,8 @@@ static int mb_var_thread(AVCodecContex
      MpegEncContext *s= *(void**)arg;
      int mb_x, mb_y;
  
 +    ff_check_alignment();
 +
      for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
          for(mb_x=0; mb_x < s->mb_width; mb_x++) {
              int xx = mb_x * 16;
@@@ -2675,7 -2487,7 +2675,7 @@@ static void write_slice_end(MpegEncCont
  
          ff_mpeg4_stuffing(&s->pb);
      }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
 -        ff_mjpeg_encode_stuffing(&s->pb);
 +        ff_mjpeg_encode_stuffing(s);
      }
  
      avpriv_align_put_bits(&s->pb);
@@@ -2728,35 -2540,6 +2728,35 @@@ static void update_mb_info(MpegEncConte
      write_mb_info(s);
  }
  
 +int ff_mpv_reallocate_putbitbuffer(MpegEncContext *s, size_t threshold, size_t size_increase)
 +{
 +    if (   s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < threshold
 +        && s->slice_context_count == 1
 +        && s->pb.buf == s->avctx->internal->byte_buffer) {
 +        int lastgob_pos = s->ptr_lastgob - s->pb.buf;
 +        int vbv_pos     = s->vbv_delay_ptr - s->pb.buf;
 +
 +        uint8_t *new_buffer = NULL;
 +        int new_buffer_size = 0;
 +
 +        av_fast_padded_malloc(&new_buffer, &new_buffer_size,
 +                              s->avctx->internal->byte_buffer_size + size_increase);
 +        if (!new_buffer)
 +            return AVERROR(ENOMEM);
 +
 +        memcpy(new_buffer, s->avctx->internal->byte_buffer, s->avctx->internal->byte_buffer_size);
 +        av_free(s->avctx->internal->byte_buffer);
 +        s->avctx->internal->byte_buffer      = new_buffer;
 +        s->avctx->internal->byte_buffer_size = new_buffer_size;
 +        rebase_put_bits(&s->pb, new_buffer, new_buffer_size);
 +        s->ptr_lastgob   = s->pb.buf + lastgob_pos;
 +        s->vbv_delay_ptr = s->pb.buf + vbv_pos;
 +    }
 +    if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < threshold)
 +        return AVERROR(EINVAL);
 +    return 0;
 +}
 +
  static int encode_thread(AVCodecContext *c, void *arg){
      MpegEncContext *s= *(void**)arg;
      int mb_x, mb_y, pdif = 0;
      uint8_t bit_buf_tex[2][MAX_MB_BYTES];
      PutBitContext pb[2], pb2[2], tex_pb[2];
  
 +    ff_check_alignment();
 +
      for(i=0; i<2; i++){
          init_put_bits(&pb    [i], bit_buf    [i], MAX_MB_BYTES);
          init_put_bits(&pb2   [i], bit_buf2   [i], MAX_MB_BYTES);
          /* note: quant matrix value (8) is implied here */
          s->last_dc[i] = 128 << s->intra_dc_precision;
  
 -        s->current_picture.f->error[i] = 0;
 +        s->current_picture.error[i] = 0;
 +    }
 +    if(s->codec_id==AV_CODEC_ID_AMV){
 +        s->last_dc[0] = 128*8/13;
 +        s->last_dc[1] = 128*8/14;
 +        s->last_dc[2] = 128*8/14;
      }
      s->mb_skip_run = 0;
      memset(s->last_mv, 0, sizeof(s->last_mv));
  //            int d;
              int dmin= INT_MAX;
              int dir;
 +            int size_increase =  s->avctx->internal->byte_buffer_size/4
 +                               + s->mb_width*MAX_MB_BYTES;
  
 +            ff_mpv_reallocate_putbitbuffer(s, MAX_MB_BYTES, size_increase);
              if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
                  av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
                  return -1;
              if(s->data_partitioning){
                  if(   s->pb2   .buf_end - s->pb2   .buf - (put_bits_count(&s->    pb2)>>3) < MAX_MB_BYTES
                     || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
 -                    av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
 +                    av_log(s->avctx, AV_LOG_ERROR, "encoded partitioned frame too large\n");
                      return -1;
                  }
              }
                  case AV_CODEC_ID_MPEG1VIDEO:
                      if(s->mb_skip_run) is_gob_start=0;
                      break;
 +                case AV_CODEC_ID_MJPEG:
 +                    if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
 +                    break;
                  }
  
                  if(is_gob_start){
                          }
                      }
  
 -                    assert((put_bits_count(&s->pb)&7) == 0);
 +                    av_assert2((put_bits_count(&s->pb)&7) == 0);
                      current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
  
                      if (s->error_rate && s->resync_mb_x + s->resync_mb_y > 0) {
                          int16_t ac[6][16];
                          const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
                          static const int dquant_tab[4]={-1,1,-2,2};
 +                        int storecoefs = s->mb_intra && s->dc_val[0];
  
 -                        assert(backup_s.dquant == 0);
 +                        av_assert2(backup_s.dquant == 0);
  
                          //FIXME intra
                          s->mv_dir= best_s.mv_dir;
                              if(qp < s->avctx->qmin || qp > s->avctx->qmax)
                                  continue;
                              backup_s.dquant= dquant;
 -                            if(s->mb_intra && s->dc_val[0]){
 +                            if(storecoefs){
                                  for(i=0; i<6; i++){
                                      dc[i]= s->dc_val[0][ s->block_index[i] ];
                                      memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(int16_t)*16);
                              encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
                                           &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
                              if(best_s.qscale != qp){
 -                                if(s->mb_intra && s->dc_val[0]){
 +                                if(storecoefs){
                                      for(i=0; i<6; i++){
                                          s->dc_val[0][ s->block_index[i] ]= dc[i];
                                          memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(int16_t)*16);
                  if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
                  if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  
 -                s->current_picture.f->error[0] += sse(
 +                s->current_picture.error[0] += sse(
                      s, s->new_picture.f->data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
                      s->dest[0], w, h, s->linesize);
 -                s->current_picture.f->error[1] += sse(
 +                s->current_picture.error[1] += sse(
                      s, s->new_picture.f->data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
                      s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
 -                s->current_picture.f->error[2] += sse(
 +                s->current_picture.error[2] += sse(
                      s, s->new_picture.f->data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
                      s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
              }
@@@ -3420,9 -3189,9 +3420,9 @@@ static void merge_context_after_encode(
      MERGE(misc_bits);
      MERGE(er.error_count);
      MERGE(padding_bug_score);
 -    MERGE(current_picture.f->error[0]);
 -    MERGE(current_picture.f->error[1]);
 -    MERGE(current_picture.f->error[2]);
 +    MERGE(current_picture.error[0]);
 +    MERGE(current_picture.error[1]);
 +    MERGE(current_picture.error[2]);
  
      if(dst->avctx->noise_reduction){
          for(i=0; i<64; i++){
@@@ -3475,7 -3244,7 +3475,7 @@@ static int estimate_qp(MpegEncContext *
  
  /* must be called before writing the header */
  static void set_frame_distances(MpegEncContext * s){
 -    assert(s->current_picture_ptr->f->pts != AV_NOPTS_VALUE);
 +    av_assert1(s->current_picture_ptr->f->pts != AV_NOPTS_VALUE);
      s->time = s->current_picture_ptr->f->pts * s->avctx->time_base.num;
  
      if(s->pict_type==AV_PICTURE_TYPE_B){
@@@ -3531,13 -3300,6 +3531,13 @@@ static int encode_picture(MpegEncContex
          update_qscale(s);
      }
  
 +    if(s->codec_id != AV_CODEC_ID_AMV && s->codec_id != AV_CODEC_ID_MJPEG){
 +        if(s->q_chroma_intra_matrix   != s->q_intra_matrix  ) av_freep(&s->q_chroma_intra_matrix);
 +        if(s->q_chroma_intra_matrix16 != s->q_intra_matrix16) av_freep(&s->q_chroma_intra_matrix16);
 +        s->q_chroma_intra_matrix   = s->q_intra_matrix;
 +        s->q_chroma_intra_matrix16 = s->q_intra_matrix16;
 +    }
 +
      s->mb_intra=0; //for the rate distortion & bit compare functions
      for(i=1; i<context_count; i++){
          ret = ff_update_duplicate_context(s->thread_context[i], s);
          s->pict_type= AV_PICTURE_TYPE_I;
          for(i=0; i<s->mb_stride*s->mb_height; i++)
              s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
 -        ff_dlog(s, "Scene change detected, encoding as I Frame %d %d\n",
 +        if(s->msmpeg4_version >= 3)
 +            s->no_rounding=1;
 +        ff_dlog(s, "Scene change detected, encoding as I Frame %"PRId64" %"PRId64"\n",
                  s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
      }
  
          s->qscale= 3; //reduce clipping problems
  
      if (s->out_format == FMT_MJPEG) {
 +        const uint16_t *  luma_matrix = ff_mpeg1_default_intra_matrix;
 +        const uint16_t *chroma_matrix = ff_mpeg1_default_intra_matrix;
 +
 +        if (s->avctx->intra_matrix) {
 +            chroma_matrix =
 +            luma_matrix = s->avctx->intra_matrix;
 +        }
 +        if (s->avctx->chroma_intra_matrix)
 +            chroma_matrix = s->avctx->chroma_intra_matrix;
 +
          /* for mjpeg, we do include qscale in the matrix */
          for(i=1;i<64;i++){
              int j = s->idsp.idct_permutation[i];
  
 -            s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
 +            s->chroma_intra_matrix[j] = av_clip_uint8((chroma_matrix[i] * s->qscale) >> 3);
 +            s->       intra_matrix[j] = av_clip_uint8((  luma_matrix[i] * s->qscale) >> 3);
          }
          s->y_dc_scale_table=
          s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];
 +        s->chroma_intra_matrix[0] =
          s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];
          ff_convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16,
                         s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
 +        ff_convert_matrix(s, s->q_chroma_intra_matrix, s->q_chroma_intra_matrix16,
 +                       s->chroma_intra_matrix, s->intra_quant_bias, 8, 8, 1);
 +        s->qscale= 8;
 +    }
 +    if(s->codec_id == AV_CODEC_ID_AMV){
 +        static const uint8_t y[32]={13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13};
 +        static const uint8_t c[32]={14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14};
 +        for(i=1;i<64;i++){
 +            int j= s->idsp.idct_permutation[ff_zigzag_direct[i]];
 +
 +            s->intra_matrix[j] = sp5x_quant_table[5*2+0][i];
 +            s->chroma_intra_matrix[j] = sp5x_quant_table[5*2+1][i];
 +        }
 +        s->y_dc_scale_table= y;
 +        s->c_dc_scale_table= c;
 +        s->intra_matrix[0] = 13;
 +        s->chroma_intra_matrix[0] = 14;
 +        ff_convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16,
 +                       s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
 +        ff_convert_matrix(s, s->q_chroma_intra_matrix, s->q_chroma_intra_matrix16,
 +                       s->chroma_intra_matrix, s->intra_quant_bias, 8, 8, 1);
          s->qscale= 8;
      }
  
      if (s->current_picture.f->key_frame)
          s->picture_in_gop_number=0;
  
 +    s->mb_x = s->mb_y = 0;
      s->last_bits= put_bits_count(&s->pb);
      switch(s->out_format) {
      case FMT_MJPEG:
          if (CONFIG_MJPEG_ENCODER)
              ff_mjpeg_encode_picture_header(s->avctx, &s->pb, &s->intra_scantable,
 -                                           s->intra_matrix);
 +                                           s->intra_matrix, s->chroma_intra_matrix);
          break;
      case FMT_H261:
          if (CONFIG_H261_ENCODER)
              ff_mpeg1_encode_picture_header(s, picture_number);
          break;
      default:
 -        assert(0);
 +        av_assert0(0);
      }
      bits= put_bits_count(&s->pb);
      s->header_bits= bits - s->last_bits;
      }
      s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
      for(i=1; i<context_count; i++){
 +        if (s->pb.buf_end == s->thread_context[i]->pb.buf)
 +            set_put_bits_buffer_size(&s->pb, FFMIN(s->thread_context[i]->pb.buf_end - s->pb.buf, INT_MAX/8-32));
          merge_context_after_encode(s, s->thread_context[i]);
      }
      emms_c();
@@@ -3787,7 -3511,6 +3787,7 @@@ static int dct_quantize_trellis_c(MpegE
                                    int16_t *block, int n,
                                    int qscale, int *overflow){
      const int *qmat;
 +    const uint16_t *matrix;
      const uint8_t *scantable= s->intra_scantable.scantable;
      const uint8_t *perm_scantable= s->intra_scantable.permutated;
      int max=0;
          block[0] = (block[0] + (q >> 1)) / q;
          start_i = 1;
          last_non_zero = 0;
 -        qmat = s->q_intra_matrix[qscale];
 -        if(s->mpeg_quant || s->out_format == FMT_MPEG1)
 +        qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
 +        matrix = n < 4 ? s->intra_matrix : s->chroma_intra_matrix;
 +        if(s->mpeg_quant || s->out_format == FMT_MPEG1 || s->out_format == FMT_MJPEG)
              bias= 1<<(QMAT_SHIFT-1);
 -        length     = s->intra_ac_vlc_length;
 -        last_length= s->intra_ac_vlc_last_length;
 +
 +        if (n > 3 && s->intra_chroma_ac_vlc_length) {
 +            length     = s->intra_chroma_ac_vlc_length;
 +            last_length= s->intra_chroma_ac_vlc_last_length;
 +        } else {
 +            length     = s->intra_ac_vlc_length;
 +            last_length= s->intra_ac_vlc_last_length;
 +        }
      } else {
          start_i = 0;
          last_non_zero = -1;
          qmat = s->q_inter_matrix[qscale];
 +        matrix = s->inter_matrix;
          length     = s->inter_ac_vlc_length;
          last_length= s->inter_ac_vlc_last_length;
      }
  //                coeff[2][k]= -level+2;
              }
              coeff_count[i]= FFMIN(level, 2);
 -            assert(coeff_count[i]);
 +            av_assert2(coeff_count[i]);
              max |=level;
          }else{
              coeff[0][i]= (level>>31)|1;
              const int alevel= FFABS(level);
              int unquant_coeff;
  
 -            assert(level);
 +            av_assert2(level);
  
 -            if(s->out_format == FMT_H263){
 +            if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
                  unquant_coeff= alevel*qmul + qadd;
 +            } else if(s->out_format == FMT_MJPEG) {
 +                j = s->idsp.idct_permutation[scantable[i]];
 +                unquant_coeff = alevel * matrix[j] * 8;
              }else{ //MPEG1
                  j = s->idsp.idct_permutation[scantable[i]]; // FIXME: optimize
                  if(s->mb_intra){
 -                        unquant_coeff = (int)(  alevel  * qscale * s->intra_matrix[j]) >> 3;
 +                        unquant_coeff = (int)(  alevel  * qscale * matrix[j]) >> 3;
                          unquant_coeff =   (unquant_coeff - 1) | 1;
                  }else{
 -                        unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
 +                        unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) matrix[j])) >> 4;
                          unquant_coeff =   (unquant_coeff - 1) | 1;
                  }
                  unquant_coeff<<= 3;
                      }
                  }
  
 -                if(s->out_format == FMT_H263){
 +                if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
                      for(j=survivor_count-1; j>=0; j--){
                          int run= i - survivor[j];
                          int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
                      }
                  }
  
 -                if(s->out_format == FMT_H263){
 +                if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
                    for(j=survivor_count-1; j>=0; j--){
                          int run= i - survivor[j];
                          int score= distortion + score_tab[i-run];
          survivor[ survivor_count++ ]= i+1;
      }
  
 -    if(s->out_format != FMT_H263){
 +    if(s->out_format != FMT_H263 && s->out_format != FMT_H261){
          last_score= 256*256*256*120;
          for(i= survivor[0]; i<=last_non_zero + 1; i++){
              int score= score_tab[i];
              int alevel= FFABS(level);
              int unquant_coeff, score, distortion;
  
 -            if(s->out_format == FMT_H263){
 +            if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
                      unquant_coeff= (alevel*qmul + qadd)>>3;
              }else{ //MPEG1
 -                    unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
 +                    unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) matrix[0])) >> 4;
                      unquant_coeff =   (unquant_coeff - 1) | 1;
              }
              unquant_coeff = (unquant_coeff + 4) >> 3;
      }
  
      i= last_i;
 -    assert(last_level);
 +    av_assert2(last_level);
  
      block[ perm_scantable[last_non_zero] ]= last_level;
      i -= last_run + 1;
@@@ -4159,13 -3871,8 +4159,13 @@@ static int messed_sign=0
          start_i = 1;
  //        if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  //            bias= 1<<(QMAT_SHIFT-1);
 -        length     = s->intra_ac_vlc_length;
 -        last_length= s->intra_ac_vlc_last_length;
 +        if (n > 3 && s->intra_chroma_ac_vlc_length) {
 +            length     = s->intra_chroma_ac_vlc_length;
 +            last_length= s->intra_chroma_ac_vlc_last_length;
 +        } else {
 +            length     = s->intra_ac_vlc_length;
 +            last_length= s->intra_ac_vlc_last_length;
 +        }
      } else {
          dc= 0;
          start_i = 0;
@@@ -4196,8 -3903,8 +4196,8 @@@ STOP_TIMER("memset rem[]")
          weight[i] = w;
  //        w=weight[i] = (63*qns + (w/2)) / w;
  
 -        assert(w>0);
 -        assert(w<(1<<6));
 +        av_assert2(w>0);
 +        av_assert2(w<(1<<6));
          sum += w*w;
      }
      lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
@@@ -4263,7 -3970,7 +4263,7 @@@ STOP_TIMER("dct")
              const int level= block[0];
              int change, old_coeff;
  
 -            assert(s->mb_intra);
 +            av_assert2(s->mb_intra);
  
              old_coeff= q*level;
  
              }else{
                  old_coeff=0;
                  run2--;
 -                assert(run2>=0 || i >= last_non_zero );
 +                av_assert2(run2>=0 || i >= last_non_zero );
              }
  
              for(change=-1; change<=1; change+=2){
                                           - last_length[UNI_AC_ENC_INDEX(run, level+64)];
                          }
                      }else{
 -                        assert(FFABS(new_level)==1);
 +                        av_assert2(FFABS(new_level)==1);
  
                          if(analyze_gradient){
                              int g= d1[ scantable[i] ];
                      }
                  }else{
                      new_coeff=0;
 -                    assert(FFABS(level)==1);
 +                    av_assert2(FFABS(level)==1);
  
                      if(i < last_non_zero){
                          int next_i= i + run2 + 1;
                  score *= lambda;
  
                  unquant_change= new_coeff - old_coeff;
 -                assert((score < 100*lambda && score > -100*lambda) || lambda==0);
 +                av_assert2((score < 100*lambda && score > -100*lambda) || lambda==0);
  
                  score += s->mpvencdsp.try_8x8basis(rem, weight, basis[j],
                                                     unquant_change);
@@@ -4429,7 -4136,7 +4429,7 @@@ STOP_TIMER("iterative step")
  
              if(best_coeff > last_non_zero){
                  last_non_zero= best_coeff;
 -                assert(block[j]);
 +                av_assert2(block[j]);
  #ifdef REFINE_STATS
  after_last++;
  #endif
@@@ -4457,7 -4164,7 +4457,7 @@@ if(block[j])
  #ifdef REFINE_STATS
  count++;
  if(256*256*256*64 % count == 0){
 -    printf("after_last:%d to_zero:%d from_zero:%d raise:%d lower:%d sign:%d xyp:%d/%d/%d\n", after_last, to_zero, from_zero, raise, lower, messed_sign, s->mb_x, s->mb_y, s->picture_number);
 +    av_log(s->avctx, AV_LOG_DEBUG, "after_last:%d to_zero:%d from_zero:%d raise:%d lower:%d sign:%d xyp:%d/%d/%d\n", after_last, to_zero, from_zero, raise, lower, messed_sign, s->mb_x, s->mb_y, s->picture_number);
  }
  #endif
              run=0;
@@@ -4489,6 -4196,42 +4489,42 @@@ STOP_TIMER("iterative search"
      return last_non_zero;
  }
  
+ /**
+  * Permute an 8x8 block according to permuatation.
+  * @param block the block which will be permuted according to
+  *              the given permutation vector
+  * @param permutation the permutation vector
+  * @param last the last non zero coefficient in scantable order, used to
+  *             speed the permutation up
+  * @param scantable the used scantable, this is only used to speed the
+  *                  permutation up, the block is not (inverse) permutated
+  *                  to scantable order!
+  */
+ static void block_permute(int16_t *block, uint8_t *permutation,
+                           const uint8_t *scantable, int last)
+ {
+     int i;
+     int16_t temp[64];
+     if (last <= 0)
+         return;
+     //FIXME it is ok but not clean and might fail for some permutations
+     // if (permutation[1] == 1)
+     // return;
+     for (i = 0; i <= last; i++) {
+         const int j = scantable[i];
+         temp[j] = block[j];
+         block[j] = 0;
+     }
+     for (i = 0; i <= last; i++) {
+         const int j = scantable[i];
+         const int perm_j = permutation[j];
+         block[perm_j] = temp[j];
+     }
+ }
  int ff_dct_quantize_c(MpegEncContext *s,
                          int16_t *block, int n,
                          int qscale, int *overflow)
          block[0] = (block[0] + (q >> 1)) / q;
          start_i = 1;
          last_non_zero = 0;
 -        qmat = s->q_intra_matrix[qscale];
 +        qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
          bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
      } else {
          start_i = 0;
  
      /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
      if (s->idsp.perm_type != FF_IDCT_PERM_NONE)
-         ff_block_permute(block, s->idsp.idct_permutation,
-                          scantable, last_non_zero);
+         block_permute(block, s->idsp.idct_permutation,
+                       scantable, last_non_zero);
  
      return last_non_zero;
  }