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