mpegvideo.c
上传用户:lctgjx
上传日期:2022-06-04
资源大小:8887k
文件大小:89k
源码类别:

流媒体/Mpeg4/MP4

开发平台:

Visual C++

  1. /*
  2.  * The simplest mpeg encoder (well, it was the simplest!)
  3.  * Copyright (c) 2000,2001 Fabrice Bellard.
  4.  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
  5.  *
  6.  * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
  7.  *
  8.  * This file is part of FFmpeg.
  9.  *
  10.  * FFmpeg is free software; you can redistribute it and/or
  11.  * modify it under the terms of the GNU Lesser General Public
  12.  * License as published by the Free Software Foundation; either
  13.  * version 2.1 of the License, or (at your option) any later version.
  14.  *
  15.  * FFmpeg is distributed in the hope that it will be useful,
  16.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  18.  * Lesser General Public License for more details.
  19.  *
  20.  * You should have received a copy of the GNU Lesser General Public
  21.  * License along with FFmpeg; if not, write to the Free Software
  22.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23.  */
  24. /**
  25.  * @file mpegvideo.c
  26.  * The simplest mpeg encoder (well, it was the simplest!).
  27.  */
  28. #include "avcodec.h"
  29. #include "dsputil.h"
  30. #include "mpegvideo.h"
  31. #include "mpegvideo_common.h"
  32. #include "mjpegenc.h"
  33. #include "msmpeg4.h"
  34. #include "faandct.h"
  35. #include "internal.h"
  36. #include <limits.h>
  37. //#undef NDEBUG
  38. //#include <assert.h>
  39. static void dct_unquantize_mpeg1_intra_c(MpegEncContext *s,
  40.                                    DCTELEM *block, int n, int qscale);
  41. static void dct_unquantize_mpeg1_inter_c(MpegEncContext *s,
  42.                                    DCTELEM *block, int n, int qscale);
  43. static void dct_unquantize_mpeg2_intra_c(MpegEncContext *s,
  44.                                    DCTELEM *block, int n, int qscale);
  45. static void dct_unquantize_mpeg2_intra_bitexact(MpegEncContext *s,
  46.                                    DCTELEM *block, int n, int qscale);
  47. static void dct_unquantize_mpeg2_inter_c(MpegEncContext *s,
  48.                                    DCTELEM *block, int n, int qscale);
  49. static void dct_unquantize_h263_intra_c(MpegEncContext *s,
  50.                                   DCTELEM *block, int n, int qscale);
  51. static void dct_unquantize_h263_inter_c(MpegEncContext *s,
  52.                                   DCTELEM *block, int n, int qscale);
  53. extern int  XVMC_field_start(MpegEncContext*s, AVCodecContext *avctx);
  54. extern void XVMC_field_end(MpegEncContext *s);
  55. extern void XVMC_decode_mb(MpegEncContext *s);
  56. /* enable all paranoid tests for rounding, overflows, etc... */
  57. //#define PARANOID
  58. //#define DEBUG
  59. static const uint8_t ff_default_chroma_qscale_table[32]={
  60. //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
  61.     0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
  62. };
  63. const uint8_t ff_mpeg1_dc_scale_table[128]={
  64. //  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
  65.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  66.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  67.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  68.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  69. };
  70. const uint8_t *ff_find_start_code(const uint8_t * restrict p, const uint8_t *end, uint32_t * restrict state){
  71.     int i;
  72.     assert(p<=end);
  73.     if(p>=end)
  74.         return end;
  75.     for(i=0; i<3; i++){
  76.         uint32_t tmp= *state << 8;
  77.         *state= tmp + *(p++);
  78.         if(tmp == 0x100 || p==end)
  79.             return p;
  80.     }
  81.     while(p<end){
  82.         if     (p[-1] > 1      ) p+= 3;
  83.         else if(p[-2]          ) p+= 2;
  84.         else if(p[-3]|(p[-1]-1)) p++;
  85.         else{
  86.             p++;
  87.             break;
  88.         }
  89.     }
  90.     p= FFMIN(p, end)-4;
  91.     *state= AV_RB32(p);
  92.     return p+4;
  93. }
  94. /* init common dct for both encoder and decoder */
  95. int ff_dct_common_init(MpegEncContext *s)
  96. {
  97.     s->dct_unquantize_h263_intra = dct_unquantize_h263_intra_c;
  98.     s->dct_unquantize_h263_inter = dct_unquantize_h263_inter_c;
  99.     s->dct_unquantize_mpeg1_intra = dct_unquantize_mpeg1_intra_c;
  100.     s->dct_unquantize_mpeg1_inter = dct_unquantize_mpeg1_inter_c;
  101.     s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_c;
  102.     if(s->flags & CODEC_FLAG_BITEXACT)
  103.         s->dct_unquantize_mpeg2_intra = dct_unquantize_mpeg2_intra_bitexact;
  104.     s->dct_unquantize_mpeg2_inter = dct_unquantize_mpeg2_inter_c;
  105. #if defined(HAVE_MMX)
  106.     MPV_common_init_mmx(s);
  107. #elif defined(ARCH_ALPHA)
  108.     MPV_common_init_axp(s);
  109. #elif defined(CONFIG_MLIB)
  110.     MPV_common_init_mlib(s);
  111. #elif defined(HAVE_MMI)
  112.     MPV_common_init_mmi(s);
  113. #elif defined(ARCH_ARMV4L)
  114.     MPV_common_init_armv4l(s);
  115. #elif defined(HAVE_ALTIVEC)
  116.     MPV_common_init_altivec(s);
  117. #elif defined(ARCH_BFIN)
  118.     MPV_common_init_bfin(s);
  119. #endif
  120.     /* load & permutate scantables
  121.        note: only wmv uses different ones
  122.     */
  123.     if(s->alternate_scan){
  124.         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);
  125.         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);
  126.     }else{
  127.         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);
  128.         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);
  129.     }
  130.     ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
  131.     ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
  132.     return 0;
  133. }
  134. void copy_picture(Picture *dst, Picture *src){
  135.     *dst = *src;
  136.     dst->type= FF_BUFFER_TYPE_COPY;
  137. }
  138. /**
  139.  * allocates a Picture
  140.  * The pixels are allocated/set by calling get_buffer() if shared=0
  141.  */
  142. int alloc_picture(MpegEncContext *s, Picture *pic, int shared){
  143.     const int big_mb_num= s->mb_stride*(s->mb_height+1) + 1; //the +1 is needed so memset(,,stride*height) does not sig11
  144.     const int mb_array_size= s->mb_stride*s->mb_height;
  145.     const int b8_array_size= s->b8_stride*s->mb_height*2;
  146.     const int b4_array_size= s->b4_stride*s->mb_height*4;
  147.     int i;
  148.     int r= -1;
  149.     if(shared){
  150.         assert(pic->data[0]);
  151.         assert(pic->type == 0 || pic->type == FF_BUFFER_TYPE_SHARED);
  152.         pic->type= FF_BUFFER_TYPE_SHARED;
  153.     }else{
  154.         assert(!pic->data[0]);
  155.         r= s->avctx->get_buffer(s->avctx, (AVFrame*)pic);
  156.         if(r<0 || !pic->age || !pic->type || !pic->data[0]){
  157.             av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (%d %d %d %p)n", r, pic->age, pic->type, pic->data[0]);
  158.             return -1;
  159.         }
  160.         if(s->linesize && (s->linesize != pic->linesize[0] || s->uvlinesize != pic->linesize[1])){
  161.             av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (stride changed)n");
  162.             s->avctx->release_buffer(s->avctx, (AVFrame*)pic);
  163.             return -1;
  164.         }
  165.         if(pic->linesize[1] != pic->linesize[2]){
  166.             av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (uv stride mismatch)n");
  167.             s->avctx->release_buffer(s->avctx, (AVFrame*)pic);
  168.             return -1;
  169.         }
  170.         s->linesize  = pic->linesize[0];
  171.         s->uvlinesize= pic->linesize[1];
  172.     }
  173.     if(pic->qscale_table==NULL){
  174.         if (s->encoding) {
  175.             CHECKED_ALLOCZ(pic->mb_var   , mb_array_size * sizeof(int16_t))
  176.             CHECKED_ALLOCZ(pic->mc_mb_var, mb_array_size * sizeof(int16_t))
  177.             CHECKED_ALLOCZ(pic->mb_mean  , mb_array_size * sizeof(int8_t))
  178.         }
  179.         CHECKED_ALLOCZ(pic->mbskip_table , mb_array_size * sizeof(uint8_t)+2) //the +2 is for the slice end check
  180.         CHECKED_ALLOCZ(pic->qscale_table , mb_array_size * sizeof(uint8_t))
  181.         CHECKED_ALLOCZ(pic->mb_type_base , (big_mb_num + s->mb_stride) * sizeof(uint32_t))
  182.         pic->mb_type= pic->mb_type_base + 2*s->mb_stride+1;
  183.         if(s->out_format == FMT_H264){
  184.             for(i=0; i<2; i++){
  185.                 CHECKED_ALLOCZ(pic->motion_val_base[i], 2 * (b4_array_size+4)  * sizeof(int16_t))
  186.                 pic->motion_val[i]= pic->motion_val_base[i]+4;
  187.                 CHECKED_ALLOCZ(pic->ref_index[i], b8_array_size * sizeof(uint8_t))
  188.             }
  189.             pic->motion_subsample_log2= 2;
  190.         }else if(s->out_format == FMT_H263 || s->encoding || (s->avctx->debug&FF_DEBUG_MV) || (s->avctx->debug_mv)){
  191.             for(i=0; i<2; i++){
  192.                 CHECKED_ALLOCZ(pic->motion_val_base[i], 2 * (b8_array_size+4) * sizeof(int16_t))
  193.                 pic->motion_val[i]= pic->motion_val_base[i]+4;
  194.                 CHECKED_ALLOCZ(pic->ref_index[i], b8_array_size * sizeof(uint8_t))
  195.             }
  196.             pic->motion_subsample_log2= 3;
  197.         }
  198.         if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {
  199.             CHECKED_ALLOCZ(pic->dct_coeff, 64 * mb_array_size * sizeof(DCTELEM)*6)
  200.         }
  201.         pic->qstride= s->mb_stride;
  202.         CHECKED_ALLOCZ(pic->pan_scan , 1 * sizeof(AVPanScan))
  203.     }
  204.     /* It might be nicer if the application would keep track of these
  205.      * but it would require an API change. */
  206.     memmove(s->prev_pict_types+1, s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE-1);
  207.     s->prev_pict_types[0]= s->dropable ? FF_B_TYPE : s->pict_type;
  208.     if(pic->age < PREV_PICT_TYPES_BUFFER_SIZE && s->prev_pict_types[pic->age] == FF_B_TYPE)
  209.         pic->age= INT_MAX; // Skipped MBs in B-frames are quite rare in MPEG-1/2 and it is a bit tricky to skip them anyway.
  210.     return 0;
  211. fail: //for the CHECKED_ALLOCZ macro
  212.     if(r>=0)
  213.         s->avctx->release_buffer(s->avctx, (AVFrame*)pic);
  214.     return -1;
  215. }
  216. /**
  217.  * deallocates a picture
  218.  */
  219. static void free_picture(MpegEncContext *s, Picture *pic){
  220.     int i;
  221.     if(pic->data[0] && pic->type!=FF_BUFFER_TYPE_SHARED){
  222.         s->avctx->release_buffer(s->avctx, (AVFrame*)pic);
  223.     }
  224.     av_freep(&pic->mb_var);
  225.     av_freep(&pic->mc_mb_var);
  226.     av_freep(&pic->mb_mean);
  227.     av_freep(&pic->mbskip_table);
  228.     av_freep(&pic->qscale_table);
  229.     av_freep(&pic->mb_type_base);
  230.     av_freep(&pic->dct_coeff);
  231.     av_freep(&pic->pan_scan);
  232.     pic->mb_type= NULL;
  233.     for(i=0; i<2; i++){
  234.         av_freep(&pic->motion_val_base[i]);
  235.         av_freep(&pic->ref_index[i]);
  236.     }
  237.     if(pic->type == FF_BUFFER_TYPE_SHARED){
  238.         for(i=0; i<4; i++){
  239.             pic->base[i]=
  240.             pic->data[i]= NULL;
  241.         }
  242.         pic->type= 0;
  243.     }
  244. }
  245. static int init_duplicate_context(MpegEncContext *s, MpegEncContext *base){
  246.     int i;
  247.     // edge emu needs blocksize + filter length - 1 (=17x17 for halfpel / 21x21 for h264)
  248.     CHECKED_ALLOCZ(s->allocated_edge_emu_buffer, (s->width+64)*2*21*2); //(width + edge + align)*interlaced*MBsize*tolerance
  249.     s->edge_emu_buffer= s->allocated_edge_emu_buffer + (s->width+64)*2*21;
  250.      //FIXME should be linesize instead of s->width*2 but that is not known before get_buffer()
  251.     CHECKED_ALLOCZ(s->me.scratchpad,  (s->width+64)*4*16*2*sizeof(uint8_t))
  252.     s->rd_scratchpad=   s->me.scratchpad;
  253.     s->b_scratchpad=    s->me.scratchpad;
  254.     s->obmc_scratchpad= s->me.scratchpad + 16;
  255.     if (s->encoding) {
  256.         CHECKED_ALLOCZ(s->me.map      , ME_MAP_SIZE*sizeof(uint32_t))
  257.         CHECKED_ALLOCZ(s->me.score_map, ME_MAP_SIZE*sizeof(uint32_t))
  258.         if(s->avctx->noise_reduction){
  259.             CHECKED_ALLOCZ(s->dct_error_sum, 2 * 64 * sizeof(int))
  260.         }
  261.     }
  262.     CHECKED_ALLOCZ(s->blocks, 64*12*2 * sizeof(DCTELEM))
  263.     s->block= s->blocks[0];
  264.     for(i=0;i<12;i++){
  265.         s->pblocks[i] = (short *)(&s->block[i]);
  266.     }
  267.     return 0;
  268. fail:
  269.     return -1; //free() through MPV_common_end()
  270. }
  271. static void free_duplicate_context(MpegEncContext *s){
  272.     if(s==NULL) return;
  273.     av_freep(&s->allocated_edge_emu_buffer); s->edge_emu_buffer= NULL;
  274.     av_freep(&s->me.scratchpad);
  275.     s->rd_scratchpad=
  276.     s->b_scratchpad=
  277.     s->obmc_scratchpad= NULL;
  278.     av_freep(&s->dct_error_sum);
  279.     av_freep(&s->me.map);
  280.     av_freep(&s->me.score_map);
  281.     av_freep(&s->blocks);
  282.     s->block= NULL;
  283. }
  284. static void backup_duplicate_context(MpegEncContext *bak, MpegEncContext *src){
  285. #define COPY(a) bak->a= src->a
  286.     COPY(allocated_edge_emu_buffer);
  287.     COPY(edge_emu_buffer);
  288.     COPY(me.scratchpad);
  289.     COPY(rd_scratchpad);
  290.     COPY(b_scratchpad);
  291.     COPY(obmc_scratchpad);
  292.     COPY(me.map);
  293.     COPY(me.score_map);
  294.     COPY(blocks);
  295.     COPY(block);
  296.     COPY(start_mb_y);
  297.     COPY(end_mb_y);
  298.     COPY(me.map_generation);
  299.     COPY(pb);
  300.     COPY(dct_error_sum);
  301.     COPY(dct_count[0]);
  302.     COPY(dct_count[1]);
  303. #undef COPY
  304. }
  305. void ff_update_duplicate_context(MpegEncContext *dst, MpegEncContext *src){
  306.     MpegEncContext bak;
  307.     int i;
  308.     //FIXME copy only needed parts
  309. //START_TIMER
  310.     backup_duplicate_context(&bak, dst);
  311.     memcpy(dst, src, sizeof(MpegEncContext));
  312.     backup_duplicate_context(dst, &bak);
  313.     for(i=0;i<12;i++){
  314.         dst->pblocks[i] = (short *)(&dst->block[i]);
  315.     }
  316. //STOP_TIMER("update_duplicate_context") //about 10k cycles / 0.01 sec for 1000frames on 1ghz with 2 threads
  317. }
  318. /**
  319.  * sets the given MpegEncContext to common defaults (same for encoding and decoding).
  320.  * the changed fields will not depend upon the prior state of the MpegEncContext.
  321.  */
  322. void MPV_common_defaults(MpegEncContext *s){
  323.     s->y_dc_scale_table=
  324.     s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
  325.     s->chroma_qscale_table= ff_default_chroma_qscale_table;
  326.     s->progressive_frame= 1;
  327.     s->progressive_sequence= 1;
  328.     s->picture_structure= PICT_FRAME;
  329.     s->coded_picture_number = 0;
  330.     s->picture_number = 0;
  331.     s->input_picture_number = 0;
  332.     s->picture_in_gop_number = 0;
  333.     s->f_code = 1;
  334.     s->b_code = 1;
  335. }
  336. /**
  337.  * sets the given MpegEncContext to defaults for decoding.
  338.  * the changed fields will not depend upon the prior state of the MpegEncContext.
  339.  */
  340. void MPV_decode_defaults(MpegEncContext *s){
  341.     MPV_common_defaults(s);
  342. }
  343. /**
  344.  * init common structure for both encoder and decoder.
  345.  * this assumes that some variables like width/height are already set
  346.  */
  347. int MPV_common_init(MpegEncContext *s)
  348. {
  349.     int y_size, c_size, yc_size, i, mb_array_size, mv_table_size, x, y, threads;
  350.     s->mb_height = (s->height + 15) / 16;
  351.     if(s->avctx->thread_count > MAX_THREADS || (s->avctx->thread_count > s->mb_height && s->mb_height)){
  352.         av_log(s->avctx, AV_LOG_ERROR, "too many threadsn");
  353.         return -1;
  354.     }
  355.     if((s->width || s->height) && avcodec_check_dimensions(s->avctx, s->width, s->height))
  356.         return -1;
  357. //    dsputil_init(&s->dsp, s->avctx);
  358.     ff_dct_common_init(s);
  359.     s->flags= s->avctx->flags;
  360.     s->flags2= s->avctx->flags2;
  361.     s->mb_width  = (s->width  + 15) / 16;
  362.     s->mb_stride = s->mb_width + 1;
  363.     s->b8_stride = s->mb_width*2 + 1;
  364.     s->b4_stride = s->mb_width*4 + 1;
  365.     mb_array_size= s->mb_height * s->mb_stride;
  366.     mv_table_size= (s->mb_height+2) * s->mb_stride + 1;
  367.     /* set chroma shifts */
  368.     avcodec_get_chroma_sub_sample(s->avctx->pix_fmt,&(s->chroma_x_shift),
  369.                                                     &(s->chroma_y_shift) );
  370.     /* set default edge pos, will be overriden in decode_header if needed */
  371.     s->h_edge_pos= s->mb_width*16;
  372.     s->v_edge_pos= s->mb_height*16;
  373.     s->mb_num = s->mb_width * s->mb_height;
  374.     s->block_wrap[0]=
  375.     s->block_wrap[1]=
  376.     s->block_wrap[2]=
  377.     s->block_wrap[3]= s->b8_stride;
  378.     s->block_wrap[4]=
  379.     s->block_wrap[5]= s->mb_stride;
  380.     y_size = s->b8_stride * (2 * s->mb_height + 1);
  381.     c_size = s->mb_stride * (s->mb_height + 1);
  382.     yc_size = y_size + 2 * c_size;
  383.     /* convert fourcc to upper case */
  384.     s->codec_tag=          toupper( s->avctx->codec_tag     &0xFF)
  385.                         + (toupper((s->avctx->codec_tag>>8 )&0xFF)<<8 )
  386.                         + (toupper((s->avctx->codec_tag>>16)&0xFF)<<16)
  387.                         + (toupper((s->avctx->codec_tag>>24)&0xFF)<<24);
  388.     s->stream_codec_tag=          toupper( s->avctx->stream_codec_tag     &0xFF)
  389.                                + (toupper((s->avctx->stream_codec_tag>>8 )&0xFF)<<8 )
  390.                                + (toupper((s->avctx->stream_codec_tag>>16)&0xFF)<<16)
  391.                                + (toupper((s->avctx->stream_codec_tag>>24)&0xFF)<<24);
  392.     s->avctx->coded_frame= (AVFrame*)&s->current_picture;
  393.     CHECKED_ALLOCZ(s->mb_index2xy, (s->mb_num+1)*sizeof(int)) //error ressilience code looks cleaner with this
  394.     for(y=0; y<s->mb_height; y++){
  395.         for(x=0; x<s->mb_width; x++){
  396.             s->mb_index2xy[ x + y*s->mb_width ] = x + y*s->mb_stride;
  397.         }
  398.     }
  399.     s->mb_index2xy[ s->mb_height*s->mb_width ] = (s->mb_height-1)*s->mb_stride + s->mb_width; //FIXME really needed?
  400.     if (s->encoding) {
  401.         /* Allocate MV tables */
  402.         CHECKED_ALLOCZ(s->p_mv_table_base            , mv_table_size * 2 * sizeof(int16_t))
  403.         CHECKED_ALLOCZ(s->b_forw_mv_table_base       , mv_table_size * 2 * sizeof(int16_t))
  404.         CHECKED_ALLOCZ(s->b_back_mv_table_base       , mv_table_size * 2 * sizeof(int16_t))
  405.         CHECKED_ALLOCZ(s->b_bidir_forw_mv_table_base , mv_table_size * 2 * sizeof(int16_t))
  406.         CHECKED_ALLOCZ(s->b_bidir_back_mv_table_base , mv_table_size * 2 * sizeof(int16_t))
  407.         CHECKED_ALLOCZ(s->b_direct_mv_table_base     , mv_table_size * 2 * sizeof(int16_t))
  408.         s->p_mv_table           = s->p_mv_table_base            + s->mb_stride + 1;
  409.         s->b_forw_mv_table      = s->b_forw_mv_table_base       + s->mb_stride + 1;
  410.         s->b_back_mv_table      = s->b_back_mv_table_base       + s->mb_stride + 1;
  411.         s->b_bidir_forw_mv_table= s->b_bidir_forw_mv_table_base + s->mb_stride + 1;
  412.         s->b_bidir_back_mv_table= s->b_bidir_back_mv_table_base + s->mb_stride + 1;
  413.         s->b_direct_mv_table    = s->b_direct_mv_table_base     + s->mb_stride + 1;
  414.         if(s->msmpeg4_version){
  415.             CHECKED_ALLOCZ(s->ac_stats, 2*2*(MAX_LEVEL+1)*(MAX_RUN+1)*2*sizeof(int));
  416.         }
  417.         CHECKED_ALLOCZ(s->avctx->stats_out, 256);
  418.         /* Allocate MB type table */
  419.         CHECKED_ALLOCZ(s->mb_type  , mb_array_size * sizeof(uint16_t)) //needed for encoding
  420.         CHECKED_ALLOCZ(s->lambda_table, mb_array_size * sizeof(int))
  421.         CHECKED_ALLOCZ(s->q_intra_matrix, 64*32 * sizeof(int))
  422.         CHECKED_ALLOCZ(s->q_inter_matrix, 64*32 * sizeof(int))
  423.         CHECKED_ALLOCZ(s->q_intra_matrix16, 64*32*2 * sizeof(uint16_t))
  424.         CHECKED_ALLOCZ(s->q_inter_matrix16, 64*32*2 * sizeof(uint16_t))
  425.         CHECKED_ALLOCZ(s->input_picture, MAX_PICTURE_COUNT * sizeof(Picture*))
  426.         CHECKED_ALLOCZ(s->reordered_input_picture, MAX_PICTURE_COUNT * sizeof(Picture*))
  427.         if(s->avctx->noise_reduction){
  428.             CHECKED_ALLOCZ(s->dct_offset, 2 * 64 * sizeof(uint16_t))
  429.         }
  430.     }
  431.     CHECKED_ALLOCZ(s->picture, MAX_PICTURE_COUNT * sizeof(Picture))
  432.     CHECKED_ALLOCZ(s->error_status_table, mb_array_size*sizeof(uint8_t))
  433.     if(s->codec_id==CODEC_ID_MPEG4 || (s->flags & CODEC_FLAG_INTERLACED_ME)){
  434.         /* interlaced direct mode decoding tables */
  435.             for(i=0; i<2; i++){
  436.                 int j, k;
  437.                 for(j=0; j<2; j++){
  438.                     for(k=0; k<2; k++){
  439.                         CHECKED_ALLOCZ(s->b_field_mv_table_base[i][j][k]     , mv_table_size * 2 * sizeof(int16_t))
  440.                         s->b_field_mv_table[i][j][k]    = s->b_field_mv_table_base[i][j][k]     + s->mb_stride + 1;
  441.                     }
  442.                     CHECKED_ALLOCZ(s->b_field_select_table[i][j]     , mb_array_size * 2 * sizeof(uint8_t))
  443.                     CHECKED_ALLOCZ(s->p_field_mv_table_base[i][j]     , mv_table_size * 2 * sizeof(int16_t))
  444.                     s->p_field_mv_table[i][j]    = s->p_field_mv_table_base[i][j]     + s->mb_stride + 1;
  445.                 }
  446.                 CHECKED_ALLOCZ(s->p_field_select_table[i]      , mb_array_size * 2 * sizeof(uint8_t))
  447.             }
  448.     }
  449.     if (s->out_format == FMT_H263) {
  450.         /* ac values */
  451.         CHECKED_ALLOCZ(s->ac_val_base, yc_size * sizeof(int16_t) * 16);
  452.         s->ac_val[0] = s->ac_val_base + s->b8_stride + 1;
  453.         s->ac_val[1] = s->ac_val_base + y_size + s->mb_stride + 1;
  454.         s->ac_val[2] = s->ac_val[1] + c_size;
  455.         /* cbp values */
  456.         CHECKED_ALLOCZ(s->coded_block_base, y_size);
  457.         s->coded_block= s->coded_block_base + s->b8_stride + 1;
  458.         /* cbp, ac_pred, pred_dir */
  459.         CHECKED_ALLOCZ(s->cbp_table  , mb_array_size * sizeof(uint8_t))
  460.         CHECKED_ALLOCZ(s->pred_dir_table, mb_array_size * sizeof(uint8_t))
  461.     }
  462.     if (s->h263_pred || s->h263_plus || !s->encoding) {
  463.         /* dc values */
  464.         //MN: we need these for error resilience of intra-frames
  465.         CHECKED_ALLOCZ(s->dc_val_base, yc_size * sizeof(int16_t));
  466.         s->dc_val[0] = s->dc_val_base + s->b8_stride + 1;
  467.         s->dc_val[1] = s->dc_val_base + y_size + s->mb_stride + 1;
  468.         s->dc_val[2] = s->dc_val[1] + c_size;
  469.         for(i=0;i<yc_size;i++)
  470.             s->dc_val_base[i] = 1024;
  471.     }
  472.     /* which mb is a intra block */
  473.     CHECKED_ALLOCZ(s->mbintra_table, mb_array_size);
  474.     memset(s->mbintra_table, 1, mb_array_size);
  475.     /* init macroblock skip table */
  476.     CHECKED_ALLOCZ(s->mbskip_table, mb_array_size+2);
  477.     //Note the +1 is for a quicker mpeg4 slice_end detection
  478.     CHECKED_ALLOCZ(s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE);
  479.     s->parse_context.state= -1;
  480.     if((s->avctx->debug&(FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) || (s->avctx->debug_mv)){
  481.        s->visualization_buffer[0] = av_malloc((s->mb_width*16 + 2*EDGE_WIDTH) * s->mb_height*16 + 2*EDGE_WIDTH);
  482.        s->visualization_buffer[1] = av_malloc((s->mb_width*8 + EDGE_WIDTH) * s->mb_height*8 + EDGE_WIDTH);
  483.        s->visualization_buffer[2] = av_malloc((s->mb_width*8 + EDGE_WIDTH) * s->mb_height*8 + EDGE_WIDTH);
  484.     }
  485.     s->context_initialized = 1;
  486.     s->thread_context[0]= s;
  487.     threads = s->avctx->thread_count;
  488.     for(i=1; i<threads; i++){
  489.         s->thread_context[i]= av_malloc(sizeof(MpegEncContext));
  490.         memcpy(s->thread_context[i], s, sizeof(MpegEncContext));
  491.     }
  492.     for(i=0; i<threads; i++){
  493.         if(init_duplicate_context(s->thread_context[i], s) < 0)
  494.            goto fail;
  495.         s->thread_context[i]->start_mb_y= (s->mb_height*(i  ) + s->avctx->thread_count/2) / s->avctx->thread_count;
  496.         s->thread_context[i]->end_mb_y  = (s->mb_height*(i+1) + s->avctx->thread_count/2) / s->avctx->thread_count;
  497.     }
  498.     return 0;
  499.  fail:
  500.     MPV_common_end(s);
  501.     return -1;
  502. }
  503. /* init common structure for both encoder and decoder */
  504. void MPV_common_end(MpegEncContext *s)
  505. {
  506.     int i, j, k;
  507.     for(i=0; i<s->avctx->thread_count; i++){
  508.         free_duplicate_context(s->thread_context[i]);
  509.     }
  510.     for(i=1; i<s->avctx->thread_count; i++){
  511.         av_freep(&s->thread_context[i]);
  512.     }
  513.     av_freep(&s->parse_context.buffer);
  514.     s->parse_context.buffer_size=0;
  515.     av_freep(&s->mb_type);
  516.     av_freep(&s->p_mv_table_base);
  517.     av_freep(&s->b_forw_mv_table_base);
  518.     av_freep(&s->b_back_mv_table_base);
  519.     av_freep(&s->b_bidir_forw_mv_table_base);
  520.     av_freep(&s->b_bidir_back_mv_table_base);
  521.     av_freep(&s->b_direct_mv_table_base);
  522.     s->p_mv_table= NULL;
  523.     s->b_forw_mv_table= NULL;
  524.     s->b_back_mv_table= NULL;
  525.     s->b_bidir_forw_mv_table= NULL;
  526.     s->b_bidir_back_mv_table= NULL;
  527.     s->b_direct_mv_table= NULL;
  528.     for(i=0; i<2; i++){
  529.         for(j=0; j<2; j++){
  530.             for(k=0; k<2; k++){
  531.                 av_freep(&s->b_field_mv_table_base[i][j][k]);
  532.                 s->b_field_mv_table[i][j][k]=NULL;
  533.             }
  534.             av_freep(&s->b_field_select_table[i][j]);
  535.             av_freep(&s->p_field_mv_table_base[i][j]);
  536.             s->p_field_mv_table[i][j]=NULL;
  537.         }
  538.         av_freep(&s->p_field_select_table[i]);
  539.     }
  540.     av_freep(&s->dc_val_base);
  541.     av_freep(&s->ac_val_base);
  542.     av_freep(&s->coded_block_base);
  543.     av_freep(&s->mbintra_table);
  544.     av_freep(&s->cbp_table);
  545.     av_freep(&s->pred_dir_table);
  546.     av_freep(&s->mbskip_table);
  547.     av_freep(&s->prev_pict_types);
  548.     av_freep(&s->bitstream_buffer);
  549.     s->allocated_bitstream_buffer_size=0;
  550.     av_freep(&s->avctx->stats_out);
  551.     av_freep(&s->ac_stats);
  552.     av_freep(&s->error_status_table);
  553.     av_freep(&s->mb_index2xy);
  554.     av_freep(&s->lambda_table);
  555.     av_freep(&s->q_intra_matrix);
  556.     av_freep(&s->q_inter_matrix);
  557.     av_freep(&s->q_intra_matrix16);
  558.     av_freep(&s->q_inter_matrix16);
  559.     av_freep(&s->input_picture);
  560.     av_freep(&s->reordered_input_picture);
  561.     av_freep(&s->dct_offset);
  562.     if(s->picture){
  563.         for(i=0; i<MAX_PICTURE_COUNT; i++){
  564.             free_picture(s, &s->picture[i]);
  565.         }
  566.     }
  567.     av_freep(&s->picture);
  568.     s->context_initialized = 0;
  569.     s->last_picture_ptr=
  570.     s->next_picture_ptr=
  571.     s->current_picture_ptr= NULL;
  572.     s->linesize= s->uvlinesize= 0;
  573.     for(i=0; i<3; i++)
  574.         av_freep(&s->visualization_buffer[i]);
  575.     avcodec_default_free_buffers(s->avctx);
  576. }
  577. void init_rl(RLTable *rl, uint8_t static_store[2][2*MAX_RUN + MAX_LEVEL + 3])
  578. {
  579.     int8_t max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
  580.     uint8_t index_run[MAX_RUN+1];
  581.     int last, run, level, start, end, i;
  582.     /* If table is static, we can quit if rl->max_level[0] is not NULL */
  583.     if(static_store && rl->max_level[0])
  584.         return;
  585.     /* compute max_level[], max_run[] and index_run[] */
  586.     for(last=0;last<2;last++) {
  587.         if (last == 0) {
  588.             start = 0;
  589.             end = rl->last;
  590.         } else {
  591.             start = rl->last;
  592.             end = rl->n;
  593.         }
  594.         memset(max_level, 0, MAX_RUN + 1);
  595.         memset(max_run, 0, MAX_LEVEL + 1);
  596.         memset(index_run, rl->n, MAX_RUN + 1);
  597.         for(i=start;i<end;i++) {
  598.             run = rl->table_run[i];
  599.             level = rl->table_level[i];
  600.             if (index_run[run] == rl->n)
  601.                 index_run[run] = i;
  602.             if (level > max_level[run])
  603.                 max_level[run] = level;
  604.             if (run > max_run[level])
  605.                 max_run[level] = run;
  606.         }
  607.         if(static_store)
  608.             rl->max_level[last] = static_store[last];
  609.         else
  610.             rl->max_level[last] = av_malloc(MAX_RUN + 1);
  611.         memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
  612.         if(static_store)
  613.             rl->max_run[last] = static_store[last] + MAX_RUN + 1;
  614.         else
  615.             rl->max_run[last] = av_malloc(MAX_LEVEL + 1);
  616.         memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
  617.         if(static_store)
  618.             rl->index_run[last] = static_store[last] + MAX_RUN + MAX_LEVEL + 2;
  619.         else
  620.             rl->index_run[last] = av_malloc(MAX_RUN + 1);
  621.         memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
  622.     }
  623. }
  624. void init_vlc_rl(RLTable *rl)
  625. {
  626.     int i, q;
  627.     for(q=0; q<32; q++){
  628.         int qmul= q*2;
  629.         int qadd= (q-1)|1;
  630.         if(q==0){
  631.             qmul=1;
  632.             qadd=0;
  633.         }
  634.         for(i=0; i<rl->vlc.table_size; i++){
  635.             int code= rl->vlc.table[i][0];
  636.             int len = rl->vlc.table[i][1];
  637.             int level, run;
  638.             if(len==0){ // illegal code
  639.                 run= 66;
  640.                 level= MAX_LEVEL;
  641.             }else if(len<0){ //more bits needed
  642.                 run= 0;
  643.                 level= code;
  644.             }else{
  645.                 if(code==rl->n){ //esc
  646.                     run= 66;
  647.                     level= 0;
  648.                 }else{
  649.                     run=   rl->table_run  [code] + 1;
  650.                     level= rl->table_level[code] * qmul + qadd;
  651.                     if(code >= rl->last) run+=192;
  652.                 }
  653.             }
  654.             rl->rl_vlc[q][i].len= len;
  655.             rl->rl_vlc[q][i].level= level;
  656.             rl->rl_vlc[q][i].run= run;
  657.         }
  658.     }
  659. }
  660. int ff_find_unused_picture(MpegEncContext *s, int shared){
  661.     int i;
  662.     if(shared){
  663.         for(i=0; i<MAX_PICTURE_COUNT; i++){
  664.             if(s->picture[i].data[0]==NULL && s->picture[i].type==0) return i;
  665.         }
  666.     }else{
  667.         for(i=0; i<MAX_PICTURE_COUNT; i++){
  668.             if(s->picture[i].data[0]==NULL && s->picture[i].type!=0) return i; //FIXME
  669.         }
  670.         for(i=0; i<MAX_PICTURE_COUNT; i++){
  671.             if(s->picture[i].data[0]==NULL) return i;
  672.         }
  673.     }
  674.     av_log(s->avctx, AV_LOG_FATAL, "Internal error, picture buffer overflown");
  675.     /* We could return -1, but the codec would crash trying to draw into a
  676.      * non-existing frame anyway. This is safer than waiting for a random crash.
  677.      * Also the return of this is never useful, an encoder must only allocate
  678.      * as much as allowed in the specification. This has no relationship to how
  679.      * much libavcodec could allocate (and MAX_PICTURE_COUNT is always large
  680.      * enough for such valid streams).
  681.      * Plus, a decoder has to check stream validity and remove frames if too
  682.      * many reference frames are around. Waiting for "OOM" is not correct at
  683.      * all. Similarly, missing reference frames have to be replaced by
  684.      * interpolated/MC frames, anything else is a bug in the codec ...
  685.      */
  686.     abort();
  687.     return -1;
  688. }
  689. static void update_noise_reduction(MpegEncContext *s){
  690.     int intra, i;
  691.     for(intra=0; intra<2; intra++){
  692.         if(s->dct_count[intra] > (1<<16)){
  693.             for(i=0; i<64; i++){
  694.                 s->dct_error_sum[intra][i] >>=1;
  695.             }
  696.             s->dct_count[intra] >>= 1;
  697.         }
  698.         for(i=0; i<64; i++){
  699.             s->dct_offset[intra][i]= (s->avctx->noise_reduction * s->dct_count[intra] + s->dct_error_sum[intra][i]/2) / (s->dct_error_sum[intra][i]+1);
  700.         }
  701.     }
  702. }
  703. /**
  704.  * generic function for encode/decode called after coding/decoding the header and before a frame is coded/decoded
  705.  */
  706. int MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
  707. {
  708.     int i;
  709.     AVFrame *pic;
  710.     s->mb_skipped = 0;
  711.     assert(s->last_picture_ptr==NULL || s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3);
  712.     /* mark&release old frames */
  713.     if (s->pict_type != FF_B_TYPE && s->last_picture_ptr && s->last_picture_ptr != s->next_picture_ptr && s->last_picture_ptr->data[0]) {
  714.       if(s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3){
  715.         avctx->release_buffer(avctx, (AVFrame*)s->last_picture_ptr);
  716.         /* release forgotten pictures */
  717.         /* if(mpeg124/h263) */
  718.         if(!s->encoding){
  719.             for(i=0; i<MAX_PICTURE_COUNT; i++){
  720.                 if(s->picture[i].data[0] && &s->picture[i] != s->next_picture_ptr && s->picture[i].reference){
  721.                     av_log(avctx, AV_LOG_ERROR, "releasing zombie picturen");
  722.                     avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);
  723.                 }
  724.             }
  725.         }
  726.       }
  727.     }
  728. alloc:
  729.     if(!s->encoding){
  730.         /* release non reference frames */
  731.         for(i=0; i<MAX_PICTURE_COUNT; i++){
  732.             if(s->picture[i].data[0] && !s->picture[i].reference /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/){
  733.                 s->avctx->release_buffer(s->avctx, (AVFrame*)&s->picture[i]);
  734.             }
  735.         }
  736.         if(s->current_picture_ptr && s->current_picture_ptr->data[0]==NULL)
  737.             pic= (AVFrame*)s->current_picture_ptr; //we already have a unused image (maybe it was set before reading the header)
  738.         else{
  739.             i= ff_find_unused_picture(s, 0);
  740.             pic= (AVFrame*)&s->picture[i];
  741.         }
  742.         pic->reference= 0;
  743.         if (!s->dropable){
  744.             if (s->codec_id == CODEC_ID_H264)
  745.                 pic->reference = s->picture_structure;
  746.             else if (s->pict_type != FF_B_TYPE)
  747.                 pic->reference = 3;
  748.         }
  749.         pic->coded_picture_number= s->coded_picture_number++;
  750.         if( alloc_picture(s, (Picture*)pic, 0) < 0)
  751.             return -1;
  752.         s->current_picture_ptr= (Picture*)pic;
  753.         s->current_picture_ptr->top_field_first= s->top_field_first; //FIXME use only the vars from current_pic
  754.         s->current_picture_ptr->interlaced_frame= !s->progressive_frame && !s->progressive_sequence;
  755.     }
  756.     s->current_picture_ptr->pict_type= s->pict_type;
  757. //    if(s->flags && CODEC_FLAG_QSCALE)
  758.   //      s->current_picture_ptr->quality= s->new_picture_ptr->quality;
  759.     s->current_picture_ptr->key_frame= s->pict_type == FF_I_TYPE;
  760.     copy_picture(&s->current_picture, s->current_picture_ptr);
  761.     if (s->pict_type != FF_B_TYPE) {
  762.         s->last_picture_ptr= s->next_picture_ptr;
  763.         if(!s->dropable)
  764.             s->next_picture_ptr= s->current_picture_ptr;
  765.     }
  766. /*    av_log(s->avctx, AV_LOG_DEBUG, "L%p N%p C%p L%p N%p C%p type:%d drop:%dn", s->last_picture_ptr, s->next_picture_ptr,s->current_picture_ptr,
  767.         s->last_picture_ptr    ? s->last_picture_ptr->data[0] : NULL,
  768.         s->next_picture_ptr    ? s->next_picture_ptr->data[0] : NULL,
  769.         s->current_picture_ptr ? s->current_picture_ptr->data[0] : NULL,
  770.         s->pict_type, s->dropable);*/
  771.     if(s->last_picture_ptr) copy_picture(&s->last_picture, s->last_picture_ptr);
  772.     if(s->next_picture_ptr) copy_picture(&s->next_picture, s->next_picture_ptr);
  773.     if(s->pict_type != FF_I_TYPE && (s->last_picture_ptr==NULL || s->last_picture_ptr->data[0]==NULL) && !s->dropable){
  774.         av_log(avctx, AV_LOG_ERROR, "warning: first frame is no keyframen");
  775.         assert(s->pict_type != FF_B_TYPE); //these should have been dropped if we don't have a reference
  776.         goto alloc;
  777.     }
  778.     assert(s->pict_type == FF_I_TYPE || (s->last_picture_ptr && s->last_picture_ptr->data[0]));
  779.     if(s->picture_structure!=PICT_FRAME && s->out_format != FMT_H264){
  780.         int i;
  781.         for(i=0; i<4; i++){
  782.             if(s->picture_structure == PICT_BOTTOM_FIELD){
  783.                  s->current_picture.data[i] += s->current_picture.linesize[i];
  784.             }
  785.             s->current_picture.linesize[i] *= 2;
  786.             s->last_picture.linesize[i] *=2;
  787.             s->next_picture.linesize[i] *=2;
  788.         }
  789.     }
  790.     s->hurry_up= s->avctx->hurry_up;
  791.     s->error_resilience= avctx->error_resilience;
  792.     /* set dequantizer, we can't do it during init as it might change for mpeg4
  793.        and we can't do it in the header decode as init is not called for mpeg4 there yet */
  794.     if(s->mpeg_quant || s->codec_id == CODEC_ID_MPEG2VIDEO){
  795.         s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;
  796.         s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;
  797.     }else if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
  798.         s->dct_unquantize_intra = s->dct_unquantize_h263_intra;
  799.         s->dct_unquantize_inter = s->dct_unquantize_h263_inter;
  800.     }else{
  801.         s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;
  802.         s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;
  803.     }
  804.     if(s->dct_error_sum){
  805.         assert(s->avctx->noise_reduction && s->encoding);
  806.         update_noise_reduction(s);
  807.     }
  808. #ifdef HAVE_XVMC
  809.     if(s->avctx->xvmc_acceleration)
  810.         return XVMC_field_start(s, avctx);
  811. #endif
  812.     return 0;
  813. }
  814. /* generic function for encode/decode called after a frame has been coded/decoded */
  815. void MPV_frame_end(MpegEncContext *s)
  816. {
  817.     int i;
  818.     /* draw edge for correct motion prediction if outside */
  819. #ifdef HAVE_XVMC
  820. //just to make sure that all data is rendered.
  821.     if(s->avctx->xvmc_acceleration){
  822.         XVMC_field_end(s);
  823.     }else
  824. #endif
  825.     if(s->unrestricted_mv && s->current_picture.reference && !s->intra_only && !(s->flags&CODEC_FLAG_EMU_EDGE)) {
  826.             s->dsp.draw_edges(s->current_picture.data[0], s->linesize  , s->h_edge_pos   , s->v_edge_pos   , EDGE_WIDTH  );
  827.             s->dsp.draw_edges(s->current_picture.data[1], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
  828.             s->dsp.draw_edges(s->current_picture.data[2], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
  829.     }
  830.     emms_c();
  831.     s->last_pict_type    = s->pict_type;
  832.     s->last_lambda_for[s->pict_type]= s->current_picture_ptr->quality;
  833.     if(s->pict_type!=FF_B_TYPE){
  834.         s->last_non_b_pict_type= s->pict_type;
  835.     }
  836. #if 0
  837.         /* copy back current_picture variables */
  838.     for(i=0; i<MAX_PICTURE_COUNT; i++){
  839.         if(s->picture[i].data[0] == s->current_picture.data[0]){
  840.             s->picture[i]= s->current_picture;
  841.             break;
  842.         }
  843.     }
  844.     assert(i<MAX_PICTURE_COUNT);
  845. #endif
  846.     if(s->encoding){
  847.         /* release non-reference frames */
  848.         for(i=0; i<MAX_PICTURE_COUNT; i++){
  849.             if(s->picture[i].data[0] && !s->picture[i].reference /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/){
  850.                 s->avctx->release_buffer(s->avctx, (AVFrame*)&s->picture[i]);
  851.             }
  852.         }
  853.     }
  854.     // clear copies, to avoid confusion
  855. #if 0
  856.     memset(&s->last_picture, 0, sizeof(Picture));
  857.     memset(&s->next_picture, 0, sizeof(Picture));
  858.     memset(&s->current_picture, 0, sizeof(Picture));
  859. #endif
  860.     s->avctx->coded_frame= (AVFrame*)s->current_picture_ptr;
  861. }
  862. /**
  863.  * draws an line from (ex, ey) -> (sx, sy).
  864.  * @param w width of the image
  865.  * @param h height of the image
  866.  * @param stride stride/linesize of the image
  867.  * @param color color of the arrow
  868.  */
  869. static void draw_line(uint8_t *buf, int sx, int sy, int ex, int ey, int w, int h, int stride, int color){
  870.     int x, y, fr, f;
  871.     sx= av_clip(sx, 0, w-1);
  872.     sy= av_clip(sy, 0, h-1);
  873.     ex= av_clip(ex, 0, w-1);
  874.     ey= av_clip(ey, 0, h-1);
  875.     buf[sy*stride + sx]+= color;
  876.     if(FFABS(ex - sx) > FFABS(ey - sy)){
  877.         if(sx > ex){
  878.             FFSWAP(int, sx, ex);
  879.             FFSWAP(int, sy, ey);
  880.         }
  881.         buf+= sx + sy*stride;
  882.         ex-= sx;
  883.         f= ((ey-sy)<<16)/ex;
  884.         for(x= 0; x <= ex; x++){
  885.             y = (x*f)>>16;
  886.             fr= (x*f)&0xFFFF;
  887.             buf[ y   *stride + x]+= (color*(0x10000-fr))>>16;
  888.             buf[(y+1)*stride + x]+= (color*         fr )>>16;
  889.         }
  890.     }else{
  891.         if(sy > ey){
  892.             FFSWAP(int, sx, ex);
  893.             FFSWAP(int, sy, ey);
  894.         }
  895.         buf+= sx + sy*stride;
  896.         ey-= sy;
  897.         if(ey) f= ((ex-sx)<<16)/ey;
  898.         else   f= 0;
  899.         for(y= 0; y <= ey; y++){
  900.             x = (y*f)>>16;
  901.             fr= (y*f)&0xFFFF;
  902.             buf[y*stride + x  ]+= (color*(0x10000-fr))>>16;
  903.             buf[y*stride + x+1]+= (color*         fr )>>16;
  904.         }
  905.     }
  906. }
  907. /**
  908.  * draws an arrow from (ex, ey) -> (sx, sy).
  909.  * @param w width of the image
  910.  * @param h height of the image
  911.  * @param stride stride/linesize of the image
  912.  * @param color color of the arrow
  913.  */
  914. static void draw_arrow(uint8_t *buf, int sx, int sy, int ex, int ey, int w, int h, int stride, int color){
  915.     int dx,dy;
  916.     sx= av_clip(sx, -100, w+100);
  917.     sy= av_clip(sy, -100, h+100);
  918.     ex= av_clip(ex, -100, w+100);
  919.     ey= av_clip(ey, -100, h+100);
  920.     dx= ex - sx;
  921.     dy= ey - sy;
  922.     if(dx*dx + dy*dy > 3*3){
  923.         int rx=  dx + dy;
  924.         int ry= -dx + dy;
  925.         int length= ff_sqrt((rx*rx + ry*ry)<<8);
  926.         //FIXME subpixel accuracy
  927.         rx= ROUNDED_DIV(rx*3<<4, length);
  928.         ry= ROUNDED_DIV(ry*3<<4, length);
  929.         draw_line(buf, sx, sy, sx + rx, sy + ry, w, h, stride, color);
  930.         draw_line(buf, sx, sy, sx - ry, sy + rx, w, h, stride, color);
  931.     }
  932.     draw_line(buf, sx, sy, ex, ey, w, h, stride, color);
  933. }
  934. /**
  935.  * prints debuging info for the given picture.
  936.  */
  937. void ff_print_debug_info(MpegEncContext *s, AVFrame *pict){
  938.     if(!pict || !pict->mb_type) return;
  939.     if(s->avctx->debug&(FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)){
  940.         int x,y;
  941.         av_log(s->avctx,AV_LOG_DEBUG,"New frame, type: ");
  942.         switch (pict->pict_type) {
  943.             case FF_I_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"In"); break;
  944.             case FF_P_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"Pn"); break;
  945.             case FF_B_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"Bn"); break;
  946.             case FF_S_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"Sn"); break;
  947.             case FF_SI_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"SIn"); break;
  948.             case FF_SP_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"SPn"); break;
  949.         }
  950.         for(y=0; y<s->mb_height; y++){
  951.             for(x=0; x<s->mb_width; x++){
  952.                 if(s->avctx->debug&FF_DEBUG_SKIP){
  953.                     int count= s->mbskip_table[x + y*s->mb_stride];
  954.                     if(count>9) count=9;
  955.                     av_log(s->avctx, AV_LOG_DEBUG, "%1d", count);
  956.                 }
  957.                 if(s->avctx->debug&FF_DEBUG_QP){
  958.                     av_log(s->avctx, AV_LOG_DEBUG, "%2d", pict->qscale_table[x + y*s->mb_stride]);
  959.                 }
  960.                 if(s->avctx->debug&FF_DEBUG_MB_TYPE){
  961.                     int mb_type= pict->mb_type[x + y*s->mb_stride];
  962.                     //Type & MV direction
  963.                     if(IS_PCM(mb_type))
  964.                         av_log(s->avctx, AV_LOG_DEBUG, "P");
  965.                     else if(IS_INTRA(mb_type) && IS_ACPRED(mb_type))
  966.                         av_log(s->avctx, AV_LOG_DEBUG, "A");
  967.                     else if(IS_INTRA4x4(mb_type))
  968.                         av_log(s->avctx, AV_LOG_DEBUG, "i");
  969.                     else if(IS_INTRA16x16(mb_type))
  970.                         av_log(s->avctx, AV_LOG_DEBUG, "I");
  971.                     else if(IS_DIRECT(mb_type) && IS_SKIP(mb_type))
  972.                         av_log(s->avctx, AV_LOG_DEBUG, "d");
  973.                     else if(IS_DIRECT(mb_type))
  974.                         av_log(s->avctx, AV_LOG_DEBUG, "D");
  975.                     else if(IS_GMC(mb_type) && IS_SKIP(mb_type))
  976.                         av_log(s->avctx, AV_LOG_DEBUG, "g");
  977.                     else if(IS_GMC(mb_type))
  978.                         av_log(s->avctx, AV_LOG_DEBUG, "G");
  979.                     else if(IS_SKIP(mb_type))
  980.                         av_log(s->avctx, AV_LOG_DEBUG, "S");
  981.                     else if(!USES_LIST(mb_type, 1))
  982.                         av_log(s->avctx, AV_LOG_DEBUG, ">");
  983.                     else if(!USES_LIST(mb_type, 0))
  984.                         av_log(s->avctx, AV_LOG_DEBUG, "<");
  985.                     else{
  986.                         assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
  987.                         av_log(s->avctx, AV_LOG_DEBUG, "X");
  988.                     }
  989.                     //segmentation
  990.                     if(IS_8X8(mb_type))
  991.                         av_log(s->avctx, AV_LOG_DEBUG, "+");
  992.                     else if(IS_16X8(mb_type))
  993.                         av_log(s->avctx, AV_LOG_DEBUG, "-");
  994.                     else if(IS_8X16(mb_type))
  995.                         av_log(s->avctx, AV_LOG_DEBUG, "|");
  996.                     else if(IS_INTRA(mb_type) || IS_16X16(mb_type))
  997.                         av_log(s->avctx, AV_LOG_DEBUG, " ");
  998.                     else
  999.                         av_log(s->avctx, AV_LOG_DEBUG, "?");
  1000.                     if(IS_INTERLACED(mb_type) && s->codec_id == CODEC_ID_H264)
  1001.                         av_log(s->avctx, AV_LOG_DEBUG, "=");
  1002.                     else
  1003.                         av_log(s->avctx, AV_LOG_DEBUG, " ");
  1004.                 }
  1005. //                av_log(s->avctx, AV_LOG_DEBUG, " ");
  1006.             }
  1007.             av_log(s->avctx, AV_LOG_DEBUG, "n");
  1008.         }
  1009.     }
  1010.     if((s->avctx->debug&(FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) || (s->avctx->debug_mv)){
  1011.         const int shift= 1 + s->quarter_sample;
  1012.         int mb_y;
  1013.         uint8_t *ptr;
  1014.         int i;
  1015.         int h_chroma_shift, v_chroma_shift;
  1016.         const int width = s->avctx->width;
  1017.         const int height= s->avctx->height;
  1018.         const int mv_sample_log2= 4 - pict->motion_subsample_log2;
  1019.         const int mv_stride= (s->mb_width << mv_sample_log2) + (s->codec_id == CODEC_ID_H264 ? 0 : 1);
  1020.         s->low_delay=0; //needed to see the vectors without trashing the buffers
  1021.         avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
  1022.         for(i=0; i<3; i++){
  1023.             memcpy(s->visualization_buffer[i], pict->data[i], (i==0) ? pict->linesize[i]*height:pict->linesize[i]*height >> v_chroma_shift);
  1024.             pict->data[i]= s->visualization_buffer[i];
  1025.         }
  1026.         pict->type= FF_BUFFER_TYPE_COPY;
  1027.         ptr= pict->data[0];
  1028.         for(mb_y=0; mb_y<s->mb_height; mb_y++){
  1029.             int mb_x;
  1030.             for(mb_x=0; mb_x<s->mb_width; mb_x++){
  1031.                 const int mb_index= mb_x + mb_y*s->mb_stride;
  1032.                 if((s->avctx->debug_mv) && pict->motion_val){
  1033.                   int type;
  1034.                   for(type=0; type<3; type++){
  1035.                     int direction = 0;
  1036.                     switch (type) {
  1037.                       case 0: if ((!(s->avctx->debug_mv&FF_DEBUG_VIS_MV_P_FOR)) || (pict->pict_type!=FF_P_TYPE))
  1038.                                 continue;
  1039.                               direction = 0;
  1040.                               break;
  1041.                       case 1: if ((!(s->avctx->debug_mv&FF_DEBUG_VIS_MV_B_FOR)) || (pict->pict_type!=FF_B_TYPE))
  1042.                                 continue;
  1043.                               direction = 0;
  1044.                               break;
  1045.                       case 2: if ((!(s->avctx->debug_mv&FF_DEBUG_VIS_MV_B_BACK)) || (pict->pict_type!=FF_B_TYPE))
  1046.                                 continue;
  1047.                               direction = 1;
  1048.                               break;
  1049.                     }
  1050.                     if(!USES_LIST(pict->mb_type[mb_index], direction))
  1051.                         continue;
  1052.                     if(IS_8X8(pict->mb_type[mb_index])){
  1053.                       int i;
  1054.                       for(i=0; i<4; i++){
  1055.                         int sx= mb_x*16 + 4 + 8*(i&1);
  1056.                         int sy= mb_y*16 + 4 + 8*(i>>1);
  1057.                         int xy= (mb_x*2 + (i&1) + (mb_y*2 + (i>>1))*mv_stride) << (mv_sample_log2-1);
  1058.                         int mx= (pict->motion_val[direction][xy][0]>>shift) + sx;
  1059.                         int my= (pict->motion_val[direction][xy][1]>>shift) + sy;
  1060.                         draw_arrow(ptr, sx, sy, mx, my, width, height, s->linesize, 100);
  1061.                       }
  1062.                     }else if(IS_16X8(pict->mb_type[mb_index])){
  1063.                       int i;
  1064.                       for(i=0; i<2; i++){
  1065.                         int sx=mb_x*16 + 8;
  1066.                         int sy=mb_y*16 + 4 + 8*i;
  1067.                         int xy= (mb_x*2 + (mb_y*2 + i)*mv_stride) << (mv_sample_log2-1);
  1068.                         int mx=(pict->motion_val[direction][xy][0]>>shift);
  1069.                         int my=(pict->motion_val[direction][xy][1]>>shift);
  1070.                         if(IS_INTERLACED(pict->mb_type[mb_index]))
  1071.                             my*=2;
  1072.                         draw_arrow(ptr, sx, sy, mx+sx, my+sy, width, height, s->linesize, 100);
  1073.                       }
  1074.                     }else if(IS_8X16(pict->mb_type[mb_index])){
  1075.                       int i;
  1076.                       for(i=0; i<2; i++){
  1077.                         int sx=mb_x*16 + 4 + 8*i;
  1078.                         int sy=mb_y*16 + 8;
  1079.                         int xy= (mb_x*2 + i + mb_y*2*mv_stride) << (mv_sample_log2-1);
  1080.                         int mx=(pict->motion_val[direction][xy][0]>>shift);
  1081.                         int my=(pict->motion_val[direction][xy][1]>>shift);
  1082.                         if(IS_INTERLACED(pict->mb_type[mb_index]))
  1083.                             my*=2;
  1084.                         draw_arrow(ptr, sx, sy, mx+sx, my+sy, width, height, s->linesize, 100);
  1085.                       }
  1086.                     }else{
  1087.                       int sx= mb_x*16 + 8;
  1088.                       int sy= mb_y*16 + 8;
  1089.                       int xy= (mb_x + mb_y*mv_stride) << mv_sample_log2;
  1090.                       int mx= (pict->motion_val[direction][xy][0]>>shift) + sx;
  1091.                       int my= (pict->motion_val[direction][xy][1]>>shift) + sy;
  1092.                       draw_arrow(ptr, sx, sy, mx, my, width, height, s->linesize, 100);
  1093.                     }
  1094.                   }
  1095.                 }
  1096.                 if((s->avctx->debug&FF_DEBUG_VIS_QP) && pict->motion_val){
  1097.                     uint64_t c= (pict->qscale_table[mb_index]*128/31) * 0x0101010101010101;
  1098.                     int y;
  1099.                     for(y=0; y<8; y++){
  1100.                         *(uint64_t*)(pict->data[1] + 8*mb_x + (8*mb_y + y)*pict->linesize[1])= c;
  1101.                         *(uint64_t*)(pict->data[2] + 8*mb_x + (8*mb_y + y)*pict->linesize[2])= c;
  1102.                     }
  1103.                 }
  1104.                 if((s->avctx->debug&FF_DEBUG_VIS_MB_TYPE) && pict->motion_val){
  1105.                     int mb_type= pict->mb_type[mb_index];
  1106.                     uint64_t u,v;
  1107.                     int y;
  1108. #define COLOR(theta, r)
  1109. u= (int)(128 + r*cos(theta*3.141592/180));
  1110. v= (int)(128 + r*sin(theta*3.141592/180));
  1111.                     u=v=128;
  1112.                     if(IS_PCM(mb_type)){
  1113.                         COLOR(120,48)
  1114.                     }else if((IS_INTRA(mb_type) && IS_ACPRED(mb_type)) || IS_INTRA16x16(mb_type)){
  1115.                         COLOR(30,48)
  1116.                     }else if(IS_INTRA4x4(mb_type)){
  1117.                         COLOR(90,48)
  1118.                     }else if(IS_DIRECT(mb_type) && IS_SKIP(mb_type)){
  1119. //                        COLOR(120,48)
  1120.                     }else if(IS_DIRECT(mb_type)){
  1121.                         COLOR(150,48)
  1122.                     }else if(IS_GMC(mb_type) && IS_SKIP(mb_type)){
  1123.                         COLOR(170,48)
  1124.                     }else if(IS_GMC(mb_type)){
  1125.                         COLOR(190,48)
  1126.                     }else if(IS_SKIP(mb_type)){
  1127. //                        COLOR(180,48)
  1128.                     }else if(!USES_LIST(mb_type, 1)){
  1129.                         COLOR(240,48)
  1130.                     }else if(!USES_LIST(mb_type, 0)){
  1131.                         COLOR(0,48)
  1132.                     }else{
  1133.                         assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
  1134.                         COLOR(300,48)
  1135.                     }
  1136.                     u*= 0x0101010101010101;
  1137.                     v*= 0x0101010101010101;
  1138.                     for(y=0; y<8; y++){
  1139.                         *(uint64_t*)(pict->data[1] + 8*mb_x + (8*mb_y + y)*pict->linesize[1])= u;
  1140.                         *(uint64_t*)(pict->data[2] + 8*mb_x + (8*mb_y + y)*pict->linesize[2])= v;
  1141.                     }
  1142.                     //segmentation
  1143.                     if(IS_8X8(mb_type) || IS_16X8(mb_type)){
  1144.                         *(uint64_t*)(pict->data[0] + 16*mb_x + 0 + (16*mb_y + 8)*pict->linesize[0])^= 0x8080808080808080;
  1145.                         *(uint64_t*)(pict->data[0] + 16*mb_x + 8 + (16*mb_y + 8)*pict->linesize[0])^= 0x8080808080808080;
  1146.                     }
  1147.                     if(IS_8X8(mb_type) || IS_8X16(mb_type)){
  1148.                         for(y=0; y<16; y++)
  1149.                             pict->data[0][16*mb_x + 8 + (16*mb_y + y)*pict->linesize[0]]^= 0x80;
  1150.                     }
  1151.                     if(IS_8X8(mb_type) && mv_sample_log2 >= 2){
  1152.                         int dm= 1 << (mv_sample_log2-2);
  1153.                         for(i=0; i<4; i++){
  1154.                             int sx= mb_x*16 + 8*(i&1);
  1155.                             int sy= mb_y*16 + 8*(i>>1);
  1156.                             int xy= (mb_x*2 + (i&1) + (mb_y*2 + (i>>1))*mv_stride) << (mv_sample_log2-1);
  1157.                             //FIXME bidir
  1158.                             int32_t *mv = (int32_t*)&pict->motion_val[0][xy];
  1159.                             if(mv[0] != mv[dm] || mv[dm*mv_stride] != mv[dm*(mv_stride+1)])
  1160.                                 for(y=0; y<8; y++)
  1161.                                     pict->data[0][sx + 4 + (sy + y)*pict->linesize[0]]^= 0x80;
  1162.                             if(mv[0] != mv[dm*mv_stride] || mv[dm] != mv[dm*(mv_stride+1)])
  1163.                                 *(uint64_t*)(pict->data[0] + sx + (sy + 4)*pict->linesize[0])^= 0x8080808080808080;
  1164.                         }
  1165.                     }
  1166.                     if(IS_INTERLACED(mb_type) && s->codec_id == CODEC_ID_H264){
  1167.                         // hmm
  1168.                     }
  1169.                 }
  1170.                 s->mbskip_table[mb_index]=0;
  1171.             }
  1172.         }
  1173.     }
  1174. }
  1175. static inline int hpel_motion_lowres(MpegEncContext *s,
  1176.                                   uint8_t *dest, uint8_t *src,
  1177.                                   int field_based, int field_select,
  1178.                                   int src_x, int src_y,
  1179.                                   int width, int height, int stride,
  1180.                                   int h_edge_pos, int v_edge_pos,
  1181.                                   int w, int h, h264_chroma_mc_func *pix_op,
  1182.                                   int motion_x, int motion_y)
  1183. {
  1184.     const int lowres= s->avctx->lowres;
  1185.     const int s_mask= (2<<lowres)-1;
  1186.     int emu=0;
  1187.     int sx, sy;
  1188.     if(s->quarter_sample){
  1189.         motion_x/=2;
  1190.         motion_y/=2;
  1191.     }
  1192.     sx= motion_x & s_mask;
  1193.     sy= motion_y & s_mask;
  1194.     src_x += motion_x >> (lowres+1);
  1195.     src_y += motion_y >> (lowres+1);
  1196.     src += src_y * stride + src_x;
  1197.     if(   (unsigned)src_x > h_edge_pos                 - (!!sx) - w
  1198.        || (unsigned)src_y >(v_edge_pos >> field_based) - (!!sy) - h){
  1199.         ff_emulated_edge_mc(s->edge_emu_buffer, src, s->linesize, w+1, (h+1)<<field_based,
  1200.                             src_x, src_y<<field_based, h_edge_pos, v_edge_pos);
  1201.         src= s->edge_emu_buffer;
  1202.         emu=1;
  1203.     }
  1204.     sx <<= 2 - lowres;
  1205.     sy <<= 2 - lowres;
  1206.     if(field_select)
  1207.         src += s->linesize;
  1208.     pix_op[lowres](dest, src, stride, h, sx, sy);
  1209.     return emu;
  1210. }
  1211. /* apply one mpeg motion vector to the three components */
  1212. static av_always_inline void mpeg_motion_lowres(MpegEncContext *s,
  1213.                                uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1214.                                int field_based, int bottom_field, int field_select,
  1215.                                uint8_t **ref_picture, h264_chroma_mc_func *pix_op,
  1216.                                int motion_x, int motion_y, int h)
  1217. {
  1218.     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  1219.     int mx, my, src_x, src_y, uvsrc_x, uvsrc_y, uvlinesize, linesize, sx, sy, uvsx, uvsy;
  1220.     const int lowres= s->avctx->lowres;
  1221.     const int block_s= 8>>lowres;
  1222.     const int s_mask= (2<<lowres)-1;
  1223.     const int h_edge_pos = s->h_edge_pos >> lowres;
  1224.     const int v_edge_pos = s->v_edge_pos >> lowres;
  1225.     linesize   = s->current_picture.linesize[0] << field_based;
  1226.     uvlinesize = s->current_picture.linesize[1] << field_based;
  1227.     if(s->quarter_sample){ //FIXME obviously not perfect but qpel wont work in lowres anyway
  1228.         motion_x/=2;
  1229.         motion_y/=2;
  1230.     }
  1231.     if(field_based){
  1232.         motion_y += (bottom_field - field_select)*((1<<lowres)-1);
  1233.     }
  1234.     sx= motion_x & s_mask;
  1235.     sy= motion_y & s_mask;
  1236.     src_x = s->mb_x*2*block_s               + (motion_x >> (lowres+1));
  1237.     src_y =(s->mb_y*2*block_s>>field_based) + (motion_y >> (lowres+1));
  1238.     if (s->out_format == FMT_H263) {
  1239.         uvsx = ((motion_x>>1) & s_mask) | (sx&1);
  1240.         uvsy = ((motion_y>>1) & s_mask) | (sy&1);
  1241.         uvsrc_x = src_x>>1;
  1242.         uvsrc_y = src_y>>1;
  1243.     }else if(s->out_format == FMT_H261){//even chroma mv's are full pel in H261
  1244.         mx = motion_x / 4;
  1245.         my = motion_y / 4;
  1246.         uvsx = (2*mx) & s_mask;
  1247.         uvsy = (2*my) & s_mask;
  1248.         uvsrc_x = s->mb_x*block_s               + (mx >> lowres);
  1249.         uvsrc_y = s->mb_y*block_s               + (my >> lowres);
  1250.     } else {
  1251.         mx = motion_x / 2;
  1252.         my = motion_y / 2;
  1253.         uvsx = mx & s_mask;
  1254.         uvsy = my & s_mask;
  1255.         uvsrc_x = s->mb_x*block_s               + (mx >> (lowres+1));
  1256.         uvsrc_y =(s->mb_y*block_s>>field_based) + (my >> (lowres+1));
  1257.     }
  1258.     ptr_y  = ref_picture[0] + src_y * linesize + src_x;
  1259.     ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;
  1260.     ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;
  1261.     if(   (unsigned)src_x > h_edge_pos                 - (!!sx) - 2*block_s
  1262.        || (unsigned)src_y >(v_edge_pos >> field_based) - (!!sy) - h){
  1263.             ff_emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize, 17, 17+field_based,
  1264.                              src_x, src_y<<field_based, h_edge_pos, v_edge_pos);
  1265.             ptr_y = s->edge_emu_buffer;
  1266.             if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1267.                 uint8_t *uvbuf= s->edge_emu_buffer+18*s->linesize;
  1268.                 ff_emulated_edge_mc(uvbuf  , ptr_cb, s->uvlinesize, 9, 9+field_based,
  1269.                                  uvsrc_x, uvsrc_y<<field_based, h_edge_pos>>1, v_edge_pos>>1);
  1270.                 ff_emulated_edge_mc(uvbuf+16, ptr_cr, s->uvlinesize, 9, 9+field_based,
  1271.                                  uvsrc_x, uvsrc_y<<field_based, h_edge_pos>>1, v_edge_pos>>1);
  1272.                 ptr_cb= uvbuf;
  1273.                 ptr_cr= uvbuf+16;
  1274.             }
  1275.     }
  1276.     if(bottom_field){ //FIXME use this for field pix too instead of the obnoxious hack which changes picture.data
  1277.         dest_y += s->linesize;
  1278.         dest_cb+= s->uvlinesize;
  1279.         dest_cr+= s->uvlinesize;
  1280.     }
  1281.     if(field_select){
  1282.         ptr_y += s->linesize;
  1283.         ptr_cb+= s->uvlinesize;
  1284.         ptr_cr+= s->uvlinesize;
  1285.     }
  1286.     sx <<= 2 - lowres;
  1287.     sy <<= 2 - lowres;
  1288.     pix_op[lowres-1](dest_y, ptr_y, linesize, h, sx, sy);
  1289.     if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1290.         uvsx <<= 2 - lowres;
  1291.         uvsy <<= 2 - lowres;
  1292.         pix_op[lowres](dest_cb, ptr_cb, uvlinesize, h >> s->chroma_y_shift, uvsx, uvsy);
  1293.         pix_op[lowres](dest_cr, ptr_cr, uvlinesize, h >> s->chroma_y_shift, uvsx, uvsy);
  1294.     }
  1295.     //FIXME h261 lowres loop filter
  1296. }
  1297. static inline void chroma_4mv_motion_lowres(MpegEncContext *s,
  1298.                                      uint8_t *dest_cb, uint8_t *dest_cr,
  1299.                                      uint8_t **ref_picture,
  1300.                                      h264_chroma_mc_func *pix_op,
  1301.                                      int mx, int my){
  1302.     const int lowres= s->avctx->lowres;
  1303.     const int block_s= 8>>lowres;
  1304.     const int s_mask= (2<<lowres)-1;
  1305.     const int h_edge_pos = s->h_edge_pos >> (lowres+1);
  1306.     const int v_edge_pos = s->v_edge_pos >> (lowres+1);
  1307.     int emu=0, src_x, src_y, offset, sx, sy;
  1308.     uint8_t *ptr;
  1309.     if(s->quarter_sample){
  1310.         mx/=2;
  1311.         my/=2;
  1312.     }
  1313.     /* In case of 8X8, we construct a single chroma motion vector
  1314.        with a special rounding */
  1315.     mx= ff_h263_round_chroma(mx);
  1316.     my= ff_h263_round_chroma(my);
  1317.     sx= mx & s_mask;
  1318.     sy= my & s_mask;
  1319.     src_x = s->mb_x*block_s + (mx >> (lowres+1));
  1320.     src_y = s->mb_y*block_s + (my >> (lowres+1));
  1321.     offset = src_y * s->uvlinesize + src_x;
  1322.     ptr = ref_picture[1] + offset;
  1323.     if(s->flags&CODEC_FLAG_EMU_EDGE){
  1324.         if(   (unsigned)src_x > h_edge_pos - (!!sx) - block_s
  1325.            || (unsigned)src_y > v_edge_pos - (!!sy) - block_s){
  1326.             ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, h_edge_pos, v_edge_pos);
  1327.             ptr= s->edge_emu_buffer;
  1328.             emu=1;
  1329.         }
  1330.     }
  1331.     sx <<= 2 - lowres;
  1332.     sy <<= 2 - lowres;
  1333.     pix_op[lowres](dest_cb, ptr, s->uvlinesize, block_s, sx, sy);
  1334.     ptr = ref_picture[2] + offset;
  1335.     if(emu){
  1336.         ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, h_edge_pos, v_edge_pos);
  1337.         ptr= s->edge_emu_buffer;
  1338.     }
  1339.     pix_op[lowres](dest_cr, ptr, s->uvlinesize, block_s, sx, sy);
  1340. }
  1341. /**
  1342.  * motion compensation of a single macroblock
  1343.  * @param s context
  1344.  * @param dest_y luma destination pointer
  1345.  * @param dest_cb chroma cb/u destination pointer
  1346.  * @param dest_cr chroma cr/v destination pointer
  1347.  * @param dir direction (0->forward, 1->backward)
  1348.  * @param ref_picture array[3] of pointers to the 3 planes of the reference picture
  1349.  * @param pic_op halfpel motion compensation function (average or put normally)
  1350.  * the motion vectors are taken from s->mv and the MV type from s->mv_type
  1351.  */
  1352. static inline void MPV_motion_lowres(MpegEncContext *s,
  1353.                               uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1354.                               int dir, uint8_t **ref_picture,
  1355.                               h264_chroma_mc_func *pix_op)
  1356. {
  1357.     int mx, my;
  1358.     int mb_x, mb_y, i;
  1359.     const int lowres= s->avctx->lowres;
  1360.     const int block_s= 8>>lowres;
  1361.     mb_x = s->mb_x;
  1362.     mb_y = s->mb_y;
  1363.     switch(s->mv_type) {
  1364.     case MV_TYPE_16X16:
  1365.         mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1366.                     0, 0, 0,
  1367.                     ref_picture, pix_op,
  1368.                     s->mv[dir][0][0], s->mv[dir][0][1], 2*block_s);
  1369.         break;
  1370.     case MV_TYPE_8X8:
  1371.         mx = 0;
  1372.         my = 0;
  1373.             for(i=0;i<4;i++) {
  1374.                 hpel_motion_lowres(s, dest_y + ((i & 1) + (i >> 1) * s->linesize)*block_s,
  1375.                             ref_picture[0], 0, 0,
  1376.                             (2*mb_x + (i & 1))*block_s, (2*mb_y + (i >>1))*block_s,
  1377.                             s->width, s->height, s->linesize,
  1378.                             s->h_edge_pos >> lowres, s->v_edge_pos >> lowres,
  1379.                             block_s, block_s, pix_op,
  1380.                             s->mv[dir][i][0], s->mv[dir][i][1]);
  1381.                 mx += s->mv[dir][i][0];
  1382.                 my += s->mv[dir][i][1];
  1383.             }
  1384.         if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY))
  1385.             chroma_4mv_motion_lowres(s, dest_cb, dest_cr, ref_picture, pix_op, mx, my);
  1386.         break;
  1387.     case MV_TYPE_FIELD:
  1388.         if (s->picture_structure == PICT_FRAME) {
  1389.             /* top field */
  1390.             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1391.                         1, 0, s->field_select[dir][0],
  1392.                         ref_picture, pix_op,
  1393.                         s->mv[dir][0][0], s->mv[dir][0][1], block_s);
  1394.             /* bottom field */
  1395.             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1396.                         1, 1, s->field_select[dir][1],
  1397.                         ref_picture, pix_op,
  1398.                         s->mv[dir][1][0], s->mv[dir][1][1], block_s);
  1399.         } else {
  1400.             if(s->picture_structure != s->field_select[dir][0] + 1 && s->pict_type != FF_B_TYPE && !s->first_field){
  1401.                 ref_picture= s->current_picture_ptr->data;
  1402.             }
  1403.             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1404.                         0, 0, s->field_select[dir][0],
  1405.                         ref_picture, pix_op,
  1406.                         s->mv[dir][0][0], s->mv[dir][0][1], 2*block_s);
  1407.         }
  1408.         break;
  1409.     case MV_TYPE_16X8:
  1410.         for(i=0; i<2; i++){
  1411.             uint8_t ** ref2picture;
  1412.             if(s->picture_structure == s->field_select[dir][i] + 1 || s->pict_type == FF_B_TYPE || s->first_field){
  1413.                 ref2picture= ref_picture;
  1414.             }else{
  1415.                 ref2picture= s->current_picture_ptr->data;
  1416.             }
  1417.             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1418.                         0, 0, s->field_select[dir][i],
  1419.                         ref2picture, pix_op,
  1420.                         s->mv[dir][i][0], s->mv[dir][i][1] + 2*block_s*i, block_s);
  1421.             dest_y += 2*block_s*s->linesize;
  1422.             dest_cb+= (2*block_s>>s->chroma_y_shift)*s->uvlinesize;
  1423.             dest_cr+= (2*block_s>>s->chroma_y_shift)*s->uvlinesize;
  1424.         }
  1425.         break;
  1426.     case MV_TYPE_DMV:
  1427.         if(s->picture_structure == PICT_FRAME){
  1428.             for(i=0; i<2; i++){
  1429.                 int j;
  1430.                 for(j=0; j<2; j++){
  1431.                     mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1432.                                 1, j, j^i,
  1433.                                 ref_picture, pix_op,
  1434.                                 s->mv[dir][2*i + j][0], s->mv[dir][2*i + j][1], block_s);
  1435.                 }
  1436.                 pix_op = s->dsp.avg_h264_chroma_pixels_tab;
  1437.             }
  1438.         }else{
  1439.             for(i=0; i<2; i++){
  1440.                 mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1441.                             0, 0, s->picture_structure != i+1,
  1442.                             ref_picture, pix_op,
  1443.                             s->mv[dir][2*i][0],s->mv[dir][2*i][1],2*block_s);
  1444.                 // after put we make avg of the same block
  1445.                 pix_op = s->dsp.avg_h264_chroma_pixels_tab;
  1446.                 //opposite parity is always in the same frame if this is second field
  1447.                 if(!s->first_field){
  1448.                     ref_picture = s->current_picture_ptr->data;
  1449.                 }
  1450.             }
  1451.         }
  1452.     break;
  1453.     default: assert(0);
  1454.     }
  1455. }
  1456. /* put block[] to dest[] */
  1457. static inline void put_dct(MpegEncContext *s,
  1458.                            DCTELEM *block, int i, uint8_t *dest, int line_size, int qscale)
  1459. {
  1460.     s->dct_unquantize_intra(s, block, i, qscale);
  1461.     s->dsp.idct_put (dest, line_size, block);
  1462. }
  1463. /* add block[] to dest[] */
  1464. static inline void add_dct(MpegEncContext *s,
  1465.                            DCTELEM *block, int i, uint8_t *dest, int line_size)
  1466. {
  1467.     if (s->block_last_index[i] >= 0) {
  1468.         s->dsp.idct_add (dest, line_size, block);
  1469.     }
  1470. }
  1471. static inline void add_dequant_dct(MpegEncContext *s,
  1472.                            DCTELEM *block, int i, uint8_t *dest, int line_size, int qscale)
  1473. {
  1474.     if (s->block_last_index[i] >= 0) {
  1475.         s->dct_unquantize_inter(s, block, i, qscale);
  1476.         s->dsp.idct_add (dest, line_size, block);
  1477.     }
  1478. }
  1479. /**
  1480.  * cleans dc, ac, coded_block for the current non intra MB
  1481.  */
  1482. void ff_clean_intra_table_entries(MpegEncContext *s)
  1483. {
  1484.     int wrap = s->b8_stride;
  1485.     int xy = s->block_index[0];
  1486.     s->dc_val[0][xy           ] =
  1487.     s->dc_val[0][xy + 1       ] =
  1488.     s->dc_val[0][xy     + wrap] =
  1489.     s->dc_val[0][xy + 1 + wrap] = 1024;
  1490.     /* ac pred */
  1491.     memset(s->ac_val[0][xy       ], 0, 32 * sizeof(int16_t));
  1492.     memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(int16_t));
  1493.     if (s->msmpeg4_version>=3) {
  1494.         s->coded_block[xy           ] =
  1495.         s->coded_block[xy + 1       ] =
  1496.         s->coded_block[xy     + wrap] =
  1497.         s->coded_block[xy + 1 + wrap] = 0;
  1498.     }
  1499.     /* chroma */
  1500.     wrap = s->mb_stride;
  1501.     xy = s->mb_x + s->mb_y * wrap;
  1502.     s->dc_val[1][xy] =
  1503.     s->dc_val[2][xy] = 1024;
  1504.     /* ac pred */
  1505.     memset(s->ac_val[1][xy], 0, 16 * sizeof(int16_t));
  1506.     memset(s->ac_val[2][xy], 0, 16 * sizeof(int16_t));
  1507.     s->mbintra_table[xy]= 0;
  1508. }
  1509. /* generic function called after a macroblock has been parsed by the
  1510.    decoder or after it has been encoded by the encoder.
  1511.    Important variables used:
  1512.    s->mb_intra : true if intra macroblock
  1513.    s->mv_dir   : motion vector direction
  1514.    s->mv_type  : motion vector type
  1515.    s->mv       : motion vector
  1516.    s->interlaced_dct : true if interlaced dct used (mpeg2)
  1517.  */
  1518. static av_always_inline
  1519. void MPV_decode_mb_internal(MpegEncContext *s, DCTELEM block[12][64],
  1520.                             int lowres_flag, int is_mpeg12)
  1521. {
  1522.     int mb_x, mb_y;
  1523.     const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
  1524. #ifdef HAVE_XVMC
  1525.     if(s->avctx->xvmc_acceleration){
  1526.         XVMC_decode_mb(s);//xvmc uses pblocks
  1527.         return;
  1528.     }
  1529. #endif
  1530.     mb_x = s->mb_x;
  1531.     mb_y = s->mb_y;
  1532.     if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {
  1533.        /* save DCT coefficients */
  1534.        int i,j;
  1535.        DCTELEM *dct = &s->current_picture.dct_coeff[mb_xy*64*6];
  1536.        for(i=0; i<6; i++)
  1537.            for(j=0; j<64; j++)
  1538.                *dct++ = block[i][s->dsp.idct_permutation[j]];
  1539.     }
  1540.     s->current_picture.qscale_table[mb_xy]= s->qscale;
  1541.     /* update DC predictors for P macroblocks */
  1542.     if (!s->mb_intra) {
  1543.         if (!is_mpeg12 && (s->h263_pred || s->h263_aic)) {
  1544.             if(s->mbintra_table[mb_xy])
  1545.                 ff_clean_intra_table_entries(s);
  1546.         } else {
  1547.             s->last_dc[0] =
  1548.             s->last_dc[1] =
  1549.             s->last_dc[2] = 128 << s->intra_dc_precision;
  1550.         }
  1551.     }
  1552.     else if (!is_mpeg12 && (s->h263_pred || s->h263_aic))
  1553.         s->mbintra_table[mb_xy]=1;
  1554.     if ((s->flags&CODEC_FLAG_PSNR) || !(s->encoding && (s->intra_only || s->pict_type==FF_B_TYPE) && s->avctx->mb_decision != FF_MB_DECISION_RD)) { //FIXME precalc
  1555.         uint8_t *dest_y, *dest_cb, *dest_cr;
  1556.         int dct_linesize, dct_offset;
  1557.         op_pixels_func (*op_pix)[4];
  1558.         qpel_mc_func (*op_qpix)[16];
  1559.         const int linesize= s->current_picture.linesize[0]; //not s->linesize as this would be wrong for field pics
  1560.         const int uvlinesize= s->current_picture.linesize[1];
  1561.         const int readable= s->pict_type != FF_B_TYPE || s->encoding || s->avctx->draw_horiz_band || lowres_flag;
  1562.         const int block_size= lowres_flag ? 8>>s->avctx->lowres : 8;
  1563.         /* avoid copy if macroblock skipped in last frame too */
  1564.         /* skip only during decoding as we might trash the buffers during encoding a bit */
  1565.         if(!s->encoding){
  1566.             uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];
  1567.             const int age= s->current_picture.age;
  1568.             assert(age);
  1569.             if (s->mb_skipped) {
  1570.                 s->mb_skipped= 0;
  1571.                 assert(s->pict_type!=FF_I_TYPE);
  1572.                 (*mbskip_ptr) ++; /* indicate that this time we skipped it */
  1573.                 if(*mbskip_ptr >99) *mbskip_ptr= 99;
  1574.                 /* if previous was skipped too, then nothing to do !  */
  1575.                 if (*mbskip_ptr >= age && s->current_picture.reference){
  1576.                     return;
  1577.                 }
  1578.             } else if(!s->current_picture.reference){
  1579.                 (*mbskip_ptr) ++; /* increase counter so the age can be compared cleanly */
  1580.                 if(*mbskip_ptr >99) *mbskip_ptr= 99;
  1581.             } else{
  1582.                 *mbskip_ptr = 0; /* not skipped */
  1583.             }
  1584.         }
  1585.         dct_linesize = linesize << s->interlaced_dct;
  1586.         dct_offset =(s->interlaced_dct)? linesize : linesize*block_size;
  1587.         if(readable){
  1588.             dest_y=  s->dest[0];
  1589.             dest_cb= s->dest[1];
  1590.             dest_cr= s->dest[2];
  1591.         }else{
  1592.             dest_y = s->b_scratchpad;
  1593.             dest_cb= s->b_scratchpad+16*linesize;
  1594.             dest_cr= s->b_scratchpad+32*linesize;
  1595.         }
  1596.         if (!s->mb_intra) {
  1597.             /* motion handling */
  1598.             /* decoding or more than one mb_type (MC was already done otherwise) */
  1599.             if(!s->encoding){
  1600.                 if(lowres_flag){
  1601.                     h264_chroma_mc_func *op_pix = s->dsp.put_h264_chroma_pixels_tab;
  1602.                     if (s->mv_dir & MV_DIR_FORWARD) {
  1603.                         MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix);
  1604.                         op_pix = s->dsp.avg_h264_chroma_pixels_tab;
  1605.                     }
  1606.                     if (s->mv_dir & MV_DIR_BACKWARD) {
  1607.                         MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix);
  1608.                     }
  1609.                 }else{
  1610.                     op_qpix= s->me.qpel_put;
  1611.                     if ((!s->no_rounding) || s->pict_type==FF_B_TYPE){
  1612.                         op_pix = s->dsp.put_pixels_tab;
  1613.                     }else{
  1614.                         op_pix = s->dsp.put_no_rnd_pixels_tab;
  1615.                     }
  1616.                     if (s->mv_dir & MV_DIR_FORWARD) {
  1617.                         MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
  1618.                         op_pix = s->dsp.avg_pixels_tab;
  1619.                         op_qpix= s->me.qpel_avg;
  1620.                     }
  1621.                     if (s->mv_dir & MV_DIR_BACKWARD) {
  1622.                         MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
  1623.                     }
  1624.                 }
  1625.             }
  1626.             /* skip dequant / idct if we are really late ;) */
  1627.             if(s->hurry_up>1) goto skip_idct;
  1628.             if(s->avctx->skip_idct){
  1629.                 if(  (s->avctx->skip_idct >= AVDISCARD_NONREF && s->pict_type == FF_B_TYPE)
  1630.                    ||(s->avctx->skip_idct >= AVDISCARD_NONKEY && s->pict_type != FF_I_TYPE)
  1631.                    || s->avctx->skip_idct >= AVDISCARD_ALL)
  1632.                     goto skip_idct;
  1633.             }
  1634.             /* add dct residue */
  1635.             if(s->encoding || !(   s->h263_msmpeg4 || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO
  1636.                                 || (s->codec_id==CODEC_ID_MPEG4 && !s->mpeg_quant))){
  1637.                 add_dequant_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);
  1638.                 add_dequant_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);
  1639.                 add_dequant_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);
  1640.                 add_dequant_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);
  1641.                 if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1642.                     if (s->chroma_y_shift){
  1643.                         add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
  1644.                         add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
  1645.                     }else{
  1646.                         dct_linesize >>= 1;
  1647.                         dct_offset >>=1;
  1648.                         add_dequant_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);
  1649.                         add_dequant_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);
  1650.                         add_dequant_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);
  1651.                         add_dequant_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);
  1652.                     }
  1653.                 }
  1654.             } else if(is_mpeg12 || (s->codec_id != CODEC_ID_WMV2)){
  1655.                 add_dct(s, block[0], 0, dest_y                          , dct_linesize);
  1656.                 add_dct(s, block[1], 1, dest_y              + block_size, dct_linesize);
  1657.                 add_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize);
  1658.                 add_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize);
  1659.                 if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1660.                     if(s->chroma_y_shift){//Chroma420
  1661.                         add_dct(s, block[4], 4, dest_cb, uvlinesize);
  1662.                         add_dct(s, block[5], 5, dest_cr, uvlinesize);
  1663.                     }else{
  1664.                         //chroma422
  1665.                         dct_linesize = uvlinesize << s->interlaced_dct;
  1666.                         dct_offset =(s->interlaced_dct)? uvlinesize : uvlinesize*8;
  1667.                         add_dct(s, block[4], 4, dest_cb, dct_linesize);
  1668.                         add_dct(s, block[5], 5, dest_cr, dct_linesize);
  1669.                         add_dct(s, block[6], 6, dest_cb+dct_offset, dct_linesize);
  1670.                         add_dct(s, block[7], 7, dest_cr+dct_offset, dct_linesize);
  1671.                         if(!s->chroma_x_shift){//Chroma444
  1672.                             add_dct(s, block[8], 8, dest_cb+8, dct_linesize);
  1673.                             add_dct(s, block[9], 9, dest_cr+8, dct_linesize);
  1674.                             add_dct(s, block[10], 10, dest_cb+8+dct_offset, dct_linesize);
  1675.                             add_dct(s, block[11], 11, dest_cr+8+dct_offset, dct_linesize);
  1676.                         }
  1677.                     }
  1678.                 }//fi gray
  1679.             }
  1680.             else if (1) {
  1681. //                ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);
  1682.             }
  1683.         } else {
  1684.             /* dct only in intra block */
  1685.             if(s->encoding || !(s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO)){
  1686.                 put_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);
  1687.                 put_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);
  1688.                 put_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);
  1689.                 put_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);
  1690.                 if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1691.                     if(s->chroma_y_shift){
  1692.                         put_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
  1693.                         put_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
  1694.                     }else{
  1695.                         dct_offset >>=1;
  1696.                         dct_linesize >>=1;
  1697.                         put_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);
  1698.                         put_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);
  1699.                         put_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);
  1700.                         put_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);
  1701.                     }
  1702.                 }
  1703.             }else{
  1704.                 s->dsp.idct_put(dest_y                          , dct_linesize, block[0]);
  1705.                 s->dsp.idct_put(dest_y              + block_size, dct_linesize, block[1]);
  1706.                 s->dsp.idct_put(dest_y + dct_offset             , dct_linesize, block[2]);
  1707.                 s->dsp.idct_put(dest_y + dct_offset + block_size, dct_linesize, block[3]);
  1708.                 if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1709.                     if(s->chroma_y_shift){
  1710.                         s->dsp.idct_put(dest_cb, uvlinesize, block[4]);
  1711.                         s->dsp.idct_put(dest_cr, uvlinesize, block[5]);
  1712.                     }else{
  1713.                         dct_linesize = uvlinesize << s->interlaced_dct;
  1714.                         dct_offset =(s->interlaced_dct)? uvlinesize : uvlinesize*8;
  1715.                         s->dsp.idct_put(dest_cb,              dct_linesize, block[4]);
  1716.                         s->dsp.idct_put(dest_cr,              dct_linesize, block[5]);
  1717.                         s->dsp.idct_put(dest_cb + dct_offset, dct_linesize, block[6]);
  1718.                         s->dsp.idct_put(dest_cr + dct_offset, dct_linesize, block[7]);
  1719.                         if(!s->chroma_x_shift){//Chroma444
  1720.                             s->dsp.idct_put(dest_cb + 8,              dct_linesize, block[8]);
  1721.                             s->dsp.idct_put(dest_cr + 8,              dct_linesize, block[9]);
  1722.                             s->dsp.idct_put(dest_cb + 8 + dct_offset, dct_linesize, block[10]);
  1723.                             s->dsp.idct_put(dest_cr + 8 + dct_offset, dct_linesize, block[11]);
  1724.                         }
  1725.                     }
  1726.                 }//gray
  1727.             }
  1728.         }
  1729. skip_idct:
  1730.         if(!readable){
  1731.             s->dsp.put_pixels_tab[0][0](s->dest[0], dest_y ,   linesize,16);
  1732.             s->dsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[1], dest_cb, uvlinesize,16 >> s->chroma_y_shift);
  1733.             s->dsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[2], dest_cr, uvlinesize,16 >> s->chroma_y_shift);
  1734.         }
  1735.     }
  1736. }
  1737. void MPV_decode_mb(MpegEncContext *s, DCTELEM block[12][64]){
  1738. #ifndef CONFIG_SMALL
  1739.     if(s->out_format == FMT_MPEG1) {
  1740.         if(s->avctx->lowres) MPV_decode_mb_internal(s, block, 1, 1);
  1741.         else                 MPV_decode_mb_internal(s, block, 0, 1);
  1742.     } else
  1743. #endif
  1744.     if(s->avctx->lowres) MPV_decode_mb_internal(s, block, 1, 0);
  1745.     else                  MPV_decode_mb_internal(s, block, 0, 0);
  1746. }
  1747. /**
  1748.  *
  1749.  * @param h is the normal height, this will be reduced automatically if needed for the last row
  1750.  */
  1751. void ff_draw_horiz_band(MpegEncContext *s, int y, int h){
  1752.     if (s->avctx->draw_horiz_band) {
  1753.         AVFrame *src;
  1754.         int offset[4];
  1755.         if(s->picture_structure != PICT_FRAME){
  1756.             h <<= 1;
  1757.             y <<= 1;
  1758.             if(s->first_field  && !(s->avctx->slice_flags&SLICE_FLAG_ALLOW_FIELD)) return;
  1759.         }
  1760.         h= FFMIN(h, s->avctx->height - y);
  1761.         if(s->pict_type==FF_B_TYPE || s->low_delay || (s->avctx->slice_flags&SLICE_FLAG_CODED_ORDER))
  1762.             src= (AVFrame*)s->current_picture_ptr;
  1763.         else if(s->last_picture_ptr)
  1764.             src= (AVFrame*)s->last_picture_ptr;
  1765.         else
  1766.             return;
  1767.         if(s->pict_type==FF_B_TYPE && s->picture_structure == PICT_FRAME && s->out_format != FMT_H264){
  1768.             offset[0]=
  1769.             offset[1]=
  1770.             offset[2]=
  1771.             offset[3]= 0;
  1772.         }else{
  1773.             offset[0]= y * s->linesize;
  1774.             offset[1]=
  1775.             offset[2]= (y >> s->chroma_y_shift) * s->uvlinesize;
  1776.             offset[3]= 0;
  1777.         }
  1778.         emms_c();
  1779.         s->avctx->draw_horiz_band(s->avctx, src, offset,
  1780.                                   y, s->picture_structure, h);
  1781.     }
  1782. }
  1783. void ff_init_block_index(MpegEncContext *s){ //FIXME maybe rename
  1784.     const int linesize= s->current_picture.linesize[0]; //not s->linesize as this would be wrong for field pics
  1785.     const int uvlinesize= s->current_picture.linesize[1];
  1786.     const int mb_size= 4 - s->avctx->lowres;
  1787.     s->block_index[0]= s->b8_stride*(s->mb_y*2    ) - 2 + s->mb_x*2;
  1788.     s->block_index[1]= s->b8_stride*(s->mb_y*2    ) - 1 + s->mb_x*2;
  1789.     s->block_index[2]= s->b8_stride*(s->mb_y*2 + 1) - 2 + s->mb_x*2;
  1790.     s->block_index[3]= s->b8_stride*(s->mb_y*2 + 1) - 1 + s->mb_x*2;
  1791.     s->block_index[4]= s->mb_stride*(s->mb_y + 1)                + s->b8_stride*s->mb_height*2 + s->mb_x - 1;
  1792.     s->block_index[5]= s->mb_stride*(s->mb_y + s->mb_height + 2) + s->b8_stride*s->mb_height*2 + s->mb_x - 1;
  1793.     //block_index is not used by mpeg2, so it is not affected by chroma_format
  1794.     s->dest[0] = s->current_picture.data[0] + ((s->mb_x - 1) << mb_size);
  1795.     s->dest[1] = s->current_picture.data[1] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
  1796.     s->dest[2] = s->current_picture.data[2] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
  1797.     if(!(s->pict_type==FF_B_TYPE && s->avctx->draw_horiz_band && s->picture_structure==PICT_FRAME))
  1798.     {
  1799.         s->dest[0] += s->mb_y *   linesize << mb_size;
  1800.         s->dest[1] += s->mb_y * uvlinesize << (mb_size - s->chroma_y_shift);
  1801.         s->dest[2] += s->mb_y * uvlinesize << (mb_size - s->chroma_y_shift);
  1802.     }
  1803. }
  1804. void ff_mpeg_flush(AVCodecContext *avctx){
  1805.     int i;
  1806.     MpegEncContext *s = avctx->priv_data;
  1807.     if(s==NULL || s->picture==NULL)
  1808.         return;
  1809.     for(i=0; i<MAX_PICTURE_COUNT; i++){
  1810.        if(s->picture[i].data[0] && (   s->picture[i].type == FF_BUFFER_TYPE_INTERNAL
  1811.                                     || s->picture[i].type == FF_BUFFER_TYPE_USER))
  1812.         avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);
  1813.     }
  1814.     s->current_picture_ptr = s->last_picture_ptr = s->next_picture_ptr = NULL;
  1815.     s->mb_x= s->mb_y= 0;
  1816.     s->parse_context.state= -1;
  1817.     s->parse_context.frame_start_found= 0;
  1818.     s->parse_context.overread= 0;
  1819.     s->parse_context.overread_index= 0;
  1820.     s->parse_context.index= 0;
  1821.     s->parse_context.last_index= 0;
  1822.     s->bitstream_buffer_size=0;
  1823.     s->pp_time=0;
  1824. }
  1825. static void dct_unquantize_mpeg1_intra_c(MpegEncContext *s,
  1826.                                    DCTELEM *block, int n, int qscale)
  1827. {
  1828.     int i, level, nCoeffs;
  1829.     const uint16_t *quant_matrix;
  1830.     nCoeffs= s->block_last_index[n];
  1831.     if (n < 4)
  1832.         block[0] = block[0] * s->y_dc_scale;
  1833.     else
  1834.         block[0] = block[0] * s->c_dc_scale;
  1835.     /* XXX: only mpeg1 */
  1836.     quant_matrix = s->intra_matrix;
  1837.     for(i=1;i<=nCoeffs;i++) {
  1838.         int j= s->intra_scantable.permutated[i];
  1839.         level = block[j];
  1840.         if (level) {
  1841.             if (level < 0) {
  1842.                 level = -level;
  1843.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1844.                 level = (level - 1) | 1;
  1845.                 level = -level;
  1846.             } else {
  1847.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1848.                 level = (level - 1) | 1;
  1849.             }
  1850.             block[j] = level;
  1851.         }
  1852.     }
  1853. }
  1854. static void dct_unquantize_mpeg1_inter_c(MpegEncContext *s,
  1855.                                    DCTELEM *block, int n, int qscale)
  1856. {
  1857.     int i, level, nCoeffs;
  1858.     const uint16_t *quant_matrix;
  1859.     nCoeffs= s->block_last_index[n];
  1860.     quant_matrix = s->inter_matrix;
  1861.     for(i=0; i<=nCoeffs; i++) {
  1862.         int j= s->intra_scantable.permutated[i];
  1863.         level = block[j];
  1864.         if (level) {
  1865.             if (level < 0) {
  1866.                 level = -level;
  1867.                 level = (((level << 1) + 1) * qscale *
  1868.                          ((int) (quant_matrix[j]))) >> 4;
  1869.                 level = (level - 1) | 1;
  1870.                 level = -level;
  1871.             } else {
  1872.                 level = (((level << 1) + 1) * qscale *
  1873.                          ((int) (quant_matrix[j]))) >> 4;
  1874.                 level = (level - 1) | 1;
  1875.             }
  1876.             block[j] = level;
  1877.         }
  1878.     }
  1879. }
  1880. static void dct_unquantize_mpeg2_intra_c(MpegEncContext *s,
  1881.                                    DCTELEM *block, int n, int qscale)
  1882. {
  1883.     int i, level, nCoeffs;
  1884.     const uint16_t *quant_matrix;
  1885.     if(s->alternate_scan) nCoeffs= 63;
  1886.     else nCoeffs= s->block_last_index[n];
  1887.     if (n < 4)
  1888.         block[0] = block[0] * s->y_dc_scale;
  1889.     else
  1890.         block[0] = block[0] * s->c_dc_scale;
  1891.     quant_matrix = s->intra_matrix;
  1892.     for(i=1;i<=nCoeffs;i++) {
  1893.         int j= s->intra_scantable.permutated[i];
  1894.         level = block[j];
  1895.         if (level) {
  1896.             if (level < 0) {
  1897.                 level = -level;
  1898.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1899.                 level = -level;
  1900.             } else {
  1901.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1902.             }
  1903.             block[j] = level;
  1904.         }
  1905.     }
  1906. }
  1907. static void dct_unquantize_mpeg2_intra_bitexact(MpegEncContext *s,
  1908.                                    DCTELEM *block, int n, int qscale)
  1909. {
  1910.     int i, level, nCoeffs;
  1911.     const uint16_t *quant_matrix;
  1912.     int sum=-1;
  1913.     if(s->alternate_scan) nCoeffs= 63;
  1914.     else nCoeffs= s->block_last_index[n];
  1915.     if (n < 4)
  1916.         block[0] = block[0] * s->y_dc_scale;
  1917.     else
  1918.         block[0] = block[0] * s->c_dc_scale;
  1919.     quant_matrix = s->intra_matrix;
  1920.     for(i=1;i<=nCoeffs;i++) {
  1921.         int j= s->intra_scantable.permutated[i];
  1922.         level = block[j];
  1923.         if (level) {
  1924.             if (level < 0) {
  1925.                 level = -level;
  1926.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1927.                 level = -level;
  1928.             } else {
  1929.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1930.             }
  1931.             block[j] = level;
  1932.             sum+=level;
  1933.         }
  1934.     }
  1935.     block[63]^=sum&1;
  1936. }
  1937. static void dct_unquantize_mpeg2_inter_c(MpegEncContext *s,
  1938.                                    DCTELEM *block, int n, int qscale)
  1939. {
  1940.     int i, level, nCoeffs;
  1941.     const uint16_t *quant_matrix;
  1942.     int sum=-1;
  1943.     if(s->alternate_scan) nCoeffs= 63;
  1944.     else nCoeffs= s->block_last_index[n];
  1945.     quant_matrix = s->inter_matrix;
  1946.     for(i=0; i<=nCoeffs; i++) {
  1947.         int j= s->intra_scantable.permutated[i];
  1948.         level = block[j];
  1949.         if (level) {
  1950.             if (level < 0) {
  1951.                 level = -level;
  1952.                 level = (((level << 1) + 1) * qscale *
  1953.                          ((int) (quant_matrix[j]))) >> 4;
  1954.                 level = -level;
  1955.             } else {
  1956.                 level = (((level << 1) + 1) * qscale *
  1957.                          ((int) (quant_matrix[j]))) >> 4;
  1958.             }
  1959.             block[j] = level;
  1960.             sum+=level;
  1961.         }
  1962.     }
  1963.     block[63]^=sum&1;
  1964. }
  1965. static void dct_unquantize_h263_intra_c(MpegEncContext *s,
  1966.                                   DCTELEM *block, int n, int qscale)
  1967. {
  1968.     int i, level, qmul, qadd;
  1969.     int nCoeffs;
  1970.     assert(s->block_last_index[n]>=0);
  1971.     qmul = qscale << 1;
  1972.     if (!s->h263_aic) {
  1973.         if (n < 4)
  1974.             block[0] = block[0] * s->y_dc_scale;
  1975.         else
  1976.             block[0] = block[0] * s->c_dc_scale;
  1977.         qadd = (qscale - 1) | 1;
  1978.     }else{
  1979.         qadd = 0;
  1980.     }
  1981.     if(s->ac_pred)
  1982.         nCoeffs=63;
  1983.     else
  1984.         nCoeffs= s->inter_scantable.raster_end[ s->block_last_index[n] ];
  1985.     for(i=1; i<=nCoeffs; i++) {
  1986.         level = block[i];
  1987.         if (level) {
  1988.             if (level < 0) {
  1989.                 level = level * qmul - qadd;
  1990.             } else {
  1991.                 level = level * qmul + qadd;
  1992.             }
  1993.             block[i] = level;
  1994.         }
  1995.     }
  1996. }
  1997. static void dct_unquantize_h263_inter_c(MpegEncContext *s,
  1998.                                   DCTELEM *block, int n, int qscale)
  1999. {
  2000.     int i, level, qmul, qadd;
  2001.     int nCoeffs;
  2002.     assert(s->block_last_index[n]>=0);
  2003.     qadd = (qscale - 1) | 1;
  2004.     qmul = qscale << 1;
  2005.     nCoeffs= s->inter_scantable.raster_end[ s->block_last_index[n] ];
  2006.     for(i=0; i<=nCoeffs; i++) {
  2007.         level = block[i];
  2008.         if (level) {
  2009.             if (level < 0) {
  2010.                 level = level * qmul - qadd;
  2011.             } else {
  2012.                 level = level * qmul + qadd;
  2013.             }
  2014.             block[i] = level;
  2015.         }
  2016.     }
  2017. }
  2018. /**
  2019.  * set qscale and update qscale dependent variables.
  2020.  */
  2021. void ff_set_qscale(MpegEncContext * s, int qscale)
  2022. {
  2023.     if (qscale < 1)
  2024.         qscale = 1;
  2025.     else if (qscale > 31)
  2026.         qscale = 31;
  2027.     s->qscale = qscale;
  2028.     s->chroma_qscale= s->chroma_qscale_table[qscale];
  2029.     s->y_dc_scale= s->y_dc_scale_table[ qscale ];
  2030.     s->c_dc_scale= s->c_dc_scale_table[ s->chroma_qscale ];
  2031. }