Libav 0.7.1
libavcodec/mpegvideo_enc.c
Go to the documentation of this file.
00001 /*
00002  * The simplest mpeg encoder (well, it was the simplest!)
00003  * Copyright (c) 2000,2001 Fabrice Bellard
00004  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
00005  *
00006  * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
00007  *
00008  * This file is part of Libav.
00009  *
00010  * Libav is free software; you can redistribute it and/or
00011  * modify it under the terms of the GNU Lesser General Public
00012  * License as published by the Free Software Foundation; either
00013  * version 2.1 of the License, or (at your option) any later version.
00014  *
00015  * Libav is distributed in the hope that it will be useful,
00016  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00017  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00018  * Lesser General Public License for more details.
00019  *
00020  * You should have received a copy of the GNU Lesser General Public
00021  * License along with Libav; if not, write to the Free Software
00022  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00023  */
00024 
00030 #include "libavutil/intmath.h"
00031 #include "avcodec.h"
00032 #include "dsputil.h"
00033 #include "mpegvideo.h"
00034 #include "mpegvideo_common.h"
00035 #include "h263.h"
00036 #include "mjpegenc.h"
00037 #include "msmpeg4.h"
00038 #include "faandct.h"
00039 #include "thread.h"
00040 #include "aandcttab.h"
00041 #include "flv.h"
00042 #include "mpeg4video.h"
00043 #include "internal.h"
00044 #include <limits.h>
00045 
00046 //#undef NDEBUG
00047 //#include <assert.h>
00048 
00049 static int encode_picture(MpegEncContext *s, int picture_number);
00050 static int dct_quantize_refine(MpegEncContext *s, DCTELEM *block, int16_t *weight, DCTELEM *orig, int n, int qscale);
00051 static int sse_mb(MpegEncContext *s);
00052 static void denoise_dct_c(MpegEncContext *s, DCTELEM *block);
00053 static int dct_quantize_trellis_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
00054 
00055 /* enable all paranoid tests for rounding, overflows, etc... */
00056 //#define PARANOID
00057 
00058 //#define DEBUG
00059 
00060 static uint8_t default_mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
00061 static uint8_t default_fcode_tab[MAX_MV*2+1];
00062 
00063 void ff_convert_matrix(DSPContext *dsp, int (*qmat)[64], uint16_t (*qmat16)[2][64],
00064                            const uint16_t *quant_matrix, int bias, int qmin, int qmax, int intra)
00065 {
00066     int qscale;
00067     int shift=0;
00068 
00069     for(qscale=qmin; qscale<=qmax; qscale++){
00070         int i;
00071         if (dsp->fdct == ff_jpeg_fdct_islow
00072 #ifdef FAAN_POSTSCALE
00073             || dsp->fdct == ff_faandct
00074 #endif
00075             ) {
00076             for(i=0;i<64;i++) {
00077                 const int j= dsp->idct_permutation[i];
00078                 /* 16 <= qscale * quant_matrix[i] <= 7905 */
00079                 /* 19952             <= ff_aanscales[i] * qscale * quant_matrix[i]               <= 249205026 */
00080                 /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1 << 36) / 249205026 */
00081                 /* 3444240           >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
00082 
00083                 qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) /
00084                                 (qscale * quant_matrix[j]));
00085             }
00086         } else if (dsp->fdct == fdct_ifast
00087 #ifndef FAAN_POSTSCALE
00088                    || dsp->fdct == ff_faandct
00089 #endif
00090                    ) {
00091             for(i=0;i<64;i++) {
00092                 const int j= dsp->idct_permutation[i];
00093                 /* 16 <= qscale * quant_matrix[i] <= 7905 */
00094                 /* 19952             <= ff_aanscales[i] * qscale * quant_matrix[i]               <= 249205026 */
00095                 /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
00096                 /* 3444240           >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
00097 
00098                 qmat[qscale][i] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) /
00099                                 (ff_aanscales[i] * qscale * quant_matrix[j]));
00100             }
00101         } else {
00102             for(i=0;i<64;i++) {
00103                 const int j= dsp->idct_permutation[i];
00104                 /* We can safely suppose that 16 <= quant_matrix[i] <= 255
00105                    So 16           <= qscale * quant_matrix[i]             <= 7905
00106                    so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
00107                    so 32768        >= (1<<19) / (qscale * quant_matrix[i]) >= 67
00108                 */
00109                 qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) / (qscale * quant_matrix[j]));
00110 //                qmat  [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
00111                 qmat16[qscale][0][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[j]);
00112 
00113                 if(qmat16[qscale][0][i]==0 || qmat16[qscale][0][i]==128*256) qmat16[qscale][0][i]=128*256-1;
00114                 qmat16[qscale][1][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][0][i]);
00115             }
00116         }
00117 
00118         for(i=intra; i<64; i++){
00119             int64_t max= 8191;
00120             if (dsp->fdct == fdct_ifast
00121 #ifndef FAAN_POSTSCALE
00122                    || dsp->fdct == ff_faandct
00123 #endif
00124                    ) {
00125                 max = (8191LL*ff_aanscales[i]) >> 14;
00126             }
00127             while(((max * qmat[qscale][i]) >> shift) > INT_MAX){
00128                 shift++;
00129             }
00130         }
00131     }
00132     if(shift){
00133         av_log(NULL, AV_LOG_INFO, "Warning, QMAT_SHIFT is larger than %d, overflows possible\n", QMAT_SHIFT - shift);
00134     }
00135 }
00136 
00137 static inline void update_qscale(MpegEncContext *s){
00138     s->qscale= (s->lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
00139     s->qscale= av_clip(s->qscale, s->avctx->qmin, s->avctx->qmax);
00140 
00141     s->lambda2= (s->lambda*s->lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
00142 }
00143 
00144 void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix){
00145     int i;
00146 
00147     if(matrix){
00148         put_bits(pb, 1, 1);
00149         for(i=0;i<64;i++) {
00150             put_bits(pb, 8, matrix[ ff_zigzag_direct[i] ]);
00151         }
00152     }else
00153         put_bits(pb, 1, 0);
00154 }
00155 
00159 void ff_init_qscale_tab(MpegEncContext *s){
00160     int8_t * const qscale_table= s->current_picture.qscale_table;
00161     int i;
00162 
00163     for(i=0; i<s->mb_num; i++){
00164         unsigned int lam= s->lambda_table[ s->mb_index2xy[i] ];
00165         int qp= (lam*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
00166         qscale_table[ s->mb_index2xy[i] ]= av_clip(qp, s->avctx->qmin, s->avctx->qmax);
00167     }
00168 }
00169 
00170 static void copy_picture_attributes(MpegEncContext *s, AVFrame *dst, AVFrame *src){
00171     int i;
00172 
00173     dst->pict_type              = src->pict_type;
00174     dst->quality                = src->quality;
00175     dst->coded_picture_number   = src->coded_picture_number;
00176     dst->display_picture_number = src->display_picture_number;
00177 //    dst->reference              = src->reference;
00178     dst->pts                    = src->pts;
00179     dst->interlaced_frame       = src->interlaced_frame;
00180     dst->top_field_first        = src->top_field_first;
00181 
00182     if(s->avctx->me_threshold){
00183         if(!src->motion_val[0])
00184             av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_val not set!\n");
00185         if(!src->mb_type)
00186             av_log(s->avctx, AV_LOG_ERROR, "AVFrame.mb_type not set!\n");
00187         if(!src->ref_index[0])
00188             av_log(s->avctx, AV_LOG_ERROR, "AVFrame.ref_index not set!\n");
00189         if(src->motion_subsample_log2 != dst->motion_subsample_log2)
00190             av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_subsample_log2 doesn't match! (%d!=%d)\n",
00191             src->motion_subsample_log2, dst->motion_subsample_log2);
00192 
00193         memcpy(dst->mb_type, src->mb_type, s->mb_stride * s->mb_height * sizeof(dst->mb_type[0]));
00194 
00195         for(i=0; i<2; i++){
00196             int stride= ((16*s->mb_width )>>src->motion_subsample_log2) + 1;
00197             int height= ((16*s->mb_height)>>src->motion_subsample_log2);
00198 
00199             if(src->motion_val[i] && src->motion_val[i] != dst->motion_val[i]){
00200                 memcpy(dst->motion_val[i], src->motion_val[i], 2*stride*height*sizeof(int16_t));
00201             }
00202             if(src->ref_index[i] && src->ref_index[i] != dst->ref_index[i]){
00203                 memcpy(dst->ref_index[i], src->ref_index[i], s->mb_stride*4*s->mb_height*sizeof(int8_t));
00204             }
00205         }
00206     }
00207 }
00208 
00209 static void update_duplicate_context_after_me(MpegEncContext *dst, MpegEncContext *src){
00210 #define COPY(a) dst->a= src->a
00211     COPY(pict_type);
00212     COPY(current_picture);
00213     COPY(f_code);
00214     COPY(b_code);
00215     COPY(qscale);
00216     COPY(lambda);
00217     COPY(lambda2);
00218     COPY(picture_in_gop_number);
00219     COPY(gop_picture_number);
00220     COPY(frame_pred_frame_dct); //FIXME don't set in encode_header
00221     COPY(progressive_frame); //FIXME don't set in encode_header
00222     COPY(partitioned_frame); //FIXME don't set in encode_header
00223 #undef COPY
00224 }
00225 
00230 static void MPV_encode_defaults(MpegEncContext *s){
00231     int i;
00232     MPV_common_defaults(s);
00233 
00234     for(i=-16; i<16; i++){
00235         default_fcode_tab[i + MAX_MV]= 1;
00236     }
00237     s->me.mv_penalty= default_mv_penalty;
00238     s->fcode_tab= default_fcode_tab;
00239 }
00240 
00241 /* init video encoder */
00242 av_cold int MPV_encode_init(AVCodecContext *avctx)
00243 {
00244     MpegEncContext *s = avctx->priv_data;
00245     int i;
00246     int chroma_h_shift, chroma_v_shift;
00247 
00248     MPV_encode_defaults(s);
00249 
00250     switch (avctx->codec_id) {
00251     case CODEC_ID_MPEG2VIDEO:
00252         if(avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P){
00253             av_log(avctx, AV_LOG_ERROR, "only YUV420 and YUV422 are supported\n");
00254             return -1;
00255         }
00256         break;
00257     case CODEC_ID_LJPEG:
00258         if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P && avctx->pix_fmt != PIX_FMT_YUVJ444P && avctx->pix_fmt != PIX_FMT_BGRA &&
00259            ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P && avctx->pix_fmt != PIX_FMT_YUV444P) || avctx->strict_std_compliance>FF_COMPLIANCE_UNOFFICIAL)){
00260             av_log(avctx, AV_LOG_ERROR, "colorspace not supported in LJPEG\n");
00261             return -1;
00262         }
00263         break;
00264     case CODEC_ID_MJPEG:
00265         if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P &&
00266            ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P) || avctx->strict_std_compliance>FF_COMPLIANCE_UNOFFICIAL)){
00267             av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");
00268             return -1;
00269         }
00270         break;
00271     default:
00272         if(avctx->pix_fmt != PIX_FMT_YUV420P){
00273             av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");
00274             return -1;
00275         }
00276     }
00277 
00278     switch (avctx->pix_fmt) {
00279     case PIX_FMT_YUVJ422P:
00280     case PIX_FMT_YUV422P:
00281         s->chroma_format = CHROMA_422;
00282         break;
00283     case PIX_FMT_YUVJ420P:
00284     case PIX_FMT_YUV420P:
00285     default:
00286         s->chroma_format = CHROMA_420;
00287         break;
00288     }
00289 
00290     s->bit_rate = avctx->bit_rate;
00291     s->width = avctx->width;
00292     s->height = avctx->height;
00293     if(avctx->gop_size > 600 && avctx->strict_std_compliance>FF_COMPLIANCE_EXPERIMENTAL){
00294         av_log(avctx, AV_LOG_ERROR, "Warning keyframe interval too large! reducing it ...\n");
00295         avctx->gop_size=600;
00296     }
00297     s->gop_size = avctx->gop_size;
00298     s->avctx = avctx;
00299     s->flags= avctx->flags;
00300     s->flags2= avctx->flags2;
00301     s->max_b_frames= avctx->max_b_frames;
00302     s->codec_id= avctx->codec->id;
00303     s->luma_elim_threshold  = avctx->luma_elim_threshold;
00304     s->chroma_elim_threshold= avctx->chroma_elim_threshold;
00305     s->strict_std_compliance= avctx->strict_std_compliance;
00306     s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
00307     s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;
00308     s->mpeg_quant= avctx->mpeg_quant;
00309     s->rtp_mode= !!avctx->rtp_payload_size;
00310     s->intra_dc_precision= avctx->intra_dc_precision;
00311     s->user_specified_pts = AV_NOPTS_VALUE;
00312 
00313     if (s->gop_size <= 1) {
00314         s->intra_only = 1;
00315         s->gop_size = 12;
00316     } else {
00317         s->intra_only = 0;
00318     }
00319 
00320     s->me_method = avctx->me_method;
00321 
00322     /* Fixed QSCALE */
00323     s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);
00324 
00325     s->adaptive_quant= (   s->avctx->lumi_masking
00326                         || s->avctx->dark_masking
00327                         || s->avctx->temporal_cplx_masking
00328                         || s->avctx->spatial_cplx_masking
00329                         || s->avctx->p_masking
00330                         || s->avctx->border_masking
00331                         || (s->flags&CODEC_FLAG_QP_RD))
00332                        && !s->fixed_qscale;
00333 
00334     s->obmc= !!(s->flags & CODEC_FLAG_OBMC);
00335     s->loop_filter= !!(s->flags & CODEC_FLAG_LOOP_FILTER);
00336     s->alternate_scan= !!(s->flags & CODEC_FLAG_ALT_SCAN);
00337     s->intra_vlc_format= !!(s->flags2 & CODEC_FLAG2_INTRA_VLC);
00338     s->q_scale_type= !!(s->flags2 & CODEC_FLAG2_NON_LINEAR_QUANT);
00339 
00340     if(avctx->rc_max_rate && !avctx->rc_buffer_size){
00341         av_log(avctx, AV_LOG_ERROR, "a vbv buffer size is needed, for encoding with a maximum bitrate\n");
00342         return -1;
00343     }
00344 
00345     if(avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate){
00346         av_log(avctx, AV_LOG_INFO, "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");
00347     }
00348 
00349     if(avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate){
00350         av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");
00351         return -1;
00352     }
00353 
00354     if(avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate){
00355         av_log(avctx, AV_LOG_INFO, "bitrate above max bitrate\n");
00356         return -1;
00357     }
00358 
00359     if(avctx->rc_max_rate && avctx->rc_max_rate == avctx->bit_rate && avctx->rc_max_rate != avctx->rc_min_rate){
00360         av_log(avctx, AV_LOG_INFO, "impossible bitrate constraints, this will fail\n");
00361     }
00362 
00363     if(avctx->rc_buffer_size && avctx->bit_rate*(int64_t)avctx->time_base.num > avctx->rc_buffer_size * (int64_t)avctx->time_base.den){
00364         av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");
00365         return -1;
00366     }
00367 
00368     if(!s->fixed_qscale && avctx->bit_rate*av_q2d(avctx->time_base) > avctx->bit_rate_tolerance){
00369         av_log(avctx, AV_LOG_ERROR, "bitrate tolerance too small for bitrate\n");
00370         return -1;
00371     }
00372 
00373     if(   s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate
00374        && (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO)
00375        && 90000LL * (avctx->rc_buffer_size-1) > s->avctx->rc_max_rate*0xFFFFLL){
00376 
00377         av_log(avctx, AV_LOG_INFO, "Warning vbv_delay will be set to 0xFFFF (=VBR) as the specified vbv buffer is too large for the given bitrate!\n");
00378     }
00379 
00380     if((s->flags & CODEC_FLAG_4MV) && s->codec_id != CODEC_ID_MPEG4
00381        && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P && s->codec_id != CODEC_ID_FLV1){
00382         av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
00383         return -1;
00384     }
00385 
00386     if(s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE){
00387         av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with simple mb decision\n");
00388         return -1;
00389     }
00390 
00391     if(s->obmc && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P){
00392         av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with H263(+)\n");
00393         return -1;
00394     }
00395 
00396     if(s->quarter_sample && s->codec_id != CODEC_ID_MPEG4){
00397         av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
00398         return -1;
00399     }
00400 
00401     if(s->data_partitioning && s->codec_id != CODEC_ID_MPEG4){
00402         av_log(avctx, AV_LOG_ERROR, "data partitioning not supported by codec\n");
00403         return -1;
00404     }
00405 
00406     if(s->max_b_frames && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO){
00407         av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
00408         return -1;
00409     }
00410 
00411     if ((s->codec_id == CODEC_ID_MPEG4 || s->codec_id == CODEC_ID_H263 ||
00412          s->codec_id == CODEC_ID_H263P) &&
00413         (avctx->sample_aspect_ratio.num > 255 || avctx->sample_aspect_ratio.den > 255)) {
00414         av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i, limit is 255/255\n",
00415                avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
00416         return -1;
00417     }
00418 
00419     if((s->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN))
00420        && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG2VIDEO){
00421         av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");
00422         return -1;
00423     }
00424 
00425     if(s->mpeg_quant && s->codec_id != CODEC_ID_MPEG4){ //FIXME mpeg2 uses that too
00426         av_log(avctx, AV_LOG_ERROR, "mpeg2 style quantization not supported by codec\n");
00427         return -1;
00428     }
00429 
00430     if((s->flags & CODEC_FLAG_CBP_RD) && !avctx->trellis){
00431         av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
00432         return -1;
00433     }
00434 
00435     if((s->flags & CODEC_FLAG_QP_RD) && s->avctx->mb_decision != FF_MB_DECISION_RD){
00436         av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");
00437         return -1;
00438     }
00439 
00440     if(s->avctx->scenechange_threshold < 1000000000 && (s->flags & CODEC_FLAG_CLOSED_GOP)){
00441         av_log(avctx, AV_LOG_ERROR, "closed gop with scene change detection are not supported yet, set threshold to 1000000000\n");
00442         return -1;
00443     }
00444 
00445     if((s->flags2 & CODEC_FLAG2_INTRA_VLC) && s->codec_id != CODEC_ID_MPEG2VIDEO){
00446         av_log(avctx, AV_LOG_ERROR, "intra vlc table not supported by codec\n");
00447         return -1;
00448     }
00449 
00450     if(s->flags & CODEC_FLAG_LOW_DELAY){
00451         if (s->codec_id != CODEC_ID_MPEG2VIDEO){
00452             av_log(avctx, AV_LOG_ERROR, "low delay forcing is only available for mpeg2\n");
00453             return -1;
00454         }
00455         if (s->max_b_frames != 0){
00456             av_log(avctx, AV_LOG_ERROR, "b frames cannot be used with low delay\n");
00457             return -1;
00458         }
00459     }
00460 
00461     if(s->q_scale_type == 1){
00462         if(s->codec_id != CODEC_ID_MPEG2VIDEO){
00463             av_log(avctx, AV_LOG_ERROR, "non linear quant is only available for mpeg2\n");
00464             return -1;
00465         }
00466         if(avctx->qmax > 12){
00467             av_log(avctx, AV_LOG_ERROR, "non linear quant only supports qmax <= 12 currently\n");
00468             return -1;
00469         }
00470     }
00471 
00472     if(s->avctx->thread_count > 1 && s->codec_id != CODEC_ID_MPEG4
00473        && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO
00474        && (s->codec_id != CODEC_ID_H263P || !(s->flags & CODEC_FLAG_H263P_SLICE_STRUCT))){
00475         av_log(avctx, AV_LOG_ERROR, "multi threaded encoding not supported by codec\n");
00476         return -1;
00477     }
00478 
00479     if(s->avctx->thread_count < 1){
00480         av_log(avctx, AV_LOG_ERROR, "automatic thread number detection not supported by codec, patch welcome\n");
00481         return -1;
00482     }
00483 
00484     if(s->avctx->thread_count > 1)
00485         s->rtp_mode= 1;
00486 
00487     if(!avctx->time_base.den || !avctx->time_base.num){
00488         av_log(avctx, AV_LOG_ERROR, "framerate not set\n");
00489         return -1;
00490     }
00491 
00492     i= (INT_MAX/2+128)>>8;
00493     if(avctx->me_threshold >= i){
00494         av_log(avctx, AV_LOG_ERROR, "me_threshold too large, max is %d\n", i - 1);
00495         return -1;
00496     }
00497     if(avctx->mb_threshold >= i){
00498         av_log(avctx, AV_LOG_ERROR, "mb_threshold too large, max is %d\n", i - 1);
00499         return -1;
00500     }
00501 
00502     if(avctx->b_frame_strategy && (avctx->flags&CODEC_FLAG_PASS2)){
00503         av_log(avctx, AV_LOG_INFO, "notice: b_frame_strategy only affects the first pass\n");
00504         avctx->b_frame_strategy = 0;
00505     }
00506 
00507     i= av_gcd(avctx->time_base.den, avctx->time_base.num);
00508     if(i > 1){
00509         av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");
00510         avctx->time_base.den /= i;
00511         avctx->time_base.num /= i;
00512 //        return -1;
00513     }
00514 
00515     if(s->mpeg_quant || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO || s->codec_id==CODEC_ID_MJPEG){
00516         s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
00517         s->inter_quant_bias= 0;
00518     }else{
00519         s->intra_quant_bias=0;
00520         s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
00521     }
00522 
00523     if(avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
00524         s->intra_quant_bias= avctx->intra_quant_bias;
00525     if(avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
00526         s->inter_quant_bias= avctx->inter_quant_bias;
00527 
00528     avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);
00529 
00530     if(avctx->codec_id == CODEC_ID_MPEG4 && s->avctx->time_base.den > (1<<16)-1){
00531         av_log(avctx, AV_LOG_ERROR, "timebase %d/%d not supported by MPEG 4 standard, "
00532                "the maximum admitted value for the timebase denominator is %d\n",
00533                s->avctx->time_base.num, s->avctx->time_base.den, (1<<16)-1);
00534         return -1;
00535     }
00536     s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
00537 
00538     switch(avctx->codec->id) {
00539     case CODEC_ID_MPEG1VIDEO:
00540         s->out_format = FMT_MPEG1;
00541         s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
00542         avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
00543         break;
00544     case CODEC_ID_MPEG2VIDEO:
00545         s->out_format = FMT_MPEG1;
00546         s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
00547         avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
00548         s->rtp_mode= 1;
00549         break;
00550     case CODEC_ID_LJPEG:
00551     case CODEC_ID_MJPEG:
00552         s->out_format = FMT_MJPEG;
00553         s->intra_only = 1; /* force intra only for jpeg */
00554         if(avctx->codec->id == CODEC_ID_LJPEG && avctx->pix_fmt == PIX_FMT_BGRA){
00555             s->mjpeg_vsample[0] = s->mjpeg_hsample[0] =
00556             s->mjpeg_vsample[1] = s->mjpeg_hsample[1] =
00557             s->mjpeg_vsample[2] = s->mjpeg_hsample[2] = 1;
00558         }else{
00559             s->mjpeg_vsample[0] = 2;
00560             s->mjpeg_vsample[1] = 2>>chroma_v_shift;
00561             s->mjpeg_vsample[2] = 2>>chroma_v_shift;
00562             s->mjpeg_hsample[0] = 2;
00563             s->mjpeg_hsample[1] = 2>>chroma_h_shift;
00564             s->mjpeg_hsample[2] = 2>>chroma_h_shift;
00565         }
00566         if (!(CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER)
00567             || ff_mjpeg_encode_init(s) < 0)
00568             return -1;
00569         avctx->delay=0;
00570         s->low_delay=1;
00571         break;
00572     case CODEC_ID_H261:
00573         if (!CONFIG_H261_ENCODER)  return -1;
00574         if (ff_h261_get_picture_format(s->width, s->height) < 0) {
00575             av_log(avctx, AV_LOG_ERROR, "The specified picture size of %dx%d is not valid for the H.261 codec.\nValid sizes are 176x144, 352x288\n", s->width, s->height);
00576             return -1;
00577         }
00578         s->out_format = FMT_H261;
00579         avctx->delay=0;
00580         s->low_delay=1;
00581         break;
00582     case CODEC_ID_H263:
00583         if (!CONFIG_H263_ENCODER)  return -1;
00584         if (ff_match_2uint16(h263_format, FF_ARRAY_ELEMS(h263_format), s->width, s->height) == 8) {
00585             av_log(avctx, AV_LOG_INFO, "The specified picture size of %dx%d is not valid for the H.263 codec.\nValid sizes are 128x96, 176x144, 352x288, 704x576, and 1408x1152. Try H.263+.\n", s->width, s->height);
00586             return -1;
00587         }
00588         s->out_format = FMT_H263;
00589         s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
00590         avctx->delay=0;
00591         s->low_delay=1;
00592         break;
00593     case CODEC_ID_H263P:
00594         s->out_format = FMT_H263;
00595         s->h263_plus = 1;
00596         /* Fx */
00597         s->umvplus = (avctx->flags & CODEC_FLAG_H263P_UMV) ? 1:0;
00598         s->h263_aic= (avctx->flags & CODEC_FLAG_AC_PRED) ? 1:0;
00599         s->modified_quant= s->h263_aic;
00600         s->alt_inter_vlc= (avctx->flags & CODEC_FLAG_H263P_AIV) ? 1:0;
00601         s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
00602         s->loop_filter= (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1:0;
00603         s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;
00604         s->h263_slice_structured= (s->flags & CODEC_FLAG_H263P_SLICE_STRUCT) ? 1:0;
00605 
00606         /* /Fx */
00607         /* These are just to be sure */
00608         avctx->delay=0;
00609         s->low_delay=1;
00610         break;
00611     case CODEC_ID_FLV1:
00612         s->out_format = FMT_H263;
00613         s->h263_flv = 2; /* format = 1; 11-bit codes */
00614         s->unrestricted_mv = 1;
00615         s->rtp_mode=0; /* don't allow GOB */
00616         avctx->delay=0;
00617         s->low_delay=1;
00618         break;
00619     case CODEC_ID_RV10:
00620         s->out_format = FMT_H263;
00621         avctx->delay=0;
00622         s->low_delay=1;
00623         break;
00624     case CODEC_ID_RV20:
00625         s->out_format = FMT_H263;
00626         avctx->delay=0;
00627         s->low_delay=1;
00628         s->modified_quant=1;
00629         s->h263_aic=1;
00630         s->h263_plus=1;
00631         s->loop_filter=1;
00632         s->unrestricted_mv= 0;
00633         break;
00634     case CODEC_ID_MPEG4:
00635         s->out_format = FMT_H263;
00636         s->h263_pred = 1;
00637         s->unrestricted_mv = 1;
00638         s->low_delay= s->max_b_frames ? 0 : 1;
00639         avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
00640         break;
00641     case CODEC_ID_MSMPEG4V2:
00642         s->out_format = FMT_H263;
00643         s->h263_pred = 1;
00644         s->unrestricted_mv = 1;
00645         s->msmpeg4_version= 2;
00646         avctx->delay=0;
00647         s->low_delay=1;
00648         break;
00649     case CODEC_ID_MSMPEG4V3:
00650         s->out_format = FMT_H263;
00651         s->h263_pred = 1;
00652         s->unrestricted_mv = 1;
00653         s->msmpeg4_version= 3;
00654         s->flipflop_rounding=1;
00655         avctx->delay=0;
00656         s->low_delay=1;
00657         break;
00658     case CODEC_ID_WMV1:
00659         s->out_format = FMT_H263;
00660         s->h263_pred = 1;
00661         s->unrestricted_mv = 1;
00662         s->msmpeg4_version= 4;
00663         s->flipflop_rounding=1;
00664         avctx->delay=0;
00665         s->low_delay=1;
00666         break;
00667     case CODEC_ID_WMV2:
00668         s->out_format = FMT_H263;
00669         s->h263_pred = 1;
00670         s->unrestricted_mv = 1;
00671         s->msmpeg4_version= 5;
00672         s->flipflop_rounding=1;
00673         avctx->delay=0;
00674         s->low_delay=1;
00675         break;
00676     default:
00677         return -1;
00678     }
00679 
00680     avctx->has_b_frames= !s->low_delay;
00681 
00682     s->encoding = 1;
00683 
00684     s->progressive_frame=
00685     s->progressive_sequence= !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN));
00686 
00687     /* init */
00688     if (MPV_common_init(s) < 0)
00689         return -1;
00690 
00691     if(!s->dct_quantize)
00692         s->dct_quantize = dct_quantize_c;
00693     if(!s->denoise_dct)
00694         s->denoise_dct = denoise_dct_c;
00695     s->fast_dct_quantize = s->dct_quantize;
00696     if(avctx->trellis)
00697         s->dct_quantize = dct_quantize_trellis_c;
00698 
00699     if((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)
00700         s->chroma_qscale_table= ff_h263_chroma_qscale_table;
00701 
00702     s->quant_precision=5;
00703 
00704     ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);
00705     ff_set_cmp(&s->dsp, s->dsp.frame_skip_cmp, s->avctx->frame_skip_cmp);
00706 
00707     if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)
00708         ff_h261_encode_init(s);
00709     if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)
00710         h263_encode_init(s);
00711     if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
00712         ff_msmpeg4_encode_init(s);
00713     if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
00714         && s->out_format == FMT_MPEG1)
00715         ff_mpeg1_encode_init(s);
00716 
00717     /* init q matrix */
00718     for(i=0;i<64;i++) {
00719         int j= s->dsp.idct_permutation[i];
00720         if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
00721             s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
00722             s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
00723         }else if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
00724             s->intra_matrix[j] =
00725             s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
00726         }else
00727         { /* mpeg1/2 */
00728             s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
00729             s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
00730         }
00731         if(s->avctx->intra_matrix)
00732             s->intra_matrix[j] = s->avctx->intra_matrix[i];
00733         if(s->avctx->inter_matrix)
00734             s->inter_matrix[j] = s->avctx->inter_matrix[i];
00735     }
00736 
00737     /* precompute matrix */
00738     /* for mjpeg, we do include qscale in the matrix */
00739     if (s->out_format != FMT_MJPEG) {
00740         ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
00741                        s->intra_matrix, s->intra_quant_bias, avctx->qmin, 31, 1);
00742         ff_convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,
00743                        s->inter_matrix, s->inter_quant_bias, avctx->qmin, 31, 0);
00744     }
00745 
00746     if(ff_rate_control_init(s) < 0)
00747         return -1;
00748 
00749     return 0;
00750 }
00751 
00752 av_cold int MPV_encode_end(AVCodecContext *avctx)
00753 {
00754     MpegEncContext *s = avctx->priv_data;
00755 
00756     ff_rate_control_uninit(s);
00757 
00758     MPV_common_end(s);
00759     if ((CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER) && s->out_format == FMT_MJPEG)
00760         ff_mjpeg_encode_close(s);
00761 
00762     av_freep(&avctx->extradata);
00763 
00764     return 0;
00765 }
00766 
00767 static int get_sae(uint8_t *src, int ref, int stride){
00768     int x,y;
00769     int acc=0;
00770 
00771     for(y=0; y<16; y++){
00772         for(x=0; x<16; x++){
00773             acc+= FFABS(src[x+y*stride] - ref);
00774         }
00775     }
00776 
00777     return acc;
00778 }
00779 
00780 static int get_intra_count(MpegEncContext *s, uint8_t *src, uint8_t *ref, int stride){
00781     int x, y, w, h;
00782     int acc=0;
00783 
00784     w= s->width &~15;
00785     h= s->height&~15;
00786 
00787     for(y=0; y<h; y+=16){
00788         for(x=0; x<w; x+=16){
00789             int offset= x + y*stride;
00790             int sad = s->dsp.sad[0](NULL, src + offset, ref + offset, stride, 16);
00791             int mean= (s->dsp.pix_sum(src + offset, stride) + 128)>>8;
00792             int sae = get_sae(src + offset, mean, stride);
00793 
00794             acc+= sae + 500 < sad;
00795         }
00796     }
00797     return acc;
00798 }
00799 
00800 
00801 static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
00802     AVFrame *pic=NULL;
00803     int64_t pts;
00804     int i;
00805     const int encoding_delay= s->max_b_frames;
00806     int direct=1;
00807 
00808     if(pic_arg){
00809         pts= pic_arg->pts;
00810         pic_arg->display_picture_number= s->input_picture_number++;
00811 
00812         if(pts != AV_NOPTS_VALUE){
00813             if(s->user_specified_pts != AV_NOPTS_VALUE){
00814                 int64_t time= pts;
00815                 int64_t last= s->user_specified_pts;
00816 
00817                 if(time <= last){
00818                     av_log(s->avctx, AV_LOG_ERROR, "Error, Invalid timestamp=%"PRId64", last=%"PRId64"\n", pts, s->user_specified_pts);
00819                     return -1;
00820                 }
00821             }
00822             s->user_specified_pts= pts;
00823         }else{
00824             if(s->user_specified_pts != AV_NOPTS_VALUE){
00825                 s->user_specified_pts=
00826                 pts= s->user_specified_pts + 1;
00827                 av_log(s->avctx, AV_LOG_INFO, "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n", pts);
00828             }else{
00829                 pts= pic_arg->display_picture_number;
00830             }
00831         }
00832     }
00833 
00834   if(pic_arg){
00835     if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
00836     if(pic_arg->linesize[0] != s->linesize) direct=0;
00837     if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
00838     if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
00839 
00840 //    av_log(AV_LOG_DEBUG, "%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);
00841 
00842     if(direct){
00843         i= ff_find_unused_picture(s, 1);
00844 
00845         pic= (AVFrame*)&s->picture[i];
00846         pic->reference= 3;
00847 
00848         for(i=0; i<4; i++){
00849             pic->data[i]= pic_arg->data[i];
00850             pic->linesize[i]= pic_arg->linesize[i];
00851         }
00852         if(ff_alloc_picture(s, (Picture*)pic, 1) < 0){
00853             return -1;
00854         }
00855     }else{
00856         i= ff_find_unused_picture(s, 0);
00857 
00858         pic= (AVFrame*)&s->picture[i];
00859         pic->reference= 3;
00860 
00861         if(ff_alloc_picture(s, (Picture*)pic, 0) < 0){
00862             return -1;
00863         }
00864 
00865         if(   pic->data[0] + INPLACE_OFFSET == pic_arg->data[0]
00866            && pic->data[1] + INPLACE_OFFSET == pic_arg->data[1]
00867            && pic->data[2] + INPLACE_OFFSET == pic_arg->data[2]){
00868        // empty
00869         }else{
00870             int h_chroma_shift, v_chroma_shift;
00871             avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
00872 
00873             for(i=0; i<3; i++){
00874                 int src_stride= pic_arg->linesize[i];
00875                 int dst_stride= i ? s->uvlinesize : s->linesize;
00876                 int h_shift= i ? h_chroma_shift : 0;
00877                 int v_shift= i ? v_chroma_shift : 0;
00878                 int w= s->width >>h_shift;
00879                 int h= s->height>>v_shift;
00880                 uint8_t *src= pic_arg->data[i];
00881                 uint8_t *dst= pic->data[i];
00882 
00883                 if(!s->avctx->rc_buffer_size)
00884                     dst +=INPLACE_OFFSET;
00885 
00886                 if(src_stride==dst_stride)
00887                     memcpy(dst, src, src_stride*h);
00888                 else{
00889                     while(h--){
00890                         memcpy(dst, src, w);
00891                         dst += dst_stride;
00892                         src += src_stride;
00893                     }
00894                 }
00895             }
00896         }
00897     }
00898     copy_picture_attributes(s, pic, pic_arg);
00899     pic->pts= pts; //we set this here to avoid modifiying pic_arg
00900   }
00901 
00902     /* shift buffer entries */
00903     for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
00904         s->input_picture[i-1]= s->input_picture[i];
00905 
00906     s->input_picture[encoding_delay]= (Picture*)pic;
00907 
00908     return 0;
00909 }
00910 
00911 static int skip_check(MpegEncContext *s, Picture *p, Picture *ref){
00912     int x, y, plane;
00913     int score=0;
00914     int64_t score64=0;
00915 
00916     for(plane=0; plane<3; plane++){
00917         const int stride= p->linesize[plane];
00918         const int bw= plane ? 1 : 2;
00919         for(y=0; y<s->mb_height*bw; y++){
00920             for(x=0; x<s->mb_width*bw; x++){
00921                 int off= p->type == FF_BUFFER_TYPE_SHARED ? 0: 16;
00922                 int v= s->dsp.frame_skip_cmp[1](s, p->data[plane] + 8*(x + y*stride)+off, ref->data[plane] + 8*(x + y*stride), stride, 8);
00923 
00924                 switch(s->avctx->frame_skip_exp){
00925                     case 0: score= FFMAX(score, v); break;
00926                     case 1: score+= FFABS(v);break;
00927                     case 2: score+= v*v;break;
00928                     case 3: score64+= FFABS(v*v*(int64_t)v);break;
00929                     case 4: score64+= v*v*(int64_t)(v*v);break;
00930                 }
00931             }
00932         }
00933     }
00934 
00935     if(score) score64= score;
00936 
00937     if(score64 < s->avctx->frame_skip_threshold)
00938         return 1;
00939     if(score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda)>>8))
00940         return 1;
00941     return 0;
00942 }
00943 
00944 static int estimate_best_b_count(MpegEncContext *s){
00945     AVCodec *codec= avcodec_find_encoder(s->avctx->codec_id);
00946     AVCodecContext *c= avcodec_alloc_context();
00947     AVFrame input[FF_MAX_B_FRAMES+2];
00948     const int scale= s->avctx->brd_scale;
00949     int i, j, out_size, p_lambda, b_lambda, lambda2;
00950     int outbuf_size= s->width * s->height; //FIXME
00951     uint8_t *outbuf= av_malloc(outbuf_size);
00952     int64_t best_rd= INT64_MAX;
00953     int best_b_count= -1;
00954 
00955     assert(scale>=0 && scale <=3);
00956 
00957 //    emms_c();
00958     p_lambda= s->last_lambda_for[AV_PICTURE_TYPE_P]; //s->next_picture_ptr->quality;
00959     b_lambda= s->last_lambda_for[AV_PICTURE_TYPE_B]; //p_lambda *FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
00960     if(!b_lambda) b_lambda= p_lambda; //FIXME we should do this somewhere else
00961     lambda2= (b_lambda*b_lambda + (1<<FF_LAMBDA_SHIFT)/2 ) >> FF_LAMBDA_SHIFT;
00962 
00963     c->width = s->width >> scale;
00964     c->height= s->height>> scale;
00965     c->flags= CODEC_FLAG_QSCALE | CODEC_FLAG_PSNR | CODEC_FLAG_INPUT_PRESERVED /*| CODEC_FLAG_EMU_EDGE*/;
00966     c->flags|= s->avctx->flags & CODEC_FLAG_QPEL;
00967     c->mb_decision= s->avctx->mb_decision;
00968     c->me_cmp= s->avctx->me_cmp;
00969     c->mb_cmp= s->avctx->mb_cmp;
00970     c->me_sub_cmp= s->avctx->me_sub_cmp;
00971     c->pix_fmt = PIX_FMT_YUV420P;
00972     c->time_base= s->avctx->time_base;
00973     c->max_b_frames= s->max_b_frames;
00974 
00975     if (avcodec_open(c, codec) < 0)
00976         return -1;
00977 
00978     for(i=0; i<s->max_b_frames+2; i++){
00979         int ysize= c->width*c->height;
00980         int csize= (c->width/2)*(c->height/2);
00981         Picture pre_input, *pre_input_ptr= i ? s->input_picture[i-1] : s->next_picture_ptr;
00982 
00983         avcodec_get_frame_defaults(&input[i]);
00984         input[i].data[0]= av_malloc(ysize + 2*csize);
00985         input[i].data[1]= input[i].data[0] + ysize;
00986         input[i].data[2]= input[i].data[1] + csize;
00987         input[i].linesize[0]= c->width;
00988         input[i].linesize[1]=
00989         input[i].linesize[2]= c->width/2;
00990 
00991         if(pre_input_ptr && (!i || s->input_picture[i-1])) {
00992             pre_input= *pre_input_ptr;
00993 
00994             if(pre_input.type != FF_BUFFER_TYPE_SHARED && i) {
00995                 pre_input.data[0]+=INPLACE_OFFSET;
00996                 pre_input.data[1]+=INPLACE_OFFSET;
00997                 pre_input.data[2]+=INPLACE_OFFSET;
00998             }
00999 
01000             s->dsp.shrink[scale](input[i].data[0], input[i].linesize[0], pre_input.data[0], pre_input.linesize[0], c->width, c->height);
01001             s->dsp.shrink[scale](input[i].data[1], input[i].linesize[1], pre_input.data[1], pre_input.linesize[1], c->width>>1, c->height>>1);
01002             s->dsp.shrink[scale](input[i].data[2], input[i].linesize[2], pre_input.data[2], pre_input.linesize[2], c->width>>1, c->height>>1);
01003         }
01004     }
01005 
01006     for(j=0; j<s->max_b_frames+1; j++){
01007         int64_t rd=0;
01008 
01009         if(!s->input_picture[j])
01010             break;
01011 
01012         c->error[0]= c->error[1]= c->error[2]= 0;
01013 
01014         input[0].pict_type= AV_PICTURE_TYPE_I;
01015         input[0].quality= 1 * FF_QP2LAMBDA;
01016         out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[0]);
01017 //        rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
01018 
01019         for(i=0; i<s->max_b_frames+1; i++){
01020             int is_p= i % (j+1) == j || i==s->max_b_frames;
01021 
01022             input[i+1].pict_type= is_p ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_B;
01023             input[i+1].quality= is_p ? p_lambda : b_lambda;
01024             out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[i+1]);
01025             rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
01026         }
01027 
01028         /* get the delayed frames */
01029         while(out_size){
01030             out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
01031             rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
01032         }
01033 
01034         rd += c->error[0] + c->error[1] + c->error[2];
01035 
01036         if(rd < best_rd){
01037             best_rd= rd;
01038             best_b_count= j;
01039         }
01040     }
01041 
01042     av_freep(&outbuf);
01043     avcodec_close(c);
01044     av_freep(&c);
01045 
01046     for(i=0; i<s->max_b_frames+2; i++){
01047         av_freep(&input[i].data[0]);
01048     }
01049 
01050     return best_b_count;
01051 }
01052 
01053 static int select_input_picture(MpegEncContext *s){
01054     int i;
01055 
01056     for(i=1; i<MAX_PICTURE_COUNT; i++)
01057         s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
01058     s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;
01059 
01060     /* set next picture type & ordering */
01061     if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
01062         if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture_ptr==NULL || s->intra_only){
01063             s->reordered_input_picture[0]= s->input_picture[0];
01064             s->reordered_input_picture[0]->pict_type= AV_PICTURE_TYPE_I;
01065             s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
01066         }else{
01067             int b_frames;
01068 
01069             if(s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor){
01070                 if(s->picture_in_gop_number < s->gop_size && skip_check(s, s->input_picture[0], s->next_picture_ptr)){
01071                 //FIXME check that te gop check above is +-1 correct
01072 //av_log(NULL, AV_LOG_DEBUG, "skip %p %"PRId64"\n", s->input_picture[0]->data[0], s->input_picture[0]->pts);
01073 
01074                     if(s->input_picture[0]->type == FF_BUFFER_TYPE_SHARED){
01075                         for(i=0; i<4; i++)
01076                             s->input_picture[0]->data[i]= NULL;
01077                         s->input_picture[0]->type= 0;
01078                     }else{
01079                         assert(   s->input_picture[0]->type==FF_BUFFER_TYPE_USER
01080                                || s->input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
01081 
01082                         s->avctx->release_buffer(s->avctx, (AVFrame*)s->input_picture[0]);
01083                     }
01084 
01085                     emms_c();
01086                     ff_vbv_update(s, 0);
01087 
01088                     goto no_output_pic;
01089                 }
01090             }
01091 
01092             if(s->flags&CODEC_FLAG_PASS2){
01093                 for(i=0; i<s->max_b_frames+1; i++){
01094                     int pict_num= s->input_picture[0]->display_picture_number + i;
01095 
01096                     if(pict_num >= s->rc_context.num_entries)
01097                         break;
01098                     if(!s->input_picture[i]){
01099                         s->rc_context.entry[pict_num-1].new_pict_type = AV_PICTURE_TYPE_P;
01100                         break;
01101                     }
01102 
01103                     s->input_picture[i]->pict_type=
01104                         s->rc_context.entry[pict_num].new_pict_type;
01105                 }
01106             }
01107 
01108             if(s->avctx->b_frame_strategy==0){
01109                 b_frames= s->max_b_frames;
01110                 while(b_frames && !s->input_picture[b_frames]) b_frames--;
01111             }else if(s->avctx->b_frame_strategy==1){
01112                 for(i=1; i<s->max_b_frames+1; i++){
01113                     if(s->input_picture[i] && s->input_picture[i]->b_frame_score==0){
01114                         s->input_picture[i]->b_frame_score=
01115                             get_intra_count(s, s->input_picture[i  ]->data[0],
01116                                                s->input_picture[i-1]->data[0], s->linesize) + 1;
01117                     }
01118                 }
01119                 for(i=0; i<s->max_b_frames+1; i++){
01120                     if(s->input_picture[i]==NULL || s->input_picture[i]->b_frame_score - 1 > s->mb_num/s->avctx->b_sensitivity) break;
01121                 }
01122 
01123                 b_frames= FFMAX(0, i-1);
01124 
01125                 /* reset scores */
01126                 for(i=0; i<b_frames+1; i++){
01127                     s->input_picture[i]->b_frame_score=0;
01128                 }
01129             }else if(s->avctx->b_frame_strategy==2){
01130                 b_frames= estimate_best_b_count(s);
01131             }else{
01132                 av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
01133                 b_frames=0;
01134             }
01135 
01136             emms_c();
01137 //static int b_count=0;
01138 //b_count+= b_frames;
01139 //av_log(s->avctx, AV_LOG_DEBUG, "b_frames: %d\n", b_count);
01140 
01141             for(i= b_frames - 1; i>=0; i--){
01142                 int type= s->input_picture[i]->pict_type;
01143                 if(type && type != AV_PICTURE_TYPE_B)
01144                     b_frames= i;
01145             }
01146             if(s->input_picture[b_frames]->pict_type == AV_PICTURE_TYPE_B && b_frames == s->max_b_frames){
01147                 av_log(s->avctx, AV_LOG_ERROR, "warning, too many b frames in a row\n");
01148             }
01149 
01150             if(s->picture_in_gop_number + b_frames >= s->gop_size){
01151               if((s->flags2 & CODEC_FLAG2_STRICT_GOP) && s->gop_size > s->picture_in_gop_number){
01152                     b_frames= s->gop_size - s->picture_in_gop_number - 1;
01153               }else{
01154                 if(s->flags & CODEC_FLAG_CLOSED_GOP)
01155                     b_frames=0;
01156                 s->input_picture[b_frames]->pict_type= AV_PICTURE_TYPE_I;
01157               }
01158             }
01159 
01160             if(   (s->flags & CODEC_FLAG_CLOSED_GOP)
01161                && b_frames
01162                && s->input_picture[b_frames]->pict_type== AV_PICTURE_TYPE_I)
01163                 b_frames--;
01164 
01165             s->reordered_input_picture[0]= s->input_picture[b_frames];
01166             if(s->reordered_input_picture[0]->pict_type != AV_PICTURE_TYPE_I)
01167                 s->reordered_input_picture[0]->pict_type= AV_PICTURE_TYPE_P;
01168             s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
01169             for(i=0; i<b_frames; i++){
01170                 s->reordered_input_picture[i+1]= s->input_picture[i];
01171                 s->reordered_input_picture[i+1]->pict_type= AV_PICTURE_TYPE_B;
01172                 s->reordered_input_picture[i+1]->coded_picture_number= s->coded_picture_number++;
01173             }
01174         }
01175     }
01176 no_output_pic:
01177     if(s->reordered_input_picture[0]){
01178         s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=AV_PICTURE_TYPE_B ? 3 : 0;
01179 
01180         ff_copy_picture(&s->new_picture, s->reordered_input_picture[0]);
01181 
01182         if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_SHARED || s->avctx->rc_buffer_size){
01183             // input is a shared pix, so we can't modifiy it -> alloc a new one & ensure that the shared one is reuseable
01184 
01185             int i= ff_find_unused_picture(s, 0);
01186             Picture *pic= &s->picture[i];
01187 
01188             pic->reference              = s->reordered_input_picture[0]->reference;
01189             if(ff_alloc_picture(s, pic, 0) < 0){
01190                 return -1;
01191             }
01192 
01193             /* mark us unused / free shared pic */
01194             if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_INTERNAL)
01195                 s->avctx->release_buffer(s->avctx, (AVFrame*)s->reordered_input_picture[0]);
01196             for(i=0; i<4; i++)
01197                 s->reordered_input_picture[0]->data[i]= NULL;
01198             s->reordered_input_picture[0]->type= 0;
01199 
01200             copy_picture_attributes(s, (AVFrame*)pic, (AVFrame*)s->reordered_input_picture[0]);
01201 
01202             s->current_picture_ptr= pic;
01203         }else{
01204             // input is not a shared pix -> reuse buffer for current_pix
01205 
01206             assert(   s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER
01207                    || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
01208 
01209             s->current_picture_ptr= s->reordered_input_picture[0];
01210             for(i=0; i<4; i++){
01211                 s->new_picture.data[i]+= INPLACE_OFFSET;
01212             }
01213         }
01214         ff_copy_picture(&s->current_picture, s->current_picture_ptr);
01215 
01216         s->picture_number= s->new_picture.display_picture_number;
01217 //printf("dpn:%d\n", s->picture_number);
01218     }else{
01219        memset(&s->new_picture, 0, sizeof(Picture));
01220     }
01221     return 0;
01222 }
01223 
01224 int MPV_encode_picture(AVCodecContext *avctx,
01225                        unsigned char *buf, int buf_size, void *data)
01226 {
01227     MpegEncContext *s = avctx->priv_data;
01228     AVFrame *pic_arg = data;
01229     int i, stuffing_count, context_count = avctx->thread_count;
01230 
01231     for(i=0; i<context_count; i++){
01232         int start_y= s->thread_context[i]->start_mb_y;
01233         int   end_y= s->thread_context[i]->  end_mb_y;
01234         int h= s->mb_height;
01235         uint8_t *start= buf + (size_t)(((int64_t) buf_size)*start_y/h);
01236         uint8_t *end  = buf + (size_t)(((int64_t) buf_size)*  end_y/h);
01237 
01238         init_put_bits(&s->thread_context[i]->pb, start, end - start);
01239     }
01240 
01241     s->picture_in_gop_number++;
01242 
01243     if(load_input_picture(s, pic_arg) < 0)
01244         return -1;
01245 
01246     if(select_input_picture(s) < 0){
01247         return -1;
01248     }
01249 
01250     /* output? */
01251     if(s->new_picture.data[0]){
01252         s->pict_type= s->new_picture.pict_type;
01253 //emms_c();
01254 //printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
01255         MPV_frame_start(s, avctx);
01256 vbv_retry:
01257         if (encode_picture(s, s->picture_number) < 0)
01258             return -1;
01259 
01260         avctx->header_bits = s->header_bits;
01261         avctx->mv_bits     = s->mv_bits;
01262         avctx->misc_bits   = s->misc_bits;
01263         avctx->i_tex_bits  = s->i_tex_bits;
01264         avctx->p_tex_bits  = s->p_tex_bits;
01265         avctx->i_count     = s->i_count;
01266         avctx->p_count     = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
01267         avctx->skip_count  = s->skip_count;
01268 
01269         MPV_frame_end(s);
01270 
01271         if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
01272             ff_mjpeg_encode_picture_trailer(s);
01273 
01274         if(avctx->rc_buffer_size){
01275             RateControlContext *rcc= &s->rc_context;
01276             int max_size= rcc->buffer_index * avctx->rc_max_available_vbv_use;
01277 
01278             if(put_bits_count(&s->pb) > max_size && s->lambda < s->avctx->lmax){
01279                 s->next_lambda= FFMAX(s->lambda+1, s->lambda*(s->qscale+1) / s->qscale);
01280                 if(s->adaptive_quant){
01281                     int i;
01282                     for(i=0; i<s->mb_height*s->mb_stride; i++)
01283                         s->lambda_table[i]= FFMAX(s->lambda_table[i]+1, s->lambda_table[i]*(s->qscale+1) / s->qscale);
01284                 }
01285                 s->mb_skipped = 0;        //done in MPV_frame_start()
01286                 if(s->pict_type==AV_PICTURE_TYPE_P){ //done in encode_picture() so we must undo it
01287                     if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
01288                         s->no_rounding ^= 1;
01289                 }
01290                 if(s->pict_type!=AV_PICTURE_TYPE_B){
01291                     s->time_base= s->last_time_base;
01292                     s->last_non_b_time= s->time - s->pp_time;
01293                 }
01294 //                av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);
01295                 for(i=0; i<context_count; i++){
01296                     PutBitContext *pb= &s->thread_context[i]->pb;
01297                     init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
01298                 }
01299                 goto vbv_retry;
01300             }
01301 
01302             assert(s->avctx->rc_max_rate);
01303         }
01304 
01305         if(s->flags&CODEC_FLAG_PASS1)
01306             ff_write_pass1_stats(s);
01307 
01308         for(i=0; i<4; i++){
01309             s->current_picture_ptr->error[i]= s->current_picture.error[i];
01310             avctx->error[i] += s->current_picture_ptr->error[i];
01311         }
01312 
01313         if(s->flags&CODEC_FLAG_PASS1)
01314             assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb));
01315         flush_put_bits(&s->pb);
01316         s->frame_bits  = put_bits_count(&s->pb);
01317 
01318         stuffing_count= ff_vbv_update(s, s->frame_bits);
01319         if(stuffing_count){
01320             if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){
01321                 av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
01322                 return -1;
01323             }
01324 
01325             switch(s->codec_id){
01326             case CODEC_ID_MPEG1VIDEO:
01327             case CODEC_ID_MPEG2VIDEO:
01328                 while(stuffing_count--){
01329                     put_bits(&s->pb, 8, 0);
01330                 }
01331             break;
01332             case CODEC_ID_MPEG4:
01333                 put_bits(&s->pb, 16, 0);
01334                 put_bits(&s->pb, 16, 0x1C3);
01335                 stuffing_count -= 4;
01336                 while(stuffing_count--){
01337                     put_bits(&s->pb, 8, 0xFF);
01338                 }
01339             break;
01340             default:
01341                 av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
01342             }
01343             flush_put_bits(&s->pb);
01344             s->frame_bits  = put_bits_count(&s->pb);
01345         }
01346 
01347         /* update mpeg1/2 vbv_delay for CBR */
01348         if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1
01349            && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){
01350             int vbv_delay, min_delay;
01351             double inbits = s->avctx->rc_max_rate*av_q2d(s->avctx->time_base);
01352             int    minbits= s->frame_bits - 8*(s->vbv_delay_ptr - s->pb.buf - 1);
01353             double bits   = s->rc_context.buffer_index + minbits - inbits;
01354 
01355             if(bits<0)
01356                 av_log(s->avctx, AV_LOG_ERROR, "Internal error, negative bits\n");
01357 
01358             assert(s->repeat_first_field==0);
01359 
01360             vbv_delay=     bits * 90000                               / s->avctx->rc_max_rate;
01361             min_delay= (minbits * 90000LL + s->avctx->rc_max_rate - 1)/ s->avctx->rc_max_rate;
01362 
01363             vbv_delay= FFMAX(vbv_delay, min_delay);
01364 
01365             assert(vbv_delay < 0xFFFF);
01366 
01367             s->vbv_delay_ptr[0] &= 0xF8;
01368             s->vbv_delay_ptr[0] |= vbv_delay>>13;
01369             s->vbv_delay_ptr[1]  = vbv_delay>>5;
01370             s->vbv_delay_ptr[2] &= 0x07;
01371             s->vbv_delay_ptr[2] |= vbv_delay<<3;
01372             avctx->vbv_delay = vbv_delay*300;
01373         }
01374         s->total_bits += s->frame_bits;
01375         avctx->frame_bits  = s->frame_bits;
01376     }else{
01377         assert((put_bits_ptr(&s->pb) == s->pb.buf));
01378         s->frame_bits=0;
01379     }
01380     assert((s->frame_bits&7)==0);
01381 
01382     return s->frame_bits/8;
01383 }
01384 
01385 static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
01386 {
01387     static const char tab[64]=
01388         {3,2,2,1,1,1,1,1,
01389          1,1,1,1,1,1,1,1,
01390          1,1,1,1,1,1,1,1,
01391          0,0,0,0,0,0,0,0,
01392          0,0,0,0,0,0,0,0,
01393          0,0,0,0,0,0,0,0,
01394          0,0,0,0,0,0,0,0,
01395          0,0,0,0,0,0,0,0};
01396     int score=0;
01397     int run=0;
01398     int i;
01399     DCTELEM *block= s->block[n];
01400     const int last_index= s->block_last_index[n];
01401     int skip_dc;
01402 
01403     if(threshold<0){
01404         skip_dc=0;
01405         threshold= -threshold;
01406     }else
01407         skip_dc=1;
01408 
01409     /* Are all we could set to zero already zero? */
01410     if(last_index<=skip_dc - 1) return;
01411 
01412     for(i=0; i<=last_index; i++){
01413         const int j = s->intra_scantable.permutated[i];
01414         const int level = FFABS(block[j]);
01415         if(level==1){
01416             if(skip_dc && i==0) continue;
01417             score+= tab[run];
01418             run=0;
01419         }else if(level>1){
01420             return;
01421         }else{
01422             run++;
01423         }
01424     }
01425     if(score >= threshold) return;
01426     for(i=skip_dc; i<=last_index; i++){
01427         const int j = s->intra_scantable.permutated[i];
01428         block[j]=0;
01429     }
01430     if(block[0]) s->block_last_index[n]= 0;
01431     else         s->block_last_index[n]= -1;
01432 }
01433 
01434 static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
01435 {
01436     int i;
01437     const int maxlevel= s->max_qcoeff;
01438     const int minlevel= s->min_qcoeff;
01439     int overflow=0;
01440 
01441     if(s->mb_intra){
01442         i=1; //skip clipping of intra dc
01443     }else
01444         i=0;
01445 
01446     for(;i<=last_index; i++){
01447         const int j= s->intra_scantable.permutated[i];
01448         int level = block[j];
01449 
01450         if     (level>maxlevel){
01451             level=maxlevel;
01452             overflow++;
01453         }else if(level<minlevel){
01454             level=minlevel;
01455             overflow++;
01456         }
01457 
01458         block[j]= level;
01459     }
01460 
01461     if(overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
01462         av_log(s->avctx, AV_LOG_INFO, "warning, clipping %d dct coefficients to %d..%d\n", overflow, minlevel, maxlevel);
01463 }
01464 
01465 static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride){
01466     int x, y;
01467 //FIXME optimize
01468     for(y=0; y<8; y++){
01469         for(x=0; x<8; x++){
01470             int x2, y2;
01471             int sum=0;
01472             int sqr=0;
01473             int count=0;
01474 
01475             for(y2= FFMAX(y-1, 0); y2 < FFMIN(8, y+2); y2++){
01476                 for(x2= FFMAX(x-1, 0); x2 < FFMIN(8, x+2); x2++){
01477                     int v= ptr[x2 + y2*stride];
01478                     sum += v;
01479                     sqr += v*v;
01480                     count++;
01481                 }
01482             }
01483             weight[x + 8*y]= (36*ff_sqrt(count*sqr - sum*sum)) / count;
01484         }
01485     }
01486 }
01487 
01488 static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x, int motion_y, int mb_block_height, int mb_block_count)
01489 {
01490     int16_t weight[8][64];
01491     DCTELEM orig[8][64];
01492     const int mb_x= s->mb_x;
01493     const int mb_y= s->mb_y;
01494     int i;
01495     int skip_dct[8];
01496     int dct_offset   = s->linesize*8; //default for progressive frames
01497     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
01498     int wrap_y, wrap_c;
01499 
01500     for(i=0; i<mb_block_count; i++) skip_dct[i]=s->skipdct;
01501 
01502     if(s->adaptive_quant){
01503         const int last_qp= s->qscale;
01504         const int mb_xy= mb_x + mb_y*s->mb_stride;
01505 
01506         s->lambda= s->lambda_table[mb_xy];
01507         update_qscale(s);
01508 
01509         if(!(s->flags&CODEC_FLAG_QP_RD)){
01510             s->qscale= s->current_picture_ptr->qscale_table[mb_xy];
01511             s->dquant= s->qscale - last_qp;
01512 
01513             if(s->out_format==FMT_H263){
01514                 s->dquant= av_clip(s->dquant, -2, 2);
01515 
01516                 if(s->codec_id==CODEC_ID_MPEG4){
01517                     if(!s->mb_intra){
01518                         if(s->pict_type == AV_PICTURE_TYPE_B){
01519                             if(s->dquant&1 || s->mv_dir&MV_DIRECT)
01520                                 s->dquant= 0;
01521                         }
01522                         if(s->mv_type==MV_TYPE_8X8)
01523                             s->dquant=0;
01524                     }
01525                 }
01526             }
01527         }
01528         ff_set_qscale(s, last_qp + s->dquant);
01529     }else if(s->flags&CODEC_FLAG_QP_RD)
01530         ff_set_qscale(s, s->qscale + s->dquant);
01531 
01532     wrap_y = s->linesize;
01533     wrap_c = s->uvlinesize;
01534     ptr_y = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
01535     ptr_cb = s->new_picture.data[1] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
01536     ptr_cr = s->new_picture.data[2] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
01537 
01538     if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
01539         uint8_t *ebuf= s->edge_emu_buffer + 32;
01540         s->dsp.emulated_edge_mc(ebuf            , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width   , s->height);
01541         ptr_y= ebuf;
01542         s->dsp.emulated_edge_mc(ebuf+18*wrap_y  , ptr_cb, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
01543         ptr_cb= ebuf+18*wrap_y;
01544         s->dsp.emulated_edge_mc(ebuf+18*wrap_y+8, ptr_cr, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
01545         ptr_cr= ebuf+18*wrap_y+8;
01546     }
01547 
01548     if (s->mb_intra) {
01549         if(s->flags&CODEC_FLAG_INTERLACED_DCT){
01550             int progressive_score, interlaced_score;
01551 
01552             s->interlaced_dct=0;
01553             progressive_score= s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y, 8)
01554                               +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;
01555 
01556             if(progressive_score > 0){
01557                 interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y*2, 8)
01558                                   +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y  , NULL, wrap_y*2, 8);
01559                 if(progressive_score > interlaced_score){
01560                     s->interlaced_dct=1;
01561 
01562                     dct_offset= wrap_y;
01563                     wrap_y<<=1;
01564                     if (s->chroma_format == CHROMA_422)
01565                         wrap_c<<=1;
01566                 }
01567             }
01568         }
01569 
01570         s->dsp.get_pixels(s->block[0], ptr_y                 , wrap_y);
01571         s->dsp.get_pixels(s->block[1], ptr_y              + 8, wrap_y);
01572         s->dsp.get_pixels(s->block[2], ptr_y + dct_offset    , wrap_y);
01573         s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
01574 
01575         if(s->flags&CODEC_FLAG_GRAY){
01576             skip_dct[4]= 1;
01577             skip_dct[5]= 1;
01578         }else{
01579             s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
01580             s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
01581             if(!s->chroma_y_shift){ /* 422 */
01582                 s->dsp.get_pixels(s->block[6], ptr_cb + (dct_offset>>1), wrap_c);
01583                 s->dsp.get_pixels(s->block[7], ptr_cr + (dct_offset>>1), wrap_c);
01584             }
01585         }
01586     }else{
01587         op_pixels_func (*op_pix)[4];
01588         qpel_mc_func (*op_qpix)[16];
01589         uint8_t *dest_y, *dest_cb, *dest_cr;
01590 
01591         dest_y  = s->dest[0];
01592         dest_cb = s->dest[1];
01593         dest_cr = s->dest[2];
01594 
01595         if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
01596             op_pix = s->dsp.put_pixels_tab;
01597             op_qpix= s->dsp.put_qpel_pixels_tab;
01598         }else{
01599             op_pix = s->dsp.put_no_rnd_pixels_tab;
01600             op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
01601         }
01602 
01603         if (s->mv_dir & MV_DIR_FORWARD) {
01604             MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
01605             op_pix = s->dsp.avg_pixels_tab;
01606             op_qpix= s->dsp.avg_qpel_pixels_tab;
01607         }
01608         if (s->mv_dir & MV_DIR_BACKWARD) {
01609             MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
01610         }
01611 
01612         if(s->flags&CODEC_FLAG_INTERLACED_DCT){
01613             int progressive_score, interlaced_score;
01614 
01615             s->interlaced_dct=0;
01616             progressive_score= s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y, 8)
01617                               +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;
01618 
01619             if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;
01620 
01621             if(progressive_score>0){
01622                 interlaced_score = s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y*2, 8)
01623                                   +s->dsp.ildct_cmp[0](s, dest_y + wrap_y  , ptr_y + wrap_y  , wrap_y*2, 8);
01624 
01625                 if(progressive_score > interlaced_score){
01626                     s->interlaced_dct=1;
01627 
01628                     dct_offset= wrap_y;
01629                     wrap_y<<=1;
01630                     if (s->chroma_format == CHROMA_422)
01631                         wrap_c<<=1;
01632                 }
01633             }
01634         }
01635 
01636         s->dsp.diff_pixels(s->block[0], ptr_y                 , dest_y                 , wrap_y);
01637         s->dsp.diff_pixels(s->block[1], ptr_y              + 8, dest_y              + 8, wrap_y);
01638         s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset    , dest_y + dct_offset    , wrap_y);
01639         s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
01640 
01641         if(s->flags&CODEC_FLAG_GRAY){
01642             skip_dct[4]= 1;
01643             skip_dct[5]= 1;
01644         }else{
01645             s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
01646             s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
01647             if(!s->chroma_y_shift){ /* 422 */
01648                 s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset>>1), dest_cb + (dct_offset>>1), wrap_c);
01649                 s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset>>1), dest_cr + (dct_offset>>1), wrap_c);
01650             }
01651         }
01652         /* pre quantization */
01653         if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
01654             //FIXME optimize
01655             if(s->dsp.sad[1](NULL, ptr_y               , dest_y               , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;
01656             if(s->dsp.sad[1](NULL, ptr_y            + 8, dest_y            + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;
01657             if(s->dsp.sad[1](NULL, ptr_y +dct_offset   , dest_y +dct_offset   , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;
01658             if(s->dsp.sad[1](NULL, ptr_y +dct_offset+ 8, dest_y +dct_offset+ 8, wrap_y, 8) < 20*s->qscale) skip_dct[3]= 1;
01659             if(s->dsp.sad[1](NULL, ptr_cb              , dest_cb              , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;
01660             if(s->dsp.sad[1](NULL, ptr_cr              , dest_cr              , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;
01661             if(!s->chroma_y_shift){ /* 422 */
01662                 if(s->dsp.sad[1](NULL, ptr_cb +(dct_offset>>1), dest_cb +(dct_offset>>1), wrap_c, 8) < 20*s->qscale) skip_dct[6]= 1;
01663                 if(s->dsp.sad[1](NULL, ptr_cr +(dct_offset>>1), dest_cr +(dct_offset>>1), wrap_c, 8) < 20*s->qscale) skip_dct[7]= 1;
01664             }
01665         }
01666     }
01667 
01668     if(s->avctx->quantizer_noise_shaping){
01669         if(!skip_dct[0]) get_visual_weight(weight[0], ptr_y                 , wrap_y);
01670         if(!skip_dct[1]) get_visual_weight(weight[1], ptr_y              + 8, wrap_y);
01671         if(!skip_dct[2]) get_visual_weight(weight[2], ptr_y + dct_offset    , wrap_y);
01672         if(!skip_dct[3]) get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
01673         if(!skip_dct[4]) get_visual_weight(weight[4], ptr_cb                , wrap_c);
01674         if(!skip_dct[5]) get_visual_weight(weight[5], ptr_cr                , wrap_c);
01675         if(!s->chroma_y_shift){ /* 422 */
01676             if(!skip_dct[6]) get_visual_weight(weight[6], ptr_cb + (dct_offset>>1), wrap_c);
01677             if(!skip_dct[7]) get_visual_weight(weight[7], ptr_cr + (dct_offset>>1), wrap_c);
01678         }
01679         memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*mb_block_count);
01680     }
01681 
01682     /* DCT & quantize */
01683     assert(s->out_format!=FMT_MJPEG || s->qscale==8);
01684     {
01685         for(i=0;i<mb_block_count;i++) {
01686             if(!skip_dct[i]){
01687                 int overflow;
01688                 s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
01689             // FIXME we could decide to change to quantizer instead of clipping
01690             // JS: I don't think that would be a good idea it could lower quality instead
01691             //     of improve it. Just INTRADC clipping deserves changes in quantizer
01692                 if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
01693             }else
01694                 s->block_last_index[i]= -1;
01695         }
01696         if(s->avctx->quantizer_noise_shaping){
01697             for(i=0;i<mb_block_count;i++) {
01698                 if(!skip_dct[i]){
01699                     s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);
01700                 }
01701             }
01702         }
01703 
01704         if(s->luma_elim_threshold && !s->mb_intra)
01705             for(i=0; i<4; i++)
01706                 dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
01707         if(s->chroma_elim_threshold && !s->mb_intra)
01708             for(i=4; i<mb_block_count; i++)
01709                 dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
01710 
01711         if(s->flags & CODEC_FLAG_CBP_RD){
01712             for(i=0;i<mb_block_count;i++) {
01713                 if(s->block_last_index[i] == -1)
01714                     s->coded_score[i]= INT_MAX/256;
01715             }
01716         }
01717     }
01718 
01719     if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
01720         s->block_last_index[4]=
01721         s->block_last_index[5]= 0;
01722         s->block[4][0]=
01723         s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
01724     }
01725 
01726     //non c quantize code returns incorrect block_last_index FIXME
01727     if(s->alternate_scan && s->dct_quantize != dct_quantize_c){
01728         for(i=0; i<mb_block_count; i++){
01729             int j;
01730             if(s->block_last_index[i]>0){
01731                 for(j=63; j>0; j--){
01732                     if(s->block[i][ s->intra_scantable.permutated[j] ]) break;
01733                 }
01734                 s->block_last_index[i]= j;
01735             }
01736         }
01737     }
01738 
01739     /* huffman encode */
01740     switch(s->codec_id){ //FIXME funct ptr could be slightly faster
01741     case CODEC_ID_MPEG1VIDEO:
01742     case CODEC_ID_MPEG2VIDEO:
01743         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
01744             mpeg1_encode_mb(s, s->block, motion_x, motion_y);
01745         break;
01746     case CODEC_ID_MPEG4:
01747         if (CONFIG_MPEG4_ENCODER)
01748             mpeg4_encode_mb(s, s->block, motion_x, motion_y);
01749         break;
01750     case CODEC_ID_MSMPEG4V2:
01751     case CODEC_ID_MSMPEG4V3:
01752     case CODEC_ID_WMV1:
01753         if (CONFIG_MSMPEG4_ENCODER)
01754             msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
01755         break;
01756     case CODEC_ID_WMV2:
01757         if (CONFIG_WMV2_ENCODER)
01758             ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
01759         break;
01760     case CODEC_ID_H261:
01761         if (CONFIG_H261_ENCODER)
01762             ff_h261_encode_mb(s, s->block, motion_x, motion_y);
01763         break;
01764     case CODEC_ID_H263:
01765     case CODEC_ID_H263P:
01766     case CODEC_ID_FLV1:
01767     case CODEC_ID_RV10:
01768     case CODEC_ID_RV20:
01769         if (CONFIG_H263_ENCODER)
01770             h263_encode_mb(s, s->block, motion_x, motion_y);
01771         break;
01772     case CODEC_ID_MJPEG:
01773         if (CONFIG_MJPEG_ENCODER)
01774             ff_mjpeg_encode_mb(s, s->block);
01775         break;
01776     default:
01777         assert(0);
01778     }
01779 }
01780 
01781 static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
01782 {
01783     if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y,  8, 6);
01784     else                                encode_mb_internal(s, motion_x, motion_y, 16, 8);
01785 }
01786 
01787 static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
01788     int i;
01789 
01790     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
01791 
01792     /* mpeg1 */
01793     d->mb_skip_run= s->mb_skip_run;
01794     for(i=0; i<3; i++)
01795         d->last_dc[i]= s->last_dc[i];
01796 
01797     /* statistics */
01798     d->mv_bits= s->mv_bits;
01799     d->i_tex_bits= s->i_tex_bits;
01800     d->p_tex_bits= s->p_tex_bits;
01801     d->i_count= s->i_count;
01802     d->f_count= s->f_count;
01803     d->b_count= s->b_count;
01804     d->skip_count= s->skip_count;
01805     d->misc_bits= s->misc_bits;
01806     d->last_bits= 0;
01807 
01808     d->mb_skipped= 0;
01809     d->qscale= s->qscale;
01810     d->dquant= s->dquant;
01811 
01812     d->esc3_level_length= s->esc3_level_length;
01813 }
01814 
01815 static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
01816     int i;
01817 
01818     memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
01819     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
01820 
01821     /* mpeg1 */
01822     d->mb_skip_run= s->mb_skip_run;
01823     for(i=0; i<3; i++)
01824         d->last_dc[i]= s->last_dc[i];
01825 
01826     /* statistics */
01827     d->mv_bits= s->mv_bits;
01828     d->i_tex_bits= s->i_tex_bits;
01829     d->p_tex_bits= s->p_tex_bits;
01830     d->i_count= s->i_count;
01831     d->f_count= s->f_count;
01832     d->b_count= s->b_count;
01833     d->skip_count= s->skip_count;
01834     d->misc_bits= s->misc_bits;
01835 
01836     d->mb_intra= s->mb_intra;
01837     d->mb_skipped= s->mb_skipped;
01838     d->mv_type= s->mv_type;
01839     d->mv_dir= s->mv_dir;
01840     d->pb= s->pb;
01841     if(s->data_partitioning){
01842         d->pb2= s->pb2;
01843         d->tex_pb= s->tex_pb;
01844     }
01845     d->block= s->block;
01846     for(i=0; i<8; i++)
01847         d->block_last_index[i]= s->block_last_index[i];
01848     d->interlaced_dct= s->interlaced_dct;
01849     d->qscale= s->qscale;
01850 
01851     d->esc3_level_length= s->esc3_level_length;
01852 }
01853 
01854 static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
01855                            PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
01856                            int *dmin, int *next_block, int motion_x, int motion_y)
01857 {
01858     int score;
01859     uint8_t *dest_backup[3];
01860 
01861     copy_context_before_encode(s, backup, type);
01862 
01863     s->block= s->blocks[*next_block];
01864     s->pb= pb[*next_block];
01865     if(s->data_partitioning){
01866         s->pb2   = pb2   [*next_block];
01867         s->tex_pb= tex_pb[*next_block];
01868     }
01869 
01870     if(*next_block){
01871         memcpy(dest_backup, s->dest, sizeof(s->dest));
01872         s->dest[0] = s->rd_scratchpad;
01873         s->dest[1] = s->rd_scratchpad + 16*s->linesize;
01874         s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
01875         assert(s->linesize >= 32); //FIXME
01876     }
01877 
01878     encode_mb(s, motion_x, motion_y);
01879 
01880     score= put_bits_count(&s->pb);
01881     if(s->data_partitioning){
01882         score+= put_bits_count(&s->pb2);
01883         score+= put_bits_count(&s->tex_pb);
01884     }
01885 
01886     if(s->avctx->mb_decision == FF_MB_DECISION_RD){
01887         MPV_decode_mb(s, s->block);
01888 
01889         score *= s->lambda2;
01890         score += sse_mb(s) << FF_LAMBDA_SHIFT;
01891     }
01892 
01893     if(*next_block){
01894         memcpy(s->dest, dest_backup, sizeof(s->dest));
01895     }
01896 
01897     if(score<*dmin){
01898         *dmin= score;
01899         *next_block^=1;
01900 
01901         copy_context_after_encode(best, s, type);
01902     }
01903 }
01904 
01905 static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
01906     uint32_t *sq = ff_squareTbl + 256;
01907     int acc=0;
01908     int x,y;
01909 
01910     if(w==16 && h==16)
01911         return s->dsp.sse[0](NULL, src1, src2, stride, 16);
01912     else if(w==8 && h==8)
01913         return s->dsp.sse[1](NULL, src1, src2, stride, 8);
01914 
01915     for(y=0; y<h; y++){
01916         for(x=0; x<w; x++){
01917             acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
01918         }
01919     }
01920 
01921     assert(acc>=0);
01922 
01923     return acc;
01924 }
01925 
01926 static int sse_mb(MpegEncContext *s){
01927     int w= 16;
01928     int h= 16;
01929 
01930     if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
01931     if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
01932 
01933     if(w==16 && h==16)
01934       if(s->avctx->mb_cmp == FF_CMP_NSSE){
01935         return  s->dsp.nsse[0](s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)
01936                +s->dsp.nsse[1](s, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)
01937                +s->dsp.nsse[1](s, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);
01938       }else{
01939         return  s->dsp.sse[0](NULL, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)
01940                +s->dsp.sse[1](NULL, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)
01941                +s->dsp.sse[1](NULL, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);
01942       }
01943     else
01944         return  sse(s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], w, h, s->linesize)
01945                +sse(s, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], w>>1, h>>1, s->uvlinesize)
01946                +sse(s, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], w>>1, h>>1, s->uvlinesize);
01947 }
01948 
01949 static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
01950     MpegEncContext *s= *(void**)arg;
01951 
01952 
01953     s->me.pre_pass=1;
01954     s->me.dia_size= s->avctx->pre_dia_size;
01955     s->first_slice_line=1;
01956     for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
01957         for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
01958             ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
01959         }
01960         s->first_slice_line=0;
01961     }
01962 
01963     s->me.pre_pass=0;
01964 
01965     return 0;
01966 }
01967 
01968 static int estimate_motion_thread(AVCodecContext *c, void *arg){
01969     MpegEncContext *s= *(void**)arg;
01970 
01971     ff_check_alignment();
01972 
01973     s->me.dia_size= s->avctx->dia_size;
01974     s->first_slice_line=1;
01975     for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
01976         s->mb_x=0; //for block init below
01977         ff_init_block_index(s);
01978         for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
01979             s->block_index[0]+=2;
01980             s->block_index[1]+=2;
01981             s->block_index[2]+=2;
01982             s->block_index[3]+=2;
01983 
01984             /* compute motion vector & mb_type and store in context */
01985             if(s->pict_type==AV_PICTURE_TYPE_B)
01986                 ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
01987             else
01988                 ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
01989         }
01990         s->first_slice_line=0;
01991     }
01992     return 0;
01993 }
01994 
01995 static int mb_var_thread(AVCodecContext *c, void *arg){
01996     MpegEncContext *s= *(void**)arg;
01997     int mb_x, mb_y;
01998 
01999     ff_check_alignment();
02000 
02001     for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
02002         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
02003             int xx = mb_x * 16;
02004             int yy = mb_y * 16;
02005             uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
02006             int varc;
02007             int sum = s->dsp.pix_sum(pix, s->linesize);
02008 
02009             varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
02010 
02011             s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
02012             s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
02013             s->me.mb_var_sum_temp    += varc;
02014         }
02015     }
02016     return 0;
02017 }
02018 
02019 static void write_slice_end(MpegEncContext *s){
02020     if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4){
02021         if(s->partitioned_frame){
02022             ff_mpeg4_merge_partitions(s);
02023         }
02024 
02025         ff_mpeg4_stuffing(&s->pb);
02026     }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
02027         ff_mjpeg_encode_stuffing(&s->pb);
02028     }
02029 
02030     align_put_bits(&s->pb);
02031     flush_put_bits(&s->pb);
02032 
02033     if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
02034         s->misc_bits+= get_bits_diff(s);
02035 }
02036 
02037 static int encode_thread(AVCodecContext *c, void *arg){
02038     MpegEncContext *s= *(void**)arg;
02039     int mb_x, mb_y, pdif = 0;
02040     int chr_h= 16>>s->chroma_y_shift;
02041     int i, j;
02042     MpegEncContext best_s, backup_s;
02043     uint8_t bit_buf[2][MAX_MB_BYTES];
02044     uint8_t bit_buf2[2][MAX_MB_BYTES];
02045     uint8_t bit_buf_tex[2][MAX_MB_BYTES];
02046     PutBitContext pb[2], pb2[2], tex_pb[2];
02047 //printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
02048 
02049     ff_check_alignment();
02050 
02051     for(i=0; i<2; i++){
02052         init_put_bits(&pb    [i], bit_buf    [i], MAX_MB_BYTES);
02053         init_put_bits(&pb2   [i], bit_buf2   [i], MAX_MB_BYTES);
02054         init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
02055     }
02056 
02057     s->last_bits= put_bits_count(&s->pb);
02058     s->mv_bits=0;
02059     s->misc_bits=0;
02060     s->i_tex_bits=0;
02061     s->p_tex_bits=0;
02062     s->i_count=0;
02063     s->f_count=0;
02064     s->b_count=0;
02065     s->skip_count=0;
02066 
02067     for(i=0; i<3; i++){
02068         /* init last dc values */
02069         /* note: quant matrix value (8) is implied here */
02070         s->last_dc[i] = 128 << s->intra_dc_precision;
02071 
02072         s->current_picture.error[i] = 0;
02073     }
02074     s->mb_skip_run = 0;
02075     memset(s->last_mv, 0, sizeof(s->last_mv));
02076 
02077     s->last_mv_dir = 0;
02078 
02079     switch(s->codec_id){
02080     case CODEC_ID_H263:
02081     case CODEC_ID_H263P:
02082     case CODEC_ID_FLV1:
02083         if (CONFIG_H263_ENCODER)
02084             s->gob_index = ff_h263_get_gob_height(s);
02085         break;
02086     case CODEC_ID_MPEG4:
02087         if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
02088             ff_mpeg4_init_partitions(s);
02089         break;
02090     }
02091 
02092     s->resync_mb_x=0;
02093     s->resync_mb_y=0;
02094     s->first_slice_line = 1;
02095     s->ptr_lastgob = s->pb.buf;
02096     for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
02097 //    printf("row %d at %X\n", s->mb_y, (int)s);
02098         s->mb_x=0;
02099         s->mb_y= mb_y;
02100 
02101         ff_set_qscale(s, s->qscale);
02102         ff_init_block_index(s);
02103 
02104         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
02105             int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
02106             int mb_type= s->mb_type[xy];
02107 //            int d;
02108             int dmin= INT_MAX;
02109             int dir;
02110 
02111             if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
02112                 av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
02113                 return -1;
02114             }
02115             if(s->data_partitioning){
02116                 if(   s->pb2   .buf_end - s->pb2   .buf - (put_bits_count(&s->    pb2)>>3) < MAX_MB_BYTES
02117                    || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
02118                     av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
02119                     return -1;
02120                 }
02121             }
02122 
02123             s->mb_x = mb_x;
02124             s->mb_y = mb_y;  // moved into loop, can get changed by H.261
02125             ff_update_block_index(s);
02126 
02127             if(CONFIG_H261_ENCODER && s->codec_id == CODEC_ID_H261){
02128                 ff_h261_reorder_mb_index(s);
02129                 xy= s->mb_y*s->mb_stride + s->mb_x;
02130                 mb_type= s->mb_type[xy];
02131             }
02132 
02133             /* write gob / video packet header  */
02134             if(s->rtp_mode){
02135                 int current_packet_size, is_gob_start;
02136 
02137                 current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
02138 
02139                 is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
02140 
02141                 if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
02142 
02143                 switch(s->codec_id){
02144                 case CODEC_ID_H263:
02145                 case CODEC_ID_H263P:
02146                     if(!s->h263_slice_structured)
02147                         if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
02148                     break;
02149                 case CODEC_ID_MPEG2VIDEO:
02150                     if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
02151                 case CODEC_ID_MPEG1VIDEO:
02152                     if(s->mb_skip_run) is_gob_start=0;
02153                     break;
02154                 }
02155 
02156                 if(is_gob_start){
02157                     if(s->start_mb_y != mb_y || mb_x!=0){
02158                         write_slice_end(s);
02159 
02160                         if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
02161                             ff_mpeg4_init_partitions(s);
02162                         }
02163                     }
02164 
02165                     assert((put_bits_count(&s->pb)&7) == 0);
02166                     current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
02167 
02168                     if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
02169                         int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
02170                         int d= 100 / s->avctx->error_rate;
02171                         if(r % d == 0){
02172                             current_packet_size=0;
02173 #ifndef ALT_BITSTREAM_WRITER
02174                             s->pb.buf_ptr= s->ptr_lastgob;
02175 #endif
02176                             assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
02177                         }
02178                     }
02179 
02180                     if (s->avctx->rtp_callback){
02181                         int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
02182                         s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
02183                     }
02184 
02185                     switch(s->codec_id){
02186                     case CODEC_ID_MPEG4:
02187                         if (CONFIG_MPEG4_ENCODER) {
02188                             ff_mpeg4_encode_video_packet_header(s);
02189                             ff_mpeg4_clean_buffers(s);
02190                         }
02191                     break;
02192                     case CODEC_ID_MPEG1VIDEO:
02193                     case CODEC_ID_MPEG2VIDEO:
02194                         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
02195                             ff_mpeg1_encode_slice_header(s);
02196                             ff_mpeg1_clean_buffers(s);
02197                         }
02198                     break;
02199                     case CODEC_ID_H263:
02200                     case CODEC_ID_H263P:
02201                         if (CONFIG_H263_ENCODER)
02202                             h263_encode_gob_header(s, mb_y);
02203                     break;
02204                     }
02205 
02206                     if(s->flags&CODEC_FLAG_PASS1){
02207                         int bits= put_bits_count(&s->pb);
02208                         s->misc_bits+= bits - s->last_bits;
02209                         s->last_bits= bits;
02210                     }
02211 
02212                     s->ptr_lastgob += current_packet_size;
02213                     s->first_slice_line=1;
02214                     s->resync_mb_x=mb_x;
02215                     s->resync_mb_y=mb_y;
02216                 }
02217             }
02218 
02219             if(  (s->resync_mb_x   == s->mb_x)
02220                && s->resync_mb_y+1 == s->mb_y){
02221                 s->first_slice_line=0;
02222             }
02223 
02224             s->mb_skipped=0;
02225             s->dquant=0; //only for QP_RD
02226 
02227             if(mb_type & (mb_type-1) || (s->flags & CODEC_FLAG_QP_RD)){ // more than 1 MB type possible or CODEC_FLAG_QP_RD
02228                 int next_block=0;
02229                 int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
02230 
02231                 copy_context_before_encode(&backup_s, s, -1);
02232                 backup_s.pb= s->pb;
02233                 best_s.data_partitioning= s->data_partitioning;
02234                 best_s.partitioned_frame= s->partitioned_frame;
02235                 if(s->data_partitioning){
02236                     backup_s.pb2= s->pb2;
02237                     backup_s.tex_pb= s->tex_pb;
02238                 }
02239 
02240                 if(mb_type&CANDIDATE_MB_TYPE_INTER){
02241                     s->mv_dir = MV_DIR_FORWARD;
02242                     s->mv_type = MV_TYPE_16X16;
02243                     s->mb_intra= 0;
02244                     s->mv[0][0][0] = s->p_mv_table[xy][0];
02245                     s->mv[0][0][1] = s->p_mv_table[xy][1];
02246                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
02247                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
02248                 }
02249                 if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
02250                     s->mv_dir = MV_DIR_FORWARD;
02251                     s->mv_type = MV_TYPE_FIELD;
02252                     s->mb_intra= 0;
02253                     for(i=0; i<2; i++){
02254                         j= s->field_select[0][i] = s->p_field_select_table[i][xy];
02255                         s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
02256                         s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
02257                     }
02258                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
02259                                  &dmin, &next_block, 0, 0);
02260                 }
02261                 if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
02262                     s->mv_dir = MV_DIR_FORWARD;
02263                     s->mv_type = MV_TYPE_16X16;
02264                     s->mb_intra= 0;
02265                     s->mv[0][0][0] = 0;
02266                     s->mv[0][0][1] = 0;
02267                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
02268                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
02269                 }
02270                 if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
02271                     s->mv_dir = MV_DIR_FORWARD;
02272                     s->mv_type = MV_TYPE_8X8;
02273                     s->mb_intra= 0;
02274                     for(i=0; i<4; i++){
02275                         s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
02276                         s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
02277                     }
02278                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
02279                                  &dmin, &next_block, 0, 0);
02280                 }
02281                 if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
02282                     s->mv_dir = MV_DIR_FORWARD;
02283                     s->mv_type = MV_TYPE_16X16;
02284                     s->mb_intra= 0;
02285                     s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
02286                     s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
02287                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
02288                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
02289                 }
02290                 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
02291                     s->mv_dir = MV_DIR_BACKWARD;
02292                     s->mv_type = MV_TYPE_16X16;
02293                     s->mb_intra= 0;
02294                     s->mv[1][0][0] = s->b_back_mv_table[xy][0];
02295                     s->mv[1][0][1] = s->b_back_mv_table[xy][1];
02296                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
02297                                  &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
02298                 }
02299                 if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
02300                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
02301                     s->mv_type = MV_TYPE_16X16;
02302                     s->mb_intra= 0;
02303                     s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
02304                     s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
02305                     s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
02306                     s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
02307                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
02308                                  &dmin, &next_block, 0, 0);
02309                 }
02310                 if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
02311                     s->mv_dir = MV_DIR_FORWARD;
02312                     s->mv_type = MV_TYPE_FIELD;
02313                     s->mb_intra= 0;
02314                     for(i=0; i<2; i++){
02315                         j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
02316                         s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
02317                         s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
02318                     }
02319                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
02320                                  &dmin, &next_block, 0, 0);
02321                 }
02322                 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
02323                     s->mv_dir = MV_DIR_BACKWARD;
02324                     s->mv_type = MV_TYPE_FIELD;
02325                     s->mb_intra= 0;
02326                     for(i=0; i<2; i++){
02327                         j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
02328                         s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
02329                         s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
02330                     }
02331                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
02332                                  &dmin, &next_block, 0, 0);
02333                 }
02334                 if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
02335                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
02336                     s->mv_type = MV_TYPE_FIELD;
02337                     s->mb_intra= 0;
02338                     for(dir=0; dir<2; dir++){
02339                         for(i=0; i<2; i++){
02340                             j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
02341                             s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
02342                             s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
02343                         }
02344                     }
02345                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
02346                                  &dmin, &next_block, 0, 0);
02347                 }
02348                 if(mb_type&CANDIDATE_MB_TYPE_INTRA){
02349                     s->mv_dir = 0;
02350                     s->mv_type = MV_TYPE_16X16;
02351                     s->mb_intra= 1;
02352                     s->mv[0][0][0] = 0;
02353                     s->mv[0][0][1] = 0;
02354                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
02355                                  &dmin, &next_block, 0, 0);
02356                     if(s->h263_pred || s->h263_aic){
02357                         if(best_s.mb_intra)
02358                             s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
02359                         else
02360                             ff_clean_intra_table_entries(s); //old mode?
02361                     }
02362                 }
02363 
02364                 if((s->flags & CODEC_FLAG_QP_RD) && dmin < INT_MAX){
02365                     if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
02366                         const int last_qp= backup_s.qscale;
02367                         int qpi, qp, dc[6];
02368                         DCTELEM ac[6][16];
02369                         const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
02370                         static const int dquant_tab[4]={-1,1,-2,2};
02371 
02372                         assert(backup_s.dquant == 0);
02373 
02374                         //FIXME intra
02375                         s->mv_dir= best_s.mv_dir;
02376                         s->mv_type = MV_TYPE_16X16;
02377                         s->mb_intra= best_s.mb_intra;
02378                         s->mv[0][0][0] = best_s.mv[0][0][0];
02379                         s->mv[0][0][1] = best_s.mv[0][0][1];
02380                         s->mv[1][0][0] = best_s.mv[1][0][0];
02381                         s->mv[1][0][1] = best_s.mv[1][0][1];
02382 
02383                         qpi = s->pict_type == AV_PICTURE_TYPE_B ? 2 : 0;
02384                         for(; qpi<4; qpi++){
02385                             int dquant= dquant_tab[qpi];
02386                             qp= last_qp + dquant;
02387                             if(qp < s->avctx->qmin || qp > s->avctx->qmax)
02388                                 continue;
02389                             backup_s.dquant= dquant;
02390                             if(s->mb_intra && s->dc_val[0]){
02391                                 for(i=0; i<6; i++){
02392                                     dc[i]= s->dc_val[0][ s->block_index[i] ];
02393                                     memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(DCTELEM)*16);
02394                                 }
02395                             }
02396 
02397                             encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
02398                                          &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
02399                             if(best_s.qscale != qp){
02400                                 if(s->mb_intra && s->dc_val[0]){
02401                                     for(i=0; i<6; i++){
02402                                         s->dc_val[0][ s->block_index[i] ]= dc[i];
02403                                         memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(DCTELEM)*16);
02404                                     }
02405                                 }
02406                             }
02407                         }
02408                     }
02409                 }
02410                 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
02411                     int mx= s->b_direct_mv_table[xy][0];
02412                     int my= s->b_direct_mv_table[xy][1];
02413 
02414                     backup_s.dquant = 0;
02415                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
02416                     s->mb_intra= 0;
02417                     ff_mpeg4_set_direct_mv(s, mx, my);
02418                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
02419                                  &dmin, &next_block, mx, my);
02420                 }
02421                 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
02422                     backup_s.dquant = 0;
02423                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
02424                     s->mb_intra= 0;
02425                     ff_mpeg4_set_direct_mv(s, 0, 0);
02426                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
02427                                  &dmin, &next_block, 0, 0);
02428                 }
02429                 if(!best_s.mb_intra && s->flags2&CODEC_FLAG2_SKIP_RD){
02430                     int coded=0;
02431                     for(i=0; i<6; i++)
02432                         coded |= s->block_last_index[i];
02433                     if(coded){
02434                         int mx,my;
02435                         memcpy(s->mv, best_s.mv, sizeof(s->mv));
02436                         if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
02437                             mx=my=0; //FIXME find the one we actually used
02438                             ff_mpeg4_set_direct_mv(s, mx, my);
02439                         }else if(best_s.mv_dir&MV_DIR_BACKWARD){
02440                             mx= s->mv[1][0][0];
02441                             my= s->mv[1][0][1];
02442                         }else{
02443                             mx= s->mv[0][0][0];
02444                             my= s->mv[0][0][1];
02445                         }
02446 
02447                         s->mv_dir= best_s.mv_dir;
02448                         s->mv_type = best_s.mv_type;
02449                         s->mb_intra= 0;
02450 /*                        s->mv[0][0][0] = best_s.mv[0][0][0];
02451                         s->mv[0][0][1] = best_s.mv[0][0][1];
02452                         s->mv[1][0][0] = best_s.mv[1][0][0];
02453                         s->mv[1][0][1] = best_s.mv[1][0][1];*/
02454                         backup_s.dquant= 0;
02455                         s->skipdct=1;
02456                         encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
02457                                         &dmin, &next_block, mx, my);
02458                         s->skipdct=0;
02459                     }
02460                 }
02461 
02462                 s->current_picture.qscale_table[xy]= best_s.qscale;
02463 
02464                 copy_context_after_encode(s, &best_s, -1);
02465 
02466                 pb_bits_count= put_bits_count(&s->pb);
02467                 flush_put_bits(&s->pb);
02468                 ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
02469                 s->pb= backup_s.pb;
02470 
02471                 if(s->data_partitioning){
02472                     pb2_bits_count= put_bits_count(&s->pb2);
02473                     flush_put_bits(&s->pb2);
02474                     ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
02475                     s->pb2= backup_s.pb2;
02476 
02477                     tex_pb_bits_count= put_bits_count(&s->tex_pb);
02478                     flush_put_bits(&s->tex_pb);
02479                     ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
02480                     s->tex_pb= backup_s.tex_pb;
02481                 }
02482                 s->last_bits= put_bits_count(&s->pb);
02483 
02484                 if (CONFIG_H263_ENCODER &&
02485                     s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
02486                     ff_h263_update_motion_val(s);
02487 
02488                 if(next_block==0){ //FIXME 16 vs linesize16
02489                     s->dsp.put_pixels_tab[0][0](s->dest[0], s->rd_scratchpad                     , s->linesize  ,16);
02490                     s->dsp.put_pixels_tab[1][0](s->dest[1], s->rd_scratchpad + 16*s->linesize    , s->uvlinesize, 8);
02491                     s->dsp.put_pixels_tab[1][0](s->dest[2], s->rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
02492                 }
02493 
02494                 if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
02495                     MPV_decode_mb(s, s->block);
02496             } else {
02497                 int motion_x = 0, motion_y = 0;
02498                 s->mv_type=MV_TYPE_16X16;
02499                 // only one MB-Type possible
02500 
02501                 switch(mb_type){
02502                 case CANDIDATE_MB_TYPE_INTRA:
02503                     s->mv_dir = 0;
02504                     s->mb_intra= 1;
02505                     motion_x= s->mv[0][0][0] = 0;
02506                     motion_y= s->mv[0][0][1] = 0;
02507                     break;
02508                 case CANDIDATE_MB_TYPE_INTER:
02509                     s->mv_dir = MV_DIR_FORWARD;
02510                     s->mb_intra= 0;
02511                     motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
02512                     motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
02513                     break;
02514                 case CANDIDATE_MB_TYPE_INTER_I:
02515                     s->mv_dir = MV_DIR_FORWARD;
02516                     s->mv_type = MV_TYPE_FIELD;
02517                     s->mb_intra= 0;
02518                     for(i=0; i<2; i++){
02519                         j= s->field_select[0][i] = s->p_field_select_table[i][xy];
02520                         s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
02521                         s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
02522                     }
02523                     break;
02524                 case CANDIDATE_MB_TYPE_INTER4V:
02525                     s->mv_dir = MV_DIR_FORWARD;
02526                     s->mv_type = MV_TYPE_8X8;
02527                     s->mb_intra= 0;
02528                     for(i=0; i<4; i++){
02529                         s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
02530                         s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
02531                     }
02532                     break;
02533                 case CANDIDATE_MB_TYPE_DIRECT:
02534                     if (CONFIG_MPEG4_ENCODER) {
02535                         s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
02536                         s->mb_intra= 0;
02537                         motion_x=s->b_direct_mv_table[xy][0];
02538                         motion_y=s->b_direct_mv_table[xy][1];
02539                         ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
02540                     }
02541                     break;
02542                 case CANDIDATE_MB_TYPE_DIRECT0:
02543                     if (CONFIG_MPEG4_ENCODER) {
02544                         s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
02545                         s->mb_intra= 0;
02546                         ff_mpeg4_set_direct_mv(s, 0, 0);
02547                     }
02548                     break;
02549                 case CANDIDATE_MB_TYPE_BIDIR:
02550                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
02551                     s->mb_intra= 0;
02552                     s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
02553                     s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
02554                     s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
02555                     s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
02556                     break;
02557                 case CANDIDATE_MB_TYPE_BACKWARD:
02558                     s->mv_dir = MV_DIR_BACKWARD;
02559                     s->mb_intra= 0;
02560                     motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
02561                     motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
02562                     break;
02563                 case CANDIDATE_MB_TYPE_FORWARD:
02564                     s->mv_dir = MV_DIR_FORWARD;
02565                     s->mb_intra= 0;
02566                     motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
02567                     motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
02568 //                    printf(" %d %d ", motion_x, motion_y);
02569                     break;
02570                 case CANDIDATE_MB_TYPE_FORWARD_I:
02571                     s->mv_dir = MV_DIR_FORWARD;
02572                     s->mv_type = MV_TYPE_FIELD;
02573                     s->mb_intra= 0;
02574                     for(i=0; i<2; i++){
02575                         j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
02576                         s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
02577                         s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
02578                     }
02579                     break;
02580                 case CANDIDATE_MB_TYPE_BACKWARD_I:
02581                     s->mv_dir = MV_DIR_BACKWARD;
02582                     s->mv_type = MV_TYPE_FIELD;
02583                     s->mb_intra= 0;
02584                     for(i=0; i<2; i++){
02585                         j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
02586                         s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
02587                         s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
02588                     }
02589                     break;
02590                 case CANDIDATE_MB_TYPE_BIDIR_I:
02591                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
02592                     s->mv_type = MV_TYPE_FIELD;
02593                     s->mb_intra= 0;
02594                     for(dir=0; dir<2; dir++){
02595                         for(i=0; i<2; i++){
02596                             j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
02597                             s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
02598                             s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
02599                         }
02600                     }
02601                     break;
02602                 default:
02603                     av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
02604                 }
02605 
02606                 encode_mb(s, motion_x, motion_y);
02607 
02608                 // RAL: Update last macroblock type
02609                 s->last_mv_dir = s->mv_dir;
02610 
02611                 if (CONFIG_H263_ENCODER &&
02612                     s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
02613                     ff_h263_update_motion_val(s);
02614 
02615                 MPV_decode_mb(s, s->block);
02616             }
02617 
02618             /* clean the MV table in IPS frames for direct mode in B frames */
02619             if(s->mb_intra /* && I,P,S_TYPE */){
02620                 s->p_mv_table[xy][0]=0;
02621                 s->p_mv_table[xy][1]=0;
02622             }
02623 
02624             if(s->flags&CODEC_FLAG_PSNR){
02625                 int w= 16;
02626                 int h= 16;
02627 
02628                 if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
02629                 if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
02630 
02631                 s->current_picture.error[0] += sse(
02632                     s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
02633                     s->dest[0], w, h, s->linesize);
02634                 s->current_picture.error[1] += sse(
02635                     s, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
02636                     s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
02637                 s->current_picture.error[2] += sse(
02638                     s, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
02639                     s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
02640             }
02641             if(s->loop_filter){
02642                 if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
02643                     ff_h263_loop_filter(s);
02644             }
02645 //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, put_bits_count(&s->pb));
02646         }
02647     }
02648 
02649     //not beautiful here but we must write it before flushing so it has to be here
02650     if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == AV_PICTURE_TYPE_I)
02651         msmpeg4_encode_ext_header(s);
02652 
02653     write_slice_end(s);
02654 
02655     /* Send the last GOB if RTP */
02656     if (s->avctx->rtp_callback) {
02657         int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
02658         pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
02659         /* Call the RTP callback to send the last GOB */
02660         emms_c();
02661         s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
02662     }
02663 
02664     return 0;
02665 }
02666 
02667 #define MERGE(field) dst->field += src->field; src->field=0
02668 static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
02669     MERGE(me.scene_change_score);
02670     MERGE(me.mc_mb_var_sum_temp);
02671     MERGE(me.mb_var_sum_temp);
02672 }
02673 
02674 static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
02675     int i;
02676 
02677     MERGE(dct_count[0]); //note, the other dct vars are not part of the context
02678     MERGE(dct_count[1]);
02679     MERGE(mv_bits);
02680     MERGE(i_tex_bits);
02681     MERGE(p_tex_bits);
02682     MERGE(i_count);
02683     MERGE(f_count);
02684     MERGE(b_count);
02685     MERGE(skip_count);
02686     MERGE(misc_bits);
02687     MERGE(error_count);
02688     MERGE(padding_bug_score);
02689     MERGE(current_picture.error[0]);
02690     MERGE(current_picture.error[1]);
02691     MERGE(current_picture.error[2]);
02692 
02693     if(dst->avctx->noise_reduction){
02694         for(i=0; i<64; i++){
02695             MERGE(dct_error_sum[0][i]);
02696             MERGE(dct_error_sum[1][i]);
02697         }
02698     }
02699 
02700     assert(put_bits_count(&src->pb) % 8 ==0);
02701     assert(put_bits_count(&dst->pb) % 8 ==0);
02702     ff_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
02703     flush_put_bits(&dst->pb);
02704 }
02705 
02706 static int estimate_qp(MpegEncContext *s, int dry_run){
02707     if (s->next_lambda){
02708         s->current_picture_ptr->quality=
02709         s->current_picture.quality = s->next_lambda;
02710         if(!dry_run) s->next_lambda= 0;
02711     } else if (!s->fixed_qscale) {
02712         s->current_picture_ptr->quality=
02713         s->current_picture.quality = ff_rate_estimate_qscale(s, dry_run);
02714         if (s->current_picture.quality < 0)
02715             return -1;
02716     }
02717 
02718     if(s->adaptive_quant){
02719         switch(s->codec_id){
02720         case CODEC_ID_MPEG4:
02721             if (CONFIG_MPEG4_ENCODER)
02722                 ff_clean_mpeg4_qscales(s);
02723             break;
02724         case CODEC_ID_H263:
02725         case CODEC_ID_H263P:
02726         case CODEC_ID_FLV1:
02727             if (CONFIG_H263_ENCODER)
02728                 ff_clean_h263_qscales(s);
02729             break;
02730         default:
02731             ff_init_qscale_tab(s);
02732         }
02733 
02734         s->lambda= s->lambda_table[0];
02735         //FIXME broken
02736     }else
02737         s->lambda= s->current_picture.quality;
02738 //printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
02739     update_qscale(s);
02740     return 0;
02741 }
02742 
02743 /* must be called before writing the header */
02744 static void set_frame_distances(MpegEncContext * s){
02745     assert(s->current_picture_ptr->pts != AV_NOPTS_VALUE);
02746     s->time= s->current_picture_ptr->pts*s->avctx->time_base.num;
02747 
02748     if(s->pict_type==AV_PICTURE_TYPE_B){
02749         s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
02750         assert(s->pb_time > 0 && s->pb_time < s->pp_time);
02751     }else{
02752         s->pp_time= s->time - s->last_non_b_time;
02753         s->last_non_b_time= s->time;
02754         assert(s->picture_number==0 || s->pp_time > 0);
02755     }
02756 }
02757 
02758 static int encode_picture(MpegEncContext *s, int picture_number)
02759 {
02760     int i;
02761     int bits;
02762     int context_count = s->avctx->thread_count;
02763 
02764     s->picture_number = picture_number;
02765 
02766     /* Reset the average MB variance */
02767     s->me.mb_var_sum_temp    =
02768     s->me.mc_mb_var_sum_temp = 0;
02769 
02770     /* we need to initialize some time vars before we can encode b-frames */
02771     // RAL: Condition added for MPEG1VIDEO
02772     if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->msmpeg4_version))
02773         set_frame_distances(s);
02774     if(CONFIG_MPEG4_ENCODER && s->codec_id == CODEC_ID_MPEG4)
02775         ff_set_mpeg4_time(s);
02776 
02777     s->me.scene_change_score=0;
02778 
02779 //    s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
02780 
02781     if(s->pict_type==AV_PICTURE_TYPE_I){
02782         if(s->msmpeg4_version >= 3) s->no_rounding=1;
02783         else                        s->no_rounding=0;
02784     }else if(s->pict_type!=AV_PICTURE_TYPE_B){
02785         if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
02786             s->no_rounding ^= 1;
02787     }
02788 
02789     if(s->flags & CODEC_FLAG_PASS2){
02790         if (estimate_qp(s,1) < 0)
02791             return -1;
02792         ff_get_2pass_fcode(s);
02793     }else if(!(s->flags & CODEC_FLAG_QSCALE)){
02794         if(s->pict_type==AV_PICTURE_TYPE_B)
02795             s->lambda= s->last_lambda_for[s->pict_type];
02796         else
02797             s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
02798         update_qscale(s);
02799     }
02800 
02801     s->mb_intra=0; //for the rate distortion & bit compare functions
02802     for(i=1; i<context_count; i++){
02803         ff_update_duplicate_context(s->thread_context[i], s);
02804     }
02805 
02806     if(ff_init_me(s)<0)
02807         return -1;
02808 
02809     /* Estimate motion for every MB */
02810     if(s->pict_type != AV_PICTURE_TYPE_I){
02811         s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
02812         s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
02813         if(s->pict_type != AV_PICTURE_TYPE_B && s->avctx->me_threshold==0){
02814             if((s->avctx->pre_me && s->last_non_b_pict_type==AV_PICTURE_TYPE_I) || s->avctx->pre_me==2){
02815                 s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
02816             }
02817         }
02818 
02819         s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
02820     }else /* if(s->pict_type == AV_PICTURE_TYPE_I) */{
02821         /* I-Frame */
02822         for(i=0; i<s->mb_stride*s->mb_height; i++)
02823             s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
02824 
02825         if(!s->fixed_qscale){
02826             /* finding spatial complexity for I-frame rate control */
02827             s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
02828         }
02829     }
02830     for(i=1; i<context_count; i++){
02831         merge_context_after_me(s, s->thread_context[i]);
02832     }
02833     s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
02834     s->current_picture.   mb_var_sum= s->current_picture_ptr->   mb_var_sum= s->me.   mb_var_sum_temp;
02835     emms_c();
02836 
02837     if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == AV_PICTURE_TYPE_P){
02838         s->pict_type= AV_PICTURE_TYPE_I;
02839         for(i=0; i<s->mb_stride*s->mb_height; i++)
02840             s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
02841 //printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
02842     }
02843 
02844     if(!s->umvplus){
02845         if(s->pict_type==AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
02846             s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
02847 
02848             if(s->flags & CODEC_FLAG_INTERLACED_ME){
02849                 int a,b;
02850                 a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
02851                 b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
02852                 s->f_code= FFMAX3(s->f_code, a, b);
02853             }
02854 
02855             ff_fix_long_p_mvs(s);
02856             ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
02857             if(s->flags & CODEC_FLAG_INTERLACED_ME){
02858                 int j;
02859                 for(i=0; i<2; i++){
02860                     for(j=0; j<2; j++)
02861                         ff_fix_long_mvs(s, s->p_field_select_table[i], j,
02862                                         s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
02863                 }
02864             }
02865         }
02866 
02867         if(s->pict_type==AV_PICTURE_TYPE_B){
02868             int a, b;
02869 
02870             a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
02871             b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
02872             s->f_code = FFMAX(a, b);
02873 
02874             a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
02875             b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
02876             s->b_code = FFMAX(a, b);
02877 
02878             ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
02879             ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
02880             ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
02881             ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
02882             if(s->flags & CODEC_FLAG_INTERLACED_ME){
02883                 int dir, j;
02884                 for(dir=0; dir<2; dir++){
02885                     for(i=0; i<2; i++){
02886                         for(j=0; j<2; j++){
02887                             int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
02888                                           : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
02889                             ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
02890                                             s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
02891                         }
02892                     }
02893                 }
02894             }
02895         }
02896     }
02897 
02898     if (estimate_qp(s, 0) < 0)
02899         return -1;
02900 
02901     if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==AV_PICTURE_TYPE_I && !(s->flags & CODEC_FLAG_QSCALE))
02902         s->qscale= 3; //reduce clipping problems
02903 
02904     if (s->out_format == FMT_MJPEG) {
02905         /* for mjpeg, we do include qscale in the matrix */
02906         for(i=1;i<64;i++){
02907             int j= s->dsp.idct_permutation[i];
02908 
02909             s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
02910         }
02911         s->y_dc_scale_table=
02912         s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];
02913         s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];
02914         ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
02915                        s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
02916         s->qscale= 8;
02917     }
02918 
02919     //FIXME var duplication
02920     s->current_picture_ptr->key_frame=
02921     s->current_picture.key_frame= s->pict_type == AV_PICTURE_TYPE_I; //FIXME pic_ptr
02922     s->current_picture_ptr->pict_type=
02923     s->current_picture.pict_type= s->pict_type;
02924 
02925     if(s->current_picture.key_frame)
02926         s->picture_in_gop_number=0;
02927 
02928     s->last_bits= put_bits_count(&s->pb);
02929     switch(s->out_format) {
02930     case FMT_MJPEG:
02931         if (CONFIG_MJPEG_ENCODER)
02932             ff_mjpeg_encode_picture_header(s);
02933         break;
02934     case FMT_H261:
02935         if (CONFIG_H261_ENCODER)
02936             ff_h261_encode_picture_header(s, picture_number);
02937         break;
02938     case FMT_H263:
02939         if (CONFIG_WMV2_ENCODER && s->codec_id == CODEC_ID_WMV2)
02940             ff_wmv2_encode_picture_header(s, picture_number);
02941         else if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
02942             msmpeg4_encode_picture_header(s, picture_number);
02943         else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
02944             mpeg4_encode_picture_header(s, picture_number);
02945         else if (CONFIG_RV10_ENCODER && s->codec_id == CODEC_ID_RV10)
02946             rv10_encode_picture_header(s, picture_number);
02947         else if (CONFIG_RV20_ENCODER && s->codec_id == CODEC_ID_RV20)
02948             rv20_encode_picture_header(s, picture_number);
02949         else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
02950             ff_flv_encode_picture_header(s, picture_number);
02951         else if (CONFIG_H263_ENCODER)
02952             h263_encode_picture_header(s, picture_number);
02953         break;
02954     case FMT_MPEG1:
02955         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
02956             mpeg1_encode_picture_header(s, picture_number);
02957         break;
02958     case FMT_H264:
02959         break;
02960     default:
02961         assert(0);
02962     }
02963     bits= put_bits_count(&s->pb);
02964     s->header_bits= bits - s->last_bits;
02965 
02966     for(i=1; i<context_count; i++){
02967         update_duplicate_context_after_me(s->thread_context[i], s);
02968     }
02969     s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
02970     for(i=1; i<context_count; i++){
02971         merge_context_after_encode(s, s->thread_context[i]);
02972     }
02973     emms_c();
02974     return 0;
02975 }
02976 
02977 static void denoise_dct_c(MpegEncContext *s, DCTELEM *block){
02978     const int intra= s->mb_intra;
02979     int i;
02980 
02981     s->dct_count[intra]++;
02982 
02983     for(i=0; i<64; i++){
02984         int level= block[i];
02985 
02986         if(level){
02987             if(level>0){
02988                 s->dct_error_sum[intra][i] += level;
02989                 level -= s->dct_offset[intra][i];
02990                 if(level<0) level=0;
02991             }else{
02992                 s->dct_error_sum[intra][i] -= level;
02993                 level += s->dct_offset[intra][i];
02994                 if(level>0) level=0;
02995             }
02996             block[i]= level;
02997         }
02998     }
02999 }
03000 
03001 static int dct_quantize_trellis_c(MpegEncContext *s,
03002                                   DCTELEM *block, int n,
03003                                   int qscale, int *overflow){
03004     const int *qmat;
03005     const uint8_t *scantable= s->intra_scantable.scantable;
03006     const uint8_t *perm_scantable= s->intra_scantable.permutated;
03007     int max=0;
03008     unsigned int threshold1, threshold2;
03009     int bias=0;
03010     int run_tab[65];
03011     int level_tab[65];
03012     int score_tab[65];
03013     int survivor[65];
03014     int survivor_count;
03015     int last_run=0;
03016     int last_level=0;
03017     int last_score= 0;
03018     int last_i;
03019     int coeff[2][64];
03020     int coeff_count[64];
03021     int qmul, qadd, start_i, last_non_zero, i, dc;
03022     const int esc_length= s->ac_esc_length;
03023     uint8_t * length;
03024     uint8_t * last_length;
03025     const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
03026 
03027     s->dsp.fdct (block);
03028 
03029     if(s->dct_error_sum)
03030         s->denoise_dct(s, block);
03031     qmul= qscale*16;
03032     qadd= ((qscale-1)|1)*8;
03033 
03034     if (s->mb_intra) {
03035         int q;
03036         if (!s->h263_aic) {
03037             if (n < 4)
03038                 q = s->y_dc_scale;
03039             else
03040                 q = s->c_dc_scale;
03041             q = q << 3;
03042         } else{
03043             /* For AIC we skip quant/dequant of INTRADC */
03044             q = 1 << 3;
03045             qadd=0;
03046         }
03047 
03048         /* note: block[0] is assumed to be positive */
03049         block[0] = (block[0] + (q >> 1)) / q;
03050         start_i = 1;
03051         last_non_zero = 0;
03052         qmat = s->q_intra_matrix[qscale];
03053         if(s->mpeg_quant || s->out_format == FMT_MPEG1)
03054             bias= 1<<(QMAT_SHIFT-1);
03055         length     = s->intra_ac_vlc_length;
03056         last_length= s->intra_ac_vlc_last_length;
03057     } else {
03058         start_i = 0;
03059         last_non_zero = -1;
03060         qmat = s->q_inter_matrix[qscale];
03061         length     = s->inter_ac_vlc_length;
03062         last_length= s->inter_ac_vlc_last_length;
03063     }
03064     last_i= start_i;
03065 
03066     threshold1= (1<<QMAT_SHIFT) - bias - 1;
03067     threshold2= (threshold1<<1);
03068 
03069     for(i=63; i>=start_i; i--) {
03070         const int j = scantable[i];
03071         int level = block[j] * qmat[j];
03072 
03073         if(((unsigned)(level+threshold1))>threshold2){
03074             last_non_zero = i;
03075             break;
03076         }
03077     }
03078 
03079     for(i=start_i; i<=last_non_zero; i++) {
03080         const int j = scantable[i];
03081         int level = block[j] * qmat[j];
03082 
03083 //        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
03084 //           || bias-level >= (1<<(QMAT_SHIFT - 3))){
03085         if(((unsigned)(level+threshold1))>threshold2){
03086             if(level>0){
03087                 level= (bias + level)>>QMAT_SHIFT;
03088                 coeff[0][i]= level;
03089                 coeff[1][i]= level-1;
03090 //                coeff[2][k]= level-2;
03091             }else{
03092                 level= (bias - level)>>QMAT_SHIFT;
03093                 coeff[0][i]= -level;
03094                 coeff[1][i]= -level+1;
03095 //                coeff[2][k]= -level+2;
03096             }
03097             coeff_count[i]= FFMIN(level, 2);
03098             assert(coeff_count[i]);
03099             max |=level;
03100         }else{
03101             coeff[0][i]= (level>>31)|1;
03102             coeff_count[i]= 1;
03103         }
03104     }
03105 
03106     *overflow= s->max_qcoeff < max; //overflow might have happened
03107 
03108     if(last_non_zero < start_i){
03109         memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
03110         return last_non_zero;
03111     }
03112 
03113     score_tab[start_i]= 0;
03114     survivor[0]= start_i;
03115     survivor_count= 1;
03116 
03117     for(i=start_i; i<=last_non_zero; i++){
03118         int level_index, j, zero_distortion;
03119         int dct_coeff= FFABS(block[ scantable[i] ]);
03120         int best_score=256*256*256*120;
03121 
03122         if (   s->dsp.fdct == fdct_ifast
03123 #ifndef FAAN_POSTSCALE
03124             || s->dsp.fdct == ff_faandct
03125 #endif
03126            )
03127             dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
03128         zero_distortion= dct_coeff*dct_coeff;
03129 
03130         for(level_index=0; level_index < coeff_count[i]; level_index++){
03131             int distortion;
03132             int level= coeff[level_index][i];
03133             const int alevel= FFABS(level);
03134             int unquant_coeff;
03135 
03136             assert(level);
03137 
03138             if(s->out_format == FMT_H263){
03139                 unquant_coeff= alevel*qmul + qadd;
03140             }else{ //MPEG1
03141                 j= s->dsp.idct_permutation[ scantable[i] ]; //FIXME optimize
03142                 if(s->mb_intra){
03143                         unquant_coeff = (int)(  alevel  * qscale * s->intra_matrix[j]) >> 3;
03144                         unquant_coeff =   (unquant_coeff - 1) | 1;
03145                 }else{
03146                         unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
03147                         unquant_coeff =   (unquant_coeff - 1) | 1;
03148                 }
03149                 unquant_coeff<<= 3;
03150             }
03151 
03152             distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
03153             level+=64;
03154             if((level&(~127)) == 0){
03155                 for(j=survivor_count-1; j>=0; j--){
03156                     int run= i - survivor[j];
03157                     int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
03158                     score += score_tab[i-run];
03159 
03160                     if(score < best_score){
03161                         best_score= score;
03162                         run_tab[i+1]= run;
03163                         level_tab[i+1]= level-64;
03164                     }
03165                 }
03166 
03167                 if(s->out_format == FMT_H263){
03168                     for(j=survivor_count-1; j>=0; j--){
03169                         int run= i - survivor[j];
03170                         int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
03171                         score += score_tab[i-run];
03172                         if(score < last_score){
03173                             last_score= score;
03174                             last_run= run;
03175                             last_level= level-64;
03176                             last_i= i+1;
03177                         }
03178                     }
03179                 }
03180             }else{
03181                 distortion += esc_length*lambda;
03182                 for(j=survivor_count-1; j>=0; j--){
03183                     int run= i - survivor[j];
03184                     int score= distortion + score_tab[i-run];
03185 
03186                     if(score < best_score){
03187                         best_score= score;
03188                         run_tab[i+1]= run;
03189                         level_tab[i+1]= level-64;
03190                     }
03191                 }
03192 
03193                 if(s->out_format == FMT_H263){
03194                   for(j=survivor_count-1; j>=0; j--){
03195                         int run= i - survivor[j];
03196                         int score= distortion + score_tab[i-run];
03197                         if(score < last_score){
03198                             last_score= score;
03199                             last_run= run;
03200                             last_level= level-64;
03201                             last_i= i+1;
03202                         }
03203                     }
03204                 }
03205             }
03206         }
03207 
03208         score_tab[i+1]= best_score;
03209 
03210         //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
03211         if(last_non_zero <= 27){
03212             for(; survivor_count; survivor_count--){
03213                 if(score_tab[ survivor[survivor_count-1] ] <= best_score)
03214                     break;
03215             }
03216         }else{
03217             for(; survivor_count; survivor_count--){
03218                 if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
03219                     break;
03220             }
03221         }
03222 
03223         survivor[ survivor_count++ ]= i+1;
03224     }
03225 
03226     if(s->out_format != FMT_H263){
03227         last_score= 256*256*256*120;
03228         for(i= survivor[0]; i<=last_non_zero + 1; i++){
03229             int score= score_tab[i];
03230             if(i) score += lambda*2; //FIXME exacter?
03231 
03232             if(score < last_score){
03233                 last_score= score;
03234                 last_i= i;
03235                 last_level= level_tab[i];
03236                 last_run= run_tab[i];
03237             }
03238         }
03239     }
03240 
03241     s->coded_score[n] = last_score;
03242 
03243     dc= FFABS(block[0]);
03244     last_non_zero= last_i - 1;
03245     memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
03246 
03247     if(last_non_zero < start_i)
03248         return last_non_zero;
03249 
03250     if(last_non_zero == 0 && start_i == 0){
03251         int best_level= 0;
03252         int best_score= dc * dc;
03253 
03254         for(i=0; i<coeff_count[0]; i++){
03255             int level= coeff[i][0];
03256             int alevel= FFABS(level);
03257             int unquant_coeff, score, distortion;
03258 
03259             if(s->out_format == FMT_H263){
03260                     unquant_coeff= (alevel*qmul + qadd)>>3;
03261             }else{ //MPEG1
03262                     unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
03263                     unquant_coeff =   (unquant_coeff - 1) | 1;
03264             }
03265             unquant_coeff = (unquant_coeff + 4) >> 3;
03266             unquant_coeff<<= 3 + 3;
03267 
03268             distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
03269             level+=64;
03270             if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
03271             else                    score= distortion + esc_length*lambda;
03272 
03273             if(score < best_score){
03274                 best_score= score;
03275                 best_level= level - 64;
03276             }
03277         }
03278         block[0]= best_level;
03279         s->coded_score[n] = best_score - dc*dc;
03280         if(best_level == 0) return -1;
03281         else                return last_non_zero;
03282     }
03283 
03284     i= last_i;
03285     assert(last_level);
03286 
03287     block[ perm_scantable[last_non_zero] ]= last_level;
03288     i -= last_run + 1;
03289 
03290     for(; i>start_i; i -= run_tab[i] + 1){
03291         block[ perm_scantable[i-1] ]= level_tab[i];
03292     }
03293 
03294     return last_non_zero;
03295 }
03296 
03297 //#define REFINE_STATS 1
03298 static int16_t basis[64][64];
03299 
03300 static void build_basis(uint8_t *perm){
03301     int i, j, x, y;
03302     emms_c();
03303     for(i=0; i<8; i++){
03304         for(j=0; j<8; j++){
03305             for(y=0; y<8; y++){
03306                 for(x=0; x<8; x++){
03307                     double s= 0.25*(1<<BASIS_SHIFT);
03308                     int index= 8*i + j;
03309                     int perm_index= perm[index];
03310                     if(i==0) s*= sqrt(0.5);
03311                     if(j==0) s*= sqrt(0.5);
03312                     basis[perm_index][8*x + y]= lrintf(s * cos((M_PI/8.0)*i*(x+0.5)) * cos((M_PI/8.0)*j*(y+0.5)));
03313                 }
03314             }
03315         }
03316     }
03317 }
03318 
03319 static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
03320                         DCTELEM *block, int16_t *weight, DCTELEM *orig,
03321                         int n, int qscale){
03322     int16_t rem[64];
03323     LOCAL_ALIGNED_16(DCTELEM, d1, [64]);
03324     const uint8_t *scantable= s->intra_scantable.scantable;
03325     const uint8_t *perm_scantable= s->intra_scantable.permutated;
03326 //    unsigned int threshold1, threshold2;
03327 //    int bias=0;
03328     int run_tab[65];
03329     int prev_run=0;
03330     int prev_level=0;
03331     int qmul, qadd, start_i, last_non_zero, i, dc;
03332     uint8_t * length;
03333     uint8_t * last_length;
03334     int lambda;
03335     int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
03336 #ifdef REFINE_STATS
03337 static int count=0;
03338 static int after_last=0;
03339 static int to_zero=0;
03340 static int from_zero=0;
03341 static int raise=0;
03342 static int lower=0;
03343 static int messed_sign=0;
03344 #endif
03345 
03346     if(basis[0][0] == 0)
03347         build_basis(s->dsp.idct_permutation);
03348 
03349     qmul= qscale*2;
03350     qadd= (qscale-1)|1;
03351     if (s->mb_intra) {
03352         if (!s->h263_aic) {
03353             if (n < 4)
03354                 q = s->y_dc_scale;
03355             else
03356                 q = s->c_dc_scale;
03357         } else{
03358             /* For AIC we skip quant/dequant of INTRADC */
03359             q = 1;
03360             qadd=0;
03361         }
03362         q <<= RECON_SHIFT-3;
03363         /* note: block[0] is assumed to be positive */
03364         dc= block[0]*q;
03365 //        block[0] = (block[0] + (q >> 1)) / q;
03366         start_i = 1;
03367 //        if(s->mpeg_quant || s->out_format == FMT_MPEG1)
03368 //            bias= 1<<(QMAT_SHIFT-1);
03369         length     = s->intra_ac_vlc_length;
03370         last_length= s->intra_ac_vlc_last_length;
03371     } else {
03372         dc= 0;
03373         start_i = 0;
03374         length     = s->inter_ac_vlc_length;
03375         last_length= s->inter_ac_vlc_last_length;
03376     }
03377     last_non_zero = s->block_last_index[n];
03378 
03379 #ifdef REFINE_STATS
03380 {START_TIMER
03381 #endif
03382     dc += (1<<(RECON_SHIFT-1));
03383     for(i=0; i<64; i++){
03384         rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME  use orig dirrectly instead of copying to rem[]
03385     }
03386 #ifdef REFINE_STATS
03387 STOP_TIMER("memset rem[]")}
03388 #endif
03389     sum=0;
03390     for(i=0; i<64; i++){
03391         int one= 36;
03392         int qns=4;
03393         int w;
03394 
03395         w= FFABS(weight[i]) + qns*one;
03396         w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
03397 
03398         weight[i] = w;
03399 //        w=weight[i] = (63*qns + (w/2)) / w;
03400 
03401         assert(w>0);
03402         assert(w<(1<<6));
03403         sum += w*w;
03404     }
03405     lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
03406 #ifdef REFINE_STATS
03407 {START_TIMER
03408 #endif
03409     run=0;
03410     rle_index=0;
03411     for(i=start_i; i<=last_non_zero; i++){
03412         int j= perm_scantable[i];
03413         const int level= block[j];
03414         int coeff;
03415 
03416         if(level){
03417             if(level<0) coeff= qmul*level - qadd;
03418             else        coeff= qmul*level + qadd;
03419             run_tab[rle_index++]=run;
03420             run=0;
03421 
03422             s->dsp.add_8x8basis(rem, basis[j], coeff);
03423         }else{
03424             run++;
03425         }
03426     }
03427 #ifdef REFINE_STATS
03428 if(last_non_zero>0){
03429 STOP_TIMER("init rem[]")
03430 }
03431 }
03432 
03433 {START_TIMER
03434 #endif
03435     for(;;){
03436         int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
03437         int best_coeff=0;
03438         int best_change=0;
03439         int run2, best_unquant_change=0, analyze_gradient;
03440 #ifdef REFINE_STATS
03441 {START_TIMER
03442 #endif
03443         analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
03444 
03445         if(analyze_gradient){
03446 #ifdef REFINE_STATS
03447 {START_TIMER
03448 #endif
03449             for(i=0; i<64; i++){
03450                 int w= weight[i];
03451 
03452                 d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
03453             }
03454 #ifdef REFINE_STATS
03455 STOP_TIMER("rem*w*w")}
03456 {START_TIMER
03457 #endif
03458             s->dsp.fdct(d1);
03459 #ifdef REFINE_STATS
03460 STOP_TIMER("dct")}
03461 #endif
03462         }
03463 
03464         if(start_i){
03465             const int level= block[0];
03466             int change, old_coeff;
03467 
03468             assert(s->mb_intra);
03469 
03470             old_coeff= q*level;
03471 
03472             for(change=-1; change<=1; change+=2){
03473                 int new_level= level + change;
03474                 int score, new_coeff;
03475 
03476                 new_coeff= q*new_level;
03477                 if(new_coeff >= 2048 || new_coeff < 0)
03478                     continue;
03479 
03480                 score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
03481                 if(score<best_score){
03482                     best_score= score;
03483                     best_coeff= 0;
03484                     best_change= change;
03485                     best_unquant_change= new_coeff - old_coeff;
03486                 }
03487             }
03488         }
03489 
03490         run=0;
03491         rle_index=0;
03492         run2= run_tab[rle_index++];
03493         prev_level=0;
03494         prev_run=0;
03495 
03496         for(i=start_i; i<64; i++){
03497             int j= perm_scantable[i];
03498             const int level= block[j];
03499             int change, old_coeff;
03500 
03501             if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
03502                 break;
03503 
03504             if(level){
03505                 if(level<0) old_coeff= qmul*level - qadd;
03506                 else        old_coeff= qmul*level + qadd;
03507                 run2= run_tab[rle_index++]; //FIXME ! maybe after last
03508             }else{
03509                 old_coeff=0;
03510                 run2--;
03511                 assert(run2>=0 || i >= last_non_zero );
03512             }
03513 
03514             for(change=-1; change<=1; change+=2){
03515                 int new_level= level + change;
03516                 int score, new_coeff, unquant_change;
03517 
03518                 score=0;
03519                 if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
03520                    continue;
03521 
03522                 if(new_level){
03523                     if(new_level<0) new_coeff= qmul*new_level - qadd;
03524                     else            new_coeff= qmul*new_level + qadd;
03525                     if(new_coeff >= 2048 || new_coeff <= -2048)
03526                         continue;
03527                     //FIXME check for overflow
03528 
03529                     if(level){
03530                         if(level < 63 && level > -63){
03531                             if(i < last_non_zero)
03532                                 score +=   length[UNI_AC_ENC_INDEX(run, new_level+64)]
03533                                          - length[UNI_AC_ENC_INDEX(run, level+64)];
03534                             else
03535                                 score +=   last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
03536                                          - last_length[UNI_AC_ENC_INDEX(run, level+64)];
03537                         }
03538                     }else{
03539                         assert(FFABS(new_level)==1);
03540 
03541                         if(analyze_gradient){
03542                             int g= d1[ scantable[i] ];
03543                             if(g && (g^new_level) >= 0)
03544                                 continue;
03545                         }
03546 
03547                         if(i < last_non_zero){
03548                             int next_i= i + run2 + 1;
03549                             int next_level= block[ perm_scantable[next_i] ] + 64;
03550 
03551                             if(next_level&(~127))
03552                                 next_level= 0;
03553 
03554                             if(next_i < last_non_zero)
03555                                 score +=   length[UNI_AC_ENC_INDEX(run, 65)]
03556                                          + length[UNI_AC_ENC_INDEX(run2, next_level)]
03557                                          - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
03558                             else
03559                                 score +=  length[UNI_AC_ENC_INDEX(run, 65)]
03560                                         + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
03561                                         - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
03562                         }else{
03563                             score += last_length[UNI_AC_ENC_INDEX(run, 65)];
03564                             if(prev_level){
03565                                 score +=  length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
03566                                         - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
03567                             }
03568                         }
03569                     }
03570                 }else{
03571                     new_coeff=0;
03572                     assert(FFABS(level)==1);
03573 
03574                     if(i < last_non_zero){
03575                         int next_i= i + run2 + 1;
03576                         int next_level= block[ perm_scantable[next_i] ] + 64;
03577 
03578                         if(next_level&(~127))
03579                             next_level= 0;
03580 
03581                         if(next_i < last_non_zero)
03582                             score +=   length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
03583                                      - length[UNI_AC_ENC_INDEX(run2, next_level)]
03584                                      - length[UNI_AC_ENC_INDEX(run, 65)];
03585                         else
03586                             score +=   last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
03587                                      - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
03588                                      - length[UNI_AC_ENC_INDEX(run, 65)];
03589                     }else{
03590                         score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
03591                         if(prev_level){
03592                             score +=  last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
03593                                     - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
03594                         }
03595                     }
03596                 }
03597 
03598                 score *= lambda;
03599 
03600                 unquant_change= new_coeff - old_coeff;
03601                 assert((score < 100*lambda && score > -100*lambda) || lambda==0);
03602 
03603                 score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
03604                 if(score<best_score){
03605                     best_score= score;
03606                     best_coeff= i;
03607                     best_change= change;
03608                     best_unquant_change= unquant_change;
03609                 }
03610             }
03611             if(level){
03612                 prev_level= level + 64;
03613                 if(prev_level&(~127))
03614                     prev_level= 0;
03615                 prev_run= run;
03616                 run=0;
03617             }else{
03618                 run++;
03619             }
03620         }
03621 #ifdef REFINE_STATS
03622 STOP_TIMER("iterative step")}
03623 #endif
03624 
03625         if(best_change){
03626             int j= perm_scantable[ best_coeff ];
03627 
03628             block[j] += best_change;
03629 
03630             if(best_coeff > last_non_zero){
03631                 last_non_zero= best_coeff;
03632                 assert(block[j]);
03633 #ifdef REFINE_STATS
03634 after_last++;
03635 #endif
03636             }else{
03637 #ifdef REFINE_STATS
03638 if(block[j]){
03639     if(block[j] - best_change){
03640         if(FFABS(block[j]) > FFABS(block[j] - best_change)){
03641             raise++;
03642         }else{
03643             lower++;
03644         }
03645     }else{
03646         from_zero++;
03647     }
03648 }else{
03649     to_zero++;
03650 }
03651 #endif
03652                 for(; last_non_zero>=start_i; last_non_zero--){
03653                     if(block[perm_scantable[last_non_zero]])
03654                         break;
03655                 }
03656             }
03657 #ifdef REFINE_STATS
03658 count++;
03659 if(256*256*256*64 % count == 0){
03660     printf("after_last:%d to_zero:%d from_zero:%d raise:%d lower:%d sign:%d xyp:%d/%d/%d\n", after_last, to_zero, from_zero, raise, lower, messed_sign, s->mb_x, s->mb_y, s->picture_number);
03661 }
03662 #endif
03663             run=0;
03664             rle_index=0;
03665             for(i=start_i; i<=last_non_zero; i++){
03666                 int j= perm_scantable[i];
03667                 const int level= block[j];
03668 
03669                  if(level){
03670                      run_tab[rle_index++]=run;
03671                      run=0;
03672                  }else{
03673                      run++;
03674                  }
03675             }
03676 
03677             s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);
03678         }else{
03679             break;
03680         }
03681     }
03682 #ifdef REFINE_STATS
03683 if(last_non_zero>0){
03684 STOP_TIMER("iterative search")
03685 }
03686 }
03687 #endif
03688 
03689     return last_non_zero;
03690 }
03691 
03692 int dct_quantize_c(MpegEncContext *s,
03693                         DCTELEM *block, int n,
03694                         int qscale, int *overflow)
03695 {
03696     int i, j, level, last_non_zero, q, start_i;
03697     const int *qmat;
03698     const uint8_t *scantable= s->intra_scantable.scantable;
03699     int bias;
03700     int max=0;
03701     unsigned int threshold1, threshold2;
03702 
03703     s->dsp.fdct (block);
03704 
03705     if(s->dct_error_sum)
03706         s->denoise_dct(s, block);
03707 
03708     if (s->mb_intra) {
03709         if (!s->h263_aic) {
03710             if (n < 4)
03711                 q = s->y_dc_scale;
03712             else
03713                 q = s->c_dc_scale;
03714             q = q << 3;
03715         } else
03716             /* For AIC we skip quant/dequant of INTRADC */
03717             q = 1 << 3;
03718 
03719         /* note: block[0] is assumed to be positive */
03720         block[0] = (block[0] + (q >> 1)) / q;
03721         start_i = 1;
03722         last_non_zero = 0;
03723         qmat = s->q_intra_matrix[qscale];
03724         bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
03725     } else {
03726         start_i = 0;
03727         last_non_zero = -1;
03728         qmat = s->q_inter_matrix[qscale];
03729         bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
03730     }
03731     threshold1= (1<<QMAT_SHIFT) - bias - 1;
03732     threshold2= (threshold1<<1);
03733     for(i=63;i>=start_i;i--) {
03734         j = scantable[i];
03735         level = block[j] * qmat[j];
03736 
03737         if(((unsigned)(level+threshold1))>threshold2){
03738             last_non_zero = i;
03739             break;
03740         }else{
03741             block[j]=0;
03742         }
03743     }
03744     for(i=start_i; i<=last_non_zero; i++) {
03745         j = scantable[i];
03746         level = block[j] * qmat[j];
03747 
03748 //        if(   bias+level >= (1<<QMAT_SHIFT)
03749 //           || bias-level >= (1<<QMAT_SHIFT)){
03750         if(((unsigned)(level+threshold1))>threshold2){
03751             if(level>0){
03752                 level= (bias + level)>>QMAT_SHIFT;
03753                 block[j]= level;
03754             }else{
03755                 level= (bias - level)>>QMAT_SHIFT;
03756                 block[j]= -level;
03757             }
03758             max |=level;
03759         }else{
03760             block[j]=0;
03761         }
03762     }
03763     *overflow= s->max_qcoeff < max; //overflow might have happened
03764 
03765     /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
03766     if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
03767         ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
03768 
03769     return last_non_zero;
03770 }
03771 
03772 AVCodec ff_h263_encoder = {
03773     "h263",
03774     AVMEDIA_TYPE_VIDEO,
03775     CODEC_ID_H263,
03776     sizeof(MpegEncContext),
03777     MPV_encode_init,
03778     MPV_encode_picture,
03779     MPV_encode_end,
03780     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
03781     .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
03782 };
03783 
03784 AVCodec ff_h263p_encoder = {
03785     "h263p",
03786     AVMEDIA_TYPE_VIDEO,
03787     CODEC_ID_H263P,
03788     sizeof(MpegEncContext),
03789     MPV_encode_init,
03790     MPV_encode_picture,
03791     MPV_encode_end,
03792     .capabilities = CODEC_CAP_SLICE_THREADS,
03793     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
03794     .long_name= NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
03795 };
03796 
03797 AVCodec ff_msmpeg4v2_encoder = {
03798     "msmpeg4v2",
03799     AVMEDIA_TYPE_VIDEO,
03800     CODEC_ID_MSMPEG4V2,
03801     sizeof(MpegEncContext),
03802     MPV_encode_init,
03803     MPV_encode_picture,
03804     MPV_encode_end,
03805     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
03806     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
03807 };
03808 
03809 AVCodec ff_msmpeg4v3_encoder = {
03810     "msmpeg4",
03811     AVMEDIA_TYPE_VIDEO,
03812     CODEC_ID_MSMPEG4V3,
03813     sizeof(MpegEncContext),
03814     MPV_encode_init,
03815     MPV_encode_picture,
03816     MPV_encode_end,
03817     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
03818     .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
03819 };
03820 
03821 AVCodec ff_wmv1_encoder = {
03822     "wmv1",
03823     AVMEDIA_TYPE_VIDEO,
03824     CODEC_ID_WMV1,
03825     sizeof(MpegEncContext),
03826     MPV_encode_init,
03827     MPV_encode_picture,
03828     MPV_encode_end,
03829     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
03830     .long_name= NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
03831 };