mpegvideo.c
上传用户:jylinhe
上传日期:2022-07-11
资源大小:334k
文件大小:89k
源码类别:

多媒体编程

开发平台:

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->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3)
  765. {
  766. if (s->pict_type != FF_B_TYPE) {
  767. s->last_picture_ptr= s->next_picture_ptr;
  768. if(!s->dropable)
  769. s->next_picture_ptr= s->current_picture_ptr;
  770. }
  771. /*    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,
  772. s->last_picture_ptr    ? s->last_picture_ptr->data[0] : NULL,
  773. s->next_picture_ptr    ? s->next_picture_ptr->data[0] : NULL,
  774. s->current_picture_ptr ? s->current_picture_ptr->data[0] : NULL,
  775. s->pict_type, s->dropable);*/
  776. if(s->last_picture_ptr) ff_copy_picture(&s->last_picture, s->last_picture_ptr);
  777. if(s->next_picture_ptr) ff_copy_picture(&s->next_picture, s->next_picture_ptr);
  778. 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){
  779. av_log(avctx, AV_LOG_ERROR, "warning: first frame is no keyframen");
  780. assert(s->pict_type != FF_B_TYPE); //these should have been dropped if we don't have a reference
  781. goto alloc;
  782. }
  783. assert(s->pict_type == FF_I_TYPE || (s->last_picture_ptr && s->last_picture_ptr->data[0]));
  784. if(s->picture_structure!=PICT_FRAME && s->out_format != FMT_H264){
  785. int i;
  786. for(i=0; i<4; i++){
  787. if(s->picture_structure == PICT_BOTTOM_FIELD){
  788.  s->current_picture.data[i] += s->current_picture.linesize[i];
  789. }
  790. s->current_picture.linesize[i] *= 2;
  791. s->last_picture.linesize[i] *=2;
  792. s->next_picture.linesize[i] *=2;
  793. }
  794. }
  795. }
  796.     s->hurry_up= s->avctx->hurry_up;
  797.     s->error_recognition= avctx->error_recognition;
  798.     /* set dequantizer, we can't do it during init as it might change for mpeg4
  799.        and we can't do it in the header decode as init is not called for mpeg4 there yet */
  800.     if(s->mpeg_quant || s->codec_id == CODEC_ID_MPEG2VIDEO){
  801.         s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;
  802.         s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;
  803.     }else if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
  804.         s->dct_unquantize_intra = s->dct_unquantize_h263_intra;
  805.         s->dct_unquantize_inter = s->dct_unquantize_h263_inter;
  806.     }else{
  807.         s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;
  808.         s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;
  809.     }
  810.     if(s->dct_error_sum){
  811.         assert(s->avctx->noise_reduction && s->encoding);
  812.         update_noise_reduction(s);
  813.     }
  814. #ifdef CONFIG_XVMC
  815.     if(s->avctx->xvmc_acceleration)
  816.         return XVMC_field_start(s, avctx);
  817. #endif
  818.     return 0;
  819. }
  820. /* generic function for encode/decode called after a frame has been coded/decoded */
  821. void MPV_frame_end(MpegEncContext *s)
  822. {
  823.     int i;
  824.     /* draw edge for correct motion prediction if outside */
  825. #ifdef CONFIG_XVMC
  826. //just to make sure that all data is rendered.
  827.     if(s->avctx->xvmc_acceleration){
  828.         XVMC_field_end(s);
  829.     }else
  830. #endif
  831.     if(!(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  832.        && s->unrestricted_mv
  833.        && s->current_picture.reference
  834.        && !s->intra_only
  835.        && !(s->flags&CODEC_FLAG_EMU_EDGE)) {
  836.             s->dsp.draw_edges(s->current_picture.data[0], s->linesize  , s->h_edge_pos   , s->v_edge_pos   , EDGE_WIDTH  );
  837.             s->dsp.draw_edges(s->current_picture.data[1], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
  838.             s->dsp.draw_edges(s->current_picture.data[2], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
  839.     }
  840.     emms_c();
  841.     s->last_pict_type    = s->pict_type;
  842.     s->last_lambda_for[s->pict_type]= s->current_picture_ptr->quality;
  843.     if(s->pict_type!=FF_B_TYPE){
  844.         s->last_non_b_pict_type= s->pict_type;
  845.     }
  846. #if 0
  847.         /* copy back current_picture variables */
  848.     for(i=0; i<MAX_PICTURE_COUNT; i++){
  849.         if(s->picture[i].data[0] == s->current_picture.data[0]){
  850.             s->picture[i]= s->current_picture;
  851.             break;
  852.         }
  853.     }
  854.     assert(i<MAX_PICTURE_COUNT);
  855. #endif
  856.     if(s->encoding){
  857.         /* release non-reference frames */
  858.         for(i=0; i<MAX_PICTURE_COUNT; i++){
  859.             if(s->picture[i].data[0] && !s->picture[i].reference /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/){
  860.                 s->avctx->release_buffer(s->avctx, (AVFrame*)&s->picture[i]);
  861.             }
  862.         }
  863.     }
  864.     // clear copies, to avoid confusion
  865. #if 0
  866.     memset(&s->last_picture, 0, sizeof(Picture));
  867.     memset(&s->next_picture, 0, sizeof(Picture));
  868.     memset(&s->current_picture, 0, sizeof(Picture));
  869. #endif
  870.     s->avctx->coded_frame= (AVFrame*)s->current_picture_ptr;
  871. }
  872. /**
  873.  * draws an line from (ex, ey) -> (sx, sy).
  874.  * @param w width of the image
  875.  * @param h height of the image
  876.  * @param stride stride/linesize of the image
  877.  * @param color color of the arrow
  878.  */
  879. /*
  880. static void draw_line(uint8_t *buf, int sx, int sy, int ex, int ey, int w, int h, int stride, int color){
  881.     int x, y, fr, f;
  882.     sx= av_clip(sx, 0, w-1);
  883.     sy= av_clip(sy, 0, h-1);
  884.     ex= av_clip(ex, 0, w-1);
  885.     ey= av_clip(ey, 0, h-1);
  886.     buf[sy*stride + sx]+= color;
  887.     if(FFABS(ex - sx) > FFABS(ey - sy)){
  888.         if(sx > ex){
  889.             FFSWAP(int, sx, ex);
  890.             FFSWAP(int, sy, ey);
  891.         }
  892.         buf+= sx + sy*stride;
  893.         ex-= sx;
  894.         f= ((ey-sy)<<16)/ex;
  895.         for(x= 0; x <= ex; x++){
  896.             y = (x*f)>>16;
  897.             fr= (x*f)&0xFFFF;
  898.             buf[ y   *stride + x]+= (color*(0x10000-fr))>>16;
  899.             buf[(y+1)*stride + x]+= (color*         fr )>>16;
  900.         }
  901.     }else{
  902.         if(sy > ey){
  903.             FFSWAP(int, sx, ex);
  904.             FFSWAP(int, sy, ey);
  905.         }
  906.         buf+= sx + sy*stride;
  907.         ey-= sy;
  908.         if(ey) f= ((ex-sx)<<16)/ey;
  909.         else   f= 0;
  910.         for(y= 0; y <= ey; y++){
  911.             x = (y*f)>>16;
  912.             fr= (y*f)&0xFFFF;
  913.             buf[y*stride + x  ]+= (color*(0x10000-fr))>>16;
  914.             buf[y*stride + x+1]+= (color*         fr )>>16;
  915.         }
  916.     }
  917. }
  918. */
  919. /**
  920.  * draws an arrow from (ex, ey) -> (sx, sy).
  921.  * @param w width of the image
  922.  * @param h height of the image
  923.  * @param stride stride/linesize of the image
  924.  * @param color color of the arrow
  925.  */
  926. /*
  927. static void draw_arrow(uint8_t *buf, int sx, int sy, int ex, int ey, int w, int h, int stride, int color){
  928.     int dx,dy;
  929.     sx= av_clip(sx, -100, w+100);
  930.     sy= av_clip(sy, -100, h+100);
  931.     ex= av_clip(ex, -100, w+100);
  932.     ey= av_clip(ey, -100, h+100);
  933.     dx= ex - sx;
  934.     dy= ey - sy;
  935.     if(dx*dx + dy*dy > 3*3){
  936.         int rx=  dx + dy;
  937.         int ry= -dx + dy;
  938.         int length= ff_sqrt((rx*rx + ry*ry)<<8);
  939.         //FIXME subpixel accuracy
  940.         rx= ROUNDED_DIV(rx*3<<4, length);
  941.         ry= ROUNDED_DIV(ry*3<<4, length);
  942.         draw_line(buf, sx, sy, sx + rx, sy + ry, w, h, stride, color);
  943.         draw_line(buf, sx, sy, sx - ry, sy + rx, w, h, stride, color);
  944.     }
  945.     draw_line(buf, sx, sy, ex, ey, w, h, stride, color);
  946. }
  947. */
  948. /**
  949.  * prints debuging info for the given picture.
  950.  */
  951. /*
  952. void ff_print_debug_info(MpegEncContext *s, AVFrame *pict){
  953.     if(!pict || !pict->mb_type) return;
  954.     if(s->avctx->debug&(FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)){
  955.         int x,y;
  956.         av_log(s->avctx,AV_LOG_DEBUG,"New frame, type: ");
  957.         switch (pict->pict_type) {
  958.             case FF_I_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"In"); break;
  959.             case FF_P_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"Pn"); break;
  960.             case FF_B_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"Bn"); break;
  961.             case FF_S_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"Sn"); break;
  962.             case FF_SI_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"SIn"); break;
  963.             case FF_SP_TYPE: av_log(s->avctx,AV_LOG_DEBUG,"SPn"); break;
  964.         }
  965.         for(y=0; y<s->mb_height; y++){
  966.             for(x=0; x<s->mb_width; x++){
  967.                 if(s->avctx->debug&FF_DEBUG_SKIP){
  968.                     int count= s->mbskip_table[x + y*s->mb_stride];
  969.                     if(count>9) count=9;
  970.                     av_log(s->avctx, AV_LOG_DEBUG, "%1d", count);
  971.                 }
  972.                 if(s->avctx->debug&FF_DEBUG_QP){
  973.                     av_log(s->avctx, AV_LOG_DEBUG, "%2d", pict->qscale_table[x + y*s->mb_stride]);
  974.                 }
  975.                 if(s->avctx->debug&FF_DEBUG_MB_TYPE){
  976.                     int mb_type= pict->mb_type[x + y*s->mb_stride];
  977.                     //Type & MV direction
  978.                     if(IS_PCM(mb_type))
  979.                         av_log(s->avctx, AV_LOG_DEBUG, "P");
  980.                     else if(IS_INTRA(mb_type) && IS_ACPRED(mb_type))
  981.                         av_log(s->avctx, AV_LOG_DEBUG, "A");
  982.                     else if(IS_INTRA4x4(mb_type))
  983.                         av_log(s->avctx, AV_LOG_DEBUG, "i");
  984.                     else if(IS_INTRA16x16(mb_type))
  985.                         av_log(s->avctx, AV_LOG_DEBUG, "I");
  986.                     else if(IS_DIRECT(mb_type) && IS_SKIP(mb_type))
  987.                         av_log(s->avctx, AV_LOG_DEBUG, "d");
  988.                     else if(IS_DIRECT(mb_type))
  989.                         av_log(s->avctx, AV_LOG_DEBUG, "D");
  990.                     else if(IS_GMC(mb_type) && IS_SKIP(mb_type))
  991.                         av_log(s->avctx, AV_LOG_DEBUG, "g");
  992.                     else if(IS_GMC(mb_type))
  993.                         av_log(s->avctx, AV_LOG_DEBUG, "G");
  994.                     else if(IS_SKIP(mb_type))
  995.                         av_log(s->avctx, AV_LOG_DEBUG, "S");
  996.                     else if(!USES_LIST(mb_type, 1))
  997.                         av_log(s->avctx, AV_LOG_DEBUG, ">");
  998.                     else if(!USES_LIST(mb_type, 0))
  999.                         av_log(s->avctx, AV_LOG_DEBUG, "<");
  1000.                     else{
  1001.                         assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
  1002.                         av_log(s->avctx, AV_LOG_DEBUG, "X");
  1003.                     }
  1004.                     //segmentation
  1005.                     if(IS_8X8(mb_type))
  1006.                         av_log(s->avctx, AV_LOG_DEBUG, "+");
  1007.                     else if(IS_16X8(mb_type))
  1008.                         av_log(s->avctx, AV_LOG_DEBUG, "-");
  1009.                     else if(IS_8X16(mb_type))
  1010.                         av_log(s->avctx, AV_LOG_DEBUG, "|");
  1011.                     else if(IS_INTRA(mb_type) || IS_16X16(mb_type))
  1012.                         av_log(s->avctx, AV_LOG_DEBUG, " ");
  1013.                     else
  1014.                         av_log(s->avctx, AV_LOG_DEBUG, "?");
  1015.                     if(IS_INTERLACED(mb_type) && s->codec_id == CODEC_ID_H264)
  1016.                         av_log(s->avctx, AV_LOG_DEBUG, "=");
  1017.                     else
  1018.                         av_log(s->avctx, AV_LOG_DEBUG, " ");
  1019.                 }
  1020. //                av_log(s->avctx, AV_LOG_DEBUG, " ");
  1021.             }
  1022.             av_log(s->avctx, AV_LOG_DEBUG, "n");
  1023.         }
  1024.     }
  1025.     if((s->avctx->debug&(FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) || (s->avctx->debug_mv)){
  1026.         const int shift= 1 + s->quarter_sample;
  1027.         int mb_y;
  1028.         uint8_t *ptr;
  1029.         int i;
  1030.         int h_chroma_shift, v_chroma_shift, block_height;
  1031.         const int width = s->avctx->width;
  1032.         const int height= s->avctx->height;
  1033.         const int mv_sample_log2= 4 - pict->motion_subsample_log2;
  1034.         const int mv_stride= (s->mb_width << mv_sample_log2) + (s->codec_id == CODEC_ID_H264 ? 0 : 1);
  1035.         s->low_delay=0; //needed to see the vectors without trashing the buffers
  1036.         avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
  1037.         for(i=0; i<3; i++){
  1038.             memcpy(s->visualization_buffer[i], pict->data[i], (i==0) ? pict->linesize[i]*height:pict->linesize[i]*height >> v_chroma_shift);
  1039.             pict->data[i]= s->visualization_buffer[i];
  1040.         }
  1041.         pict->type= FF_BUFFER_TYPE_COPY;
  1042.         ptr= pict->data[0];
  1043.         block_height = 16>>v_chroma_shift;
  1044.         for(mb_y=0; mb_y<s->mb_height; mb_y++){
  1045.             int mb_x;
  1046.             for(mb_x=0; mb_x<s->mb_width; mb_x++){
  1047.                 const int mb_index= mb_x + mb_y*s->mb_stride;
  1048.                 if((s->avctx->debug_mv) && pict->motion_val){
  1049.                   int type;
  1050.                   for(type=0; type<3; type++){
  1051.                     int direction = 0;
  1052.                     switch (type) {
  1053.                       case 0: if ((!(s->avctx->debug_mv&FF_DEBUG_VIS_MV_P_FOR)) || (pict->pict_type!=FF_P_TYPE))
  1054.                                 continue;
  1055.                               direction = 0;
  1056.                               break;
  1057.                       case 1: if ((!(s->avctx->debug_mv&FF_DEBUG_VIS_MV_B_FOR)) || (pict->pict_type!=FF_B_TYPE))
  1058.                                 continue;
  1059.                               direction = 0;
  1060.                               break;
  1061.                       case 2: if ((!(s->avctx->debug_mv&FF_DEBUG_VIS_MV_B_BACK)) || (pict->pict_type!=FF_B_TYPE))
  1062.                                 continue;
  1063.                               direction = 1;
  1064.                               break;
  1065.                     }
  1066.                     if(!USES_LIST(pict->mb_type[mb_index], direction))
  1067.                         continue;
  1068.                     if(IS_8X8(pict->mb_type[mb_index])){
  1069.                       int i;
  1070.                       for(i=0; i<4; i++){
  1071.                         int sx= mb_x*16 + 4 + 8*(i&1);
  1072.                         int sy= mb_y*16 + 4 + 8*(i>>1);
  1073.                         int xy= (mb_x*2 + (i&1) + (mb_y*2 + (i>>1))*mv_stride) << (mv_sample_log2-1);
  1074.                         int mx= (pict->motion_val[direction][xy][0]>>shift) + sx;
  1075.                         int my= (pict->motion_val[direction][xy][1]>>shift) + sy;
  1076.                         draw_arrow(ptr, sx, sy, mx, my, width, height, s->linesize, 100);
  1077.                       }
  1078.                     }else if(IS_16X8(pict->mb_type[mb_index])){
  1079.                       int i;
  1080.                       for(i=0; i<2; i++){
  1081.                         int sx=mb_x*16 + 8;
  1082.                         int sy=mb_y*16 + 4 + 8*i;
  1083.                         int xy= (mb_x*2 + (mb_y*2 + i)*mv_stride) << (mv_sample_log2-1);
  1084.                         int mx=(pict->motion_val[direction][xy][0]>>shift);
  1085.                         int my=(pict->motion_val[direction][xy][1]>>shift);
  1086.                         if(IS_INTERLACED(pict->mb_type[mb_index]))
  1087.                             my*=2;
  1088.                         draw_arrow(ptr, sx, sy, mx+sx, my+sy, width, height, s->linesize, 100);
  1089.                       }
  1090.                     }else if(IS_8X16(pict->mb_type[mb_index])){
  1091.                       int i;
  1092.                       for(i=0; i<2; i++){
  1093.                         int sx=mb_x*16 + 4 + 8*i;
  1094.                         int sy=mb_y*16 + 8;
  1095.                         int xy= (mb_x*2 + i + mb_y*2*mv_stride) << (mv_sample_log2-1);
  1096.                         int mx=(pict->motion_val[direction][xy][0]>>shift);
  1097.                         int my=(pict->motion_val[direction][xy][1]>>shift);
  1098.                         if(IS_INTERLACED(pict->mb_type[mb_index]))
  1099.                             my*=2;
  1100.                         draw_arrow(ptr, sx, sy, mx+sx, my+sy, width, height, s->linesize, 100);
  1101.                       }
  1102.                     }else{
  1103.                       int sx= mb_x*16 + 8;
  1104.                       int sy= mb_y*16 + 8;
  1105.                       int xy= (mb_x + mb_y*mv_stride) << mv_sample_log2;
  1106.                       int mx= (pict->motion_val[direction][xy][0]>>shift) + sx;
  1107.                       int my= (pict->motion_val[direction][xy][1]>>shift) + sy;
  1108.                       draw_arrow(ptr, sx, sy, mx, my, width, height, s->linesize, 100);
  1109.                     }
  1110.                   }
  1111.                 }
  1112.                 if((s->avctx->debug&FF_DEBUG_VIS_QP) && pict->motion_val){
  1113.                     uint64_t c= (pict->qscale_table[mb_index]*128/31) * 0x0101010101010101ULL;
  1114.                     int y;
  1115.                     for(y=0; y<block_height; y++){
  1116.                         *(uint64_t*)(pict->data[1] + 8*mb_x + (block_height*mb_y + y)*pict->linesize[1])= c;
  1117.                         *(uint64_t*)(pict->data[2] + 8*mb_x + (block_height*mb_y + y)*pict->linesize[2])= c;
  1118.                     }
  1119.                 }
  1120.                 if((s->avctx->debug&FF_DEBUG_VIS_MB_TYPE) && pict->motion_val){
  1121.                     int mb_type= pict->mb_type[mb_index];
  1122.                     uint64_t u,v;
  1123.                     int y;
  1124. #define COLOR(theta, r)
  1125. u= (int)(128 + r*cos(theta*3.141592/180));
  1126. v= (int)(128 + r*sin(theta*3.141592/180));
  1127.                     u=v=128;
  1128.                     if(IS_PCM(mb_type)){
  1129.                         COLOR(120,48)
  1130.                     }else if((IS_INTRA(mb_type) && IS_ACPRED(mb_type)) || IS_INTRA16x16(mb_type)){
  1131.                         COLOR(30,48)
  1132.                     }else if(IS_INTRA4x4(mb_type)){
  1133.                         COLOR(90,48)
  1134.                     }else if(IS_DIRECT(mb_type) && IS_SKIP(mb_type)){
  1135. //                        COLOR(120,48)
  1136.                     }else if(IS_DIRECT(mb_type)){
  1137.                         COLOR(150,48)
  1138.                     }else if(IS_GMC(mb_type) && IS_SKIP(mb_type)){
  1139.                         COLOR(170,48)
  1140.                     }else if(IS_GMC(mb_type)){
  1141.                         COLOR(190,48)
  1142.                     }else if(IS_SKIP(mb_type)){
  1143. //                        COLOR(180,48)
  1144.                     }else if(!USES_LIST(mb_type, 1)){
  1145.                         COLOR(240,48)
  1146.                     }else if(!USES_LIST(mb_type, 0)){
  1147.                         COLOR(0,48)
  1148.                     }else{
  1149.                         assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
  1150.                         COLOR(300,48)
  1151.                     }
  1152.                     u*= 0x0101010101010101ULL;
  1153.                     v*= 0x0101010101010101ULL;
  1154.                     for(y=0; y<block_height; y++){
  1155.                         *(uint64_t*)(pict->data[1] + 8*mb_x + (block_height*mb_y + y)*pict->linesize[1])= u;
  1156.                         *(uint64_t*)(pict->data[2] + 8*mb_x + (block_height*mb_y + y)*pict->linesize[2])= v;
  1157.                     }
  1158.                     //segmentation
  1159.                     if(IS_8X8(mb_type) || IS_16X8(mb_type)){
  1160.                         *(uint64_t*)(pict->data[0] + 16*mb_x + 0 + (16*mb_y + 8)*pict->linesize[0])^= 0x8080808080808080ULL;
  1161.                         *(uint64_t*)(pict->data[0] + 16*mb_x + 8 + (16*mb_y + 8)*pict->linesize[0])^= 0x8080808080808080ULL;
  1162.                     }
  1163.                     if(IS_8X8(mb_type) || IS_8X16(mb_type)){
  1164.                         for(y=0; y<16; y++)
  1165.                             pict->data[0][16*mb_x + 8 + (16*mb_y + y)*pict->linesize[0]]^= 0x80;
  1166.                     }
  1167.                     if(IS_8X8(mb_type) && mv_sample_log2 >= 2){
  1168.                         int dm= 1 << (mv_sample_log2-2);
  1169.                         for(i=0; i<4; i++){
  1170.                             int sx= mb_x*16 + 8*(i&1);
  1171.                             int sy= mb_y*16 + 8*(i>>1);
  1172.                             int xy= (mb_x*2 + (i&1) + (mb_y*2 + (i>>1))*mv_stride) << (mv_sample_log2-1);
  1173.                             //FIXME bidir
  1174.                             int32_t *mv = (int32_t*)&pict->motion_val[0][xy];
  1175.                             if(mv[0] != mv[dm] || mv[dm*mv_stride] != mv[dm*(mv_stride+1)])
  1176.                                 for(y=0; y<8; y++)
  1177.                                     pict->data[0][sx + 4 + (sy + y)*pict->linesize[0]]^= 0x80;
  1178.                             if(mv[0] != mv[dm*mv_stride] || mv[dm] != mv[dm*(mv_stride+1)])
  1179.                                 *(uint64_t*)(pict->data[0] + sx + (sy + 4)*pict->linesize[0])^= 0x8080808080808080ULL;
  1180.                         }
  1181.                     }
  1182.                     if(IS_INTERLACED(mb_type) && s->codec_id == CODEC_ID_H264){
  1183.                         // hmm
  1184.                     }
  1185.                 }
  1186.                 s->mbskip_table[mb_index]=0;
  1187.             }
  1188.         }
  1189.     }
  1190. }*/
  1191. static inline int hpel_motion_lowres(MpegEncContext *s,
  1192.                                   uint8_t *dest, uint8_t *src,
  1193.                                   int field_based, int field_select,
  1194.                                   int src_x, int src_y,
  1195.                                   int width, int height, int stride,
  1196.                                   int h_edge_pos, int v_edge_pos,
  1197.                                   int w, int h, h264_chroma_mc_func *pix_op,
  1198.                                   int motion_x, int motion_y)
  1199. {
  1200.     const int lowres= s->avctx->lowres;
  1201.     const int s_mask= (2<<lowres)-1;
  1202.     int emu=0;
  1203.     int sx, sy;
  1204.     if(s->quarter_sample){
  1205.         motion_x/=2;
  1206.         motion_y/=2;
  1207.     }
  1208.     sx= motion_x & s_mask;
  1209.     sy= motion_y & s_mask;
  1210.     src_x += motion_x >> (lowres+1);
  1211.     src_y += motion_y >> (lowres+1);
  1212.     src += src_y * stride + src_x;
  1213.     if(   src_x > h_edge_pos                 - (!!sx) - w
  1214.        || src_y >(v_edge_pos >> field_based) - (!!sy) - h){
  1215.         ff_emulated_edge_mc(s->edge_emu_buffer, src, s->linesize, w+1, (h+1)<<field_based,
  1216.                             src_x, src_y<<field_based, h_edge_pos, v_edge_pos);
  1217.         src= s->edge_emu_buffer;
  1218.         emu=1;
  1219.     }
  1220.     sx <<= 2 - lowres;
  1221.     sy <<= 2 - lowres;
  1222.     if(field_select)
  1223.         src += s->linesize;
  1224.     pix_op[lowres](dest, src, stride, h, sx, sy);
  1225.     return emu;
  1226. }
  1227. /* apply one mpeg motion vector to the three components */
  1228. static av_always_inline void mpeg_motion_lowres(MpegEncContext *s,
  1229.                                uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1230.                                int field_based, int bottom_field, int field_select,
  1231.                                uint8_t **ref_picture, h264_chroma_mc_func *pix_op,
  1232.                                int motion_x, int motion_y, int h)
  1233. {
  1234.     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  1235.     int mx, my, src_x, src_y, uvsrc_x, uvsrc_y, uvlinesize, linesize, sx, sy, uvsx, uvsy;
  1236.     const int lowres= s->avctx->lowres;
  1237.     const int block_s= 8>>lowres;
  1238.     const int s_mask= (2<<lowres)-1;
  1239.     const int h_edge_pos = s->h_edge_pos >> lowres;
  1240.     const int v_edge_pos = s->v_edge_pos >> lowres;
  1241.     linesize   = s->current_picture.linesize[0] << field_based;
  1242.     uvlinesize = s->current_picture.linesize[1] << field_based;
  1243.     if(s->quarter_sample){ //FIXME obviously not perfect but qpel will not work in lowres anyway
  1244.         motion_x/=2;
  1245.         motion_y/=2;
  1246.     }
  1247.     if(field_based){
  1248.         motion_y += (bottom_field - field_select)*((1<<lowres)-1);
  1249.     }
  1250.     sx= motion_x & s_mask;
  1251.     sy= motion_y & s_mask;
  1252.     src_x = s->mb_x*2*block_s               + (motion_x >> (lowres+1));
  1253.     src_y =(s->mb_y*2*block_s>>field_based) + (motion_y >> (lowres+1));
  1254.     if (s->out_format == FMT_H263) {
  1255.         uvsx = ((motion_x>>1) & s_mask) | (sx&1);
  1256.         uvsy = ((motion_y>>1) & s_mask) | (sy&1);
  1257.         uvsrc_x = src_x>>1;
  1258.         uvsrc_y = src_y>>1;
  1259.     }else if(s->out_format == FMT_H261){//even chroma mv's are full pel in H261
  1260.         mx = motion_x / 4;
  1261.         my = motion_y / 4;
  1262.         uvsx = (2*mx) & s_mask;
  1263.         uvsy = (2*my) & s_mask;
  1264.         uvsrc_x = s->mb_x*block_s               + (mx >> lowres);
  1265.         uvsrc_y = s->mb_y*block_s               + (my >> lowres);
  1266.     } else {
  1267.         mx = motion_x / 2;
  1268.         my = motion_y / 2;
  1269.         uvsx = mx & s_mask;
  1270.         uvsy = my & s_mask;
  1271.         uvsrc_x = s->mb_x*block_s               + (mx >> (lowres+1));
  1272.         uvsrc_y =(s->mb_y*block_s>>field_based) + (my >> (lowres+1));
  1273.     }
  1274.     ptr_y  = ref_picture[0] + src_y * linesize + src_x;
  1275.     ptr_cb = ref_picture[1] + uvsrc_y * uvlinesize + uvsrc_x;
  1276.     ptr_cr = ref_picture[2] + uvsrc_y * uvlinesize + uvsrc_x;
  1277.     if(   src_x > h_edge_pos                 - (!!sx) - 2*block_s
  1278.        || src_y >(v_edge_pos >> field_based) - (!!sy) - h){
  1279.             ff_emulated_edge_mc(s->edge_emu_buffer, ptr_y, s->linesize, 17, 17+field_based,
  1280.                              src_x, src_y<<field_based, h_edge_pos, v_edge_pos);
  1281.             ptr_y = s->edge_emu_buffer;
  1282.             if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1283.                 uint8_t *uvbuf= s->edge_emu_buffer+18*s->linesize;
  1284.                 ff_emulated_edge_mc(uvbuf  , ptr_cb, s->uvlinesize, 9, 9+field_based,
  1285.                                  uvsrc_x, uvsrc_y<<field_based, h_edge_pos>>1, v_edge_pos>>1);
  1286.                 ff_emulated_edge_mc(uvbuf+16, ptr_cr, s->uvlinesize, 9, 9+field_based,
  1287.                                  uvsrc_x, uvsrc_y<<field_based, h_edge_pos>>1, v_edge_pos>>1);
  1288.                 ptr_cb= uvbuf;
  1289.                 ptr_cr= uvbuf+16;
  1290.             }
  1291.     }
  1292.     if(bottom_field){ //FIXME use this for field pix too instead of the obnoxious hack which changes picture.data
  1293.         dest_y += s->linesize;
  1294.         dest_cb+= s->uvlinesize;
  1295.         dest_cr+= s->uvlinesize;
  1296.     }
  1297.     if(field_select){
  1298.         ptr_y += s->linesize;
  1299.         ptr_cb+= s->uvlinesize;
  1300.         ptr_cr+= s->uvlinesize;
  1301.     }
  1302.     sx <<= 2 - lowres;
  1303.     sy <<= 2 - lowres;
  1304.     pix_op[lowres-1](dest_y, ptr_y, linesize, h, sx, sy);
  1305.     if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1306.         uvsx <<= 2 - lowres;
  1307.         uvsy <<= 2 - lowres;
  1308.         pix_op[lowres](dest_cb, ptr_cb, uvlinesize, h >> s->chroma_y_shift, uvsx, uvsy);
  1309.         pix_op[lowres](dest_cr, ptr_cr, uvlinesize, h >> s->chroma_y_shift, uvsx, uvsy);
  1310.     }
  1311.     //FIXME h261 lowres loop filter
  1312. }
  1313. static inline void chroma_4mv_motion_lowres(MpegEncContext *s,
  1314.                                      uint8_t *dest_cb, uint8_t *dest_cr,
  1315.                                      uint8_t **ref_picture,
  1316.                                      h264_chroma_mc_func *pix_op,
  1317.                                      int mx, int my){
  1318.     const int lowres= s->avctx->lowres;
  1319.     const int block_s= 8>>lowres;
  1320.     const int s_mask= (2<<lowres)-1;
  1321.     const int h_edge_pos = s->h_edge_pos >> (lowres+1);
  1322.     const int v_edge_pos = s->v_edge_pos >> (lowres+1);
  1323.     int emu=0, src_x, src_y, offset, sx, sy;
  1324.     uint8_t *ptr;
  1325.     if(s->quarter_sample){
  1326.         mx/=2;
  1327.         my/=2;
  1328.     }
  1329.     /* In case of 8X8, we construct a single chroma motion vector
  1330.        with a special rounding */
  1331.     mx= ff_h263_round_chroma(mx);
  1332.     my= ff_h263_round_chroma(my);
  1333.     sx= mx & s_mask;
  1334.     sy= my & s_mask;
  1335.     src_x = s->mb_x*block_s + (mx >> (lowres+1));
  1336.     src_y = s->mb_y*block_s + (my >> (lowres+1));
  1337.     offset = src_y * s->uvlinesize + src_x;
  1338.     ptr = ref_picture[1] + offset;
  1339.     if(s->flags&CODEC_FLAG_EMU_EDGE){
  1340.         if(   src_x > h_edge_pos - (!!sx) - block_s
  1341.            || src_y > v_edge_pos - (!!sy) - block_s){
  1342.             ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, h_edge_pos, v_edge_pos);
  1343.             ptr= s->edge_emu_buffer;
  1344.             emu=1;
  1345.         }
  1346.     }
  1347.     sx <<= 2 - lowres;
  1348.     sy <<= 2 - lowres;
  1349.     pix_op[lowres](dest_cb, ptr, s->uvlinesize, block_s, sx, sy);
  1350.     ptr = ref_picture[2] + offset;
  1351.     if(emu){
  1352.         ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, h_edge_pos, v_edge_pos);
  1353.         ptr= s->edge_emu_buffer;
  1354.     }
  1355.     pix_op[lowres](dest_cr, ptr, s->uvlinesize, block_s, sx, sy);
  1356. }
  1357. /**
  1358.  * motion compensation of a single macroblock
  1359.  * @param s context
  1360.  * @param dest_y luma destination pointer
  1361.  * @param dest_cb chroma cb/u destination pointer
  1362.  * @param dest_cr chroma cr/v destination pointer
  1363.  * @param dir direction (0->forward, 1->backward)
  1364.  * @param ref_picture array[3] of pointers to the 3 planes of the reference picture
  1365.  * @param pic_op halfpel motion compensation function (average or put normally)
  1366.  * the motion vectors are taken from s->mv and the MV type from s->mv_type
  1367.  */
  1368. static inline void MPV_motion_lowres(MpegEncContext *s,
  1369.                               uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1370.                               int dir, uint8_t **ref_picture,
  1371.                               h264_chroma_mc_func *pix_op)
  1372. {
  1373.     int mx, my;
  1374.     int mb_x, mb_y, i;
  1375.     const int lowres= s->avctx->lowres;
  1376.     const int block_s= 8>>lowres;
  1377.     mb_x = s->mb_x;
  1378.     mb_y = s->mb_y;
  1379.     switch(s->mv_type) {
  1380.     case MV_TYPE_16X16:
  1381.         mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1382.                     0, 0, 0,
  1383.                     ref_picture, pix_op,
  1384.                     s->mv[dir][0][0], s->mv[dir][0][1], 2*block_s);
  1385.         break;
  1386.     case MV_TYPE_8X8:
  1387.         mx = 0;
  1388.         my = 0;
  1389.             for(i=0;i<4;i++) {
  1390.                 hpel_motion_lowres(s, dest_y + ((i & 1) + (i >> 1) * s->linesize)*block_s,
  1391.                             ref_picture[0], 0, 0,
  1392.                             (2*mb_x + (i & 1))*block_s, (2*mb_y + (i >>1))*block_s,
  1393.                             s->width, s->height, s->linesize,
  1394.                             s->h_edge_pos >> lowres, s->v_edge_pos >> lowres,
  1395.                             block_s, block_s, pix_op,
  1396.                             s->mv[dir][i][0], s->mv[dir][i][1]);
  1397.                 mx += s->mv[dir][i][0];
  1398.                 my += s->mv[dir][i][1];
  1399.             }
  1400.         if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY))
  1401.             chroma_4mv_motion_lowres(s, dest_cb, dest_cr, ref_picture, pix_op, mx, my);
  1402.         break;
  1403.     case MV_TYPE_FIELD:
  1404.         if (s->picture_structure == PICT_FRAME) {
  1405.             /* top field */
  1406.             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1407.                         1, 0, s->field_select[dir][0],
  1408.                         ref_picture, pix_op,
  1409.                         s->mv[dir][0][0], s->mv[dir][0][1], block_s);
  1410.             /* bottom field */
  1411.             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1412.                         1, 1, s->field_select[dir][1],
  1413.                         ref_picture, pix_op,
  1414.                         s->mv[dir][1][0], s->mv[dir][1][1], block_s);
  1415.         } else {
  1416.             if(s->picture_structure != s->field_select[dir][0] + 1 && s->pict_type != FF_B_TYPE && !s->first_field){
  1417.                 ref_picture= s->current_picture_ptr->data;
  1418.             }
  1419.             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1420.                         0, 0, s->field_select[dir][0],
  1421.                         ref_picture, pix_op,
  1422.                         s->mv[dir][0][0], s->mv[dir][0][1], 2*block_s);
  1423.         }
  1424.         break;
  1425.     case MV_TYPE_16X8:
  1426.         for(i=0; i<2; i++){
  1427.             uint8_t ** ref2picture;
  1428.             if(s->picture_structure == s->field_select[dir][i] + 1 || s->pict_type == FF_B_TYPE || s->first_field){
  1429.                 ref2picture= ref_picture;
  1430.             }else{
  1431.                 ref2picture= s->current_picture_ptr->data;
  1432.             }
  1433.             mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1434.                         0, 0, s->field_select[dir][i],
  1435.                         ref2picture, pix_op,
  1436.                         s->mv[dir][i][0], s->mv[dir][i][1] + 2*block_s*i, block_s);
  1437.             dest_y += 2*block_s*s->linesize;
  1438.             dest_cb+= (2*block_s>>s->chroma_y_shift)*s->uvlinesize;
  1439.             dest_cr+= (2*block_s>>s->chroma_y_shift)*s->uvlinesize;
  1440.         }
  1441.         break;
  1442.     case MV_TYPE_DMV:
  1443.         if(s->picture_structure == PICT_FRAME){
  1444.             for(i=0; i<2; i++){
  1445.                 int j;
  1446.                 for(j=0; j<2; j++){
  1447.                     mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1448.                                 1, j, j^i,
  1449.                                 ref_picture, pix_op,
  1450.                                 s->mv[dir][2*i + j][0], s->mv[dir][2*i + j][1], block_s);
  1451.                 }
  1452.                 pix_op = s->dsp.avg_h264_chroma_pixels_tab;
  1453.             }
  1454.         }else{
  1455.             for(i=0; i<2; i++){
  1456.                 mpeg_motion_lowres(s, dest_y, dest_cb, dest_cr,
  1457.                             0, 0, s->picture_structure != i+1,
  1458.                             ref_picture, pix_op,
  1459.                             s->mv[dir][2*i][0],s->mv[dir][2*i][1],2*block_s);
  1460.                 // after put we make avg of the same block
  1461.                 pix_op = s->dsp.avg_h264_chroma_pixels_tab;
  1462.                 //opposite parity is always in the same frame if this is second field
  1463.                 if(!s->first_field){
  1464.                     ref_picture = s->current_picture_ptr->data;
  1465.                 }
  1466.             }
  1467.         }
  1468.     break;
  1469.     default: assert(0);
  1470.     }
  1471. }
  1472. /* put block[] to dest[] */
  1473. static inline void put_dct(MpegEncContext *s,
  1474.                            DCTELEM *block, int i, uint8_t *dest, int line_size, int qscale)
  1475. {
  1476.     s->dct_unquantize_intra(s, block, i, qscale);
  1477.     s->dsp.idct_put (dest, line_size, block);
  1478. }
  1479. /* add block[] to dest[] */
  1480. static inline void add_dct(MpegEncContext *s,
  1481.                            DCTELEM *block, int i, uint8_t *dest, int line_size)
  1482. {
  1483.     if (s->block_last_index[i] >= 0) {
  1484.         s->dsp.idct_add (dest, line_size, block);
  1485.     }
  1486. }
  1487. /*
  1488. static inline void add_dequant_dct(MpegEncContext *s,
  1489.                            DCTELEM *block, int i, uint8_t *dest, int line_size, int qscale)
  1490. {
  1491.     if (s->block_last_index[i] >= 0) {
  1492.         s->dct_unquantize_inter(s, block, i, qscale);
  1493.         s->dsp.idct_add (dest, line_size, block);
  1494.     }
  1495. }
  1496. */
  1497. /**
  1498.  * cleans dc, ac, coded_block for the current non intra MB
  1499.  */
  1500. void ff_clean_intra_table_entries(MpegEncContext *s)
  1501. {
  1502.     int wrap = s->b8_stride;
  1503.     int xy = s->block_index[0];
  1504.     s->dc_val[0][xy           ] =
  1505.     s->dc_val[0][xy + 1       ] =
  1506.     s->dc_val[0][xy     + wrap] =
  1507.     s->dc_val[0][xy + 1 + wrap] = 1024;
  1508.     /* ac pred */
  1509.     memset(s->ac_val[0][xy       ], 0, 32 * sizeof(int16_t));
  1510.     memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(int16_t));
  1511.     if (s->msmpeg4_version>=3) {
  1512.         s->coded_block[xy           ] =
  1513.         s->coded_block[xy + 1       ] =
  1514.         s->coded_block[xy     + wrap] =
  1515.         s->coded_block[xy + 1 + wrap] = 0;
  1516.     }
  1517.     /* chroma */
  1518.     wrap = s->mb_stride;
  1519.     xy = s->mb_x + s->mb_y * wrap;
  1520.     s->dc_val[1][xy] =
  1521.     s->dc_val[2][xy] = 1024;
  1522.     /* ac pred */
  1523.     memset(s->ac_val[1][xy], 0, 16 * sizeof(int16_t));
  1524.     memset(s->ac_val[2][xy], 0, 16 * sizeof(int16_t));
  1525.     s->mbintra_table[xy]= 0;
  1526. }
  1527. /* generic function called after a macroblock has been parsed by the
  1528.    decoder or after it has been encoded by the encoder.
  1529.    Important variables used:
  1530.    s->mb_intra : true if intra macroblock
  1531.    s->mv_dir   : motion vector direction
  1532.    s->mv_type  : motion vector type
  1533.    s->mv       : motion vector
  1534.    s->interlaced_dct : true if interlaced dct used (mpeg2)
  1535.  */
  1536. static av_always_inline
  1537. void MPV_decode_mb_internal(MpegEncContext *s, DCTELEM block[12][64],
  1538.                             int lowres_flag, int is_mpeg12)
  1539. {
  1540.     int mb_x, mb_y;
  1541.     const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
  1542. #ifdef CONFIG_XVMC
  1543.     if(s->avctx->xvmc_acceleration){
  1544.         XVMC_decode_mb(s);//xvmc uses pblocks
  1545.         return;
  1546.     }
  1547. #endif
  1548.     mb_x = s->mb_x;
  1549.     mb_y = s->mb_y;
  1550.     if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {
  1551.        /* save DCT coefficients */
  1552.        int i,j;
  1553.        DCTELEM *dct = &s->current_picture.dct_coeff[mb_xy*64*6];
  1554.        for(i=0; i<6; i++)
  1555.            for(j=0; j<64; j++)
  1556.                *dct++ = block[i][s->dsp.idct_permutation[j]];
  1557.     }
  1558.     s->current_picture.qscale_table[mb_xy]= s->qscale;
  1559.     /* update DC predictors for P macroblocks */
  1560.     if (!s->mb_intra) {
  1561.         if (!is_mpeg12 && (s->h263_pred || s->h263_aic)) {
  1562.             if(s->mbintra_table[mb_xy])
  1563.                 ff_clean_intra_table_entries(s);
  1564.         } else {
  1565.             s->last_dc[0] =
  1566.             s->last_dc[1] =
  1567.             s->last_dc[2] = 128 << s->intra_dc_precision;
  1568.         }
  1569.     }
  1570.     else if (!is_mpeg12 && (s->h263_pred || s->h263_aic))
  1571.         s->mbintra_table[mb_xy]=1;
  1572.     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
  1573.         uint8_t *dest_y, *dest_cb, *dest_cr;
  1574.         int dct_linesize, dct_offset;
  1575.         op_pixels_func (*op_pix)[4];
  1576.         qpel_mc_func (*op_qpix)[16];
  1577.         const int linesize= s->current_picture.linesize[0]; //not s->linesize as this would be wrong for field pics
  1578.         const int uvlinesize= s->current_picture.linesize[1];
  1579.         const int readable= s->pict_type != FF_B_TYPE || s->encoding || s->avctx->draw_horiz_band || lowres_flag;
  1580.         const int block_size= lowres_flag ? 8>>s->avctx->lowres : 8;
  1581.         /* avoid copy if macroblock skipped in last frame too */
  1582.         /* skip only during decoding as we might trash the buffers during encoding a bit */
  1583.         if(!s->encoding){
  1584.             uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];
  1585.             const int age= s->current_picture.age;
  1586.             assert(age);
  1587.             if (s->mb_skipped) {
  1588.                 s->mb_skipped= 0;
  1589.                 assert(s->pict_type!=FF_I_TYPE);
  1590.                 (*mbskip_ptr) ++; /* indicate that this time we skipped it */
  1591.                 if(*mbskip_ptr >99) *mbskip_ptr= 99;
  1592.                 /* if previous was skipped too, then nothing to do !  */
  1593.                 if (*mbskip_ptr >= age && s->current_picture.reference){
  1594.                     return;
  1595.                 }
  1596.             } else if(!s->current_picture.reference){
  1597.                 (*mbskip_ptr) ++; /* increase counter so the age can be compared cleanly */
  1598.                 if(*mbskip_ptr >99) *mbskip_ptr= 99;
  1599.             } else{
  1600.                 *mbskip_ptr = 0; /* not skipped */
  1601.             }
  1602.         }
  1603.         dct_linesize = linesize << s->interlaced_dct;
  1604.         dct_offset =(s->interlaced_dct)? linesize : linesize*block_size;
  1605.         if(readable){
  1606.             dest_y=  s->dest[0];
  1607.             dest_cb= s->dest[1];
  1608.             dest_cr= s->dest[2];
  1609.         }else{
  1610.             dest_y = s->b_scratchpad;
  1611.             dest_cb= s->b_scratchpad+16*linesize;
  1612.             dest_cr= s->b_scratchpad+32*linesize;
  1613.         }
  1614.         if (!s->mb_intra) 
  1615. {
  1616.             /* motion handling */
  1617.             /* decoding or more than one mb_type (MC was already done otherwise) */
  1618.             if(!s->encoding)
  1619. {
  1620.                 if(lowres_flag)
  1621. {
  1622.                     h264_chroma_mc_func *op_pix = s->dsp.put_h264_chroma_pixels_tab;
  1623.                     if (s->mv_dir & MV_DIR_FORWARD) {
  1624.                         MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix);
  1625.                         op_pix = s->dsp.avg_h264_chroma_pixels_tab;
  1626.                     }
  1627.                     if (s->mv_dir & MV_DIR_BACKWARD) {
  1628.                         MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix);
  1629.                     }
  1630.                 }
  1631. else
  1632. {
  1633.                     op_qpix= s->me.qpel_put;
  1634.                     if ((!s->no_rounding) || s->pict_type==FF_B_TYPE){
  1635.                         op_pix = s->dsp.put_pixels_tab;
  1636.                     }else{
  1637.                         op_pix = s->dsp.put_no_rnd_pixels_tab;
  1638.                     }
  1639.                     if (s->mv_dir & MV_DIR_FORWARD) {
  1640.                         MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
  1641.                         op_pix = s->dsp.avg_pixels_tab;
  1642.                         op_qpix= s->me.qpel_avg;
  1643.                     }
  1644.                     if (s->mv_dir & MV_DIR_BACKWARD) {
  1645.                         MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
  1646.                     }
  1647.                 }
  1648.             }
  1649.             /* skip dequant / idct if we are really late ;) */
  1650.             if(s->hurry_up>1) goto skip_idct;
  1651.             if(s->avctx->skip_idct){
  1652.                 if(  (s->avctx->skip_idct >= AVDISCARD_NONREF && s->pict_type == FF_B_TYPE)
  1653.                    ||(s->avctx->skip_idct >= AVDISCARD_NONKEY && s->pict_type != FF_I_TYPE)
  1654.                    || s->avctx->skip_idct >= AVDISCARD_ALL)
  1655.                     goto skip_idct;
  1656.             }
  1657.             /* add dct residue */
  1658.             /*if(s->encoding 
  1659. || 
  1660. !(   s->h263_msmpeg4 
  1661. || 
  1662. s->codec_id==CODEC_ID_MPEG1VIDEO 
  1663. || 
  1664. s->codec_id==CODEC_ID_MPEG2VIDEO
  1665.                         || 
  1666. (s->codec_id==CODEC_ID_MPEG4 && !s->mpeg_quant)))
  1667. {
  1668.                 add_dequant_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);
  1669.                 add_dequant_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);
  1670.                 add_dequant_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);
  1671.                 add_dequant_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);
  1672.                 if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1673.                     if (s->chroma_y_shift){
  1674.                         add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
  1675.                         add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
  1676.                     }else{
  1677.                         dct_linesize >>= 1;
  1678.                         dct_offset >>=1;
  1679.                         add_dequant_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);
  1680.                         add_dequant_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);
  1681.                         add_dequant_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);
  1682.                         add_dequant_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);
  1683.                     }
  1684.                 }
  1685.             } 
  1686. else*/ if(is_mpeg12 || (s->codec_id != CODEC_ID_WMV2))
  1687. {
  1688.                 add_dct(s, block[0], 0, dest_y                          , dct_linesize);
  1689.                 add_dct(s, block[1], 1, dest_y              + block_size, dct_linesize);
  1690.                 add_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize);
  1691.                 add_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize);
  1692.                 if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY))
  1693. {
  1694.                     if(s->chroma_y_shift)
  1695. {//Chroma420
  1696.                         add_dct(s, block[4], 4, dest_cb, uvlinesize);
  1697.                         add_dct(s, block[5], 5, dest_cr, uvlinesize);
  1698.                     }
  1699. else
  1700. {
  1701.                         //chroma422
  1702.                         dct_linesize = uvlinesize << s->interlaced_dct;
  1703.                         dct_offset =(s->interlaced_dct)? uvlinesize : uvlinesize*8;
  1704.                         add_dct(s, block[4], 4, dest_cb, dct_linesize);
  1705.                         add_dct(s, block[5], 5, dest_cr, dct_linesize);
  1706.                         add_dct(s, block[6], 6, dest_cb+dct_offset, dct_linesize);
  1707.                         add_dct(s, block[7], 7, dest_cr+dct_offset, dct_linesize);
  1708.                         if(!s->chroma_x_shift){//Chroma444
  1709.                             add_dct(s, block[8], 8, dest_cb+8, dct_linesize);
  1710.                             add_dct(s, block[9], 9, dest_cr+8, dct_linesize);
  1711.                             add_dct(s, block[10], 10, dest_cb+8+dct_offset, dct_linesize);
  1712.                             add_dct(s, block[11], 11, dest_cr+8+dct_offset, dct_linesize);
  1713.                         }
  1714.                     }
  1715.                 }//fi gray
  1716.             }
  1717.             /*else if (ENABLE_WMV2) 
  1718. {
  1719.                 ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);
  1720.             }*/
  1721.         } 
  1722. else 
  1723. {
  1724.             /* dct only in intra block */
  1725.             if(s->encoding || !(s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO)){
  1726.                 put_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);
  1727.                 put_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);
  1728.                 put_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);
  1729.                 put_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);
  1730.                 if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1731.                     if(s->chroma_y_shift){
  1732.                         put_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);
  1733.                         put_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);
  1734.                     }else{
  1735.                         dct_offset >>=1;
  1736.                         dct_linesize >>=1;
  1737.                         put_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);
  1738.                         put_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);
  1739.                         put_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);
  1740.                         put_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);
  1741.                     }
  1742.                 }
  1743.             }else{
  1744.                 s->dsp.idct_put(dest_y                          , dct_linesize, block[0]);
  1745.                 s->dsp.idct_put(dest_y              + block_size, dct_linesize, block[1]);
  1746.                 s->dsp.idct_put(dest_y + dct_offset             , dct_linesize, block[2]);
  1747.                 s->dsp.idct_put(dest_y + dct_offset + block_size, dct_linesize, block[3]);
  1748.                 if(!ENABLE_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1749.                     if(s->chroma_y_shift){
  1750.                         s->dsp.idct_put(dest_cb, uvlinesize, block[4]);
  1751.                         s->dsp.idct_put(dest_cr, uvlinesize, block[5]);
  1752.                     }else{
  1753.                         dct_linesize = uvlinesize << s->interlaced_dct;
  1754.                         dct_offset =(s->interlaced_dct)? uvlinesize : uvlinesize*8;
  1755.                         s->dsp.idct_put(dest_cb,              dct_linesize, block[4]);
  1756.                         s->dsp.idct_put(dest_cr,              dct_linesize, block[5]);
  1757.                         s->dsp.idct_put(dest_cb + dct_offset, dct_linesize, block[6]);
  1758.                         s->dsp.idct_put(dest_cr + dct_offset, dct_linesize, block[7]);
  1759.                         if(!s->chroma_x_shift){//Chroma444
  1760.                             s->dsp.idct_put(dest_cb + 8,              dct_linesize, block[8]);
  1761.                             s->dsp.idct_put(dest_cr + 8,              dct_linesize, block[9]);
  1762.                             s->dsp.idct_put(dest_cb + 8 + dct_offset, dct_linesize, block[10]);
  1763.                             s->dsp.idct_put(dest_cr + 8 + dct_offset, dct_linesize, block[11]);
  1764.                         }
  1765.                     }
  1766.                 }//gray
  1767.             }
  1768.         }
  1769. skip_idct:
  1770.         if(!readable){
  1771.             s->dsp.put_pixels_tab[0][0](s->dest[0], dest_y ,   linesize,16);
  1772.             s->dsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[1], dest_cb, uvlinesize,16 >> s->chroma_y_shift);
  1773.             s->dsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[2], dest_cr, uvlinesize,16 >> s->chroma_y_shift);
  1774.         }
  1775.     }
  1776. }
  1777. void MPV_decode_mb(MpegEncContext *s, DCTELEM block[12][64]){
  1778. #ifndef CONFIG_SMALL
  1779.     if(s->out_format == FMT_MPEG1) {
  1780.         if(s->avctx->lowres) MPV_decode_mb_internal(s, block, 1, 1);
  1781.         else                 MPV_decode_mb_internal(s, block, 0, 1);
  1782.     } else
  1783. #endif
  1784.     if(s->avctx->lowres) MPV_decode_mb_internal(s, block, 1, 0);
  1785.     else                  MPV_decode_mb_internal(s, block, 0, 0);
  1786. }
  1787. /**
  1788.  *
  1789.  * @param h is the normal height, this will be reduced automatically if needed for the last row
  1790.  */
  1791. void ff_draw_horiz_band(MpegEncContext *s, int y, int h){
  1792.     if (s->avctx->draw_horiz_band) {
  1793.         AVFrame *src;
  1794.         int offset[4];
  1795.         if(s->picture_structure != PICT_FRAME){
  1796.             h <<= 1;
  1797.             y <<= 1;
  1798.             if(s->first_field  && !(s->avctx->slice_flags&SLICE_FLAG_ALLOW_FIELD)) return;
  1799.         }
  1800.         h= FFMIN(h, s->avctx->height - y);
  1801.         if(s->pict_type==FF_B_TYPE || s->low_delay || (s->avctx->slice_flags&SLICE_FLAG_CODED_ORDER))
  1802.             src= (AVFrame*)s->current_picture_ptr;
  1803.         else if(s->last_picture_ptr)
  1804.             src= (AVFrame*)s->last_picture_ptr;
  1805.         else
  1806.             return;
  1807.         if(s->pict_type==FF_B_TYPE && s->picture_structure == PICT_FRAME && s->out_format != FMT_H264){
  1808.             offset[0]=
  1809.             offset[1]=
  1810.             offset[2]=
  1811.             offset[3]= 0;
  1812.         }else{
  1813.             offset[0]= y * s->linesize;
  1814.             offset[1]=
  1815.             offset[2]= (y >> s->chroma_y_shift) * s->uvlinesize;
  1816.             offset[3]= 0;
  1817.         }
  1818.         emms_c();
  1819.         s->avctx->draw_horiz_band(s->avctx, src, offset,
  1820.                                   y, s->picture_structure, h);
  1821.     }
  1822. }
  1823. void ff_init_block_index(MpegEncContext *s){ //FIXME maybe rename
  1824.     const int linesize= s->current_picture.linesize[0]; //not s->linesize as this would be wrong for field pics
  1825.     const int uvlinesize= s->current_picture.linesize[1];
  1826.     const int mb_size= 4 - s->avctx->lowres;
  1827.     s->block_index[0]= s->b8_stride*(s->mb_y*2    ) - 2 + s->mb_x*2;
  1828.     s->block_index[1]= s->b8_stride*(s->mb_y*2    ) - 1 + s->mb_x*2;
  1829.     s->block_index[2]= s->b8_stride*(s->mb_y*2 + 1) - 2 + s->mb_x*2;
  1830.     s->block_index[3]= s->b8_stride*(s->mb_y*2 + 1) - 1 + s->mb_x*2;
  1831.     s->block_index[4]= s->mb_stride*(s->mb_y + 1)                + s->b8_stride*s->mb_height*2 + s->mb_x - 1;
  1832.     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;
  1833.     //block_index is not used by mpeg2, so it is not affected by chroma_format
  1834.     s->dest[0] = s->current_picture.data[0] + ((s->mb_x - 1) << mb_size);
  1835.     s->dest[1] = s->current_picture.data[1] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
  1836.     s->dest[2] = s->current_picture.data[2] + ((s->mb_x - 1) << (mb_size - s->chroma_x_shift));
  1837.     if(!(s->pict_type==FF_B_TYPE && s->avctx->draw_horiz_band && s->picture_structure==PICT_FRAME))
  1838.     {
  1839.         s->dest[0] += s->mb_y *   linesize << mb_size;
  1840.         s->dest[1] += s->mb_y * uvlinesize << (mb_size - s->chroma_y_shift);
  1841.         s->dest[2] += s->mb_y * uvlinesize << (mb_size - s->chroma_y_shift);
  1842.     }
  1843. }
  1844. void ff_mpeg_flush(AVCodecContext *avctx){
  1845.     int i;
  1846.     MpegEncContext *s = avctx->priv_data;
  1847.     if(s==NULL || s->picture==NULL)
  1848.         return;
  1849.     for(i=0; i<MAX_PICTURE_COUNT; i++){
  1850.        if(s->picture[i].data[0] && (   s->picture[i].type == FF_BUFFER_TYPE_INTERNAL
  1851.                                     || s->picture[i].type == FF_BUFFER_TYPE_USER))
  1852.         avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);
  1853.     }
  1854.     s->current_picture_ptr = s->last_picture_ptr = s->next_picture_ptr = NULL;
  1855.     s->mb_x= s->mb_y= 0;
  1856.     s->parse_context.state= -1;
  1857.     s->parse_context.frame_start_found= 0;
  1858.     s->parse_context.overread= 0;
  1859.     s->parse_context.overread_index= 0;
  1860.     s->parse_context.index= 0;
  1861.     s->parse_context.last_index= 0;
  1862.     s->bitstream_buffer_size=0;
  1863.     s->pp_time=0;
  1864. }
  1865. static void dct_unquantize_mpeg1_intra_c(MpegEncContext *s,
  1866.                                    DCTELEM *block, int n, int qscale)
  1867. {
  1868.     int i, level, nCoeffs;
  1869.     const uint16_t *quant_matrix;
  1870.     nCoeffs= s->block_last_index[n];
  1871.     if (n < 4)
  1872.         block[0] = block[0] * s->y_dc_scale;
  1873.     else
  1874.         block[0] = block[0] * s->c_dc_scale;
  1875.     /* XXX: only mpeg1 */
  1876.     quant_matrix = s->intra_matrix;
  1877.     for(i=1;i<=nCoeffs;i++) {
  1878.         int j= s->intra_scantable.permutated[i];
  1879.         level = block[j];
  1880.         if (level) {
  1881.             if (level < 0) {
  1882.                 level = -level;
  1883.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1884.                 level = (level - 1) | 1;
  1885.                 level = -level;
  1886.             } else {
  1887.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1888.                 level = (level - 1) | 1;
  1889.             }
  1890.             block[j] = level;
  1891.         }
  1892.     }
  1893. }
  1894. static void dct_unquantize_mpeg1_inter_c(MpegEncContext *s,
  1895.                                    DCTELEM *block, int n, int qscale)
  1896. {
  1897.     int i, level, nCoeffs;
  1898.     const uint16_t *quant_matrix;
  1899.     nCoeffs= s->block_last_index[n];
  1900.     quant_matrix = s->inter_matrix;
  1901.     for(i=0; i<=nCoeffs; i++) {
  1902.         int j= s->intra_scantable.permutated[i];
  1903.         level = block[j];
  1904.         if (level) {
  1905.             if (level < 0) {
  1906.                 level = -level;
  1907.                 level = (((level << 1) + 1) * qscale *
  1908.                          ((int) (quant_matrix[j]))) >> 4;
  1909.                 level = (level - 1) | 1;
  1910.                 level = -level;
  1911.             } else {
  1912.                 level = (((level << 1) + 1) * qscale *
  1913.                          ((int) (quant_matrix[j]))) >> 4;
  1914.                 level = (level - 1) | 1;
  1915.             }
  1916.             block[j] = level;
  1917.         }
  1918.     }
  1919. }
  1920. static void dct_unquantize_mpeg2_intra_c(MpegEncContext *s,
  1921.                                    DCTELEM *block, int n, int qscale)
  1922. {
  1923.     int i, level, nCoeffs;
  1924.     const uint16_t *quant_matrix;
  1925.     if(s->alternate_scan) nCoeffs= 63;
  1926.     else nCoeffs= s->block_last_index[n];
  1927.     if (n < 4)
  1928.         block[0] = block[0] * s->y_dc_scale;
  1929.     else
  1930.         block[0] = block[0] * s->c_dc_scale;
  1931.     quant_matrix = s->intra_matrix;
  1932.     for(i=1;i<=nCoeffs;i++) {
  1933.         int j= s->intra_scantable.permutated[i];
  1934.         level = block[j];
  1935.         if (level) {
  1936.             if (level < 0) {
  1937.                 level = -level;
  1938.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1939.                 level = -level;
  1940.             } else {
  1941.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1942.             }
  1943.             block[j] = level;
  1944.         }
  1945.     }
  1946. }
  1947. static void dct_unquantize_mpeg2_intra_bitexact(MpegEncContext *s,
  1948.                                    DCTELEM *block, int n, int qscale)
  1949. {
  1950.     int i, level, nCoeffs;
  1951.     const uint16_t *quant_matrix;
  1952.     int sum=-1;
  1953.     if(s->alternate_scan) nCoeffs= 63;
  1954.     else nCoeffs= s->block_last_index[n];
  1955.     if (n < 4)
  1956.         block[0] = block[0] * s->y_dc_scale;
  1957.     else
  1958.         block[0] = block[0] * s->c_dc_scale;
  1959.     quant_matrix = s->intra_matrix;
  1960.     for(i=1;i<=nCoeffs;i++) {
  1961.         int j= s->intra_scantable.permutated[i];
  1962.         level = block[j];
  1963.         if (level) {
  1964.             if (level < 0) {
  1965.                 level = -level;
  1966.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1967.                 level = -level;
  1968.             } else {
  1969.                 level = (int)(level * qscale * quant_matrix[j]) >> 3;
  1970.             }
  1971.             block[j] = level;
  1972.             sum+=level;
  1973.         }
  1974.     }
  1975.     block[63]^=sum&1;
  1976. }
  1977. static void dct_unquantize_mpeg2_inter_c(MpegEncContext *s,
  1978.                                    DCTELEM *block, int n, int qscale)
  1979. {
  1980.     int i, level, nCoeffs;
  1981.     const uint16_t *quant_matrix;
  1982.     int sum=-1;
  1983.     if(s->alternate_scan) nCoeffs= 63;
  1984.     else nCoeffs= s->block_last_index[n];
  1985.     quant_matrix = s->inter_matrix;
  1986.     for(i=0; i<=nCoeffs; i++) {
  1987.         int j= s->intra_scantable.permutated[i];
  1988.         level = block[j];
  1989.         if (level) {
  1990.             if (level < 0) {
  1991.                 level = -level;
  1992.                 level = (((level << 1) + 1) * qscale *
  1993.                          ((int) (quant_matrix[j]))) >> 4;
  1994.                 level = -level;
  1995.             } else {
  1996.                 level = (((level << 1) + 1) * qscale *
  1997.                          ((int) (quant_matrix[j]))) >> 4;
  1998.             }
  1999.             block[j] = level;
  2000.             sum+=level;
  2001.         }
  2002.     }
  2003.     block[63]^=sum&1;
  2004. }
  2005. static void dct_unquantize_h263_intra_c(MpegEncContext *s,
  2006.                                   DCTELEM *block, int n, int qscale)
  2007. {
  2008.     int i, level, qmul, qadd;
  2009.     int nCoeffs;
  2010.     assert(s->block_last_index[n]>=0);
  2011.     qmul = qscale << 1;
  2012.     if (!s->h263_aic) {
  2013.         if (n < 4)
  2014.             block[0] = block[0] * s->y_dc_scale;
  2015.         else
  2016.             block[0] = block[0] * s->c_dc_scale;
  2017.         qadd = (qscale - 1) | 1;
  2018.     }else{
  2019.         qadd = 0;
  2020.     }
  2021.     if(s->ac_pred)
  2022.         nCoeffs=63;
  2023.     else
  2024.         nCoeffs= s->inter_scantable.raster_end[ s->block_last_index[n] ];
  2025.     for(i=1; i<=nCoeffs; i++) {
  2026.         level = block[i];
  2027.         if (level) {
  2028.             if (level < 0) {
  2029.                 level = level * qmul - qadd;
  2030.             } else {
  2031.                 level = level * qmul + qadd;
  2032.             }
  2033.             block[i] = level;
  2034.         }
  2035.     }
  2036. }
  2037. static void dct_unquantize_h263_inter_c(MpegEncContext *s,
  2038.                                   DCTELEM *block, int n, int qscale)
  2039. {
  2040.     int i, level, qmul, qadd;
  2041.     int nCoeffs;
  2042.     assert(s->block_last_index[n]>=0);
  2043.     qadd = (qscale - 1) | 1;
  2044.     qmul = qscale << 1;
  2045.     nCoeffs= s->inter_scantable.raster_end[ s->block_last_index[n] ];
  2046.     for(i=0; i<=nCoeffs; i++) {
  2047.         level = block[i];
  2048.         if (level) {
  2049.             if (level < 0) {
  2050.                 level = level * qmul - qadd;
  2051.             } else {
  2052.                 level = level * qmul + qadd;
  2053.             }
  2054.             block[i] = level;
  2055.         }
  2056.     }
  2057. }
  2058. /**
  2059.  * set qscale and update qscale dependent variables.
  2060.  */
  2061. void ff_set_qscale(MpegEncContext * s, int qscale)
  2062. {
  2063.     if (qscale < 1)
  2064.         qscale = 1;
  2065.     else if (qscale > 31)
  2066.         qscale = 31;
  2067.     s->qscale = qscale;
  2068.     s->chroma_qscale= s->chroma_qscale_table[qscale];
  2069.     s->y_dc_scale= s->y_dc_scale_table[ qscale ];
  2070.     s->c_dc_scale= s->c_dc_scale_table[ s->chroma_qscale ];
  2071. }