• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

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

Generated on Wed Apr 11 2012 07:31:34 for FFmpeg by  doxygen 1.7.1