Merge commit '5d471b73d20616f5ac701ff62e5de49465cda264'
authorMichael Niedermayer <michaelni@gmx.at>
Mon, 10 Dec 2012 00:27:10 +0000 (01:27 +0100)
committerMichael Niedermayer <michaelni@gmx.at>
Mon, 10 Dec 2012 00:27:10 +0000 (01:27 +0100)
* commit '5d471b73d20616f5ac701ff62e5de49465cda264':
  rtpdec: K&R formatting and spelling cosmetics
  cosmetics: Fix dropable --> droppable typo

Conflicts:
libavcodec/h264.c

Merged-by: Michael Niedermayer <michaelni@gmx.at>
1  2 
libavcodec/flvdec.c
libavcodec/h263dec.c
libavcodec/h264.c
libavcodec/mpegvideo.c
libavcodec/mpegvideo.h
libavcodec/vc1dec.c
libavformat/rtpdec.c

diff --combined libavcodec/flvdec.c
@@@ -1,19 -1,19 +1,19 @@@
  /*
   * FLV decoding.
 - * 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
   */
  
@@@ -40,12 -40,12 +40,12 @@@ int ff_flv_decode_picture_header(MpegEn
      /* picture header */
      if (get_bits_long(&s->gb, 17) != 1) {
          av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");
 -        return -1;
 +        return AVERROR_INVALIDDATA;
      }
      format = get_bits(&s->gb, 5);
      if (format != 0 && format != 1) {
          av_log(s->avctx, AV_LOG_ERROR, "Bad picture format\n");
 -        return -1;
 +        return AVERROR_INVALIDDATA;
      }
      s->h263_flv = format+1;
      s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */
          break;
      }
      if(av_image_check_size(width, height, 0, s->avctx))
 -        return -1;
 +        return AVERROR(EINVAL);
      s->width = width;
      s->height = height;
  
      s->pict_type = AV_PICTURE_TYPE_I + get_bits(&s->gb, 2);
-     s->dropable= s->pict_type > AV_PICTURE_TYPE_P;
-     if (s->dropable)
+     s->droppable = s->pict_type > AV_PICTURE_TYPE_P;
+     if (s->droppable)
          s->pict_type = AV_PICTURE_TYPE_P;
  
      skip_bits1(&s->gb); /* deblocking flag */
  
      if(s->avctx->debug & FF_DEBUG_PICT_INFO){
          av_log(s->avctx, AV_LOG_DEBUG, "%c esc_type:%d, qp:%d num:%d\n",
-                s->dropable ? 'D' : av_get_picture_type_char(s->pict_type), s->h263_flv-1, s->qscale, s->picture_number);
+                s->droppable ? 'D' : av_get_picture_type_char(s->pict_type),
+                s->h263_flv - 1, s->qscale, s->picture_number);
      }
  
      s->y_dc_scale_table=
@@@ -127,7 -128,6 +128,7 @@@ AVCodec ff_flv_decoder = 
      .close          = ff_h263_decode_end,
      .decode         = ff_h263_decode_frame,
      .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1,
 +    .max_lowres     = 3,
      .long_name      = NULL_IF_CONFIG_SMALL("FLV / Sorenson Spark / Sorenson H.263 (Flash Video)"),
      .pix_fmts       = ff_pixfmt_list_420,
  };
diff --combined libavcodec/h263dec.c
@@@ -3,20 -3,20 +3,20 @@@
   * Copyright (c) 2001 Fabrice Bellard
   * Copyright (c) 2002-2004 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
   */
  
@@@ -25,8 -25,6 +25,8 @@@
   * H.263 decoder.
   */
  
 +#define UNCHECKED_BITSTREAM_READER 1
 +
  #include "libavutil/cpu.h"
  #include "internal.h"
  #include "avcodec.h"
@@@ -47,7 -45,6 +47,7 @@@
  av_cold int ff_h263_decode_init(AVCodecContext *avctx)
  {
      MpegEncContext *s = avctx->priv_data;
 +    int ret;
  
      s->avctx = avctx;
      s->out_format = FMT_H263;
@@@ -70,7 -67,6 +70,7 @@@
      /* select sub codec */
      switch(avctx->codec->id) {
      case AV_CODEC_ID_H263:
 +    case AV_CODEC_ID_H263P:
          s->unrestricted_mv= 0;
          avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
          break;
          s->h263_flv = 1;
          break;
      default:
 -        return -1;
 +        return AVERROR(EINVAL);
      }
      s->codec_id= avctx->codec->id;
      avctx->hwaccel= ff_find_hwaccel(avctx->codec->id, avctx->pix_fmt);
  
      /* for h263, we allocate the images after having read the header */
 -    if (avctx->codec->id != AV_CODEC_ID_H263 && avctx->codec->id != AV_CODEC_ID_MPEG4)
 -        if (ff_MPV_common_init(s) < 0)
 -            return -1;
 +    if (avctx->codec->id != AV_CODEC_ID_H263 && avctx->codec->id != AV_CODEC_ID_H263P && avctx->codec->id != AV_CODEC_ID_MPEG4)
 +        if ((ret = ff_MPV_common_init(s)) < 0)
 +            return ret;
  
          ff_h263_decode_init_vlc(s);
  
@@@ -157,9 -153,7 +157,9 @@@ static int get_consumed_bytes(MpegEncCo
  
  static int decode_slice(MpegEncContext *s){
      const int part_mask= s->partitioned_frame ? (ER_AC_END|ER_AC_ERROR) : 0x7F;
 -    const int mb_size = 16;
 +    const int mb_size= 16>>s->avctx->lowres;
 +    int ret;
 +
      s->last_resync_gb= s->gb;
      s->first_slice_line= 1;
  
  
      if (s->avctx->hwaccel) {
          const uint8_t *start= s->gb.buffer + get_bits_count(&s->gb)/8;
 -        const uint8_t *end  = ff_h263_find_resync_marker(start + 1, s->gb.buffer_end);
 +        const uint8_t *end  = ff_h263_find_resync_marker(s, start + 1, s->gb.buffer_end);
          skip_bits_long(&s->gb, 8*(end - start));
          return s->avctx->hwaccel->decode_slice(s->avctx, start, end - start);
      }
          const int qscale= s->qscale;
  
          if(CONFIG_MPEG4_DECODER && s->codec_id==AV_CODEC_ID_MPEG4){
 -            if(ff_mpeg4_decode_partitions(s) < 0)
 -                return -1;
 +            if ((ret = ff_mpeg4_decode_partitions(s)) < 0)
 +                return ret;
          }
  
          /* restore variables which were modified */
                  }else if(ret==SLICE_NOEND){
                      av_log(s->avctx, AV_LOG_ERROR, "Slice mismatch at MB: %d\n", xy);
                      ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x+1, s->mb_y, ER_MB_END&part_mask);
 -                    return -1;
 +                    return AVERROR_INVALIDDATA;
                  }
                  av_log(s->avctx, AV_LOG_ERROR, "Error at MB: %d\n", xy);
                  ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR&part_mask);
  
 -                return -1;
 +                return AVERROR_INVALIDDATA;
              }
  
              ff_MPV_decode_mb(s, s->block);
          s->mb_x= 0;
      }
  
 -    assert(s->mb_x==0 && s->mb_y==s->mb_height);
 +    av_assert1(s->mb_x==0 && s->mb_y==s->mb_height);
  
      if(s->codec_id==AV_CODEC_ID_MPEG4
         && (s->workaround_bugs&FF_BUG_AUTODETECT)
      if(      s->codec_id==AV_CODEC_ID_MPEG4
         &&   (s->workaround_bugs&FF_BUG_AUTODETECT)
         &&    get_bits_left(&s->gb) >=0
 -       &&    get_bits_left(&s->gb) < 48
 +       &&    get_bits_left(&s->gb) < 137
  //       &&   !s->resync_marker
         &&   !s->data_partitioning){
  
              max_extra+= 17;
  
          /* buggy padding but the frame should still end approximately at the bitstream end */
 -        if((s->workaround_bugs&FF_BUG_NO_PADDING) && (s->err_recognition&AV_EF_BUFFER))
 +        if((s->workaround_bugs&FF_BUG_NO_PADDING) && (s->err_recognition&(AV_EF_BUFFER|AV_EF_AGGRESSIVE)))
              max_extra+= 48;
          else if((s->workaround_bugs&FF_BUG_NO_PADDING))
              max_extra+= 256*256*256*64;
  
      ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_END&part_mask);
  
 -    return -1;
 +    return AVERROR_INVALIDDATA;
  }
  
  int ff_h263_decode_frame(AVCodecContext *avctx,
@@@ -381,11 -375,9 +381,11 @@@ uint64_t time= rdtsc()
              next= ff_mpeg4_find_frame_end(&s->parse_context, buf, buf_size);
          }else if(CONFIG_H263_DECODER && s->codec_id==AV_CODEC_ID_H263){
              next= ff_h263_find_frame_end(&s->parse_context, buf, buf_size);
 +        }else if(CONFIG_H263P_DECODER && s->codec_id==AV_CODEC_ID_H263P){
 +            next= ff_h263_find_frame_end(&s->parse_context, buf, buf_size);
          }else{
              av_log(s->avctx, AV_LOG_ERROR, "this codec does not support truncated bitstreams\n");
 -            return -1;
 +            return AVERROR(EINVAL);
          }
  
          if( ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0 )
  
  
  retry:
 +    if(s->divx_packed && s->bitstream_buffer_size){
 +        int i;
 +        for(i=0; i<buf_size-3; i++){
 +            if(buf[i]==0 && buf[i+1]==0 && buf[i+2]==1){
 +                if(buf[i+3]==0xB0){
 +                    av_log(s->avctx, AV_LOG_WARNING, "Discarding excessive bitstream in packed xvid\n");
 +                    s->bitstream_buffer_size=0;
 +                }
 +                break;
 +            }
 +        }
 +    }
  
      if(s->bitstream_buffer_size && (s->divx_packed || buf_size<20)){ //divx 5.01+/xvid frame reorder
          init_get_bits(&s->gb, s->bitstream_buffer, s->bitstream_buffer_size*8);
      s->bitstream_buffer_size=0;
  
      if (!s->context_initialized) {
 -        if (ff_MPV_common_init(s) < 0) //we need the idct permutaton for reading a custom matrix
 -            return -1;
 +        if ((ret = ff_MPV_common_init(s)) < 0) //we need the idct permutaton for reading a custom matrix
 +            return ret;
      }
  
      /* We need to set current_picture_ptr before reading the header,
          ret = ff_h263_decode_picture_header(s);
      }
  
 +    if (ret < 0 || ret==FRAME_SKIPPED) {
 +        if (   s->width  != avctx->coded_width
 +            || s->height != avctx->coded_height) {
 +                av_log(s->avctx, AV_LOG_WARNING, "Reverting picture dimensions change due to header decoding failure\n");
 +                s->width = avctx->coded_width;
 +                s->height= avctx->coded_height;
 +        }
 +    }
      if(ret==FRAME_SKIPPED) return get_consumed_bytes(s, buf_size);
  
      /* skip if the header was thrashed */
      if (ret < 0){
          av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");
 -        return -1;
 +        return ret;
      }
  
      avctx->has_b_frames= !s->low_delay;
      if (s->codec_id == AV_CODEC_ID_MPEG4 && s->xvid_build>=0 && avctx->idct_algo == FF_IDCT_AUTO && (av_get_cpu_flags() & AV_CPU_FLAG_MMX)) {
          avctx->idct_algo= FF_IDCT_XVIDMMX;
          ff_dct_common_init(s);
 -        s->picture_number=0;
 +        goto retry;
      }
  #endif
  
          /* FIXME: By the way H263 decoder is evolving it should have */
          /* an H263EncContext                                         */
  
 -    if (!avctx->coded_width || !avctx->coded_height) {
 +    if ((!avctx->coded_width || !avctx->coded_height) && 0) {
          ParseContext pc= s->parse_context; //FIXME move these demuxng hack to avformat
  
          s->parse_context.buffer=0;
      s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
  
      /* skip B-frames if we don't have reference frames */
-     if(s->last_picture_ptr==NULL && (s->pict_type==AV_PICTURE_TYPE_B || s->dropable)) return get_consumed_bytes(s, buf_size);
+     if (s->last_picture_ptr == NULL &&
+         (s->pict_type == AV_PICTURE_TYPE_B || s->droppable))
+         return get_consumed_bytes(s, buf_size);
      if(   (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==AV_PICTURE_TYPE_B)
         || (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=AV_PICTURE_TYPE_I)
         ||  avctx->skip_frame >= AVDISCARD_ALL)
          s->me.qpel_avg= s->dsp.avg_qpel_pixels_tab;
      }
  
 -    if(ff_MPV_frame_start(s, avctx) < 0)
 -        return -1;
 +    if ((ret = ff_MPV_frame_start(s, avctx)) < 0)
 +        return ret;
  
      if (!s->divx_packed) ff_thread_finish_setup(avctx);
  
      }
  
      if (avctx->hwaccel) {
 -        if (avctx->hwaccel->start_frame(avctx, s->gb.buffer, s->gb.buffer_end - s->gb.buffer) < 0)
 -            return -1;
 +        if ((ret = avctx->hwaccel->start_frame(avctx, s->gb.buffer, s->gb.buffer_end - s->gb.buffer)) < 0)
 +            return ret;
      }
  
      ff_er_frame_start(s);
              s->error_status_table[s->mb_num-1]= ER_MB_ERROR;
          }
  
 -    assert(s->bitstream_buffer_size==0);
 +    av_assert1(s->bitstream_buffer_size==0);
  frame_end:
      /* divx 5.01+ bistream reorder stuff */
      if(s->codec_id==AV_CODEC_ID_MPEG4 && s->divx_packed){
 -        int current_pos= get_bits_count(&s->gb)>>3;
 +        int current_pos= s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb)>>3);
          int startcode_found=0;
  
 -        if(buf_size - current_pos > 5){
 +        if(buf_size - current_pos > 7){
              int i;
 -            for(i=current_pos; i<buf_size-3; i++){
 +            for(i=current_pos; i<buf_size-4; i++){
                  if(buf[i]==0 && buf[i+1]==0 && buf[i+2]==1 && buf[i+3]==0xB6){
 -                    startcode_found=1;
 +                    startcode_found=!(buf[i+4]&0x40);
                      break;
                  }
              }
          }
 -        if(s->gb.buffer == s->bitstream_buffer && buf_size>7 && s->xvid_build>=0){ //xvid style
 -            startcode_found=1;
 -            current_pos=0;
 -        }
  
          if(startcode_found){
              av_fast_malloc(
@@@ -738,8 -716,8 +740,8 @@@ intrax8_decoded
      ff_er_frame_end(s);
  
      if (avctx->hwaccel) {
 -        if (avctx->hwaccel->end_frame(avctx) < 0)
 -            return -1;
 +        if ((ret = avctx->hwaccel->end_frame(avctx)) < 0)
 +            return ret;
      }
  
      ff_MPV_frame_end(s);
@@@ -775,23 -753,6 +777,23 @@@ AVCodec ff_h263_decoder = 
      .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
                        CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
      .flush          = ff_mpeg_flush,
 +    .max_lowres     = 3,
 +    .long_name      = NULL_IF_CONFIG_SMALL("H.263 / H.263-1996, H.263+ / H.263-1998 / H.263 version 2"),
 +    .pix_fmts       = ff_hwaccel_pixfmt_list_420,
 +};
 +
 +AVCodec ff_h263p_decoder = {
 +    .name           = "h263p",
 +    .type           = AVMEDIA_TYPE_VIDEO,
 +    .id             = AV_CODEC_ID_H263P,
 +    .priv_data_size = sizeof(MpegEncContext),
 +    .init           = ff_h263_decode_init,
 +    .close          = ff_h263_decode_end,
 +    .decode         = ff_h263_decode_frame,
 +    .capabilities   = CODEC_CAP_DRAW_HORIZ_BAND | CODEC_CAP_DR1 |
 +                      CODEC_CAP_TRUNCATED | CODEC_CAP_DELAY,
 +    .flush          = ff_mpeg_flush,
 +    .max_lowres     = 3,
      .long_name      = NULL_IF_CONFIG_SMALL("H.263 / H.263-1996, H.263+ / H.263-1998 / H.263 version 2"),
      .pix_fmts       = ff_hwaccel_pixfmt_list_420,
  };
diff --combined libavcodec/h264.c
@@@ -2,20 -2,20 +2,20 @@@
   * H.26L/H.264/AVC/JVT/14496-10/... decoder
   * Copyright (c) 2003 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
   */
  
   * @author Michael Niedermayer <michaelni@gmx.at>
   */
  
 +#define UNCHECKED_BITSTREAM_READER 1
 +
  #include "libavutil/imgutils.h"
 +#include "libavutil/opt.h"
  #include "internal.h"
  #include "cabac.h"
  #include "cabac_functions.h"
@@@ -53,17 -50,13 +53,17 @@@ const uint16_t ff_h264_mb_sizes[4] = { 
  static const uint8_t rem6[QP_MAX_NUM + 1] = {
      0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
      3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
 -    0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
 +    0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
 +    3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
 +    0, 1, 2, 3,
  };
  
  static const uint8_t div6[QP_MAX_NUM + 1] = {
      0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3,  3,  3,
      3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6,  6,  6,
 -    7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
 +    7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
 +   10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
 +   14,14,14,14,
  };
  
  static const enum AVPixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
      AV_PIX_FMT_NONE
  };
  
 +int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
 +{
 +    H264Context *h = avctx->priv_data;
 +    return h ? h->sps.num_reorder_frames : 0;
 +}
 +
  /**
   * Check if the top & left blocks are available if needed and
   * change the dc mode so it only uses the available blocks.
@@@ -233,27 -220,21 +233,27 @@@ const uint8_t *ff_h264_decode_nal(H264C
      }
  #endif
  
 -    if (i >= length - 1) { // no escaped 0
 -        *dst_length = length;
 -        *consumed   = length + 1; // +1 for the header
 -        return src;
 -    }
 -
      // use second escape buffer for inter data
      bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
 -    av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
 -                   length + FF_INPUT_BUFFER_PADDING_SIZE);
 +
 +    si = h->rbsp_buffer_size[bufidx];
 +    av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
      dst = h->rbsp_buffer[bufidx];
  
      if (dst == NULL)
          return NULL;
  
 +    if(i>=length-1){ //no escaped 0
 +        *dst_length= length;
 +        *consumed= length+1; //+1 for the header
 +        if(h->s.avctx->flags2 & CODEC_FLAG2_FAST){
 +            return src;
 +        }else{
 +            memcpy(dst, src, length);
 +            return dst;
 +        }
 +    }
 +
      memcpy(dst, src, i);
      si = di = i;
      while (si + 2 < length) {
@@@ -388,7 -369,7 +388,7 @@@ static void await_references(H264Contex
      } else {
          int i;
  
 -        assert(IS_8X8(mb_type));
 +        av_assert2(IS_8X8(mb_type));
  
          for (i = 0; i < 4; i++) {
              const int sub_mb_type = h->sub_mb_type[i];
                                    nrefs);
              } else {
                  int j;
 -                assert(IS_SUB_4X4(sub_mb_type));
 +                av_assert2(IS_SUB_4X4(sub_mb_type));
                  for (j = 0; j < 4; j++) {
                      int sub_y_offset = y_offset + 2 * (j & 2);
                      get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
@@@ -759,7 -740,9 +759,7 @@@ static av_always_inline void prefetch_m
              s->dsp.prefetch(src[1] + off, s->linesize, 4);
              s->dsp.prefetch(src[2] + off, s->linesize, 4);
          } else {
 -            off = ((mx >> 1) << pixel_shift) +
 -                  ((my >> 1) + (s->mb_x & 7)) * s->uvlinesize +
 -                  (64 << pixel_shift);
 +            off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
              s->dsp.prefetch(src[1] + off, src[2] - src[1], 2);
          }
      }
@@@ -876,7 -859,7 +876,7 @@@ int ff_h264_alloc_tables(H264Context *h
  {
      MpegEncContext *const s = &h->s;
      const int big_mb_num    = s->mb_stride * (s->mb_height + 1);
 -    const int row_mb_num    = s->mb_stride * 2 * s->avctx->thread_count;
 +    const int row_mb_num    = 2*s->mb_stride*FFMAX(s->avctx->thread_count, 1);
      int x, y;
  
      FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode,
@@@ -981,18 -964,12 +981,18 @@@ static av_cold void common_init(H264Con
      s->height   = s->avctx->height;
      s->codec_id = s->avctx->codec->id;
  
 -    ff_h264dsp_init(&h->h264dsp, 8, 1);
 -    ff_h264_pred_init(&h->hpc, s->codec_id, 8, 1);
 +    s->avctx->bits_per_raw_sample = 8;
 +    h->cur_chroma_format_idc = 1;
 +
 +    ff_h264dsp_init(&h->h264dsp,
 +                    s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
 +    ff_h264_pred_init(&h->hpc, s->codec_id,
 +                      s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
  
      h->dequant_coeff_pps = -1;
      s->unrestricted_mv   = 1;
  
 +    s->dsp.dct_bits = 16;
      /* needed so that IDCT permutation is known early */
      ff_dsputil_init(&s->dsp, s->avctx);
  
      memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
  }
  
 -int ff_h264_decode_extradata(H264Context *h)
 +static int ff_h264_decode_extradata_internal(H264Context *h, const uint8_t *buf, int size)
  {
      AVCodecContext *avctx = h->s.avctx;
  
 -    if (avctx->extradata[0] == 1) {
 +    if (!buf || size <= 0)
 +        return -1;
 +
 +    if (buf[0] == 1) {
          int i, cnt, nalsize;
 -        unsigned char *p = avctx->extradata;
 +        const unsigned char *p = buf;
  
          h->is_avc = 1;
  
 -        if (avctx->extradata_size < 7) {
 +        if (size < 7) {
              av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
              return -1;
          }
          p  += 6;
          for (i = 0; i < cnt; i++) {
              nalsize = AV_RB16(p) + 2;
 -            if (p - avctx->extradata + nalsize > avctx->extradata_size)
 +            if(nalsize > size - (p-buf))
                  return -1;
              if (decode_nal_units(h, p, nalsize) < 0) {
                  av_log(avctx, AV_LOG_ERROR,
          cnt = *(p++); // Number of pps
          for (i = 0; i < cnt; i++) {
              nalsize = AV_RB16(p) + 2;
 -            if (p - avctx->extradata + nalsize > avctx->extradata_size)
 +            if(nalsize > size - (p-buf))
                  return -1;
              if (decode_nal_units(h, p, nalsize) < 0) {
                  av_log(avctx, AV_LOG_ERROR,
              p += nalsize;
          }
          // Now store right nal length size, that will be used to parse all other nals
 -        h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
 +        h->nal_length_size = (buf[4] & 0x03) + 1;
      } else {
          h->is_avc = 0;
 -        if (decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
 +        if (decode_nal_units(h, buf, size) < 0)
              return -1;
      }
 -    return 0;
 +    return size;
 +}
 +
 +int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
 +{
 +    int ret;
 +    h->decoding_extradata = 1;
 +    ret = ff_h264_decode_extradata_internal(h, buf, size);
 +    h->decoding_extradata = 0;
 +    return ret;
  }
  
  av_cold int ff_h264_decode_init(AVCodecContext *avctx)
      for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
          h->last_pocs[i] = INT_MIN;
      h->prev_poc_msb = 1 << 16;
 +    h->prev_frame_num = -1;
      h->x264_build   = -1;
      ff_h264_reset_sei(h);
      if (avctx->codec_id == AV_CODEC_ID_H264) {
 -        if (avctx->ticks_per_frame == 1)
 -            s->avctx->time_base.den *= 2;
 +        if (avctx->ticks_per_frame == 1) {
 +            if(s->avctx->time_base.den < INT_MAX/2) {
 +                s->avctx->time_base.den *= 2;
 +            } else
 +                s->avctx->time_base.num /= 2;
 +        }
          avctx->ticks_per_frame = 2;
      }
  
      if (avctx->extradata_size > 0 && avctx->extradata &&
 -        ff_h264_decode_extradata(h))
 +        ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
 +        ff_h264_free_context(h);
          return -1;
 +    }
  
      if (h->sps.bitstream_restriction_flag &&
          s->avctx->has_b_frames < h->sps.num_reorder_frames) {
          s->low_delay           = 0;
      }
  
 +    ff_init_cabac_states();
 +
      return 0;
  }
  
@@@ -1184,7 -1140,7 +1184,7 @@@ static int decode_update_thread_context
      int inited = s->context_initialized, err;
      int i;
  
 -    if (dst == src || !s1->context_initialized)
 +    if (dst == src)
          return 0;
  
      err = ff_mpeg_update_thread_context(dst, src);
                 sizeof(H264Context) - sizeof(MpegEncContext));
          memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
          memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
 +
 +        if (s1->context_initialized) {
          if (ff_h264_alloc_tables(h) < 0) {
              av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
              return AVERROR(ENOMEM);
          }
          context_init(h);
  
 +        }
 +
          for (i = 0; i < 2; i++) {
              h->rbsp_buffer[i]      = NULL;
              h->rbsp_buffer_size[i] = 0;
                         MAX_DELAYED_PIC_COUNT + 2, s, s1);
  
      h->last_slice_type = h1->last_slice_type;
 +    h->sync            = h1->sync;
  
      if (!s->current_picture_ptr)
          return 0;
  
-     if (!s->dropable) {
+     if (!s->droppable) {
          err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
          h->prev_poc_msb = h->poc_msb;
          h->prev_poc_lsb = h->poc_lsb;
@@@ -1303,7 -1254,6 +1303,7 @@@ int ff_h264_frame_start(H264Context *h
       * See decode_nal_units().
       */
      s->current_picture_ptr->f.key_frame = 0;
 +    s->current_picture_ptr->sync        = 0;
      s->current_picture_ptr->mmco_reset  = 0;
  
      assert(s->linesize && s->uvlinesize);
@@@ -1366,6 -1316,7 +1366,6 @@@ static void decode_postinit(H264Contex
      Picture *out = s->current_picture_ptr;
      Picture *cur = s->current_picture_ptr;
      int i, pics, out_of_order, out_idx;
 -    int invalid = 0, cnt = 0;
  
      s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
      s->current_picture_ptr->f.pict_type   = s->pict_type;
          }
      }
  
 +    cur->mmco_reset = h->mmco_reset;
 +    h->mmco_reset = 0;
      // FIXME do something with unavailable reference frames
  
      /* Sort B-frames into display order */
          s->low_delay           = 0;
      }
  
 +    for (i = 0; 1; i++) {
 +        if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
 +            if(i)
 +                h->last_pocs[i-1] = cur->poc;
 +            break;
 +        } else if(i) {
 +            h->last_pocs[i-1]= h->last_pocs[i];
 +        }
 +    }
 +    out_of_order = MAX_DELAYED_PIC_COUNT - i;
 +    if(   cur->f.pict_type == AV_PICTURE_TYPE_B
 +       || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
 +        out_of_order = FFMAX(out_of_order, 1);
 +    if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
 +        av_log(s->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
 +        s->avctx->has_b_frames = out_of_order;
 +        s->low_delay = 0;
 +    }
 +
      pics = 0;
      while (h->delayed_pic[pics])
          pics++;
  
 -    assert(pics <= MAX_DELAYED_PIC_COUNT);
 +    av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  
      h->delayed_pic[pics++] = cur;
      if (cur->f.reference == 0)
          cur->f.reference = DELAYED_PIC_REF;
  
 -    /* Frame reordering. This code takes pictures from coding order and sorts
 -     * them by their incremental POC value into display order. It supports POC
 -     * gaps, MMCO reset codes and random resets.
 -     * A "display group" can start either with a IDR frame (f.key_frame = 1),
 -     * and/or can be closed down with a MMCO reset code. In sequences where
 -     * there is no delay, we can't detect that (since the frame was already
 -     * output to the user), so we also set h->mmco_reset to detect the MMCO
 -     * reset code.
 -     * FIXME: if we detect insufficient delays (as per s->avctx->has_b_frames),
 -     * we increase the delay between input and output. All frames affected by
 -     * the lag (e.g. those that should have been output before another frame
 -     * that we already returned to the user) will be dropped. This is a bug
 -     * that we will fix later. */
 -    for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
 -        cnt     += out->poc < h->last_pocs[i];
 -        invalid += out->poc == INT_MIN;
 -    }
 -    if (!h->mmco_reset && !cur->f.key_frame &&
 -        cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
 -        h->mmco_reset = 2;
 -        if (pics > 1)
 -            h->delayed_pic[pics - 2]->mmco_reset = 2;
 -    }
 -    if (h->mmco_reset || cur->f.key_frame) {
 -        for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
 -            h->last_pocs[i] = INT_MIN;
 -        cnt     = 0;
 -        invalid = MAX_DELAYED_PIC_COUNT;
 -    }
 -    out     = h->delayed_pic[0];
 +    out = h->delayed_pic[0];
      out_idx = 0;
 -    for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
 -                h->delayed_pic[i] &&
 -                !h->delayed_pic[i - 1]->mmco_reset &&
 -                !h->delayed_pic[i]->f.key_frame;
 +    for (i = 1; h->delayed_pic[i] &&
 +                !h->delayed_pic[i]->f.key_frame &&
 +                !h->delayed_pic[i]->mmco_reset;
           i++)
          if (h->delayed_pic[i]->poc < out->poc) {
              out     = h->delayed_pic[i];
              out_idx = i;
          }
      if (s->avctx->has_b_frames == 0 &&
 -        (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
 +        (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
          h->next_outputed_poc = INT_MIN;
 -    out_of_order = !out->f.key_frame && !h->mmco_reset &&
 -                   (out->poc < h->next_outputed_poc);
 +    out_of_order = out->poc < h->next_outputed_poc;
  
 -    if (h->sps.bitstream_restriction_flag &&
 -        s->avctx->has_b_frames >= h->sps.num_reorder_frames) {
 -    } else if (out_of_order && pics - 1 == s->avctx->has_b_frames &&
 -               s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
 -        if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
 -            s->avctx->has_b_frames = FFMAX(s->avctx->has_b_frames, cnt);
 -        }
 -        s->low_delay = 0;
 -    } else if (s->low_delay &&
 -               ((h->next_outputed_poc != INT_MIN &&
 -                 out->poc > h->next_outputed_poc + 2) ||
 -                cur->f.pict_type == AV_PICTURE_TYPE_B)) {
 -        s->low_delay = 0;
 -        s->avctx->has_b_frames++;
 -    }
 -
 -    if (pics > s->avctx->has_b_frames) {
 +    if (out_of_order || pics > s->avctx->has_b_frames) {
          out->f.reference &= ~DELAYED_PIC_REF;
          // for frame threading, the owner must be the second field's thread or
          // else the first thread can release the picture and reuse it unsafely
          for (i = out_idx; h->delayed_pic[i]; i++)
              h->delayed_pic[i] = h->delayed_pic[i + 1];
      }
 -    memmove(h->last_pocs, &h->last_pocs[1],
 -            sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
 -    h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
      if (!out_of_order && pics > s->avctx->has_b_frames) {
          h->next_output_pic = out;
 -        if (out->mmco_reset) {
 -            if (out_idx > 0) {
 -                h->next_outputed_poc                    = out->poc;
 -                h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
 -            } else {
 -                h->next_outputed_poc = INT_MIN;
 -            }
 -        } else {
 -            if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
 -                h->next_outputed_poc = INT_MIN;
 -            } else {
 -                h->next_outputed_poc = out->poc;
 -            }
 -        }
 -        h->mmco_reset = 0;
 +        if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
 +            h->next_outputed_poc = INT_MIN;
 +        } else
 +            h->next_outputed_poc = out->poc;
      } else {
 -        av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
 +        av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
 +    }
 +
 +    if (h->next_output_pic && h->next_output_pic->sync) {
 +        h->sync |= 2;
      }
  
      if (setup_finished)
@@@ -1803,7 -1790,7 +1803,7 @@@ static av_always_inline void hl_decode_
                          uint64_t tr_high;
                          if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
                              const int topright_avail = (h->topright_samples_available << i) & 0x8000;
 -                            assert(s->mb_y || linesize <= block_offset[i]);
 +                            av_assert2(s->mb_y || linesize <= block_offset[i]);
                              if (!topright_avail) {
                                  if (pixel_shift) {
                                      tr_high  = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
@@@ -2097,14 -2084,11 +2097,14 @@@ static void implicit_weight_table(H264C
   */
  static void idr(H264Context *h)
  {
 +    int i;
      ff_h264_remove_all_refs(h);
      h->prev_frame_num        = 0;
      h->prev_frame_num_offset = 0;
 -    h->prev_poc_msb          =
 +    h->prev_poc_msb          = 1<<16;
      h->prev_poc_lsb          = 0;
 +    for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
 +        h->last_pocs[i] = INT_MIN;
  }
  
  /* forget old pics after a seek */
@@@ -2112,22 -2096,21 +2112,22 @@@ static void flush_dpb(AVCodecContext *a
  {
      H264Context *h = avctx->priv_data;
      int i;
 -    for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
 +    for (i=0; i<=MAX_DELAYED_PIC_COUNT; i++) {
          if (h->delayed_pic[i])
              h->delayed_pic[i]->f.reference = 0;
          h->delayed_pic[i] = NULL;
      }
 -    for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
 -        h->last_pocs[i] = INT_MIN;
      h->outputed_poc = h->next_outputed_poc = INT_MIN;
      h->prev_interlaced_frame = 1;
      idr(h);
 +    h->prev_frame_num = -1;
      if (h->s.current_picture_ptr)
          h->s.current_picture_ptr->f.reference = 0;
      h->s.first_field = 0;
      ff_h264_reset_sei(h);
      ff_mpeg_flush(avctx);
 +    h->recovery_frame= -1;
 +    h->sync= 0;
  }
  
  static int init_poc(H264Context *h)
@@@ -2229,19 -2212,19 +2229,19 @@@ static void init_scan_tables(H264Contex
  #undef T
      }
      if (h->sps.transform_bypass) { // FIXME same ugly
 -        h->zigzag_scan_q0          = zigzag_scan;
 -        h->zigzag_scan8x8_q0       = ff_zigzag_direct;
 -        h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
 -        h->field_scan_q0           = field_scan;
 -        h->field_scan8x8_q0        = field_scan8x8;
 -        h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;
 +        memcpy(h->zigzag_scan_q0          , zigzag_scan             , sizeof(h->zigzag_scan_q0         ));
 +        memcpy(h->zigzag_scan8x8_q0       , ff_zigzag_direct        , sizeof(h->zigzag_scan8x8_q0      ));
 +        memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc    , sizeof(h->zigzag_scan8x8_cavlc_q0));
 +        memcpy(h->field_scan_q0           , field_scan              , sizeof(h->field_scan_q0          ));
 +        memcpy(h->field_scan8x8_q0        , field_scan8x8           , sizeof(h->field_scan8x8_q0       ));
 +        memcpy(h->field_scan8x8_cavlc_q0  , field_scan8x8_cavlc     , sizeof(h->field_scan8x8_cavlc_q0 ));
      } else {
 -        h->zigzag_scan_q0          = h->zigzag_scan;
 -        h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;
 -        h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
 -        h->field_scan_q0           = h->field_scan;
 -        h->field_scan8x8_q0        = h->field_scan8x8;
 -        h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;
 +        memcpy(h->zigzag_scan_q0          , h->zigzag_scan          , sizeof(h->zigzag_scan_q0         ));
 +        memcpy(h->zigzag_scan8x8_q0       , h->zigzag_scan8x8       , sizeof(h->zigzag_scan8x8_q0      ));
 +        memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
 +        memcpy(h->field_scan_q0           , h->field_scan           , sizeof(h->field_scan_q0          ));
 +        memcpy(h->field_scan8x8_q0        , h->field_scan8x8        , sizeof(h->field_scan8x8_q0       ));
 +        memcpy(h->field_scan8x8_cavlc_q0  , h->field_scan8x8_cavlc  , sizeof(h->field_scan8x8_cavlc_q0 ));
      }
  }
  
@@@ -2252,7 -2235,7 +2252,7 @@@ static int field_end(H264Context *h, in
      int err = 0;
      s->mb_y = 0;
  
-     if (!in_setup && !s->dropable)
+     if (!in_setup && !s->droppable)
          ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
                                    s->picture_structure == PICT_BOTTOM_FIELD);
  
          ff_vdpau_h264_set_reference_frames(s);
  
      if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
-         if (!s->dropable) {
+         if (!s->droppable) {
              err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
              h->prev_poc_msb = h->poc_msb;
              h->prev_poc_lsb = h->poc_lsb;
@@@ -2373,11 -2356,10 +2373,11 @@@ static int decode_slice_header(H264Cont
      MpegEncContext *const s0 = &h0->s;
      unsigned int first_mb_in_slice;
      unsigned int pps_id;
 -    int num_ref_idx_active_override_flag, max_refs;
 +    int num_ref_idx_active_override_flag;
      unsigned int slice_type, tmp, i, j;
      int default_ref_list_done = 0;
-     int last_pic_structure, last_pic_dropable;
+     int last_pic_structure, last_pic_droppable;
 +    int must_reinit;
  
      /* FIXME: 2tap qpel isn't implemented for high bit depth. */
      if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
          s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
      }
  
 -    first_mb_in_slice = get_ue_golomb(&s->gb);
 +    first_mb_in_slice = get_ue_golomb_long(&s->gb);
  
      if (first_mb_in_slice == 0) { // FIXME better field boundary detection
          if (h0->current_slice && FIELD_PICTURE) {
  
          h0->current_slice = 0;
          if (!s0->first_field) {
-             if (s->current_picture_ptr && !s->dropable &&
+             if (s->current_picture_ptr && !s->droppable &&
                  s->current_picture_ptr->owner2 == s) {
                  ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
                                            s->picture_structure == PICT_BOTTOM_FIELD);
      if (slice_type > 9) {
          av_log(h->s.avctx, AV_LOG_ERROR,
                 "slice type too large (%d) at %d %d\n",
 -               h->slice_type, s->mb_x, s->mb_y);
 +               slice_type, s->mb_x, s->mb_y);
          return -1;
      }
      if (slice_type > 4) {
  
      pps_id = get_ue_golomb(&s->gb);
      if (pps_id >= MAX_PPS_COUNT) {
 -        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
 +        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
          return -1;
      }
      if (!h0->pps_buffers[pps_id]) {
      s->avctx->level   = h->sps.level_idc;
      s->avctx->refs    = h->sps.ref_frame_count;
  
 +    must_reinit = (s->context_initialized &&
 +                    (   16*h->sps.mb_width != s->avctx->coded_width
 +                     || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != s->avctx->coded_height
 +                     || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
 +                     || h->cur_chroma_format_idc != h->sps.chroma_format_idc
 +                     || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio)));
 +
 +    if(must_reinit && (h != h0 || (s->avctx->active_thread_type & FF_THREAD_FRAME))) {
 +        av_log_missing_feature(s->avctx,
 +                                "Width/height/bit depth/chroma idc changing with threads", 0);
 +        return AVERROR_PATCHWELCOME;   // width / height changed during parallelized decoding
 +    }
 +
      s->mb_width  = h->sps.mb_width;
      s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  
  
      s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  
 -    s->width = 16 * s->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
 -    if (h->sps.frame_mbs_only_flag)
 -        s->height = 16 * s->mb_height - (1 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
 -    else
 -        s->height = 16 * s->mb_height - (2 << s->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> s->chroma_y_shift) - 1);
 -
 -    if (FFALIGN(s->avctx->width,  16) == s->width &&
 -        FFALIGN(s->avctx->height, 16) == s->height) {
 -        s->width  = s->avctx->width;
 -        s->height = s->avctx->height;
 -    }
 +    s->width  = 16 * s->mb_width;
 +    s->height = 16 * s->mb_height;
  
 -    if (s->context_initialized &&
 -        (s->width != s->avctx->width || s->height != s->avctx->height ||
 -         av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
 -        if (h != h0 || (HAVE_THREADS && h->s.avctx->active_thread_type & FF_THREAD_FRAME)) {
 -            av_log_missing_feature(s->avctx,
 -                                   "Width/height changing with threads", 0);
 -            return AVERROR_PATCHWELCOME;   // width / height changed during parallelized decoding
 -        }
 +    if(must_reinit) {
          free_tables(h, 0);
          flush_dpb(s->avctx);
          ff_MPV_common_end(s);
 +        h->list_count = 0;
 +        h->current_slice = 0;
      }
      if (!s->context_initialized) {
          if (h != h0) {
                     "Cannot (re-)initialize context during parallel decoding.\n");
              return -1;
          }
 -
 -        avcodec_set_dimensions(s->avctx, s->width, s->height);
 +        if(   FFALIGN(s->avctx->width , 16                                 ) == s->width
 +           && FFALIGN(s->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == s->height
 +           && !h->sps.crop_right && !h->sps.crop_bottom
 +           && (s->avctx->width != s->width || s->avctx->height && s->height)
 +        ) {
 +            av_log(h->s.avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
 +            s->avctx->coded_width  = s->width;
 +            s->avctx->coded_height = s->height;
 +        } else{
 +            avcodec_set_dimensions(s->avctx, s->width, s->height);
 +            s->avctx->width  -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
 +            s->avctx->height -= (1<<s->chroma_y_shift)*FFMIN(h->sps.crop_bottom, (16>>s->chroma_y_shift)-1) * (2 - h->sps.frame_mbs_only_flag);
 +        }
          s->avctx->sample_aspect_ratio = h->sps.sar;
          av_assert0(s->avctx->sample_aspect_ratio.den);
  
 +        if (s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU
 +            && (h->sps.bit_depth_luma != 8 ||
 +                h->sps.chroma_format_idc > 1)) {
 +            av_log(s->avctx, AV_LOG_ERROR,
 +                   "VDPAU decoding does not support video "
 +                   "colorspace\n");
 +            return -1;
 +        }
 +
 +        if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
 +            h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
 +            if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 && h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
 +                (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
 +                s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
 +                h->cur_chroma_format_idc = h->sps.chroma_format_idc;
 +                h->pixel_shift = h->sps.bit_depth_luma > 8;
 +
 +                ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
 +                ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
 +                s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
 +                ff_dsputil_init(&s->dsp, s->avctx);
 +            } else {
 +                av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d chroma_idc: %d\n",
 +                       h->sps.bit_depth_luma, h->sps.chroma_format_idc);
 +                return -1;
 +            }
 +        }
 +
          if (h->sps.video_signal_type_present_flag) {
 -            s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
 +            s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
                                                        : AVCOL_RANGE_MPEG;
              if (h->sps.colour_description_present_flag) {
                  s->avctx->color_primaries = h->sps.color_primaries;
              else
                  s->avctx->pix_fmt = AV_PIX_FMT_YUV420P10;
              break;
 -        case 8:
 +        case 12:
 +            if (CHROMA444) {
 +                if (s->avctx->colorspace == AVCOL_SPC_RGB) {
 +                    s->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
 +                } else
 +                    s->avctx->pix_fmt = AV_PIX_FMT_YUV444P12;
 +            } else if (CHROMA422)
 +                s->avctx->pix_fmt = AV_PIX_FMT_YUV422P12;
 +            else
 +                s->avctx->pix_fmt = AV_PIX_FMT_YUV420P12;
 +            break;
 +        case 14:
              if (CHROMA444) {
                  if (s->avctx->colorspace == AVCOL_SPC_RGB) {
 -                    s->avctx->pix_fmt = AV_PIX_FMT_GBRP;
 +                    s->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
                  } else
 +                    s->avctx->pix_fmt = AV_PIX_FMT_YUV444P14;
 +            } else if (CHROMA422)
 +                s->avctx->pix_fmt = AV_PIX_FMT_YUV422P14;
 +            else
 +                s->avctx->pix_fmt = AV_PIX_FMT_YUV420P14;
 +            break;
 +        case 8:
 +            if (CHROMA444) {
                      s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
                                                                                    : AV_PIX_FMT_YUV444P;
 +                    if (s->avctx->colorspace == AVCOL_SPC_RGB) {
 +                        s->avctx->pix_fmt = AV_PIX_FMT_GBR24P;
 +                        av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
 +                    } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
 +                        av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
 +                    }
              } else if (CHROMA422) {
                  s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
                                                                                : AV_PIX_FMT_YUV422P;
                     "Could not allocate memory for h264\n");
              return AVERROR(ENOMEM);
          }
 +        h->bipred_scratchpad = NULL;
  
          if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
              if (context_init(h) < 0) {
                  c->sps         = h->sps;
                  c->pps         = h->pps;
                  c->pixel_shift = h->pixel_shift;
 +                c->cur_chroma_format_idc = h->cur_chroma_format_idc;
                  init_scan_tables(c);
                  clone_tables(c, h, i);
              }
      h->mb_mbaff        = 0;
      h->mb_aff_frame    = 0;
      last_pic_structure = s0->picture_structure;
-     last_pic_dropable  = s0->dropable;
-     s->dropable        = h->nal_ref_idc == 0;
+     last_pic_droppable = s0->droppable;
+     s->droppable       = h->nal_ref_idc == 0;
      if (h->sps.frame_mbs_only_flag) {
          s->picture_structure = PICT_FRAME;
      } else {
 +        if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
 +            av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
 +            return -1;
 +        }
          if (get_bits1(&s->gb)) { // field_pic_flag
              s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
          } else {
  
      if (h0->current_slice != 0) {
          if (last_pic_structure != s->picture_structure ||
-             last_pic_dropable  != s->dropable) {
+             last_pic_droppable != s->droppable) {
              av_log(h->s.avctx, AV_LOG_ERROR,
                     "Changing field mode (%d -> %d) between slices is not allowed\n",
                     last_pic_structure, s->picture_structure);
              s->picture_structure = last_pic_structure;
-             s->dropable          = last_pic_dropable;
+             s->droppable         = last_pic_droppable;
              return AVERROR_INVALIDDATA;
          } else if (!s0->current_picture_ptr) {
              av_log(s->avctx, AV_LOG_ERROR,
      } else {
          /* Shorten frame num gaps so we don't have to allocate reference
           * frames just to throw them away */
 -        if (h->frame_num != h->prev_frame_num) {
 +        if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
              int unwrap_prev_frame_num = h->prev_frame_num;
              int max_frame_num         = 1 << h->sps.log2_max_frame_num;
  
              assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
  
              /* Mark old field/frame as completed */
-             if (!last_pic_dropable && s0->current_picture_ptr->owner2 == s0) {
+             if (!last_pic_droppable && s0->current_picture_ptr->owner2 == s0) {
                  ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
                                            last_pic_structure == PICT_BOTTOM_FIELD);
              }
              if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
                  /* Previous field is unmatched. Don't display it, but let it
                   * remain for reference if marked as such. */
-                 if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
+                 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
                      ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
                                                last_pic_structure == PICT_TOP_FIELD);
                  }
                       * different frame_nums. Consider this field first in
                       * pair. Throw away previous field except for reference
                       * purposes. */
-                     if (!last_pic_dropable && last_pic_structure != PICT_FRAME) {
+                     if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
                          ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
                                                    last_pic_structure == PICT_TOP_FIELD);
                      }
                                 "Invalid field mode combination %d/%d\n",
                                 last_pic_structure, s->picture_structure);
                          s->picture_structure = last_pic_structure;
-                         s->dropable          = last_pic_dropable;
+                         s->droppable         = last_pic_droppable;
                          return AVERROR_INVALIDDATA;
-                     } else if (last_pic_dropable != s->dropable) {
+                     } else if (last_pic_droppable != s->droppable) {
                          av_log(s->avctx, AV_LOG_ERROR,
                                 "Cannot combine reference and non-reference fields in the same frame\n");
                          av_log_ask_for_sample(s->avctx, NULL);
                          s->picture_structure = last_pic_structure;
-                         s->dropable          = last_pic_dropable;
+                         s->droppable         = last_pic_droppable;
                          return AVERROR_INVALIDDATA;
                      }
  
              }
          }
  
 -        while (h->frame_num != h->prev_frame_num &&
 +        while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 &&
                 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
              Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
              av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
                  s0->first_field         = FIELD_PICTURE;
              } else {
                  if (s0->current_picture_ptr->frame_num != h->frame_num) {
 +                    ff_thread_report_progress((AVFrame*)s0->current_picture_ptr, INT_MAX,
 +                                              s0->picture_structure==PICT_BOTTOM_FIELD);
                      /* This and the previous field had different frame_nums.
                       * Consider this field first in pair. Throw away previous
                       * one except for reference purposes. */
  
      s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
  
 -    assert(s->mb_num == s->mb_width * s->mb_height);
 +    av_assert1(s->mb_num == s->mb_width * s->mb_height);
      if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
          first_mb_in_slice >= s->mb_num) {
          av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
      s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
      if (s->picture_structure == PICT_BOTTOM_FIELD)
          s->resync_mb_y = s->mb_y = s->mb_y + 1;
 -    assert(s->mb_y < s->mb_height);
 +    av_assert1(s->mb_y < s->mb_height);
  
      if (s->picture_structure == PICT_FRAME) {
          h->curr_pic_num = h->frame_num;
      h->ref_count[1] = h->pps.ref_count[1];
  
      if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
 +        unsigned max[2];
 +        max[0] = max[1] = s->picture_structure == PICT_FRAME ? 15 : 31;
 +
          if (h->slice_type_nos == AV_PICTURE_TYPE_B)
              h->direct_spatial_mv_pred = get_bits1(&s->gb);
          num_ref_idx_active_override_flag = get_bits1(&s->gb);
  
          if (num_ref_idx_active_override_flag) {
              h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
 -            if (h->ref_count[0] < 1)
 -                return AVERROR_INVALIDDATA;
              if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
                  h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
 -                if (h->ref_count[1] < 1)
 -                    return AVERROR_INVALIDDATA;
 -            }
 +            } else
 +                // full range is spec-ok in this case, even for frames
 +                h->ref_count[1] = 1;
 +        }
 +
 +        if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
 +            av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", h->ref_count[0]-1, max[0], h->ref_count[1]-1, max[1]);
 +            h->ref_count[0] = h->ref_count[1] = 1;
 +            return AVERROR_INVALIDDATA;
          }
  
          if (h->slice_type_nos == AV_PICTURE_TYPE_B)
          else
              h->list_count = 1;
      } else
 -        h->list_count = 0;
 -
 -    max_refs = s->picture_structure == PICT_FRAME ? 16 : 32;
 -
 -    if (h->ref_count[0] > max_refs || h->ref_count[1] > max_refs) {
 -        av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
 -        h->ref_count[0] = h->ref_count[1] = 1;
 -        return AVERROR_INVALIDDATA;
 -    }
 +        h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
  
      if (!default_ref_list_done)
          ff_h264_fill_default_ref_list(h);
  
      h0->last_slice_type = slice_type;
      h->slice_num = ++h0->current_slice;
 -    if (h->slice_num >= MAX_SLICES) {
 -        av_log(s->avctx, AV_LOG_ERROR,
 -               "Too many slices, increase MAX_SLICES and recompile\n");
 +
 +    if (h->slice_num)
 +        h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
 +    if (   h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
 +        && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
 +        && h->slice_num >= MAX_SLICES) {
 +        //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
 +        av_log(s->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
      }
  
      for (j = 0; j < 2; j++) {
@@@ -3206,7 -3113,7 +3206,7 @@@ static av_always_inline void fill_filte
          if (USES_LIST(top_type, list)) {
              const int b_xy  = h->mb2b_xy[top_xy] + 3 * b_stride;
              const int b8_xy = 4 * top_xy + 2;
 -            int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
 +            int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
              AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
              ref_cache[0 - 1 * 8] =
              ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
              if (USES_LIST(left_type[LTOP], list)) {
                  const int b_xy  = h->mb2b_xy[left_xy[LTOP]] + 3;
                  const int b8_xy = 4 * left_xy[LTOP] + 1;
 -                int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
 +                int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
                  AV_COPY32(mv_dst - 1 +  0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
                  AV_COPY32(mv_dst - 1 +  8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
                  AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
  
      {
          int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
 -        int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
 +        int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
          uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
          uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
          AV_WN32A(&ref_cache[0 * 8], ref01);
@@@ -3531,7 -3438,7 +3531,7 @@@ static void decode_finish_row(H264Conte
  
      ff_draw_horiz_band(s, top, height);
  
-     if (s->dropable)
+     if (s->droppable)
          return;
  
      ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
@@@ -3557,6 -3464,7 +3557,6 @@@ static int decode_slice(struct AVCodecC
          align_get_bits(&s->gb);
  
          /* init cabac */
 -        ff_init_cabac_states(&h->cabac);
          ff_init_cabac_decoder(&h->cabac,
                                s->gb.buffer + get_bits_count(&s->gb) / 8,
                                (get_bits_left(&s->gb) + 7) / 8);
                      loop_filter(h, lf_x_start, s->mb_x + 1);
                  return 0;
              }
 -            if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
 +            if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
 +                av_log(h->s.avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
 +            if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
                  av_log(h->s.avctx, AV_LOG_ERROR,
                         "error while decoding MB %d %d, bytestream (%td)\n",
                         s->mb_x, s->mb_y,
                      tprintf(s->avctx, "slice end %d %d\n",
                              get_bits_count(&s->gb), s->gb.size_in_bits);
  
 -                    if (get_bits_left(&s->gb) == 0) {
 +                    if (   get_bits_left(&s->gb) == 0
 +                        || get_bits_left(&s->gb) > 0 && !(s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
                          ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
                                          s->mb_x - 1, s->mb_y,
                                          ER_MB_END & part_mask);
                          return 0;
                      } else {
                          ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
 -                                        s->mb_x - 1, s->mb_y,
 +                                        s->mb_x, s->mb_y,
                                          ER_MB_END & part_mask);
  
                          return -1;
@@@ -3727,7 -3632,6 +3727,7 @@@ static int execute_decode_slices(H264Co
              hx                    = h->thread_context[i];
              hx->s.err_recognition = avctx->err_recognition;
              hx->s.error_count     = 0;
 +            hx->x264_build        = h->x264_build;
          }
  
          avctx->execute(avctx, decode_slice, h->thread_context,
          hx                   = h->thread_context[context_count - 1];
          s->mb_x              = hx->s.mb_x;
          s->mb_y              = hx->s.mb_y;
-         s->dropable          = hx->s.dropable;
+         s->droppable         = hx->s.droppable;
          s->picture_structure = hx->s.picture_structure;
          for (i = 1; i < context_count; i++)
              h->s.error_count += h->thread_context[i]->s.error_count;
@@@ -3757,12 -3661,7 +3757,12 @@@ static int decode_nal_units(H264Contex
      int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
      int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
      int nal_index;
 +    int idr_cleared=0;
 +
 +    h->nal_unit_type= 0;
  
 +    if(!s->slice_context_count)
 +         s->slice_context_count= 1;
      h->max_contexts = s->slice_context_count;
      if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
          h->current_slice = 0;
          ff_h264_reset_sei(h);
      }
  
 +    if (h->nal_length_size == 4) {
 +        if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
 +            h->is_avc = 0;
 +        }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
 +            h->is_avc = 1;
 +    }
 +
      for (; pass <= 1; pass++) {
          buf_index     = 0;
          context_count = 0;
                  s->workaround_bugs |= FF_BUG_TRUNCATED;
  
              if (!(s->workaround_bugs & FF_BUG_TRUNCATED))
 -                while (ptr[dst_length - 1] == 0 && dst_length > 0)
 +                while(dst_length > 0 && ptr[dst_length - 1] == 0)
                      dst_length--;
              bit_length = !dst_length ? 0
                                       : (8 * dst_length -
                                          decode_rbsp_trailing(h, ptr + dst_length - 1));
  
              if (s->avctx->debug & FF_DEBUG_STARTCODE)
 -                av_log(h->s.avctx, AV_LOG_DEBUG,
 -                       "NAL %d at %d/%d length %d\n",
 -                       hx->nal_unit_type, buf_index, buf_size, dst_length);
 +                av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d/%d at %d/%d length %d pass %d\n", hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
  
              if (h->is_avc && (nalsize != consumed) && nalsize)
                  av_log(h->s.avctx, AV_LOG_DEBUG,
  
  again:
              err = 0;
 +
 +            if (h->decoding_extradata) {
 +                switch (hx->nal_unit_type) {
 +                case NAL_IDR_SLICE:
 +                case NAL_SLICE:
 +                case NAL_DPA:
 +                case NAL_DPB:
 +                case NAL_DPC:
 +                case NAL_AUXILIARY_SLICE:
 +                    av_log(h->s.avctx, AV_LOG_WARNING, "Ignoring NAL %d in global header\n", hx->nal_unit_type);
 +                    hx->nal_unit_type = NAL_FILLER_DATA;
 +                }
 +            }
 +
              switch (hx->nal_unit_type) {
              case NAL_IDR_SLICE:
                  if (h->nal_unit_type != NAL_IDR_SLICE) {
                      buf_index = -1;
                      goto end;
                  }
 -                idr(h); // FIXME ensure we don't lose some frames if there is reordering
 +                if(!idr_cleared)
 +                    idr(h); // FIXME ensure we don't lose some frames if there is reordering
 +                idr_cleared = 1;
              case NAL_SLICE:
                  init_get_bits(&hx->s.gb, ptr, bit_length);
                  hx->intra_gb_ptr        =
                  if ((err = decode_slice_header(hx, h)))
                      break;
  
 +                if (h->sei_recovery_frame_cnt >= 0 && (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I))
 +                    h->valid_recovery_point = 1;
 +
 +                if (   h->sei_recovery_frame_cnt >= 0
 +                    && (   h->recovery_frame<0
 +                        || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
 +                    h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
 +                                        (1 << h->sps.log2_max_frame_num);
 +
 +                    if (!h->valid_recovery_point)
 +                        h->recovery_frame = h->frame_num;
 +                }
 +
                  s->current_picture_ptr->f.key_frame |=
 -                    (hx->nal_unit_type == NAL_IDR_SLICE) ||
 -                    (h->sei_recovery_frame_cnt >= 0);
 +                        (hx->nal_unit_type == NAL_IDR_SLICE);
 +
 +                if (h->recovery_frame == h->frame_num) {
 +                    s->current_picture_ptr->sync |= 1;
 +                    h->recovery_frame = -1;
 +                }
 +
 +                h->sync |= !!s->current_picture_ptr->f.key_frame;
 +                h->sync |= 3*!!(s->flags2 & CODEC_FLAG2_SHOW_ALL);
 +                s->current_picture_ptr->sync |= h->sync;
  
                  if (h->current_slice == 1) {
                      if (!(s->flags2 & CODEC_FLAG2_CHUNKS))
                  init_get_bits(&hx->inter_gb, ptr, bit_length);
                  hx->inter_gb_ptr = &hx->inter_gb;
  
 +                av_log(h->s.avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
 +                break;
 +
                  if (hx->redundant_pic_count == 0 &&
                      hx->intra_gb_ptr &&
                      hx->s.data_partitioning &&
                  break;
              case NAL_SPS:
                  init_get_bits(&s->gb, ptr, bit_length);
 -                if (ff_h264_decode_seq_parameter_set(h) < 0 &&
 -                    h->is_avc && (nalsize != consumed) && nalsize) {
 +                if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)) {
                      av_log(h->s.avctx, AV_LOG_DEBUG,
                             "SPS decoding failure, trying again with the complete NAL\n");
 -                    init_get_bits(&s->gb, buf + buf_index + 1 - consumed,
 -                                  8 * (nalsize - 1));
 +                    if (h->is_avc)
 +                        av_assert0(next_avc - buf_index + consumed == nalsize);
 +                    if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
 +                        break;
 +                    init_get_bits(&s->gb, &buf[buf_index + 1 - consumed],
 +                                  8*(next_avc - buf_index + consumed - 1));
                      ff_h264_decode_seq_parameter_set(h);
                  }
  
  
                  if (avctx->has_b_frames < 2)
                      avctx->has_b_frames = !s->low_delay;
 -
 -                if (avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
 -                    h->cur_chroma_format_idc   != h->sps.chroma_format_idc) {
 -                    if (s->avctx->codec &&
 -                        s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU
 -                        && (h->sps.bit_depth_luma != 8 ||
 -                            h->sps.chroma_format_idc > 1)) {
 -                        av_log(avctx, AV_LOG_ERROR,
 -                               "VDPAU decoding does not support video "
 -                               "colorspace\n");
 -                        buf_index = -1;
 -                        goto end;
 -                    }
 -                    if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
 -                        avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
 -                        h->cur_chroma_format_idc   = h->sps.chroma_format_idc;
 -                        h->pixel_shift             = h->sps.bit_depth_luma > 8;
 -
 -                        ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
 -                                        h->sps.chroma_format_idc);
 -                        ff_h264_pred_init(&h->hpc, s->codec_id,
 -                                          h->sps.bit_depth_luma,
 -                                          h->sps.chroma_format_idc);
 -                        s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
 -                        ff_dsputil_init(&s->dsp, s->avctx);
 -                    } else {
 -                        av_log(avctx, AV_LOG_ERROR,
 -                               "Unsupported bit depth: %d\n",
 -                               h->sps.bit_depth_luma);
 -                        buf_index = -1;
 -                        goto end;
 -                    }
 -                }
                  break;
              case NAL_PPS:
                  init_get_bits(&s->gb, ptr, bit_length);
  end:
      /* clean up */
      if (s->current_picture_ptr && s->current_picture_ptr->owner2 == s &&
-         !s->dropable) {
+         !s->droppable) {
          ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
                                    s->picture_structure == PICT_BOTTOM_FIELD);
      }
@@@ -4112,15 -3996,15 +4112,15 @@@ static int decode_frame(AVCodecContext 
      MpegEncContext *s  = &h->s;
      AVFrame *pict      = data;
      int buf_index      = 0;
 +    Picture *out;
 +    int i, out_idx;
  
      s->flags  = avctx->flags;
      s->flags2 = avctx->flags2;
  
      /* end of stream, output what is still in the buffers */
 -out:
      if (buf_size == 0) {
 -        Picture *out;
 -        int i, out_idx;
 + out:
  
          s->current_picture_ptr = NULL;
  
  
          return buf_index;
      }
 +    if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
 +        int cnt= buf[5]&0x1f;
 +        const uint8_t *p= buf+6;
 +        while(cnt--){
 +            int nalsize= AV_RB16(p) + 2;
 +            if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
 +                goto not_extra;
 +            p += nalsize;
 +        }
 +        cnt = *(p++);
 +        if(!cnt)
 +            goto not_extra;
 +        while(cnt--){
 +            int nalsize= AV_RB16(p) + 2;
 +            if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
 +                goto not_extra;
 +            p += nalsize;
 +        }
 +
 +        return ff_h264_decode_extradata(h, buf, buf_size);
 +    }
 +not_extra:
  
      buf_index = decode_nal_units(h, buf, buf_size);
      if (buf_index < 0)
          return -1;
  
      if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
 -        buf_size = 0;
 +        av_assert0(buf_index <= buf_size);
          goto out;
      }
  
      if (!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr) {
 -        if (avctx->skip_frame >= AVDISCARD_NONREF)
 -            return 0;
 +        if (avctx->skip_frame >= AVDISCARD_NONREF ||
 +            buf_size >= 4 && !memcmp("Q264", buf, 4))
 +            return buf_size;
          av_log(avctx, AV_LOG_ERROR, "no frame!\n");
          return -1;
      }
  
          field_end(h, 0);
  
 -        if (!h->next_output_pic) {
 -            /* Wait for second field. */
 -            *got_frame = 0;
 -        } else {
 +        /* Wait for second field. */
 +        *got_frame = 0;
 +        if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
              *got_frame = 1;
              *pict      = h->next_output_pic->f;
          }
@@@ -4226,7 -4088,6 +4226,7 @@@ static av_cold int h264_decode_end(AVCo
      H264Context *h    = avctx->priv_data;
      MpegEncContext *s = &h->s;
  
 +    ff_h264_remove_all_refs(h);
      ff_h264_free_context(h);
  
      ff_MPV_common_end(s);
@@@ -4253,26 -4114,6 +4253,26 @@@ static const AVProfile profiles[] = 
      { FF_PROFILE_UNKNOWN },
  };
  
 +static const AVOption h264_options[] = {
 +    {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
 +    {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
 +    {NULL}
 +};
 +
 +static const AVClass h264_class = {
 +    .class_name = "H264 Decoder",
 +    .item_name  = av_default_item_name,
 +    .option     = h264_options,
 +    .version    = LIBAVUTIL_VERSION_INT,
 +};
 +
 +static const AVClass h264_vdpau_class = {
 +    .class_name = "H264 VDPAU Decoder",
 +    .item_name  = av_default_item_name,
 +    .option     = h264_options,
 +    .version    = LIBAVUTIL_VERSION_INT,
 +};
 +
  AVCodec ff_h264_decoder = {
      .name                  = "h264",
      .type                  = AVMEDIA_TYPE_VIDEO,
      .init_thread_copy      = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
      .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
      .profiles              = NULL_IF_CONFIG_SMALL(profiles),
 +    .priv_class            = &h264_class,
  };
  
  #if CONFIG_H264_VDPAU_DECODER
@@@ -4307,6 -4147,5 +4307,6 @@@ AVCodec ff_h264_vdpau_decoder = 
      .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
                                                     AV_PIX_FMT_NONE},
      .profiles       = NULL_IF_CONFIG_SMALL(profiles),
 +    .priv_class     = &h264_vdpau_class,
  };
  #endif
diff --combined libavcodec/mpegvideo.c
@@@ -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
   */
  
@@@ -58,6 -58,9 +58,6 @@@ static void dct_unquantize_h263_inter_c
                                    DCTELEM *block, int n, int qscale);
  
  
 -/* enable all paranoid tests for rounding, overflows, etc... */
 -//#define PARANOID
 -
  //#define DEBUG
  
  
@@@ -135,9 -138,9 +135,9 @@@ const enum AVPixelFormat ff_hwaccel_pix
      AV_PIX_FMT_NONE
  };
  
 -const uint8_t *avpriv_mpv_find_start_code(const uint8_t *restrict p,
 +const uint8_t *avpriv_mpv_find_start_code(const uint8_t *av_restrict p,
                                            const uint8_t *end,
 -                                          uint32_t * restrict state)
 +                                          uint32_t *av_restrict state)
  {
      int i;
  
@@@ -419,12 -422,12 +419,12 @@@ static int init_duplicate_context(MpegE
      // edge emu needs blocksize + filter length - 1
      // (= 17x17 for  halfpel / 21x21 for  h264)
      FF_ALLOCZ_OR_GOTO(s->avctx, s->edge_emu_buffer,
 -                      (s->width + 64) * 2 * 21 * 2, fail);    // (width + edge + align)*interlaced*MBsize*tolerance
 +                      (s->width + 95) * 2 * 21 * 4, fail);    // (width + edge + align)*interlaced*MBsize*tolerance
  
      // FIXME should be linesize instead of s->width * 2
      // but that is not known before get_buffer()
      FF_ALLOCZ_OR_GOTO(s->avctx, s->me.scratchpad,
 -                      (s->width + 64) * 4 * 16 * 2 * sizeof(uint8_t), fail)
 +                      (s->width + 95) * 4 * 16 * 2 * sizeof(uint8_t), fail)
      s->me.temp         = s->me.scratchpad;
      s->rd_scratchpad   = s->me.scratchpad;
      s->b_scratchpad    = s->me.scratchpad;
@@@ -527,32 -530,27 +527,32 @@@ int ff_mpeg_update_thread_context(AVCod
                                    const AVCodecContext *src)
  {
      int i;
 +    int err;
      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) {
          memcpy(s, s1, sizeof(MpegEncContext));
  
          s->avctx                 = dst;
 -        s->picture_range_start  += MAX_PICTURE_COUNT;
 -        s->picture_range_end    += MAX_PICTURE_COUNT;
          s->bitstream_buffer      = NULL;
          s->bitstream_buffer_size = s->allocated_bitstream_buffer_size = 0;
  
 -        ff_MPV_common_init(s);
 +        if (s1->context_initialized){
 +            s->picture_range_start  += MAX_PICTURE_COUNT;
 +            s->picture_range_end    += MAX_PICTURE_COUNT;
 +            if((err = ff_MPV_common_init(s)) < 0)
 +                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;
      s->picture_number       = s1->picture_number;
      s->input_picture_number = s1->input_picture_number;
  
 +    av_assert0(!s->picture || s->picture != s1->picture);
      memcpy(s->picture, s1->picture, s1->picture_count * sizeof(Picture));
      memcpy(&s->last_picture, &s1->last_picture,
             (char *) &s1->last_picture_ptr - (char *) &s1->last_picture);
      // 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->time_increment_bits, &s1->time_increment_bits,
      // B-frame info
      s->max_b_frames = s1->max_b_frames;
      s->low_delay    = s1->low_delay;
-     s->dropable     = s1->dropable;
+     s->droppable    = s1->droppable;
  
      // DivX handling (doesn't work)
      s->divx_packed  = s1->divx_packed;
@@@ -701,32 -697,44 +701,32 @@@ static int init_context_frame(MpegEncCo
      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
 +    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);
      FF_ALLOCZ_OR_GOTO(s->avctx, s->error_status_table,
                        mb_array_size * sizeof(uint8_t), fail);
  
 -    if (s->codec_id == AV_CODEC_ID_MPEG4 ||
 -        (s->flags & CODEC_FLAG_INTERLACED_ME)) {
 +    if (s->codec_id == AV_CODEC_ID_MPEG4 || (s->flags & CODEC_FLAG_INTERLACED_ME)) {
          /* interlaced direct mode decoding tables */
          for (i = 0; i < 2; i++) {
              int j, k;
                      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) {
          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;
      FF_ALLOCZ_OR_GOTO(s->avctx, s->mbskip_table, mb_array_size + 2, fail);
      // Note the + 1 is for  a quicker mpeg4 slice_end detection
  
 -    if ((s->avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) ||
 -        s->avctx->debug_mv) {
 -        s->visualization_buffer[0] = av_malloc((s->mb_width * 16 +
 -                    2 * EDGE_WIDTH) * s->mb_height * 16 + 2 * EDGE_WIDTH);
 -        s->visualization_buffer[1] = av_malloc((s->mb_width * 16 +
 -                    2 * EDGE_WIDTH) * s->mb_height * 16 + 2 * EDGE_WIDTH);
 -        s->visualization_buffer[2] = av_malloc((s->mb_width * 16 +
 -                    2 * EDGE_WIDTH) * s->mb_height * 16 + 2 * EDGE_WIDTH);
 -    }
 -
      return 0;
  fail:
      return AVERROR(ENOMEM);
@@@ -839,34 -865,44 +839,34 @@@ av_cold int ff_MPV_common_init(MpegEncC
      s->flags  = s->avctx->flags;
      s->flags2 = s->avctx->flags2;
  
 -    if (s->width && s->height) {
 -        /* set chroma shifts */
 -        av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,
 -                                         &s->chroma_x_shift,
 -                                         &s->chroma_y_shift);
 +    /* set chroma shifts */
 +    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);
 +    s->stream_codec_tag = avpriv_toupper4(s->avctx->stream_codec_tag);
  
 -        /* convert fourcc to upper case */
 -        s->codec_tag          = avpriv_toupper4(s->avctx->codec_tag);
 +    s->avctx->coded_frame = &s->current_picture.f;
  
 -        s->stream_codec_tag   = avpriv_toupper4(s->avctx->stream_codec_tag);
 +    if (s->encoding) {
 +        if (s->msmpeg4_version) {
 +            FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_stats,
 +                                2 * 2 * (MAX_LEVEL + 1) *
 +                                (MAX_RUN + 1) * 2 * sizeof(int), fail);
 +        }
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->avctx->stats_out, 256, fail);
  
 -        s->avctx->coded_frame = &s->current_picture.f;
 +        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)
 +        FF_ALLOCZ_OR_GOTO(s->avctx, s->reordered_input_picture, MAX_PICTURE_COUNT * sizeof(Picture *), fail)
  
 -        if (s->encoding) {
 -            if (s->msmpeg4_version) {
 -                FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_stats,
 -                                  2 * 2 * (MAX_LEVEL + 1) *
 -                                  (MAX_RUN + 1) * 2 * sizeof(int), fail);
 -            }
 -            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_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_inter_matrix16,
 -                              64 * 32 * 2 * sizeof(uint16_t), fail);
 -            FF_ALLOCZ_OR_GOTO(s->avctx, s->input_picture,
 -                              MAX_PICTURE_COUNT * sizeof(Picture *), fail);
 -            FF_ALLOCZ_OR_GOTO(s->avctx, s->reordered_input_picture,
 -                              MAX_PICTURE_COUNT * sizeof(Picture *), fail);
 -
 -            if (s->avctx->noise_reduction) {
 -                FF_ALLOCZ_OR_GOTO(s->avctx, s->dct_offset,
 -                                  2 * 64 * sizeof(uint16_t), fail);
 -            }
 +        if (s->avctx->noise_reduction) {
 +            FF_ALLOCZ_OR_GOTO(s->avctx, s->dct_offset, 2 * 64 * sizeof(uint16_t), fail);
          }
      }
  
          avcodec_get_frame_defaults(&s->picture[i].f);
      }
  
 -    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;
 +        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));
              s->end_mb_y   = s->mb_height;
          }
          s->slice_context_count = nb_slices;
 -    }
 +//     }
  
      return 0;
   fail:
@@@ -962,7 -1000,6 +962,7 @@@ static int free_context_frame(MpegEncCo
      av_freep(&s->er_temp_buffer);
      av_freep(&s->mb_index2xy);
      av_freep(&s->lambda_table);
 +
      av_freep(&s->cplx_tab);
      av_freep(&s->bits_tab);
  
@@@ -1072,10 -1109,6 +1072,10 @@@ void ff_MPV_common_end(MpegEncContext *
      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);
@@@ -1237,21 -1270,7 +1237,21 @@@ static int find_unused_picture(MpegEncC
          }
      }
  
 -    return AVERROR_INVALIDDATA;
 +    av_log(s->avctx, AV_LOG_FATAL,
 +           "Internal error, picture buffer overflow\n");
 +    /* We could return -1, but the codec would crash trying to draw into a
 +     * non-existing frame anyway. This is safer than waiting for a random crash.
 +     * Also the return of this is never useful, an encoder must only allocate
 +     * as much as allowed in the specification. This has no relationship to how
 +     * much libavcodec could allocate (and MAX_PICTURE_COUNT is always large
 +     * enough for such valid streams).
 +     * Plus, a decoder has to check stream validity and remove frames if too
 +     * many reference frames are around. Waiting for "OOM" is not correct at
 +     * all. Similarly, missing reference frames have to be replaced by
 +     * interpolated/MC frames, anything else is a bug in the codec ...
 +     */
 +    abort();
 +    return -1;
  }
  
  int ff_find_unused_picture(MpegEncContext *s, int shared)
@@@ -1299,11 -1318,6 +1299,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->out_format != FMT_H264 || s->codec_id == AV_CODEC_ID_SVQ3) {
          if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&
          }
  
          pic->f.reference = 0;
-         if (!s->dropable) {
+         if (!s->droppable) {
              if (s->codec_id == AV_CODEC_ID_H264)
                  pic->f.reference = s->picture_structure;
              else if (s->pict_type != AV_PICTURE_TYPE_B)
  
      if (s->pict_type != AV_PICTURE_TYPE_B) {
          s->last_picture_ptr = s->next_picture_ptr;
-         if (!s->dropable)
+         if (!s->droppable)
              s->next_picture_ptr = s->current_picture_ptr;
      }
      av_dlog(s->avctx, "L%p N%p C%p L%p N%p C%p type:%d drop:%d\n",
              s->last_picture_ptr    ? s->last_picture_ptr->f.data[0]    : NULL,
              s->next_picture_ptr    ? s->next_picture_ptr->f.data[0]    : NULL,
              s->current_picture_ptr ? s->current_picture_ptr->f.data[0] : NULL,
-             s->pict_type, s->dropable);
+             s->pict_type, s->droppable);
  
      if (s->codec_id != AV_CODEC_ID_H264) {
          if ((s->last_picture_ptr == NULL ||
                  return i;
              }
              s->last_picture_ptr = &s->picture[i];
 +            s->last_picture_ptr->f.key_frame = 0;
              if (ff_alloc_picture(s, s->last_picture_ptr, 0) < 0) {
                  s->last_picture_ptr = NULL;
                  return -1;
              }
 +
 +            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->f, INT_MAX, 0);
              ff_thread_report_progress(&s->last_picture_ptr->f, INT_MAX, 1);
              s->last_picture_ptr->f.reference = 3;
                  return i;
              }
              s->next_picture_ptr = &s->picture[i];
 +            s->next_picture_ptr->f.key_frame = 0;
              if (ff_alloc_picture(s, s->next_picture_ptr, 0) < 0) {
                  s->next_picture_ptr = NULL;
                  return -1;
@@@ -1512,30 -1518,28 +1512,30 @@@ void ff_MPV_frame_end(MpegEncContext *s
      // just to make sure that all data is rendered.
      if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration) {
          ff_xvmc_field_end(s);
 -   } else if ((s->error_count || s->encoding) &&
 +   } else if((s->error_count || s->encoding || !(s->avctx->codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND)) &&
                !s->avctx->hwaccel &&
                !(s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) &&
                s->unrestricted_mv &&
                s->current_picture.f.reference &&
                !s->intra_only &&
 -              !(s->flags & CODEC_FLAG_EMU_EDGE)) {
 -       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->dsp.draw_edges(s->current_picture.f.data[0], s->linesize,
 -                         s->h_edge_pos, s->v_edge_pos,
 -                         EDGE_WIDTH, EDGE_WIDTH,
 -                         EDGE_TOP | EDGE_BOTTOM);
 -       s->dsp.draw_edges(s->current_picture.f.data[1], s->uvlinesize,
 -                         s->h_edge_pos >> hshift, s->v_edge_pos >> vshift,
 -                         EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
 -                         EDGE_TOP | EDGE_BOTTOM);
 -       s->dsp.draw_edges(s->current_picture.f.data[2], s->uvlinesize,
 -                         s->h_edge_pos >> hshift, s->v_edge_pos >> vshift,
 -                         EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
 -                         EDGE_TOP | EDGE_BOTTOM);
 +              !(s->flags & CODEC_FLAG_EMU_EDGE) &&
 +              !s->avctx->lowres
 +            ) {
 +        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->dsp.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->dsp.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->dsp.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, EDGE_WIDTH >> vshift,
 +                          EDGE_TOP | EDGE_BOTTOM);
      }
  
      emms_c();
@@@ -1605,11 -1609,11 +1605,11 @@@ static void draw_line(uint8_t *buf, in
          buf += sx + sy * stride;
          ex  -= sx;
          f    = ((ey - sy) << 16) / ex;
 -        for (x = 0; x = ex; x++) {
 +        for(x= 0; x <= ex; x++){
              y  = (x * f) >> 16;
              fr = (x * f) & 0xFFFF;
              buf[y * stride + x]       += (color * (0x10000 - fr)) >> 16;
 -            buf[(y + 1) * stride + x] += (color *            fr ) >> 16;
 +            if(fr) buf[(y + 1) * stride + x] += (color *            fr ) >> 16;
          }
      } else {
          if (sy > ey) {
          buf += sx + sy * stride;
          ey  -= sy;
          if (ey)
 -            f  = ((ex - sx) << 16) / ey;
 +            f = ((ex - sx) << 16) / ey;
          else
              f = 0;
 -        for (y = 0; y = ey; y++) {
 -            x  = (y * f) >> 16;
 -            fr = (y * f) & 0xFFFF;
 +        for(y= 0; y <= ey; y++){
 +            x  = (y*f) >> 16;
 +            fr = (y*f) & 0xFFFF;
              buf[y * stride + x]     += (color * (0x10000 - fr)) >> 16;
 -            buf[y * stride + x + 1] += (color *            fr ) >> 16;
 +            if(fr) buf[y * stride + x + 1] += (color *            fr ) >> 16;
          }
      }
  }
@@@ -1671,16 -1675,33 +1671,16 @@@ static void draw_arrow(uint8_t *buf, in
   */
  void ff_print_debug_info(MpegEncContext *s, AVFrame *pict)
  {
 -    if (s->avctx->hwaccel || !pict || !pict->mb_type)
 +    if (   s->avctx->hwaccel || !pict || !pict->mb_type
 +        || (s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU))
          return;
  
 +
      if (s->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;
 -        }
 +        av_log(s->avctx, AV_LOG_DEBUG, "New frame, type: %c\n",
 +               av_get_picture_type_char(pict->pict_type));
          for (y = 0; y < s->mb_height; y++) {
              for (x = 0; x < s->mb_width; x++) {
                  if (s->avctx->debug & FF_DEBUG_SKIP) {
                      else if (!USES_LIST(mb_type, 0))
                          av_log(s->avctx, AV_LOG_DEBUG, "<");
                      else {
 -                        assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
 +                        av_assert2(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
                          av_log(s->avctx, AV_LOG_DEBUG, "X");
                      }
  
                                     (s->codec_id == AV_CODEC_ID_H264 ? 0 : 1);
          s->low_delay = 0; // needed to see the vectors without trashing the buffers
  
 -        av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,
 -                                         &h_chroma_shift, &v_chroma_shift);
 +        avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
 +
          for (i = 0; i < 3; i++) {
 -            memcpy(s->visualization_buffer[i], pict->data[i],
 -                   (i == 0) ? pict->linesize[i] * height:
 -                              pict->linesize[i] * height >> v_chroma_shift);
 +            size_t size= (i == 0) ? pict->linesize[i] * FFALIGN(height, 16):
 +                         pict->linesize[i] * FFALIGN(height, 16) >> v_chroma_shift;
 +            s->visualization_buffer[i]= av_realloc(s->visualization_buffer[i], size);
 +            memcpy(s->visualization_buffer[i], pict->data[i], size);
              pict->data[i] = s->visualization_buffer[i];
          }
          pict->type   = FF_BUFFER_TYPE_COPY;
 +        pict->opaque= NULL;
          ptr          = pict->data[0];
          block_height = 16 >> v_chroma_shift;
  
              int mb_x;
              for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
                  const int mb_index = mb_x + mb_y * s->mb_stride;
 -                if ((s->avctx->debug_mv) && pict->motion_val) {
 +                if ((s->avctx->debug_mv) && pict->motion_val[0]) {
                      int type;
                      for (type = 0; type < 3; type++) {
                          int direction = 0;
                                             height, s->linesize, 100);
                              }
                          } 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 = pict->motion_val[direction][xy][0] >> shift + sx;
 -                              int my = pict->motion_val[direction][xy][1] >> shift + sy;
 +                              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= (pict->motion_val[direction][xy][0]>>shift) + sx;
 +                              int my= (pict->motion_val[direction][xy][1]>>shift) + sy;
                                draw_arrow(ptr, sx, sy, mx, my, width, height, s->linesize, 100);
                          }
                      }
                  }
 -                if ((s->avctx->debug & FF_DEBUG_VIS_QP) && pict->motion_val) {
 +                if ((s->avctx->debug & FF_DEBUG_VIS_QP)) {
                      uint64_t c = (pict->qscale_table[mb_index] * 128 / 31) *
                                   0x0101010101010101ULL;
                      int y;
                      }
                  }
                  if ((s->avctx->debug & FF_DEBUG_VIS_MB_TYPE) &&
 -                    pict->motion_val) {
 +                    pict->motion_val[0]) {
                      int mb_type = pict->mb_type[mb_index];
                      uint64_t u,v;
                      int y;
                      } else if (!USES_LIST(mb_type, 0)) {
                          COLOR(0, 48)
                      } else {
 -                        assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
 +                        av_assert2(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
                          COLOR(300,48)
                      }
  
      }
  }
  
 +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, int 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, 2);
 +    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->dsp.emulated_edge_mc(s->edge_emu_buffer, src, s->linesize, w + 1,
 +                                (h + 1) << field_based, src_x,
 +                                src_y   << field_based,
 +                                h_edge_pos,
 +                                v_edge_pos);
 +        src = s->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, uvlinesize, linesize, sx, sy,
 +        uvsx, uvsy;
 +    const int lowres     = s->avctx->lowres;
 +    const int op_index   = FFMIN(lowres-1+s->chroma_x_shift, 2);
 +    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) ||
 +        (unsigned) src_y > FFMAX((v_edge_pos >> field_based) - (!!sy) - h, 0)) {
 +        s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr_y,
 +                                linesize >> field_based, 17, 17 + field_based,
 +                                src_x, src_y << field_based, h_edge_pos,
 +                                v_edge_pos);
 +        ptr_y = s->edge_emu_buffer;
 +        if (!CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
 +            uint8_t *uvbuf = s->edge_emu_buffer + 18 * s->linesize;
 +            s->dsp.emulated_edge_mc(uvbuf , ptr_cb, uvlinesize >> field_based, 9,
 +                                    9 + field_based,
 +                                    uvsrc_x, uvsrc_y << field_based,
 +                                    h_edge_pos >> 1, v_edge_pos >> 1);
 +            s->dsp.emulated_edge_mc(uvbuf + 16, ptr_cr, uvlinesize >> field_based, 9,
 +                                    9 + field_based,
 +                                    uvsrc_x, uvsrc_y << field_based,
 +                                    h_edge_pos >> 1, v_edge_pos >> 1);
 +            ptr_cb = uvbuf;
 +            ptr_cr = uvbuf + 16;
 +        }
 +    }
 +
 +    // 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->flags & CODEC_FLAG_GRAY)) {
 +        uvsx = (uvsx << 2) >> lowres;
 +        uvsy = (uvsy << 2) >> lowres;
 +        if (h >> s->chroma_y_shift) {
 +            pix_op[op_index](dest_cb, ptr_cb, uvlinesize, h >> s->chroma_y_shift, uvsx, uvsy);
 +            pix_op[op_index](dest_cr, ptr_cr, uvlinesize, h >> s->chroma_y_shift, 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, 2);
 +    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, offset, sx, sy;
 +    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 (s->flags & CODEC_FLAG_EMU_EDGE) {
 +        if ((unsigned) src_x > FFMAX(h_edge_pos - (!!sx) - block_s, 0) ||
 +            (unsigned) src_y > FFMAX(v_edge_pos - (!!sy) - block_s, 0)) {
 +            s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize,
 +                                    9, 9, src_x, src_y, h_edge_pos, v_edge_pos);
 +            ptr = s->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->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,
 +                                src_x, src_y, h_edge_pos, v_edge_pos);
 +        ptr = s->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->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->dsp.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->dsp.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);
 +    }
 +}
 +
  /**
   * find the lowest MB row referenced in the MVs
   */
@@@ -2443,7 -2087,7 +2443,7 @@@ void ff_clean_intra_table_entries(MpegE
   */
  static av_always_inline
  void MPV_decode_mb_internal(MpegEncContext *s, DCTELEM 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(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration){
          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.f.reference) {
                  *mbskip_ptr = 1;
                      }
                  }
  
 -                op_qpix= s->me.qpel_put;
 -                if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
 -                    op_pix = s->dsp.put_pixels_tab;
 +                if(lowres_flag){
 +                    h264_chroma_mc_func *op_pix = s->dsp.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->dsp.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->dsp.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->dsp.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->dsp.put_pixels_tab;
 +                    }else{
 +                        op_pix = s->dsp.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->dsp.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->dsp.idct_put(dest_cb,              dct_linesize, block[4]);
                          s->dsp.idct_put(dest_cr,              dct_linesize, block[5]);
                          s->dsp.idct_put(dest_cb + dct_offset, dct_linesize, block[6]);
                          s->dsp.idct_put(dest_cr + dct_offset, dct_linesize, block[7]);
                          if(!s->chroma_x_shift){//Chroma444
 -                            s->dsp.idct_put(dest_cb + 8,              dct_linesize, block[8]);
 -                            s->dsp.idct_put(dest_cr + 8,              dct_linesize, block[9]);
 -                            s->dsp.idct_put(dest_cb + 8 + dct_offset, dct_linesize, block[10]);
 -                            s->dsp.idct_put(dest_cr + 8 + dct_offset, dct_linesize, block[11]);
 +                            s->dsp.idct_put(dest_cb + block_size,              dct_linesize, block[8]);
 +                            s->dsp.idct_put(dest_cr + block_size,              dct_linesize, block[9]);
 +                            s->dsp.idct_put(dest_cb + block_size + dct_offset, dct_linesize, block[10]);
 +                            s->dsp.idct_put(dest_cr + block_size + dct_offset, dct_linesize, block[11]);
                          }
                      }
                  }//gray
@@@ -2688,12 -2320,10 +2688,12 @@@ skip_idct
  void ff_MPV_decode_mb(MpegEncContext *s, DCTELEM block[12][64]){
  #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);
  }
  
  /**
@@@ -2769,7 -2399,7 +2769,7 @@@ void ff_draw_horiz_band(MpegEncContext 
  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->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));
          }
      }
  }
@@@ -2814,7 -2444,6 +2814,7 @@@ void ff_mpeg_flush(AVCodecContext *avct
      s->current_picture_ptr = s->last_picture_ptr = s->next_picture_ptr = NULL;
  
      s->mb_x= s->mb_y= 0;
 +    s->closed_gop= 0;
  
      s->parse_context.state= -1;
      s->parse_context.frame_start_found= 0;
@@@ -2834,7 -2463,10 +2834,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++) {
@@@ -2893,7 -2525,10 +2893,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];
@@@ -2921,8 -2556,10 +2921,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];
@@@ -2984,7 -2621,10 +2984,7 @@@ static void dct_unquantize_h263_intra_c
      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;
diff --combined libavcodec/mpegvideo.h
@@@ -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
   */
  
@@@ -36,7 -36,6 +36,7 @@@
  #include "parser.h"
  #include "mpeg12data.h"
  #include "rl.h"
 +#include "libavutil/timecode.h"
  
  #include "libavutil/opt.h"
  
@@@ -53,14 -52,14 +53,14 @@@ enum OutputFormat 
  #define MPEG_BUF_SIZE (16 * 1024)
  
  #define QMAT_SHIFT_MMX 16
 -#define QMAT_SHIFT 22
 +#define QMAT_SHIFT 21
  
  #define MAX_FCODE 7
  #define MAX_MV 2048
  
 -#define MAX_THREADS 16
 +#define MAX_THREADS 32
  
 -#define MAX_PICTURE_COUNT 32
 +#define MAX_PICTURE_COUNT 34
  
  #define ME_MAP_SIZE 64
  #define ME_MAP_SHIFT 3
@@@ -127,11 -126,10 +127,11 @@@ typedef struct Picture
      int pic_id;                 /**< h264 pic_num (short -> no wrap version of pic_num,
                                       pic_num & max_pic_num; long -> long_pic_num) */
      int long_ref;               ///< 1->long term reference 0->short term reference
 -    int ref_poc[2][2][32];      ///< h264 POCs of the frames used as reference (FIXME need per slice)
 +    int ref_poc[2][2][32];      ///< h264 POCs of the frames/fields used as reference (FIXME need per slice)
      int ref_count[2][2];        ///< number of entries in ref_poc              (FIXME need per slice)
      int mbaff;                  ///< h264 1 -> MBAFF frame 0-> not MBAFF
      int field_picture;          ///< whether or not the picture was encoded in separate fields
 +    int sync;                   ///< has been decoded after a keyframe
  
      int mb_var_sum;             ///< sum of MB variance for current frame
      int mc_mb_var_sum;          ///< motion compensated MB variance for current frame
@@@ -341,14 -339,11 +341,14 @@@ typedef struct MpegEncContext 
      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 dropable;
+     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
  
      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
  
      struct MJpegContext *mjpeg_ctx;
      int mjpeg_vsample[3];       ///< vertical sampling factors, default = {2, 1, 1}
      int mjpeg_hsample[3];       ///< horizontal sampling factors, default = {2, 1, 1}
 +    int esc_pos;
  
      /* MSMPEG4 specific */
      int mv_table_index;
      /* 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
      DCTELEM (*pblocks[12])[64];
  
      DCTELEM (*block)[64]; ///< points to one of the following blocks
 -    DCTELEM (*blocks)[8][64]; // for HQ mode we need to keep the best block
 +    DCTELEM (*blocks)[12][64]; // for HQ mode we need to keep the best block
      int (*decode_mb)(struct MpegEncContext *s, DCTELEM block[6][64]); // used by some codecs to avoid a switch()
  #define SLICE_OK         0
  #define SLICE_ERROR     -1
@@@ -773,8 -761,8 +773,8 @@@ void ff_MPV_frame_end(MpegEncContext *s
  int ff_MPV_encode_init(AVCodecContext *avctx);
  int ff_MPV_encode_end(AVCodecContext *avctx);
  int ff_MPV_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
 -                          const AVFrame *frame, int *got_packet);
 -void ff_MPV_encode_init_x86(MpegEncContext *s);
 +                          AVFrame *frame, int *got_packet);
 +void ff_dct_encode_init_x86(MpegEncContext *s);
  void ff_MPV_common_init_x86(MpegEncContext *s);
  void ff_MPV_common_init_axp(MpegEncContext *s);
  void ff_MPV_common_init_arm(MpegEncContext *s);
@@@ -800,7 -788,6 +800,7 @@@ void ff_er_frame_end(MpegEncContext *s)
  void ff_er_add_slice(MpegEncContext *s, int startx, int starty, int endx, int endy, int status);
  
  int ff_dct_common_init(MpegEncContext *s);
 +int ff_dct_encode_init(MpegEncContext *s);
  void ff_convert_matrix(DSPContext *dsp, 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, DCTELEM *block, int n, int qscale, int *overflow);
@@@ -825,7 -812,7 +825,7 @@@ extern const enum AVPixelFormat ff_pixf
  extern const enum AVPixelFormat ff_hwaccel_pixfmt_list_420[];
  
  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;
diff --combined libavcodec/vc1dec.c
@@@ -4,20 -4,20 +4,20 @@@
   * Copyright (c) 2006-2007 Konstantin Shishkov
   * Partly based on vc9.c (c) 2005 Anonymous, Alex Beregszaszi, 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
   */
  
@@@ -38,7 -38,6 +38,7 @@@
  #include "unary.h"
  #include "mathops.h"
  #include "vdpau_internal.h"
 +#include "libavutil/avassert.h"
  
  #undef NDEBUG
  #include <assert.h>
@@@ -369,7 -368,7 +369,7 @@@ static void vc1_mc_1mv(VC1Context *v, i
      }
      if (v->field_mode) { // interlaced field picture
          if (!dir) {
 -            if ((v->cur_field_type != v->ref_field_type[dir]) && v->cur_field_type) {
 +            if ((v->cur_field_type != v->ref_field_type[dir]) && v->second_field) {
                  srcY = s->current_picture.f.data[0];
                  srcU = s->current_picture.f.data[1];
                  srcV = s->current_picture.f.data[2];
          }
      }
  
 +    if(!srcY)
 +        return;
 +
      src_x   = s->mb_x * 16 + (mx   >> 2);
      src_y   = s->mb_y * 16 + (my   >> 2);
      uvsrc_x = s->mb_x *  8 + (uvmx >> 2);
          srcY += s->mspel * (1 + s->linesize);
      }
  
 -    if (v->field_mode && v->cur_field_type) {
 +    if (v->field_mode && v->second_field) {
          off    = s->current_picture_ptr->f.linesize[0];
          off_uv = s->current_picture_ptr->f.linesize[1];
      } else {
@@@ -564,7 -560,7 +564,7 @@@ static void vc1_mc_4mv_luma(VC1Context 
  
      if (!dir) {
          if (v->field_mode) {
 -            if ((v->cur_field_type != v->ref_field_type[dir]) && v->cur_field_type)
 +            if ((v->cur_field_type != v->ref_field_type[dir]) && v->second_field)
                  srcY = s->current_picture.f.data[0];
              else
                  srcY = s->last_picture.f.data[0];
      } else
          srcY = s->next_picture.f.data[0];
  
 +    if(!srcY)
 +        return;
 +
      if (v->field_mode) {
          if (v->cur_field_type != v->ref_field_type[dir])
              my = my - 2 + 4 * v->cur_field_type;
              tx = (chosen_mv[f][0][0] + chosen_mv[f][1][0]) / 2;
              ty = (chosen_mv[f][0][1] + chosen_mv[f][1][1]) / 2;
              break;
 +        default:
 +            av_assert2(0);
          }
          s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0] = tx;
          s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1] = ty;
          off = ((n > 1) ? s->linesize : 0) + (n & 1) * 8;
      else
          off = s->linesize * 4 * (n & 2) + (n & 1) * 8;
 -    if (v->field_mode && v->cur_field_type)
 +    if (v->field_mode && v->second_field)
          off += s->current_picture_ptr->f.linesize[0];
  
      src_x = s->mb_x * 16 + (n & 1) * 8 + (mx >> 2);
@@@ -850,33 -841,27 +850,33 @@@ static void vc1_mc_4mv_chroma(VC1Contex
      if (!dir) {
          if (v->field_mode) {
              if ((v->cur_field_type != chroma_ref_type) && v->cur_field_type) {
 -                srcU = s->current_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;
 -                srcV = s->current_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;
 +                srcU = s->current_picture.f.data[1];
 +                srcV = s->current_picture.f.data[2];
              } else {
 -                srcU = s->last_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;
 -                srcV = s->last_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;
 +                srcU = s->last_picture.f.data[1];
 +                srcV = s->last_picture.f.data[2];
              }
          } else {
 -            srcU = s->last_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;
 -            srcV = s->last_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;
 +            srcU = s->last_picture.f.data[1];
 +            srcV = s->last_picture.f.data[2];
          }
      } else {
 -        srcU = s->next_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;
 -        srcV = s->next_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;
 +        srcU = s->next_picture.f.data[1];
 +        srcV = s->next_picture.f.data[2];
      }
  
 +    if(!srcU)
 +        return;
 +
 +    srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
 +    srcV += uvsrc_y * s->uvlinesize + uvsrc_x;
 +
      if (v->field_mode) {
          if (chroma_ref_type) {
              srcU += s->current_picture_ptr->f.linesize[1];
              srcV += s->current_picture_ptr->f.linesize[2];
          }
 -        off = v->cur_field_type ? s->current_picture_ptr->f.linesize[1] : 0;
 +        off = v->second_field ? s->current_picture_ptr->f.linesize[1] : 0;
      }
  
      if (v->rangeredfrm || (v->mv_mode == MV_PMODE_INTENSITY_COMP)
@@@ -981,8 -966,7 +981,8 @@@ static void vc1_mc_4mv_chroma4(VC1Conte
          uvmy_field[i] = (uvmy_field[i] & 3) << 1;
  
          if (fieldmv && !(uvsrc_y & 1))
 -            v_edge_pos--;
 +            v_edge_pos = (s->v_edge_pos >> 1) - 1;
 +
          if (fieldmv && (uvsrc_y & 1) && uvsrc_y < 2)
              uvsrc_y--;
          if ((v->mv_mode == MV_PMODE_INTENSITY_COMP)
@@@ -1154,7 -1138,6 +1154,7 @@@ static av_always_inline void get_mvdata
          }
      }
      else {
 +        av_assert0(index < esc);
          if (extend_x)
              offs_tab = offset_table2;
          else
@@@ -1808,7 -1791,7 +1808,7 @@@ static inline void vc1_pred_mv_intfr(VC
                  } else if (c_valid) {
                      px = C[0];
                      py = C[1];
 -                }
 +                } else px = py = 0;
              }
          } else if (total_valid == 1) {
              px = (a_valid) ? A[0] : ((b_valid) ? B[0] : C[0]);
@@@ -1941,7 -1924,7 +1941,7 @@@ static void vc1_interp_mc(VC1Context *v
          srcY += s->mspel * (1 + s->linesize);
      }
  
 -    if (v->field_mode && v->cur_field_type) {
 +    if (v->field_mode && v->second_field) {
          off    = s->current_picture_ptr->f.linesize[0];
          off_uv = s->current_picture_ptr->f.linesize[1];
      } else {
@@@ -3708,7 -3691,7 +3708,7 @@@ static int vc1_decode_p_mb_intfr(VC1Con
      int idx_mbmode = 0, mvbp;
      int stride_y, fieldtx;
  
 -    mquant = v->pq; /* Loosy initialization */
 +    mquant = v->pq; /* Lossy initialization */
  
      if (v->skip_is_raw)
          skipped = get_bits1(gb);
@@@ -3912,11 -3895,11 +3912,11 @@@ static int vc1_decode_p_mb_intfi(VC1Con
      int val; /* temp values */
      int first_block = 1;
      int dst_idx, off;
 -    int pred_flag;
 +    int pred_flag = 0;
      int block_cbp = 0, pat, block_tt = 0;
      int idx_mbmode = 0;
  
 -    mquant = v->pq; /* Loosy initialization */
 +    mquant = v->pq; /* Lossy initialization */
  
      idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_IF_MBMODE_VLC_BITS, 2);
      if (idx_mbmode <= 1) { // intra MB
                  continue;
              v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);
              off  = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
 -            off += v->cur_field_type ? ((i & 4) ? s->current_picture_ptr->f.linesize[1] : s->current_picture_ptr->f.linesize[0]) : 0;
 +            off += v->second_field ? ((i & 4) ? s->current_picture_ptr->f.linesize[1] : s->current_picture_ptr->f.linesize[0]) : 0;
              s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize);
              // TODO: loop filter
          }
              dst_idx += i >> 2;
              val = ((cbp >> (5 - i)) & 1);
              off = (i & 4) ? 0 : (i & 1) * 8 + (i & 2) * 4 * s->linesize;
 -            if (v->cur_field_type)
 +            if (v->second_field)
                  off += (i & 4) ? s->current_picture_ptr->f.linesize[1] : s->current_picture_ptr->f.linesize[0];
              if (val) {
                  pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,
@@@ -4189,7 -4172,7 +4189,7 @@@ static void vc1_decode_b_mb_intfi(VC1Co
      int bmvtype = BMV_TYPE_BACKWARD;
      int idx_mbmode, interpmvp;
  
 -    mquant      = v->pq; /* Loosy initialization */
 +    mquant      = v->pq; /* Lossy initialization */
      s->mb_intra = 0;
  
      idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_IF_MBMODE_VLC_BITS, 2);
                  for (j = 0; j < 64; j++)
                      s->block[i][j] <<= 1;
              off  = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
 -            off += v->cur_field_type ? ((i & 4) ? s->current_picture_ptr->f.linesize[1] : s->current_picture_ptr->f.linesize[0]) : 0;
 +            off += v->second_field ? ((i & 4) ? s->current_picture_ptr->f.linesize[1] : s->current_picture_ptr->f.linesize[0]) : 0;
              s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize);
              // TODO: yet to perform loop filter
          }
              dst_idx += i >> 2;
              val = ((cbp >> (5 - i)) & 1);
              off = (i & 4) ? 0 : (i & 1) * 8 + (i & 2) * 4 * s->linesize;
 -            if (v->cur_field_type)
 +            if (v->second_field)
                  off += (i & 4) ? s->current_picture_ptr->f.linesize[1] : s->current_picture_ptr->f.linesize[0];
              if (val) {
                  vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,
@@@ -4661,7 -4644,7 +4661,7 @@@ static void vc1_decode_p_blocks(VC1Cont
          if (s->mb_y != s->start_mb_y) ff_draw_horiz_band(s, (s->mb_y - 1) * 16, 16);
          s->first_slice_line = 0;
      }
 -    if (apply_loop_filter) {
 +    if (apply_loop_filter && v->fcm == PROGRESSIVE) {
          s->mb_x = 0;
          ff_init_block_index(s);
          for (; s->mb_x < s->mb_width; s->mb_x++) {
@@@ -4746,11 -4729,9 +4746,11 @@@ static void vc1_decode_skip_blocks(VC1C
          s->mb_x = 0;
          ff_init_block_index(s);
          ff_update_block_index(s);
 -        memcpy(s->dest[0], s->last_picture.f.data[0] + s->mb_y * 16 * s->linesize,   s->linesize   * 16);
 -        memcpy(s->dest[1], s->last_picture.f.data[1] + s->mb_y *  8 * s->uvlinesize, s->uvlinesize *  8);
 -        memcpy(s->dest[2], s->last_picture.f.data[2] + s->mb_y *  8 * s->uvlinesize, s->uvlinesize *  8);
 +        if (s->last_picture.f.data[0]) {
 +            memcpy(s->dest[0], s->last_picture.f.data[0] + s->mb_y * 16 * s->linesize,   s->linesize   * 16);
 +            memcpy(s->dest[1], s->last_picture.f.data[1] + s->mb_y *  8 * s->uvlinesize, s->uvlinesize *  8);
 +            memcpy(s->dest[2], s->last_picture.f.data[2] + s->mb_y *  8 * s->uvlinesize, s->uvlinesize *  8);
 +        }
          ff_draw_horiz_band(s, s->mb_y * 16, 16);
          s->first_slice_line = 0;
      }
@@@ -5183,15 -5164,6 +5183,15 @@@ static av_cold int vc1_decode_init(AVCo
  
      if (ff_vc1_init_common(v) < 0)
          return -1;
 +    // ensure static VLC tables are initialized
 +    if (ff_msmpeg4_decode_init(avctx) < 0)
 +        return -1;
 +    if (ff_vc1_decode_init_alloc_tables(v) < 0)
 +        return -1;
 +    // Hack to ensure the above functions will be called
 +    // again once we know all necessary settings.
 +    // That this is necessary might indicate a bug.
 +    ff_vc1_decode_end(avctx);
      ff_vc1dsp_init(&v->vc1dsp);
  
      if (avctx->codec_id == AV_CODEC_ID_WMV3 || avctx->codec_id == AV_CODEC_ID_WMV3IMAGE) {
@@@ -5344,19 -5316,14 +5344,19 @@@ static int vc1_decode_frame(AVCodecCont
      MpegEncContext *s = &v->s;
      AVFrame *pict = data;
      uint8_t *buf2 = NULL;
 -    const uint8_t *buf_start = buf;
 -    int mb_height, n_slices1;
 +    const uint8_t *buf_start = buf, *buf_start_second_field = NULL;
 +    int mb_height, n_slices1=-1;
      struct {
          uint8_t *buf;
          GetBitContext gb;
          int mby_start;
      } *slices = NULL, *tmp;
  
 +    v->second_field = 0;
 +
 +    if(s->flags & CODEC_FLAG_LOW_DELAY)
 +        s->low_delay = 1;
 +
      /* no supplementary picture */
      if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == VC1_CODE_ENDOFSEQ)) {
          /* special case for last picture */
              *got_frame = 1;
          }
  
 -        return 0;
 +        return buf_size;
      }
  
      if (s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU) {
                      break;
                  case VC1_CODE_FIELD: {
                      int buf_size3;
 +                    if (avctx->hwaccel ||
 +                        s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
 +                        buf_start_second_field = start;
                      tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                      if (!tmp)
                          goto err;
                  av_log(avctx, AV_LOG_ERROR, "Error in WVC1 interlaced frame\n");
                  goto err;
              } else { // found field marker, unescape second field
 +                if (avctx->hwaccel ||
 +                    s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
 +                    buf_start_second_field = divider;
                  tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                  if (!tmp)
                      goto err;
          s->low_delay = !avctx->has_b_frames || v->res_sprite;
  
          if (v->profile == PROFILE_ADVANCED) {
 +            if(avctx->coded_width<=1 || avctx->coded_height<=1)
 +                goto err;
              s->h_edge_pos = avctx->coded_width;
              s->v_edge_pos = avctx->coded_height;
          }
  
      // do parse frame header
      v->pic_header_flag = 0;
 +    v->first_pic_header_flag = 1;
      if (v->profile < PROFILE_ADVANCED) {
 -        if (ff_vc1_parse_frame_header(v, &s->gb) == -1) {
 +        if (ff_vc1_parse_frame_header(v, &s->gb) < 0) {
              goto err;
          }
      } else {
 -        if (ff_vc1_parse_frame_header_adv(v, &s->gb) == -1) {
 +        if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
              goto err;
          }
      }
 +    v->first_pic_header_flag = 0;
 +
 +    if (avctx->debug & FF_DEBUG_PICT_INFO)
 +        av_log(v->s.avctx, AV_LOG_DEBUG, "pict_type: %c\n", av_get_picture_type_char(s->pict_type));
  
      if ((avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE)
          && s->pict_type != AV_PICTURE_TYPE_I) {
          goto err;
      }
  
 +    if ((s->mb_height >> v->field_mode) == 0) {
 +        av_log(v->s.avctx, AV_LOG_ERROR, "image too short\n");
 +        goto err;
 +    }
 +
      // process pulldown flags
      s->current_picture_ptr->f.repeat_pict = 0;
      // Pulldown flags are only valid when 'broadcast' has been set.
      s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
  
      /* skip B-frames if we don't have reference frames */
-     if (s->last_picture_ptr == NULL && (s->pict_type == AV_PICTURE_TYPE_B || s->dropable)) {
+     if (s->last_picture_ptr == NULL && (s->pict_type == AV_PICTURE_TYPE_B || s->droppable)) {
          goto err;
      }
      if ((avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B) ||
          goto err;
      }
  
 +    v->s.current_picture_ptr->f.interlaced_frame = (v->fcm != PROGRESSIVE);
 +    v->s.current_picture_ptr->f.top_field_first  = v->tff;
 +
      s->me.qpel_put = s->dsp.put_qpel_pixels_tab;
      s->me.qpel_avg = s->dsp.avg_qpel_pixels_tab;
  
          &&s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
          ff_vdpau_vc1_decode_picture(s, buf_start, (buf + buf_size) - buf_start);
      else if (avctx->hwaccel) {
 -        if (avctx->hwaccel->start_frame(avctx, buf, buf_size) < 0)
 -            goto err;
 -        if (avctx->hwaccel->decode_slice(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
 -            goto err;
 -        if (avctx->hwaccel->end_frame(avctx) < 0)
 -            goto err;
 +        if (v->field_mode && buf_start_second_field) {
 +            // decode first field
 +            s->picture_structure = PICT_BOTTOM_FIELD - v->tff;
 +            if (avctx->hwaccel->start_frame(avctx, buf_start, buf_start_second_field - buf_start) < 0)
 +                goto err;
 +            if (avctx->hwaccel->decode_slice(avctx, buf_start, buf_start_second_field - buf_start) < 0)
 +                goto err;
 +            if (avctx->hwaccel->end_frame(avctx) < 0)
 +                goto err;
 +
 +            // decode second field
 +            s->gb = slices[n_slices1 + 1].gb;
 +            s->picture_structure = PICT_TOP_FIELD + v->tff;
 +            v->second_field = 1;
 +            v->pic_header_flag = 0;
 +            if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
 +                av_log(avctx, AV_LOG_ERROR, "parsing header for second field failed");
 +                goto err;
 +            }
 +            v->s.current_picture_ptr->f.pict_type = v->s.pict_type;
 +
 +            if (avctx->hwaccel->start_frame(avctx, buf_start_second_field, (buf + buf_size) - buf_start_second_field) < 0)
 +                goto err;
 +            if (avctx->hwaccel->decode_slice(avctx, buf_start_second_field, (buf + buf_size) - buf_start_second_field) < 0)
 +                goto err;
 +            if (avctx->hwaccel->end_frame(avctx) < 0)
 +                goto err;
 +        } else {
 +            s->picture_structure = PICT_FRAME;
 +            if (avctx->hwaccel->start_frame(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
 +                goto err;
 +            if (avctx->hwaccel->decode_slice(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
 +                goto err;
 +            if (avctx->hwaccel->end_frame(avctx) < 0)
 +                goto err;
 +        }
      } else {
 +        if (v->fcm == ILACE_FRAME && s->pict_type == AV_PICTURE_TYPE_B)
 +            goto err; // This codepath is still incomplete thus it is disabled
 +
          ff_er_frame_start(s);
  
          v->bits = buf_size * 8;
              s->start_mb_y = (i == 0) ? 0 : FFMAX(0, slices[i-1].mby_start % mb_height);
              if (!v->field_mode || v->second_field)
                  s->end_mb_y = (i == n_slices     ) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);
 -            else
 +            else {
 +                if (i >= n_slices) {
 +                    av_log(v->s.avctx, AV_LOG_ERROR, "first field slice count too large\n");
 +                    continue;
 +                }
                  s->end_mb_y = (i <= n_slices1 + 1) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);
 +            }
 +            if (s->end_mb_y <= s->start_mb_y) {
 +                av_log(v->s.avctx, AV_LOG_ERROR, "end mb y %d %d invalid\n", s->end_mb_y, s->start_mb_y);
 +                continue;
 +            }
              ff_vc1_decode_blocks(v);
              if (i != n_slices)
                  s->gb = slices[i].gb;
                  get_bits_count(&s->gb), s->gb.size_in_bits);
  //  if (get_bits_count(&s->gb) > buf_size * 8)
  //      return -1;
 -        ff_er_frame_end(s);
 +        if(s->error_occurred && s->pict_type == AV_PICTURE_TYPE_B)
 +            goto err;
 +        if(!v->field_mode)
 +            ff_er_frame_end(s);
      }
  
      ff_MPV_frame_end(s);
diff --combined libavformat/rtpdec.c
@@@ -2,20 -2,20 +2,20 @@@
   * RTP input format
   * Copyright (c) 2002 Fabrice Bellard
   *
 - * 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 "libavcodec/get_bits.h"
  #include "avformat.h"
  #include "mpegts.h"
- #include "url.h"
  #include "network.h"
+ #include "url.h"
  #include "rtpdec.h"
  #include "rtpdec_formats.h"
  
- //#define DEBUG
- /* TODO: - add RTCP statistics reporting (should be optional).
-          - add support for h263/mpeg4 packetized output : IDEA: send a
-          buffer to 'rtp_write_packet' contains all the packets for ONE
-          frame. Each packet should have a four byte header containing
-          the length in big endian format (same trick as
-          'ffio_open_dyn_packet_buf')
- */
+ /* TODO:
+  * - add RTCP statistics reporting (should be optional).
+  *
+  * - add support for H.263/MPEG-4 packetized output: IDEA: send a
+  * buffer to 'rtp_write_packet' contains all the packets for ONE
+  * frame. Each packet should have a four byte header containing
+  * the length in big-endian format (same trick as
+  * 'ffio_open_dyn_packet_buf').
+  */
  
  static RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler = {
-     .enc_name           = "X-MP3-draft-00",
-     .codec_type         = AVMEDIA_TYPE_AUDIO,
-     .codec_id           = AV_CODEC_ID_MP3ADU,
+     .enc_name   = "X-MP3-draft-00",
+     .codec_type = AVMEDIA_TYPE_AUDIO,
+     .codec_id   = AV_CODEC_ID_MP3ADU,
  };
  
  static RTPDynamicProtocolHandler speex_dynamic_handler = {
-     .enc_name         = "speex",
-     .codec_type       = AVMEDIA_TYPE_AUDIO,
-     .codec_id         = AV_CODEC_ID_SPEEX,
+     .enc_name   = "speex",
+     .codec_type = AVMEDIA_TYPE_AUDIO,
+     .codec_id   = AV_CODEC_ID_SPEEX,
  };
  
  static RTPDynamicProtocolHandler opus_dynamic_handler = {
-     .enc_name         = "opus",
-     .codec_type       = AVMEDIA_TYPE_AUDIO,
-     .codec_id         = AV_CODEC_ID_OPUS,
+     .enc_name   = "opus",
+     .codec_type = AVMEDIA_TYPE_AUDIO,
+     .codec_id   = AV_CODEC_ID_OPUS,
  };
  
  /* statistics functions */
- static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
+ static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler = NULL;
  
  void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
  {
-     handler->next= RTPFirstDynamicPayloadHandler;
-     RTPFirstDynamicPayloadHandler= handler;
+     handler->next = RTPFirstDynamicPayloadHandler;
+     RTPFirstDynamicPayloadHandler = handler;
  }
  
  void av_register_rtp_dynamic_payload_handlers(void)
  }
  
  RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
-                                                   enum AVMediaType codec_type)
+                                                        enum AVMediaType codec_type)
  {
      RTPDynamicProtocolHandler *handler;
      for (handler = RTPFirstDynamicPayloadHandler;
  }
  
  RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
-                                                 enum AVMediaType codec_type)
+                                                      enum AVMediaType codec_type)
  {
      RTPDynamicProtocolHandler *handler;
      for (handler = RTPFirstDynamicPayloadHandler;
      return NULL;
  }
  
- static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
+ static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf,
+                              int len)
  {
      int payload_len;
      while (len >= 4) {
          switch (buf[1]) {
          case RTCP_SR:
              if (payload_len < 20) {
-                 av_log(NULL, AV_LOG_ERROR, "Invalid length for RTCP SR packet\n");
+                 av_log(NULL, AV_LOG_ERROR,
+                        "Invalid length for RTCP SR packet\n");
                  return AVERROR_INVALIDDATA;
              }
  
-             s->last_rtcp_ntp_time = AV_RB64(buf + 8);
+             s->last_rtcp_ntp_time  = AV_RB64(buf + 8);
              s->last_rtcp_timestamp = AV_RB32(buf + 16);
              if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
                  s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
      return -1;
  }
  
- #define RTP_SEQ_MOD (1<<16)
+ #define RTP_SEQ_MOD (1 << 16)
  
  static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
  {
  }
  
  /*
- * called whenever there is a large jump in sequence numbers, or when they get out of probation...
- */
+  * Called whenever there is a large jump in sequence numbers,
+  * or when they get out of probation...
+  */
  static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
  {
      s->max_seq        = seq;
      s->transit        = 0;
  }
  
- /*
- * returns 1 if we should handle this packet.
- */
+ /* Returns 1 if we should handle this packet. */
  static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
  {
      uint16_t udelta = seq - s->max_seq;
      const int MAX_MISORDER   = 100;
      const int MIN_SEQUENTIAL = 2;
  
-     /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
+     /* source not valid until MIN_SEQUENTIAL packets with sequence
+      * seq. numbers have been received */
      if (s->probation) {
          if (seq == s->max_seq + 1) {
              s->probation--;
              }
          } else {
              s->probation = MIN_SEQUENTIAL - 1;
-             s->max_seq = seq;
+             s->max_seq   = seq;
          }
      } else if (udelta < MAX_DROPOUT) {
          // in order, with permissible gap
      } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
          // sequence made a large jump...
          if (seq == s->bad_seq) {
-             // two sequential packets-- assume that the other side restarted without telling us; just resync.
+             /* two sequential packets -- assume that the other side
+              * restarted without telling us; just resync. */
              rtp_init_sequence(s, seq);
          } else {
              s->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
@@@ -256,7 -256,7 +256,7 @@@ int ff_rtp_check_and_send_back_rr(RTPDe
          return -1;
  
      /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
-     /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
+     /* XXX: MPEG pts hardcoded. RTCP send every 0.5 seconds */
      s->octet_count += count;
      rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
          RTCP_TX_RATIO_DEN;
      avio_wb32(pb, s->ssrc); // server SSRC
      // some placeholders we should really fill...
      // RFC 1889/p64
-     extended_max = stats->cycles + stats->max_seq;
-     expected = extended_max - stats->base_seq + 1;
-     lost = expected - stats->received;
-     lost = FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
-     expected_interval = expected - stats->expected_prior;
+     extended_max          = stats->cycles + stats->max_seq;
+     expected              = extended_max - stats->base_seq + 1;
+     lost                  = expected - stats->received;
+     lost                  = FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
+     expected_interval     = expected - stats->expected_prior;
      stats->expected_prior = expected;
-     received_interval = stats->received - stats->received_prior;
+     received_interval     = stats->received - stats->received_prior;
      stats->received_prior = stats->received;
-     lost_interval = expected_interval - received_interval;
+     lost_interval         = expected_interval - received_interval;
      if (expected_interval == 0 || lost_interval <= 0)
          fraction = 0;
      else
          avio_wb32(pb, 0); /* last SR timestamp */
          avio_wb32(pb, 0); /* delay since last SR */
      } else {
-         uint32_t middle_32_bits = s->last_rtcp_ntp_time >> 16; // this is valid, right? do we need to handle 64 bit values special?
+         uint32_t middle_32_bits   = s->last_rtcp_ntp_time >> 16; // this is valid, right? do we need to handle 64 bit values special?
          uint32_t delay_since_last = ntp_time - s->last_rtcp_ntp_time;
  
          avio_wb32(pb, middle_32_bits); /* last SR timestamp */
      avio_w8(pb, len);
      avio_write(pb, s->hostname, len);
      // padding
-     for (len = (6 + len) % 4; len % 4; len++) {
+     for (len = (6 + len) % 4; len % 4; len++)
          avio_w8(pb, 0);
-     }
  
      avio_flush(pb);
      len = avio_close_dyn_buf(pb, &buf);
      if ((len > 0) && buf) {
          int av_unused result;
          av_dlog(s->ic, "sending %d bytes of RR\n", len);
-         result= ffurl_write(s->rtp_ctx, buf, len);
+         result = ffurl_write(s->rtp_ctx, buf, len);
          av_dlog(s->ic, "result from ffurl_write: %d\n", result);
          av_free(buf);
      }
      return 0;
  }
  
- void ff_rtp_send_punch_packets(URLContextrtp_handle)
+ void ff_rtp_send_punch_packets(URLContext *rtp_handle)
  {
      AVIOContext *pb;
      uint8_t *buf;
      av_free(buf);
  }
  
  /**
   * open a new RTP parse context for stream 'st'. 'st' can be NULL for
-  * MPEG2TS streams to indicate that they should be demuxed inside the
+  * MPEG2-TS streams to indicate that they should be demuxed inside the
   * rtp demux (otherwise AV_CODEC_ID_MPEG2TS packets are returned)
   */
- RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, int queue_size)
+ RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st,
+                                    URLContext *rtpc, int payload_type,
+                                    int queue_size)
  {
      RTPDemuxContext *s;
  
      s = av_mallocz(sizeof(RTPDemuxContext));
      if (!s)
          return NULL;
-     s->payload_type = payload_type;
-     s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
+     s->payload_type        = payload_type;
+     s->last_rtcp_ntp_time  = AV_NOPTS_VALUE;
      s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
-     s->ic = s1;
-     s->st = st;
-     s->queue_size = queue_size;
+     s->ic                  = s1;
+     s->st                  = st;
+     s->queue_size          = queue_size;
      rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
      if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
          s->ts = ff_mpegts_parse_open(s->ic);
              return NULL;
          }
      } else if (st) {
-         switch(st->codec->codec_id) {
+         switch (st->codec->codec_id) {
          case AV_CODEC_ID_MPEG1VIDEO:
          case AV_CODEC_ID_MPEG2VIDEO:
          case AV_CODEC_ID_MP2:
@@@ -432,11 -432,12 +432,12 @@@ void ff_rtp_parse_set_dynamic_protocol(
                                         RTPDynamicProtocolHandler *handler)
  {
      s->dynamic_protocol_context = ctx;
-     s->parse_packet = handler->parse_packet;
+     s->parse_packet             = handler->parse_packet;
  }
  
  /**
-  * This was the second switch in rtp_parse packet.  Normalizes time, if required, sets stream_index, etc.
+  * This was the second switch in rtp_parse packet.
+  * Normalizes time, if required, sets stream_index, etc.
   */
  static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
  {
          /* compute pts from timestamp with received ntp_time */
          delta_timestamp = timestamp - s->last_rtcp_timestamp;
          /* convert to the PTS timebase */
-         addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);
+         addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time,
+                             s->st->time_base.den,
+                             (uint64_t) s->st->time_base.num << 32);
          pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
                     delta_timestamp;
          return;
  
      if (!s->base_timestamp)
          s->base_timestamp = timestamp;
-     /* assume that the difference is INT32_MIN < x < INT32_MAX, but allow the first timestamp to exceed INT32_MAX */
+     /* assume that the difference is INT32_MIN < x < INT32_MAX,
+      * but allow the first timestamp to exceed INT32_MAX */
      if (!s->timestamp)
          s->unwrapped_timestamp += timestamp;
      else
          s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
      s->timestamp = timestamp;
-     pkt->pts = s->unwrapped_timestamp + s->range_start_offset - s->base_timestamp;
+     pkt->pts     = s->unwrapped_timestamp + s->range_start_offset -
+                    s->base_timestamp;
  }
  
  static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
      int ext;
      AVStream *st;
      uint32_t timestamp;
-     int rv= 0;
+     int rv = 0;
  
-     ext = buf[0] & 0x10;
+     ext          = buf[0] & 0x10;
      payload_type = buf[1] & 0x7f;
      if (buf[1] & 0x80)
          flags |= RTP_FLAG_MARKER;
-     seq  = AV_RB16(buf + 2);
+     seq       = AV_RB16(buf + 2);
      timestamp = AV_RB32(buf + 4);
-     ssrc = AV_RB32(buf + 8);
+     ssrc      = AV_RB32(buf + 8);
      /* store the ssrc in the RTPDemuxContext */
      s->ssrc = ssrc;
  
  
      st = s->st;
      // only do something with this if all the rtp checks pass...
-     if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
-     {
-         av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
+     if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {
+         av_log(st ? st->codec : NULL, AV_LOG_ERROR,
+                "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
                 payload_type, seq, ((s->seq + 1) & 0xffff));
          return -1;
      }
      }
  
      s->seq = seq;
-     len -= 12;
-     buf += 12;
+     len   -= 12;
+     buf   += 12;
  
      /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
      if (ext) {
      }
  
      if (!st) {
-         /* specific MPEG2TS demux support */
+         /* specific MPEG2-TS demux support */
          ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
          /* The only error that can be returned from ff_mpegts_parse_packet
           * is "no more data to return from the provided buffer", so return
          rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
                               s->st, pkt, &timestamp, buf, len, flags);
      } else {
-         // at this point, the RTP header has been stripped;  This is ASSUMING that there is only 1 CSRC, which in't wise.
-         switch(st->codec->codec_id) {
+         /* At this point, the RTP header has been stripped;
+          * This is ASSUMING that there is only 1 CSRC, which isn't wise. */
+         switch (st->codec->codec_id) {
          case AV_CODEC_ID_MP2:
          case AV_CODEC_ID_MP3:
-             /* better than nothing: skip mpeg audio RTP header */
+             /* better than nothing: skip MPEG audio RTP header */
              if (len <= 4)
                  return -1;
-             h = AV_RB32(buf);
+             h    = AV_RB32(buf);
              len -= 4;
              buf += 4;
 -            av_new_packet(pkt, len);
 +            if (av_new_packet(pkt, len) < 0)
 +                return AVERROR(ENOMEM);
              memcpy(pkt->data, buf, len);
              break;
          case AV_CODEC_ID_MPEG1VIDEO:
          case AV_CODEC_ID_MPEG2VIDEO:
-             /* better than nothing: skip mpeg video RTP header */
+             /* better than nothing: skip MPEG video RTP header */
              if (len <= 4)
                  return -1;
-             h = AV_RB32(buf);
+             h    = AV_RB32(buf);
              buf += 4;
              len -= 4;
              if (h & (1 << 26)) {
-                 /* mpeg2 */
+                 /* MPEG-2 */
                  if (len <= 4)
                      return -1;
                  buf += 4;
                  len -= 4;
              }
 -            av_new_packet(pkt, len);
 +            if (av_new_packet(pkt, len) < 0)
 +                return AVERROR(ENOMEM);
              memcpy(pkt->data, buf, len);
              break;
          default:
 -            av_new_packet(pkt, len);
 +            if (av_new_packet(pkt, len) < 0)
 +                return AVERROR(ENOMEM);
              memcpy(pkt->data, buf, len);
              break;
          }
@@@ -610,7 -613,7 +616,7 @@@ void ff_rtp_reset_packet_queue(RTPDemux
  
  static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
  {
-     uint16_t seq = AV_RB16(buf + 2);
+     uint16_t seq   = AV_RB16(buf + 2);
      RTPPacket *cur = s->queue, *prev = NULL, *packet;
  
      /* Find the correct place in the queue to insert the packet */
          if (diff < 0)
              break;
          prev = cur;
-         cur = cur->next;
+         cur  = cur->next;
      }
  
      packet = av_mallocz(sizeof(*packet));
      if (!packet)
          return;
      packet->recvtime = av_gettime();
-     packet->seq = seq;
-     packet->len = len;
-     packet->buf = buf;
-     packet->next = cur;
+     packet->seq      = seq;
+     packet->len      = len;
+     packet->buf      = buf;
+     packet->next     = cur;
      if (prev)
          prev->next = packet;
      else
@@@ -660,7 -663,7 +666,7 @@@ static int rtp_parse_queued_packet(RTPD
                 "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
  
      /* Parse the first packet in the queue, and dequeue it */
-     rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
+     rv   = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
      next = s->queue->next;
      av_free(s->queue->buf);
      av_free(s->queue);
  static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
                                  uint8_t **bufptr, int len)
  {
-     uint8_tbuf = bufptr ? *bufptr : NULL;
+     uint8_t *buf = bufptr ? *bufptr : NULL;
      int ret, flags = 0;
      uint32_t timestamp;
-     int rv= 0;
+     int rv = 0;
  
      if (!buf) {
          /* If parsing of the previous packet actually returned 0 or an error,
          if (s->prev_ret <= 0)
              return rtp_parse_queued_packet(s, pkt);
          /* return the next packets, if any */
-         if(s->st && s->parse_packet) {
+         if (s->st && s->parse_packet) {
              /* timestamp should be overwritten by parse_packet, if not,
               * the packet is left with pts == AV_NOPTS_VALUE */
              timestamp = RTP_NOTS_VALUE;
-             rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
-                                 s->st, pkt, &timestamp, NULL, 0, flags);
+             rv        = s->parse_packet(s->ic, s->dynamic_protocol_context,
+                                         s->st, pkt, &timestamp, NULL, 0, flags);
              finalize_packet(s, pkt, timestamp);
              return rv;
          } else {
              if (s->read_buf_index >= s->read_buf_size)
                  return AVERROR(EAGAIN);
              ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
-                                       s->read_buf_size - s->read_buf_index);
+                                          s->read_buf_size - s->read_buf_index);
              if (ret < 0)
                  return AVERROR(EAGAIN);
              s->read_buf_index += ret;
@@@ -784,19 -787,21 +790,21 @@@ int ff_parse_fmtp(AVStream *stream, Pay
      int value_size = strlen(p) + 1;
  
      if (!(value = av_malloc(value_size))) {
 -        av_log(NULL, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
 +        av_log(NULL, AV_LOG_ERROR, "Failed to allocate data for FMTP.\n");
          return AVERROR(ENOMEM);
      }
  
      // remove protocol identifier
-     while (*p && *p == ' ') p++; // strip spaces
-     while (*p && *p != ' ') p++; // eat protocol identifier
-     while (*p && *p == ' ') p++; // strip trailing spaces
+     while (*p && *p == ' ')
+         p++;                     // strip spaces
+     while (*p && *p != ' ')
+         p++;                     // eat protocol identifier
+     while (*p && *p == ' ')
+         p++;                     // strip trailing spaces
  
      while (ff_rtsp_next_attr_and_value(&p,
                                         attr, sizeof(attr),
                                         value, value_size)) {
          res = parse_fmtp(stream, data, attr, value);
          if (res < 0 && res != AVERROR_PATCHWELCOME) {
              av_free(value);
@@@ -811,9 -816,9 +819,9 @@@ int ff_rtp_finalize_packet(AVPacket *pk
  {
      av_init_packet(pkt);
  
-     pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
+     pkt->size         = avio_close_dyn_buf(*dyn_buf, &pkt->data);
      pkt->stream_index = stream_idx;
      pkt->destruct     = av_destruct_packet;
-     *dyn_buf = NULL;
+     *dyn_buf          = NULL;
      return pkt->size;
  }