Cosmetic changes to h264_idct_10bit.asm.
[libav.git] / libavcodec / mpegvideo_enc.c
CommitLineData
3ada94ba
BF
1/*
2 * The simplest mpeg encoder (well, it was the simplest!)
406792e7 3 * Copyright (c) 2000,2001 Fabrice Bellard
3ada94ba
BF
4 * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5 *
7b94177e
DB
6 * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
7 *
2912e87a 8 * This file is part of Libav.
3ada94ba 9 *
2912e87a 10 * Libav is free software; you can redistribute it and/or
3ada94ba
BF
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
2912e87a 15 * Libav is distributed in the hope that it will be useful,
3ada94ba
BF
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
2912e87a 21 * License along with Libav; if not, write to the Free Software
3ada94ba 22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
3ada94ba
BF
23 */
24
25/**
ba87f080 26 * @file
3ada94ba
BF
27 * The simplest mpeg encoder (well, it was the simplest!).
28 */
29
94ca624f 30#include "libavutil/intmath.h"
3ada94ba
BF
31#include "avcodec.h"
32#include "dsputil.h"
33#include "mpegvideo.h"
34#include "mpegvideo_common.h"
c46eeae2 35#include "h263.h"
3ada94ba
BF
36#include "mjpegenc.h"
37#include "msmpeg4.h"
38#include "faandct.h"
8b22017f 39#include "aandcttab.h"
eb523769 40#include "flv.h"
ca334dd1 41#include "mpeg4video.h"
7ffd8332 42#include "internal.h"
3ada94ba
BF
43#include <limits.h>
44
45//#undef NDEBUG
46//#include <assert.h>
47
48static int encode_picture(MpegEncContext *s, int picture_number);
49static int dct_quantize_refine(MpegEncContext *s, DCTELEM *block, int16_t *weight, DCTELEM *orig, int n, int qscale);
50static int sse_mb(MpegEncContext *s);
1d4da6a4
DEP
51static void denoise_dct_c(MpegEncContext *s, DCTELEM *block);
52static int dct_quantize_trellis_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
3ada94ba
BF
53
54/* enable all paranoid tests for rounding, overflows, etc... */
55//#define PARANOID
56
57//#define DEBUG
58
3ada94ba
BF
59static uint8_t default_mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
60static uint8_t default_fcode_tab[MAX_MV*2+1];
61
69cea75f 62void ff_convert_matrix(DSPContext *dsp, int (*qmat)[64], uint16_t (*qmat16)[2][64],
3ada94ba
BF
63 const uint16_t *quant_matrix, int bias, int qmin, int qmax, int intra)
64{
65 int qscale;
66 int shift=0;
67
68 for(qscale=qmin; qscale<=qmax; qscale++){
69 int i;
70 if (dsp->fdct == ff_jpeg_fdct_islow
71#ifdef FAAN_POSTSCALE
72 || dsp->fdct == ff_faandct
73#endif
74 ) {
75 for(i=0;i<64;i++) {
76 const int j= dsp->idct_permutation[i];
77 /* 16 <= qscale * quant_matrix[i] <= 7905 */
5bdf124c
DB
78 /* 19952 <= ff_aanscales[i] * qscale * quant_matrix[i] <= 249205026 */
79 /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1 << 36) / 249205026 */
80 /* 3444240 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
3ada94ba
BF
81
82 qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) /
83 (qscale * quant_matrix[j]));
84 }
85 } else if (dsp->fdct == fdct_ifast
86#ifndef FAAN_POSTSCALE
87 || dsp->fdct == ff_faandct
88#endif
89 ) {
90 for(i=0;i<64;i++) {
91 const int j= dsp->idct_permutation[i];
92 /* 16 <= qscale * quant_matrix[i] <= 7905 */
5bdf124c
DB
93 /* 19952 <= ff_aanscales[i] * qscale * quant_matrix[i] <= 249205026 */
94 /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
95 /* 3444240 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
3ada94ba
BF
96
97 qmat[qscale][i] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) /
5bdf124c 98 (ff_aanscales[i] * qscale * quant_matrix[j]));
3ada94ba
BF
99 }
100 } else {
101 for(i=0;i<64;i++) {
102 const int j= dsp->idct_permutation[i];
103 /* We can safely suppose that 16 <= quant_matrix[i] <= 255
104 So 16 <= qscale * quant_matrix[i] <= 7905
105 so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
106 so 32768 >= (1<<19) / (qscale * quant_matrix[i]) >= 67
107 */
108 qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) / (qscale * quant_matrix[j]));
109// qmat [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
110 qmat16[qscale][0][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[j]);
111
112 if(qmat16[qscale][0][i]==0 || qmat16[qscale][0][i]==128*256) qmat16[qscale][0][i]=128*256-1;
113 qmat16[qscale][1][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][0][i]);
114 }
115 }
116
117 for(i=intra; i<64; i++){
118 int64_t max= 8191;
119 if (dsp->fdct == fdct_ifast
120#ifndef FAAN_POSTSCALE
121 || dsp->fdct == ff_faandct
122#endif
123 ) {
5bdf124c 124 max = (8191LL*ff_aanscales[i]) >> 14;
3ada94ba
BF
125 }
126 while(((max * qmat[qscale][i]) >> shift) > INT_MAX){
127 shift++;
128 }
129 }
130 }
131 if(shift){
132 av_log(NULL, AV_LOG_INFO, "Warning, QMAT_SHIFT is larger than %d, overflows possible\n", QMAT_SHIFT - shift);
133 }
134}
135
136static inline void update_qscale(MpegEncContext *s){
137 s->qscale= (s->lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
138 s->qscale= av_clip(s->qscale, s->avctx->qmin, s->avctx->qmax);
139
140 s->lambda2= (s->lambda*s->lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
141}
142
143void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix){
144 int i;
145
146 if(matrix){
147 put_bits(pb, 1, 1);
148 for(i=0;i<64;i++) {
149 put_bits(pb, 8, matrix[ ff_zigzag_direct[i] ]);
150 }
151 }else
152 put_bits(pb, 1, 0);
153}
154
9015b095
MN
155/**
156 * init s->current_picture.qscale_table from s->lambda_table
157 */
158void ff_init_qscale_tab(MpegEncContext *s){
159 int8_t * const qscale_table= s->current_picture.qscale_table;
160 int i;
161
162 for(i=0; i<s->mb_num; i++){
163 unsigned int lam= s->lambda_table[ s->mb_index2xy[i] ];
164 int qp= (lam*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
165 qscale_table[ s->mb_index2xy[i] ]= av_clip(qp, s->avctx->qmin, s->avctx->qmax);
166 }
167}
168
3ada94ba
BF
169static void copy_picture_attributes(MpegEncContext *s, AVFrame *dst, AVFrame *src){
170 int i;
171
172 dst->pict_type = src->pict_type;
173 dst->quality = src->quality;
174 dst->coded_picture_number = src->coded_picture_number;
175 dst->display_picture_number = src->display_picture_number;
176// dst->reference = src->reference;
177 dst->pts = src->pts;
178 dst->interlaced_frame = src->interlaced_frame;
179 dst->top_field_first = src->top_field_first;
180
181 if(s->avctx->me_threshold){
182 if(!src->motion_val[0])
183 av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_val not set!\n");
184 if(!src->mb_type)
185 av_log(s->avctx, AV_LOG_ERROR, "AVFrame.mb_type not set!\n");
186 if(!src->ref_index[0])
187 av_log(s->avctx, AV_LOG_ERROR, "AVFrame.ref_index not set!\n");
188 if(src->motion_subsample_log2 != dst->motion_subsample_log2)
189 av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_subsample_log2 doesn't match! (%d!=%d)\n",
190 src->motion_subsample_log2, dst->motion_subsample_log2);
191
192 memcpy(dst->mb_type, src->mb_type, s->mb_stride * s->mb_height * sizeof(dst->mb_type[0]));
193
194 for(i=0; i<2; i++){
195 int stride= ((16*s->mb_width )>>src->motion_subsample_log2) + 1;
196 int height= ((16*s->mb_height)>>src->motion_subsample_log2);
197
198 if(src->motion_val[i] && src->motion_val[i] != dst->motion_val[i]){
199 memcpy(dst->motion_val[i], src->motion_val[i], 2*stride*height*sizeof(int16_t));
200 }
201 if(src->ref_index[i] && src->ref_index[i] != dst->ref_index[i]){
fc4a2d1e 202 memcpy(dst->ref_index[i], src->ref_index[i], s->mb_stride*4*s->mb_height*sizeof(int8_t));
3ada94ba
BF
203 }
204 }
205 }
206}
207
208static void update_duplicate_context_after_me(MpegEncContext *dst, MpegEncContext *src){
209#define COPY(a) dst->a= src->a
210 COPY(pict_type);
211 COPY(current_picture);
212 COPY(f_code);
213 COPY(b_code);
214 COPY(qscale);
215 COPY(lambda);
216 COPY(lambda2);
217 COPY(picture_in_gop_number);
218 COPY(gop_picture_number);
219 COPY(frame_pred_frame_dct); //FIXME don't set in encode_header
220 COPY(progressive_frame); //FIXME don't set in encode_header
221 COPY(partitioned_frame); //FIXME don't set in encode_header
222#undef COPY
223}
224
225/**
226 * sets the given MpegEncContext to defaults for encoding.
227 * the changed fields will not depend upon the prior state of the MpegEncContext.
228 */
229static void MPV_encode_defaults(MpegEncContext *s){
230 int i;
231 MPV_common_defaults(s);
232
233 for(i=-16; i<16; i++){
234 default_fcode_tab[i + MAX_MV]= 1;
235 }
236 s->me.mv_penalty= default_mv_penalty;
237 s->fcode_tab= default_fcode_tab;
238}
239
240/* init video encoder */
98a6fff9 241av_cold int MPV_encode_init(AVCodecContext *avctx)
3ada94ba
BF
242{
243 MpegEncContext *s = avctx->priv_data;
244 int i;
245 int chroma_h_shift, chroma_v_shift;
246
247 MPV_encode_defaults(s);
248
249 switch (avctx->codec_id) {
250 case CODEC_ID_MPEG2VIDEO:
251 if(avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P){
252 av_log(avctx, AV_LOG_ERROR, "only YUV420 and YUV422 are supported\n");
253 return -1;
254 }
255 break;
256 case CODEC_ID_LJPEG:
db613296 257 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 &&
e27bf2c7
MN
258 ((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)){
259 av_log(avctx, AV_LOG_ERROR, "colorspace not supported in LJPEG\n");
260 return -1;
261 }
262 break;
3ada94ba 263 case CODEC_ID_MJPEG:
dc8465a9 264 if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P &&
2d525ef4 265 ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P) || avctx->strict_std_compliance>FF_COMPLIANCE_UNOFFICIAL)){
3ada94ba
BF
266 av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");
267 return -1;
268 }
269 break;
270 default:
271 if(avctx->pix_fmt != PIX_FMT_YUV420P){
272 av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");
273 return -1;
274 }
275 }
276
277 switch (avctx->pix_fmt) {
278 case PIX_FMT_YUVJ422P:
279 case PIX_FMT_YUV422P:
280 s->chroma_format = CHROMA_422;
281 break;
282 case PIX_FMT_YUVJ420P:
283 case PIX_FMT_YUV420P:
284 default:
285 s->chroma_format = CHROMA_420;
286 break;
287 }
288
289 s->bit_rate = avctx->bit_rate;
290 s->width = avctx->width;
291 s->height = avctx->height;
292 if(avctx->gop_size > 600 && avctx->strict_std_compliance>FF_COMPLIANCE_EXPERIMENTAL){
293 av_log(avctx, AV_LOG_ERROR, "Warning keyframe interval too large! reducing it ...\n");
294 avctx->gop_size=600;
295 }
296 s->gop_size = avctx->gop_size;
297 s->avctx = avctx;
298 s->flags= avctx->flags;
299 s->flags2= avctx->flags2;
300 s->max_b_frames= avctx->max_b_frames;
301 s->codec_id= avctx->codec->id;
302 s->luma_elim_threshold = avctx->luma_elim_threshold;
303 s->chroma_elim_threshold= avctx->chroma_elim_threshold;
304 s->strict_std_compliance= avctx->strict_std_compliance;
305 s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
306 s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;
307 s->mpeg_quant= avctx->mpeg_quant;
308 s->rtp_mode= !!avctx->rtp_payload_size;
309 s->intra_dc_precision= avctx->intra_dc_precision;
310 s->user_specified_pts = AV_NOPTS_VALUE;
311
312 if (s->gop_size <= 1) {
313 s->intra_only = 1;
314 s->gop_size = 12;
315 } else {
316 s->intra_only = 0;
317 }
318
319 s->me_method = avctx->me_method;
320
321 /* Fixed QSCALE */
322 s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);
323
324 s->adaptive_quant= ( s->avctx->lumi_masking
325 || s->avctx->dark_masking
326 || s->avctx->temporal_cplx_masking
327 || s->avctx->spatial_cplx_masking
328 || s->avctx->p_masking
329 || s->avctx->border_masking
330 || (s->flags&CODEC_FLAG_QP_RD))
331 && !s->fixed_qscale;
332
333 s->obmc= !!(s->flags & CODEC_FLAG_OBMC);
334 s->loop_filter= !!(s->flags & CODEC_FLAG_LOOP_FILTER);
335 s->alternate_scan= !!(s->flags & CODEC_FLAG_ALT_SCAN);
336 s->intra_vlc_format= !!(s->flags2 & CODEC_FLAG2_INTRA_VLC);
337 s->q_scale_type= !!(s->flags2 & CODEC_FLAG2_NON_LINEAR_QUANT);
338
339 if(avctx->rc_max_rate && !avctx->rc_buffer_size){
340 av_log(avctx, AV_LOG_ERROR, "a vbv buffer size is needed, for encoding with a maximum bitrate\n");
341 return -1;
342 }
343
344 if(avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate){
345 av_log(avctx, AV_LOG_INFO, "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");
346 }
347
348 if(avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate){
349 av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");
350 return -1;
351 }
352
353 if(avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate){
354 av_log(avctx, AV_LOG_INFO, "bitrate above max bitrate\n");
355 return -1;
356 }
357
3dd2a1c5
MN
358 if(avctx->rc_max_rate && avctx->rc_max_rate == avctx->bit_rate && avctx->rc_max_rate != avctx->rc_min_rate){
359 av_log(avctx, AV_LOG_INFO, "impossible bitrate constraints, this will fail\n");
360 }
361
b33451ee 362 if(avctx->rc_buffer_size && avctx->bit_rate*(int64_t)avctx->time_base.num > avctx->rc_buffer_size * (int64_t)avctx->time_base.den){
3ada94ba
BF
363 av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");
364 return -1;
365 }
366
8d39fbd6 367 if(!s->fixed_qscale && avctx->bit_rate*av_q2d(avctx->time_base) > avctx->bit_rate_tolerance){
3ada94ba
BF
368 av_log(avctx, AV_LOG_ERROR, "bitrate tolerance too small for bitrate\n");
369 return -1;
370 }
371
372 if( s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate
373 && (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO)
374 && 90000LL * (avctx->rc_buffer_size-1) > s->avctx->rc_max_rate*0xFFFFLL){
375
376 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");
377 }
378
379 if((s->flags & CODEC_FLAG_4MV) && s->codec_id != CODEC_ID_MPEG4
380 && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P && s->codec_id != CODEC_ID_FLV1){
381 av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
382 return -1;
383 }
384
385 if(s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE){
386 av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with simple mb decision\n");
387 return -1;
388 }
389
390 if(s->obmc && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P){
391 av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with H263(+)\n");
392 return -1;
393 }
394
395 if(s->quarter_sample && s->codec_id != CODEC_ID_MPEG4){
396 av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
397 return -1;
398 }
399
400 if(s->data_partitioning && s->codec_id != CODEC_ID_MPEG4){
401 av_log(avctx, AV_LOG_ERROR, "data partitioning not supported by codec\n");
402 return -1;
403 }
404
405 if(s->max_b_frames && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO){
406 av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
407 return -1;
408 }
409
954a0b48
MN
410 if ((s->codec_id == CODEC_ID_MPEG4 || s->codec_id == CODEC_ID_H263 ||
411 s->codec_id == CODEC_ID_H263P) &&
412 (avctx->sample_aspect_ratio.num > 255 || avctx->sample_aspect_ratio.den > 255)) {
413 av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i, limit is 255/255\n",
414 avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
415 return -1;
416 }
417
3ada94ba
BF
418 if((s->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN))
419 && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG2VIDEO){
420 av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");
421 return -1;
422 }
423
424 if(s->mpeg_quant && s->codec_id != CODEC_ID_MPEG4){ //FIXME mpeg2 uses that too
425 av_log(avctx, AV_LOG_ERROR, "mpeg2 style quantization not supported by codec\n");
426 return -1;
427 }
428
febea2f2 429 if((s->flags & CODEC_FLAG_CBP_RD) && !avctx->trellis){
3ada94ba
BF
430 av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
431 return -1;
432 }
433
434 if((s->flags & CODEC_FLAG_QP_RD) && s->avctx->mb_decision != FF_MB_DECISION_RD){
435 av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");
436 return -1;
437 }
438
439 if(s->avctx->scenechange_threshold < 1000000000 && (s->flags & CODEC_FLAG_CLOSED_GOP)){
7ce68923 440 av_log(avctx, AV_LOG_ERROR, "closed gop with scene change detection are not supported yet, set threshold to 1000000000\n");
3ada94ba
BF
441 return -1;
442 }
443
444 if((s->flags2 & CODEC_FLAG2_INTRA_VLC) && s->codec_id != CODEC_ID_MPEG2VIDEO){
445 av_log(avctx, AV_LOG_ERROR, "intra vlc table not supported by codec\n");
446 return -1;
447 }
448
449 if(s->flags & CODEC_FLAG_LOW_DELAY){
9cc440bf
MN
450 if (s->codec_id != CODEC_ID_MPEG2VIDEO){
451 av_log(avctx, AV_LOG_ERROR, "low delay forcing is only available for mpeg2\n");
3ada94ba
BF
452 return -1;
453 }
454 if (s->max_b_frames != 0){
455 av_log(avctx, AV_LOG_ERROR, "b frames cannot be used with low delay\n");
456 return -1;
457 }
458 }
459
460 if(s->q_scale_type == 1){
461 if(s->codec_id != CODEC_ID_MPEG2VIDEO){
462 av_log(avctx, AV_LOG_ERROR, "non linear quant is only available for mpeg2\n");
463 return -1;
464 }
465 if(avctx->qmax > 12){
466 av_log(avctx, AV_LOG_ERROR, "non linear quant only supports qmax <= 12 currently\n");
467 return -1;
468 }
469 }
470
471 if(s->avctx->thread_count > 1 && s->codec_id != CODEC_ID_MPEG4
472 && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO
473 && (s->codec_id != CODEC_ID_H263P || !(s->flags & CODEC_FLAG_H263P_SLICE_STRUCT))){
474 av_log(avctx, AV_LOG_ERROR, "multi threaded encoding not supported by codec\n");
475 return -1;
476 }
477
b52b0913
MN
478 if(s->avctx->thread_count < 1){
479 av_log(avctx, AV_LOG_ERROR, "automatic thread number detection not supported by codec, patch welcome\n");
480 return -1;
481 }
482
3ada94ba
BF
483 if(s->avctx->thread_count > 1)
484 s->rtp_mode= 1;
485
486 if(!avctx->time_base.den || !avctx->time_base.num){
487 av_log(avctx, AV_LOG_ERROR, "framerate not set\n");
488 return -1;
489 }
490
491 i= (INT_MAX/2+128)>>8;
492 if(avctx->me_threshold >= i){
493 av_log(avctx, AV_LOG_ERROR, "me_threshold too large, max is %d\n", i - 1);
494 return -1;
495 }
496 if(avctx->mb_threshold >= i){
497 av_log(avctx, AV_LOG_ERROR, "mb_threshold too large, max is %d\n", i - 1);
498 return -1;
499 }
500
501 if(avctx->b_frame_strategy && (avctx->flags&CODEC_FLAG_PASS2)){
502 av_log(avctx, AV_LOG_INFO, "notice: b_frame_strategy only affects the first pass\n");
503 avctx->b_frame_strategy = 0;
504 }
505
9ce6c138 506 i= av_gcd(avctx->time_base.den, avctx->time_base.num);
3ada94ba
BF
507 if(i > 1){
508 av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");
509 avctx->time_base.den /= i;
510 avctx->time_base.num /= i;
511// return -1;
512 }
513
bd57cae8 514 if(s->mpeg_quant || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO || s->codec_id==CODEC_ID_MJPEG){
3ada94ba
BF
515 s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
516 s->inter_quant_bias= 0;
517 }else{
518 s->intra_quant_bias=0;
519 s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
520 }
521
522 if(avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
523 s->intra_quant_bias= avctx->intra_quant_bias;
524 if(avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
525 s->inter_quant_bias= avctx->inter_quant_bias;
526
527 avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);
528
529 if(avctx->codec_id == CODEC_ID_MPEG4 && s->avctx->time_base.den > (1<<16)-1){
2d777bb7
SS
530 av_log(avctx, AV_LOG_ERROR, "timebase %d/%d not supported by MPEG 4 standard, "
531 "the maximum admitted value for the timebase denominator is %d\n",
532 s->avctx->time_base.num, s->avctx->time_base.den, (1<<16)-1);
3ada94ba
BF
533 return -1;
534 }
535 s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
536
537 switch(avctx->codec->id) {
538 case CODEC_ID_MPEG1VIDEO:
539 s->out_format = FMT_MPEG1;
540 s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
541 avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
542 break;
543 case CODEC_ID_MPEG2VIDEO:
544 s->out_format = FMT_MPEG1;
545 s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
546 avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
547 s->rtp_mode= 1;
548 break;
549 case CODEC_ID_LJPEG:
550 case CODEC_ID_MJPEG:
551 s->out_format = FMT_MJPEG;
552 s->intra_only = 1; /* force intra only for jpeg */
a1a63143 553 if(avctx->codec->id == CODEC_ID_LJPEG && avctx->pix_fmt == PIX_FMT_BGRA){
e0b176ad
MN
554 s->mjpeg_vsample[0] = s->mjpeg_hsample[0] =
555 s->mjpeg_vsample[1] = s->mjpeg_hsample[1] =
556 s->mjpeg_vsample[2] = s->mjpeg_hsample[2] = 1;
a1a63143
MN
557 }else{
558 s->mjpeg_vsample[0] = 2;
559 s->mjpeg_vsample[1] = 2>>chroma_v_shift;
560 s->mjpeg_vsample[2] = 2>>chroma_v_shift;
561 s->mjpeg_hsample[0] = 2;
562 s->mjpeg_hsample[1] = 2>>chroma_h_shift;
563 s->mjpeg_hsample[2] = 2>>chroma_h_shift;
e0b176ad 564 }
49fb20cb 565 if (!(CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER)
3ada94ba
BF
566 || ff_mjpeg_encode_init(s) < 0)
567 return -1;
568 avctx->delay=0;
569 s->low_delay=1;
570 break;
571 case CODEC_ID_H261:
49fb20cb 572 if (!CONFIG_H261_ENCODER) return -1;
3ada94ba
BF
573 if (ff_h261_get_picture_format(s->width, s->height) < 0) {
574 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);
575 return -1;
576 }
577 s->out_format = FMT_H261;
578 avctx->delay=0;
579 s->low_delay=1;
580 break;
581 case CODEC_ID_H263:
49fb20cb 582 if (!CONFIG_H263_ENCODER) return -1;
35e33b9a 583 if (ff_match_2uint16(h263_format, FF_ARRAY_ELEMS(h263_format), s->width, s->height) == 8) {
3ada94ba
BF
584 av_log(avctx, AV_LOG_INFO, "The specified picture size of %dx%d is not valid for the H.263 codec.\nValid sizes are 128x96, 176x144, 352x288, 704x576, and 1408x1152. Try H.263+.\n", s->width, s->height);
585 return -1;
586 }
587 s->out_format = FMT_H263;
588 s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
589 avctx->delay=0;
590 s->low_delay=1;
591 break;
592 case CODEC_ID_H263P:
593 s->out_format = FMT_H263;
594 s->h263_plus = 1;
595 /* Fx */
596 s->umvplus = (avctx->flags & CODEC_FLAG_H263P_UMV) ? 1:0;
597 s->h263_aic= (avctx->flags & CODEC_FLAG_AC_PRED) ? 1:0;
598 s->modified_quant= s->h263_aic;
599 s->alt_inter_vlc= (avctx->flags & CODEC_FLAG_H263P_AIV) ? 1:0;
600 s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
601 s->loop_filter= (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1:0;
602 s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;
603 s->h263_slice_structured= (s->flags & CODEC_FLAG_H263P_SLICE_STRUCT) ? 1:0;
604
605 /* /Fx */
606 /* These are just to be sure */
607 avctx->delay=0;
608 s->low_delay=1;
609 break;
610 case CODEC_ID_FLV1:
611 s->out_format = FMT_H263;
612 s->h263_flv = 2; /* format = 1; 11-bit codes */
613 s->unrestricted_mv = 1;
614 s->rtp_mode=0; /* don't allow GOB */
615 avctx->delay=0;
616 s->low_delay=1;
617 break;
618 case CODEC_ID_RV10:
619 s->out_format = FMT_H263;
620 avctx->delay=0;
621 s->low_delay=1;
622 break;
623 case CODEC_ID_RV20:
624 s->out_format = FMT_H263;
625 avctx->delay=0;
626 s->low_delay=1;
627 s->modified_quant=1;
628 s->h263_aic=1;
629 s->h263_plus=1;
630 s->loop_filter=1;
53eb458a 631 s->unrestricted_mv= 0;
3ada94ba
BF
632 break;
633 case CODEC_ID_MPEG4:
634 s->out_format = FMT_H263;
635 s->h263_pred = 1;
636 s->unrestricted_mv = 1;
637 s->low_delay= s->max_b_frames ? 0 : 1;
638 avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
639 break;
3ada94ba
BF
640 case CODEC_ID_MSMPEG4V2:
641 s->out_format = FMT_H263;
3ada94ba
BF
642 s->h263_pred = 1;
643 s->unrestricted_mv = 1;
644 s->msmpeg4_version= 2;
645 avctx->delay=0;
646 s->low_delay=1;
647 break;
648 case CODEC_ID_MSMPEG4V3:
649 s->out_format = FMT_H263;
3ada94ba
BF
650 s->h263_pred = 1;
651 s->unrestricted_mv = 1;
652 s->msmpeg4_version= 3;
653 s->flipflop_rounding=1;
654 avctx->delay=0;
655 s->low_delay=1;
656 break;
657 case CODEC_ID_WMV1:
658 s->out_format = FMT_H263;
3ada94ba
BF
659 s->h263_pred = 1;
660 s->unrestricted_mv = 1;
661 s->msmpeg4_version= 4;
662 s->flipflop_rounding=1;
663 avctx->delay=0;
664 s->low_delay=1;
665 break;
666 case CODEC_ID_WMV2:
667 s->out_format = FMT_H263;
3ada94ba
BF
668 s->h263_pred = 1;
669 s->unrestricted_mv = 1;
670 s->msmpeg4_version= 5;
671 s->flipflop_rounding=1;
672 avctx->delay=0;
673 s->low_delay=1;
674 break;
675 default:
676 return -1;
677 }
678
679 avctx->has_b_frames= !s->low_delay;
680
681 s->encoding = 1;
682
01bc48f4
BC
683 s->progressive_frame=
684 s->progressive_sequence= !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN));
685
3ada94ba
BF
686 /* init */
687 if (MPV_common_init(s) < 0)
688 return -1;
689
53727262
AJ
690 if(!s->dct_quantize)
691 s->dct_quantize = dct_quantize_c;
692 if(!s->denoise_dct)
693 s->denoise_dct = denoise_dct_c;
694 s->fast_dct_quantize = s->dct_quantize;
febea2f2 695 if(avctx->trellis)
53727262
AJ
696 s->dct_quantize = dct_quantize_trellis_c;
697
49fb20cb 698 if((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)
3ada94ba 699 s->chroma_qscale_table= ff_h263_chroma_qscale_table;
01bc48f4 700
3ada94ba
BF
701 s->quant_precision=5;
702
703 ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);
704 ff_set_cmp(&s->dsp, s->dsp.frame_skip_cmp, s->avctx->frame_skip_cmp);
705
49fb20cb 706 if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)
3ada94ba 707 ff_h261_encode_init(s);
f34121f3 708 if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)
3ada94ba 709 h263_encode_init(s);
49fb20cb 710 if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
3ada94ba 711 ff_msmpeg4_encode_init(s);
49fb20cb 712 if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
a6bc5731 713 && s->out_format == FMT_MPEG1)
3ada94ba
BF
714 ff_mpeg1_encode_init(s);
715
716 /* init q matrix */
717 for(i=0;i<64;i++) {
718 int j= s->dsp.idct_permutation[i];
49fb20cb 719 if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
3ada94ba
BF
720 s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
721 s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
722 }else if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
723 s->intra_matrix[j] =
724 s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
725 }else
726 { /* mpeg1/2 */
727 s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
728 s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
729 }
730 if(s->avctx->intra_matrix)
731 s->intra_matrix[j] = s->avctx->intra_matrix[i];
732 if(s->avctx->inter_matrix)
733 s->inter_matrix[j] = s->avctx->inter_matrix[i];
734 }
735
736 /* precompute matrix */
737 /* for mjpeg, we do include qscale in the matrix */
738 if (s->out_format != FMT_MJPEG) {
69cea75f 739 ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
3ada94ba 740 s->intra_matrix, s->intra_quant_bias, avctx->qmin, 31, 1);
69cea75f 741 ff_convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,
3ada94ba
BF
742 s->inter_matrix, s->inter_quant_bias, avctx->qmin, 31, 0);
743 }
744
745 if(ff_rate_control_init(s) < 0)
746 return -1;
747
748 return 0;
749}
750
98a6fff9 751av_cold int MPV_encode_end(AVCodecContext *avctx)
3ada94ba
BF
752{
753 MpegEncContext *s = avctx->priv_data;
754
755 ff_rate_control_uninit(s);
756
757 MPV_common_end(s);
49fb20cb 758 if ((CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER) && s->out_format == FMT_MJPEG)
3ada94ba
BF
759 ff_mjpeg_encode_close(s);
760
761 av_freep(&avctx->extradata);
762
763 return 0;
764}
765
766static int get_sae(uint8_t *src, int ref, int stride){
767 int x,y;
768 int acc=0;
769
770 for(y=0; y<16; y++){
771 for(x=0; x<16; x++){
772 acc+= FFABS(src[x+y*stride] - ref);
773 }
774 }
775
776 return acc;
777}
778
779static int get_intra_count(MpegEncContext *s, uint8_t *src, uint8_t *ref, int stride){
780 int x, y, w, h;
781 int acc=0;
782
783 w= s->width &~15;
784 h= s->height&~15;
785
786 for(y=0; y<h; y+=16){
787 for(x=0; x<w; x+=16){
788 int offset= x + y*stride;
789 int sad = s->dsp.sad[0](NULL, src + offset, ref + offset, stride, 16);
790 int mean= (s->dsp.pix_sum(src + offset, stride) + 128)>>8;
791 int sae = get_sae(src + offset, mean, stride);
792
793 acc+= sae + 500 < sad;
794 }
795 }
796 return acc;
797}
798
799
800static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
801 AVFrame *pic=NULL;
802 int64_t pts;
803 int i;
804 const int encoding_delay= s->max_b_frames;
805 int direct=1;
806
807 if(pic_arg){
808 pts= pic_arg->pts;
809 pic_arg->display_picture_number= s->input_picture_number++;
810
811 if(pts != AV_NOPTS_VALUE){
812 if(s->user_specified_pts != AV_NOPTS_VALUE){
813 int64_t time= pts;
814 int64_t last= s->user_specified_pts;
815
816 if(time <= last){
817 av_log(s->avctx, AV_LOG_ERROR, "Error, Invalid timestamp=%"PRId64", last=%"PRId64"\n", pts, s->user_specified_pts);
818 return -1;
819 }
820 }
821 s->user_specified_pts= pts;
822 }else{
823 if(s->user_specified_pts != AV_NOPTS_VALUE){
824 s->user_specified_pts=
825 pts= s->user_specified_pts + 1;
826 av_log(s->avctx, AV_LOG_INFO, "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n", pts);
827 }else{
828 pts= pic_arg->display_picture_number;
829 }
830 }
831 }
832
833 if(pic_arg){
834 if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
835 if(pic_arg->linesize[0] != s->linesize) direct=0;
836 if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
837 if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
838
839// av_log(AV_LOG_DEBUG, "%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);
840
841 if(direct){
842 i= ff_find_unused_picture(s, 1);
843
844 pic= (AVFrame*)&s->picture[i];
845 pic->reference= 3;
846
847 for(i=0; i<4; i++){
848 pic->data[i]= pic_arg->data[i];
849 pic->linesize[i]= pic_arg->linesize[i];
850 }
be548816
PP
851 if(ff_alloc_picture(s, (Picture*)pic, 1) < 0){
852 return -1;
853 }
3ada94ba
BF
854 }else{
855 i= ff_find_unused_picture(s, 0);
856
857 pic= (AVFrame*)&s->picture[i];
858 pic->reference= 3;
859
be548816
PP
860 if(ff_alloc_picture(s, (Picture*)pic, 0) < 0){
861 return -1;
862 }
3ada94ba
BF
863
864 if( pic->data[0] + INPLACE_OFFSET == pic_arg->data[0]
865 && pic->data[1] + INPLACE_OFFSET == pic_arg->data[1]
866 && pic->data[2] + INPLACE_OFFSET == pic_arg->data[2]){
867 // empty
868 }else{
869 int h_chroma_shift, v_chroma_shift;
870 avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
871
872 for(i=0; i<3; i++){
873 int src_stride= pic_arg->linesize[i];
874 int dst_stride= i ? s->uvlinesize : s->linesize;
875 int h_shift= i ? h_chroma_shift : 0;
876 int v_shift= i ? v_chroma_shift : 0;
877 int w= s->width >>h_shift;
878 int h= s->height>>v_shift;
879 uint8_t *src= pic_arg->data[i];
880 uint8_t *dst= pic->data[i];
881
882 if(!s->avctx->rc_buffer_size)
883 dst +=INPLACE_OFFSET;
884
885 if(src_stride==dst_stride)
886 memcpy(dst, src, src_stride*h);
887 else{
888 while(h--){
889 memcpy(dst, src, w);
890 dst += dst_stride;
891 src += src_stride;
892 }
893 }
894 }
895 }
896 }
897 copy_picture_attributes(s, pic, pic_arg);
898 pic->pts= pts; //we set this here to avoid modifiying pic_arg
899 }
900
901 /* shift buffer entries */
902 for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
903 s->input_picture[i-1]= s->input_picture[i];
904
905 s->input_picture[encoding_delay]= (Picture*)pic;
906
907 return 0;
908}
909
910static int skip_check(MpegEncContext *s, Picture *p, Picture *ref){
911 int x, y, plane;
912 int score=0;
913 int64_t score64=0;
914
915 for(plane=0; plane<3; plane++){
916 const int stride= p->linesize[plane];
917 const int bw= plane ? 1 : 2;
918 for(y=0; y<s->mb_height*bw; y++){
919 for(x=0; x<s->mb_width*bw; x++){
920 int off= p->type == FF_BUFFER_TYPE_SHARED ? 0: 16;
921 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);
922
923 switch(s->avctx->frame_skip_exp){
924 case 0: score= FFMAX(score, v); break;
925 case 1: score+= FFABS(v);break;
926 case 2: score+= v*v;break;
927 case 3: score64+= FFABS(v*v*(int64_t)v);break;
928 case 4: score64+= v*v*(int64_t)(v*v);break;
929 }
930 }
931 }
932 }
933
934 if(score) score64= score;
935
936 if(score64 < s->avctx->frame_skip_threshold)
937 return 1;
938 if(score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda)>>8))
939 return 1;
940 return 0;
941}
942
943static int estimate_best_b_count(MpegEncContext *s){
944 AVCodec *codec= avcodec_find_encoder(s->avctx->codec_id);
945 AVCodecContext *c= avcodec_alloc_context();
946 AVFrame input[FF_MAX_B_FRAMES+2];
947 const int scale= s->avctx->brd_scale;
948 int i, j, out_size, p_lambda, b_lambda, lambda2;
949 int outbuf_size= s->width * s->height; //FIXME
950 uint8_t *outbuf= av_malloc(outbuf_size);
951 int64_t best_rd= INT64_MAX;
952 int best_b_count= -1;
953
954 assert(scale>=0 && scale <=3);
955
956// emms_c();
975a1447
SS
957 p_lambda= s->last_lambda_for[AV_PICTURE_TYPE_P]; //s->next_picture_ptr->quality;
958 b_lambda= s->last_lambda_for[AV_PICTURE_TYPE_B]; //p_lambda *FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
3ada94ba
BF
959 if(!b_lambda) b_lambda= p_lambda; //FIXME we should do this somewhere else
960 lambda2= (b_lambda*b_lambda + (1<<FF_LAMBDA_SHIFT)/2 ) >> FF_LAMBDA_SHIFT;
961
962 c->width = s->width >> scale;
963 c->height= s->height>> scale;
964 c->flags= CODEC_FLAG_QSCALE | CODEC_FLAG_PSNR | CODEC_FLAG_INPUT_PRESERVED /*| CODEC_FLAG_EMU_EDGE*/;
965 c->flags|= s->avctx->flags & CODEC_FLAG_QPEL;
966 c->mb_decision= s->avctx->mb_decision;
967 c->me_cmp= s->avctx->me_cmp;
968 c->mb_cmp= s->avctx->mb_cmp;
969 c->me_sub_cmp= s->avctx->me_sub_cmp;
970 c->pix_fmt = PIX_FMT_YUV420P;
971 c->time_base= s->avctx->time_base;
972 c->max_b_frames= s->max_b_frames;
973
974 if (avcodec_open(c, codec) < 0)
975 return -1;
976
977 for(i=0; i<s->max_b_frames+2; i++){
978 int ysize= c->width*c->height;
979 int csize= (c->width/2)*(c->height/2);
980 Picture pre_input, *pre_input_ptr= i ? s->input_picture[i-1] : s->next_picture_ptr;
981
982 avcodec_get_frame_defaults(&input[i]);
983 input[i].data[0]= av_malloc(ysize + 2*csize);
984 input[i].data[1]= input[i].data[0] + ysize;
985 input[i].data[2]= input[i].data[1] + csize;
986 input[i].linesize[0]= c->width;
987 input[i].linesize[1]=
988 input[i].linesize[2]= c->width/2;
989
990 if(pre_input_ptr && (!i || s->input_picture[i-1])) {
991 pre_input= *pre_input_ptr;
992
993 if(pre_input.type != FF_BUFFER_TYPE_SHARED && i) {
994 pre_input.data[0]+=INPLACE_OFFSET;
995 pre_input.data[1]+=INPLACE_OFFSET;
996 pre_input.data[2]+=INPLACE_OFFSET;
997 }
998
999 s->dsp.shrink[scale](input[i].data[0], input[i].linesize[0], pre_input.data[0], pre_input.linesize[0], c->width, c->height);
1000 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);
1001 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);
1002 }
1003 }
1004
1005 for(j=0; j<s->max_b_frames+1; j++){
1006 int64_t rd=0;
1007
1008 if(!s->input_picture[j])
1009 break;
1010
1011 c->error[0]= c->error[1]= c->error[2]= 0;
1012
975a1447 1013 input[0].pict_type= AV_PICTURE_TYPE_I;
3ada94ba
BF
1014 input[0].quality= 1 * FF_QP2LAMBDA;
1015 out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[0]);
1016// rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
1017
1018 for(i=0; i<s->max_b_frames+1; i++){
1019 int is_p= i % (j+1) == j || i==s->max_b_frames;
1020
975a1447 1021 input[i+1].pict_type= is_p ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_B;
3ada94ba
BF
1022 input[i+1].quality= is_p ? p_lambda : b_lambda;
1023 out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[i+1]);
1024 rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
1025 }
1026
1027 /* get the delayed frames */
1028 while(out_size){
1029 out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
1030 rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
1031 }
1032
1033 rd += c->error[0] + c->error[1] + c->error[2];
1034
1035 if(rd < best_rd){
1036 best_rd= rd;
1037 best_b_count= j;
1038 }
1039 }
1040
1041 av_freep(&outbuf);
1042 avcodec_close(c);
1043 av_freep(&c);
1044
1045 for(i=0; i<s->max_b_frames+2; i++){
1046 av_freep(&input[i].data[0]);
1047 }
1048
1049 return best_b_count;
1050}
1051
be548816 1052static int select_input_picture(MpegEncContext *s){
3ada94ba
BF
1053 int i;
1054
1055 for(i=1; i<MAX_PICTURE_COUNT; i++)
1056 s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
1057 s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;
1058
1059 /* set next picture type & ordering */
1060 if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
1061 if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture_ptr==NULL || s->intra_only){
1062 s->reordered_input_picture[0]= s->input_picture[0];
975a1447 1063 s->reordered_input_picture[0]->pict_type= AV_PICTURE_TYPE_I;
3ada94ba
BF
1064 s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
1065 }else{
1066 int b_frames;
1067
1068 if(s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor){
1069 if(s->picture_in_gop_number < s->gop_size && skip_check(s, s->input_picture[0], s->next_picture_ptr)){
1070 //FIXME check that te gop check above is +-1 correct
1071//av_log(NULL, AV_LOG_DEBUG, "skip %p %"PRId64"\n", s->input_picture[0]->data[0], s->input_picture[0]->pts);
1072
1073 if(s->input_picture[0]->type == FF_BUFFER_TYPE_SHARED){
1074 for(i=0; i<4; i++)
1075 s->input_picture[0]->data[i]= NULL;
1076 s->input_picture[0]->type= 0;
1077 }else{
1078 assert( s->input_picture[0]->type==FF_BUFFER_TYPE_USER
1079 || s->input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
1080
1081 s->avctx->release_buffer(s->avctx, (AVFrame*)s->input_picture[0]);
1082 }
1083
1084 emms_c();
1085 ff_vbv_update(s, 0);
1086
1087 goto no_output_pic;
1088 }
1089 }
1090
1091 if(s->flags&CODEC_FLAG_PASS2){
1092 for(i=0; i<s->max_b_frames+1; i++){
1093 int pict_num= s->input_picture[0]->display_picture_number + i;
1094
1095 if(pict_num >= s->rc_context.num_entries)
1096 break;
1097 if(!s->input_picture[i]){
975a1447 1098 s->rc_context.entry[pict_num-1].new_pict_type = AV_PICTURE_TYPE_P;
3ada94ba
BF
1099 break;
1100 }
1101
1102 s->input_picture[i]->pict_type=
1103 s->rc_context.entry[pict_num].new_pict_type;
1104 }
1105 }
1106
1107 if(s->avctx->b_frame_strategy==0){
1108 b_frames= s->max_b_frames;
1109 while(b_frames && !s->input_picture[b_frames]) b_frames--;
1110 }else if(s->avctx->b_frame_strategy==1){
1111 for(i=1; i<s->max_b_frames+1; i++){
1112 if(s->input_picture[i] && s->input_picture[i]->b_frame_score==0){
1113 s->input_picture[i]->b_frame_score=
1114 get_intra_count(s, s->input_picture[i ]->data[0],
1115 s->input_picture[i-1]->data[0], s->linesize) + 1;
1116 }
1117 }
1118 for(i=0; i<s->max_b_frames+1; i++){
1119 if(s->input_picture[i]==NULL || s->input_picture[i]->b_frame_score - 1 > s->mb_num/s->avctx->b_sensitivity) break;
1120 }
1121
1122 b_frames= FFMAX(0, i-1);
1123
1124 /* reset scores */
1125 for(i=0; i<b_frames+1; i++){
1126 s->input_picture[i]->b_frame_score=0;
1127 }
1128 }else if(s->avctx->b_frame_strategy==2){
1129 b_frames= estimate_best_b_count(s);
1130 }else{
1131 av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
1132 b_frames=0;
1133 }
1134
1135 emms_c();
1136//static int b_count=0;
1137//b_count+= b_frames;
1138//av_log(s->avctx, AV_LOG_DEBUG, "b_frames: %d\n", b_count);
1139
1140 for(i= b_frames - 1; i>=0; i--){
1141 int type= s->input_picture[i]->pict_type;
975a1447 1142 if(type && type != AV_PICTURE_TYPE_B)
3ada94ba
BF
1143 b_frames= i;
1144 }
975a1447 1145 if(s->input_picture[b_frames]->pict_type == AV_PICTURE_TYPE_B && b_frames == s->max_b_frames){
3ada94ba
BF
1146 av_log(s->avctx, AV_LOG_ERROR, "warning, too many b frames in a row\n");
1147 }
1148
1149 if(s->picture_in_gop_number + b_frames >= s->gop_size){
1150 if((s->flags2 & CODEC_FLAG2_STRICT_GOP) && s->gop_size > s->picture_in_gop_number){
1151 b_frames= s->gop_size - s->picture_in_gop_number - 1;
1152 }else{
1153 if(s->flags & CODEC_FLAG_CLOSED_GOP)
1154 b_frames=0;
975a1447 1155 s->input_picture[b_frames]->pict_type= AV_PICTURE_TYPE_I;
3ada94ba
BF
1156 }
1157 }
1158
1159 if( (s->flags & CODEC_FLAG_CLOSED_GOP)
1160 && b_frames
975a1447 1161 && s->input_picture[b_frames]->pict_type== AV_PICTURE_TYPE_I)
3ada94ba
BF
1162 b_frames--;
1163
1164 s->reordered_input_picture[0]= s->input_picture[b_frames];
975a1447
SS
1165 if(s->reordered_input_picture[0]->pict_type != AV_PICTURE_TYPE_I)
1166 s->reordered_input_picture[0]->pict_type= AV_PICTURE_TYPE_P;
3ada94ba
BF
1167 s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
1168 for(i=0; i<b_frames; i++){
1169 s->reordered_input_picture[i+1]= s->input_picture[i];
975a1447 1170 s->reordered_input_picture[i+1]->pict_type= AV_PICTURE_TYPE_B;
3ada94ba
BF
1171 s->reordered_input_picture[i+1]->coded_picture_number= s->coded_picture_number++;
1172 }
1173 }
1174 }
1175no_output_pic:
1176 if(s->reordered_input_picture[0]){
975a1447 1177 s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=AV_PICTURE_TYPE_B ? 3 : 0;
3ada94ba 1178
8d2fc163 1179 ff_copy_picture(&s->new_picture, s->reordered_input_picture[0]);
3ada94ba
BF
1180
1181 if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_SHARED || s->avctx->rc_buffer_size){
1182 // input is a shared pix, so we can't modifiy it -> alloc a new one & ensure that the shared one is reuseable
1183
1184 int i= ff_find_unused_picture(s, 0);
1185 Picture *pic= &s->picture[i];
1186
1187 pic->reference = s->reordered_input_picture[0]->reference;
be548816
PP
1188 if(ff_alloc_picture(s, pic, 0) < 0){
1189 return -1;
1190 }
3ada94ba
BF
1191
1192 /* mark us unused / free shared pic */
1193 if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_INTERNAL)
1194 s->avctx->release_buffer(s->avctx, (AVFrame*)s->reordered_input_picture[0]);
1195 for(i=0; i<4; i++)
1196 s->reordered_input_picture[0]->data[i]= NULL;
1197 s->reordered_input_picture[0]->type= 0;
1198
1199 copy_picture_attributes(s, (AVFrame*)pic, (AVFrame*)s->reordered_input_picture[0]);
1200
1201 s->current_picture_ptr= pic;
1202 }else{
1203 // input is not a shared pix -> reuse buffer for current_pix
1204
1205 assert( s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER
1206 || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
1207
1208 s->current_picture_ptr= s->reordered_input_picture[0];
1209 for(i=0; i<4; i++){
1210 s->new_picture.data[i]+= INPLACE_OFFSET;
1211 }
1212 }
8d2fc163 1213 ff_copy_picture(&s->current_picture, s->current_picture_ptr);
3ada94ba
BF
1214
1215 s->picture_number= s->new_picture.display_picture_number;
1216//printf("dpn:%d\n", s->picture_number);
1217 }else{
1218 memset(&s->new_picture, 0, sizeof(Picture));
1219 }
be548816 1220 return 0;
3ada94ba
BF
1221}
1222
1223int MPV_encode_picture(AVCodecContext *avctx,
1224 unsigned char *buf, int buf_size, void *data)
1225{
1226 MpegEncContext *s = avctx->priv_data;
1227 AVFrame *pic_arg = data;
1228 int i, stuffing_count;
1229
1230 for(i=0; i<avctx->thread_count; i++){
1231 int start_y= s->thread_context[i]->start_mb_y;
1232 int end_y= s->thread_context[i]-> end_mb_y;
1233 int h= s->mb_height;
1234 uint8_t *start= buf + (size_t)(((int64_t) buf_size)*start_y/h);
1235 uint8_t *end = buf + (size_t)(((int64_t) buf_size)* end_y/h);
1236
1237 init_put_bits(&s->thread_context[i]->pb, start, end - start);
1238 }
1239
1240 s->picture_in_gop_number++;
1241
1242 if(load_input_picture(s, pic_arg) < 0)
1243 return -1;
1244
be548816
PP
1245 if(select_input_picture(s) < 0){
1246 return -1;
1247 }
3ada94ba
BF
1248
1249 /* output? */
1250 if(s->new_picture.data[0]){
1251 s->pict_type= s->new_picture.pict_type;
1252//emms_c();
1253//printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
1254 MPV_frame_start(s, avctx);
1255vbv_retry:
1256 if (encode_picture(s, s->picture_number) < 0)
1257 return -1;
1258
3ada94ba
BF
1259 avctx->header_bits = s->header_bits;
1260 avctx->mv_bits = s->mv_bits;
1261 avctx->misc_bits = s->misc_bits;
1262 avctx->i_tex_bits = s->i_tex_bits;
1263 avctx->p_tex_bits = s->p_tex_bits;
1264 avctx->i_count = s->i_count;
1265 avctx->p_count = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
1266 avctx->skip_count = s->skip_count;
1267
1268 MPV_frame_end(s);
1269
49fb20cb 1270 if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
3ada94ba
BF
1271 ff_mjpeg_encode_picture_trailer(s);
1272
1273 if(avctx->rc_buffer_size){
1274 RateControlContext *rcc= &s->rc_context;
3bff4d8b 1275 int max_size= rcc->buffer_index * avctx->rc_max_available_vbv_use;
3ada94ba
BF
1276
1277 if(put_bits_count(&s->pb) > max_size && s->lambda < s->avctx->lmax){
1278 s->next_lambda= FFMAX(s->lambda+1, s->lambda*(s->qscale+1) / s->qscale);
1279 if(s->adaptive_quant){
1280 int i;
1281 for(i=0; i<s->mb_height*s->mb_stride; i++)
1282 s->lambda_table[i]= FFMAX(s->lambda_table[i]+1, s->lambda_table[i]*(s->qscale+1) / s->qscale);
1283 }
1284 s->mb_skipped = 0; //done in MPV_frame_start()
975a1447 1285 if(s->pict_type==AV_PICTURE_TYPE_P){ //done in encode_picture() so we must undo it
3ada94ba
BF
1286 if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
1287 s->no_rounding ^= 1;
1288 }
975a1447 1289 if(s->pict_type!=AV_PICTURE_TYPE_B){
3ada94ba
BF
1290 s->time_base= s->last_time_base;
1291 s->last_non_b_time= s->time - s->pp_time;
1292 }
1293// av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);
1294 for(i=0; i<avctx->thread_count; i++){
1295 PutBitContext *pb= &s->thread_context[i]->pb;
1296 init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
1297 }
1298 goto vbv_retry;
1299 }
1300
1301 assert(s->avctx->rc_max_rate);
1302 }
1303
1304 if(s->flags&CODEC_FLAG_PASS1)
1305 ff_write_pass1_stats(s);
1306
1307 for(i=0; i<4; i++){
1308 s->current_picture_ptr->error[i]= s->current_picture.error[i];
1309 avctx->error[i] += s->current_picture_ptr->error[i];
1310 }
1311
1312 if(s->flags&CODEC_FLAG_PASS1)
1313 assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb));
1314 flush_put_bits(&s->pb);
1315 s->frame_bits = put_bits_count(&s->pb);
1316
1317 stuffing_count= ff_vbv_update(s, s->frame_bits);
1318 if(stuffing_count){
1319 if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){
1320 av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
1321 return -1;
1322 }
1323
1324 switch(s->codec_id){
1325 case CODEC_ID_MPEG1VIDEO:
1326 case CODEC_ID_MPEG2VIDEO:
1327 while(stuffing_count--){
1328 put_bits(&s->pb, 8, 0);
1329 }
1330 break;
1331 case CODEC_ID_MPEG4:
1332 put_bits(&s->pb, 16, 0);
1333 put_bits(&s->pb, 16, 0x1C3);
1334 stuffing_count -= 4;
1335 while(stuffing_count--){
1336 put_bits(&s->pb, 8, 0xFF);
1337 }
1338 break;
1339 default:
1340 av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
1341 }
1342 flush_put_bits(&s->pb);
1343 s->frame_bits = put_bits_count(&s->pb);
1344 }
1345
1346 /* update mpeg1/2 vbv_delay for CBR */
1347 if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1
1348 && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){
4601e76a
MN
1349 int vbv_delay, min_delay;
1350 double inbits = s->avctx->rc_max_rate*av_q2d(s->avctx->time_base);
1351 int minbits= s->frame_bits - 8*(s->vbv_delay_ptr - s->pb.buf - 1);
1352 double bits = s->rc_context.buffer_index + minbits - inbits;
1353
1354 if(bits<0)
1355 av_log(s->avctx, AV_LOG_ERROR, "Internal error, negative bits\n");
3ada94ba
BF
1356
1357 assert(s->repeat_first_field==0);
1358
4601e76a
MN
1359 vbv_delay= bits * 90000 / s->avctx->rc_max_rate;
1360 min_delay= (minbits * 90000LL + s->avctx->rc_max_rate - 1)/ s->avctx->rc_max_rate;
1361
1362 vbv_delay= FFMAX(vbv_delay, min_delay);
1363
3ada94ba
BF
1364 assert(vbv_delay < 0xFFFF);
1365
1366 s->vbv_delay_ptr[0] &= 0xF8;
1367 s->vbv_delay_ptr[0] |= vbv_delay>>13;
1368 s->vbv_delay_ptr[1] = vbv_delay>>5;
1369 s->vbv_delay_ptr[2] &= 0x07;
1370 s->vbv_delay_ptr[2] |= vbv_delay<<3;
55bad0c6 1371 avctx->vbv_delay = vbv_delay*300;
3ada94ba
BF
1372 }
1373 s->total_bits += s->frame_bits;
1374 avctx->frame_bits = s->frame_bits;
1375 }else{
fb53b4a0 1376 assert((put_bits_ptr(&s->pb) == s->pb.buf));
3ada94ba
BF
1377 s->frame_bits=0;
1378 }
1379 assert((s->frame_bits&7)==0);
1380
1381 return s->frame_bits/8;
1382}
1383
1384static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
1385{
1386 static const char tab[64]=
1387 {3,2,2,1,1,1,1,1,
1388 1,1,1,1,1,1,1,1,
1389 1,1,1,1,1,1,1,1,
1390 0,0,0,0,0,0,0,0,
1391 0,0,0,0,0,0,0,0,
1392 0,0,0,0,0,0,0,0,
1393 0,0,0,0,0,0,0,0,
1394 0,0,0,0,0,0,0,0};
1395 int score=0;
1396 int run=0;
1397 int i;
1398 DCTELEM *block= s->block[n];
1399 const int last_index= s->block_last_index[n];
1400 int skip_dc;
1401
1402 if(threshold<0){
1403 skip_dc=0;
1404 threshold= -threshold;
1405 }else
1406 skip_dc=1;
1407
bd107136 1408 /* Are all we could set to zero already zero? */
3ada94ba
BF
1409 if(last_index<=skip_dc - 1) return;
1410
1411 for(i=0; i<=last_index; i++){
1412 const int j = s->intra_scantable.permutated[i];
1413 const int level = FFABS(block[j]);
1414 if(level==1){
1415 if(skip_dc && i==0) continue;
1416 score+= tab[run];
1417 run=0;
1418 }else if(level>1){
1419 return;
1420 }else{
1421 run++;
1422 }
1423 }
1424 if(score >= threshold) return;
1425 for(i=skip_dc; i<=last_index; i++){
1426 const int j = s->intra_scantable.permutated[i];
1427 block[j]=0;
1428 }
1429 if(block[0]) s->block_last_index[n]= 0;
1430 else s->block_last_index[n]= -1;
1431}
1432
1433static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
1434{
1435 int i;
1436 const int maxlevel= s->max_qcoeff;
1437 const int minlevel= s->min_qcoeff;
1438 int overflow=0;
1439
1440 if(s->mb_intra){
1441 i=1; //skip clipping of intra dc
1442 }else
1443 i=0;
1444
1445 for(;i<=last_index; i++){
1446 const int j= s->intra_scantable.permutated[i];
1447 int level = block[j];
1448
1449 if (level>maxlevel){
1450 level=maxlevel;
1451 overflow++;
1452 }else if(level<minlevel){
1453 level=minlevel;
1454 overflow++;
1455 }
1456
1457 block[j]= level;
1458 }
1459
1460 if(overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
1461 av_log(s->avctx, AV_LOG_INFO, "warning, clipping %d dct coefficients to %d..%d\n", overflow, minlevel, maxlevel);
1462}
1463
f073a393 1464static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride){
3ada94ba
BF
1465 int x, y;
1466//FIXME optimize
1467 for(y=0; y<8; y++){
1468 for(x=0; x<8; x++){
1469 int x2, y2;
1470 int sum=0;
1471 int sqr=0;
1472 int count=0;
1473
1474 for(y2= FFMAX(y-1, 0); y2 < FFMIN(8, y+2); y2++){
1475 for(x2= FFMAX(x-1, 0); x2 < FFMIN(8, x+2); x2++){
1476 int v= ptr[x2 + y2*stride];
1477 sum += v;
1478 sqr += v*v;
1479 count++;
1480 }
1481 }
1482 weight[x + 8*y]= (36*ff_sqrt(count*sqr - sum*sum)) / count;
1483 }
1484 }
1485}
1486
1487static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x, int motion_y, int mb_block_height, int mb_block_count)
1488{
1489 int16_t weight[8][64];
1490 DCTELEM orig[8][64];
1491 const int mb_x= s->mb_x;
1492 const int mb_y= s->mb_y;
1493 int i;
1494 int skip_dct[8];
1495 int dct_offset = s->linesize*8; //default for progressive frames
1496 uint8_t *ptr_y, *ptr_cb, *ptr_cr;
1497 int wrap_y, wrap_c;
1498
1499 for(i=0; i<mb_block_count; i++) skip_dct[i]=s->skipdct;
1500
1501 if(s->adaptive_quant){
1502 const int last_qp= s->qscale;
1503 const int mb_xy= mb_x + mb_y*s->mb_stride;
1504
1505 s->lambda= s->lambda_table[mb_xy];
1506 update_qscale(s);
1507
1508 if(!(s->flags&CODEC_FLAG_QP_RD)){
1509 s->qscale= s->current_picture_ptr->qscale_table[mb_xy];
1510 s->dquant= s->qscale - last_qp;
1511
1512 if(s->out_format==FMT_H263){
1513 s->dquant= av_clip(s->dquant, -2, 2);
1514
1515 if(s->codec_id==CODEC_ID_MPEG4){
1516 if(!s->mb_intra){
975a1447 1517 if(s->pict_type == AV_PICTURE_TYPE_B){
3ada94ba
BF
1518 if(s->dquant&1 || s->mv_dir&MV_DIRECT)
1519 s->dquant= 0;
1520 }
1521 if(s->mv_type==MV_TYPE_8X8)
1522 s->dquant=0;
1523 }
1524 }
1525 }
1526 }
1527 ff_set_qscale(s, last_qp + s->dquant);
1528 }else if(s->flags&CODEC_FLAG_QP_RD)
1529 ff_set_qscale(s, s->qscale + s->dquant);
1530
1531 wrap_y = s->linesize;
1532 wrap_c = s->uvlinesize;
1533 ptr_y = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
1534 ptr_cb = s->new_picture.data[1] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
1535 ptr_cr = s->new_picture.data[2] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
1536
1537 if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
1538 uint8_t *ebuf= s->edge_emu_buffer + 32;
2e279598 1539 s->dsp.emulated_edge_mc(ebuf , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width , s->height);
3ada94ba 1540 ptr_y= ebuf;
2e279598 1541 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);
3ada94ba 1542 ptr_cb= ebuf+18*wrap_y;
2e279598 1543 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);
3ada94ba
BF
1544 ptr_cr= ebuf+18*wrap_y+8;
1545 }
1546
1547 if (s->mb_intra) {
1548 if(s->flags&CODEC_FLAG_INTERLACED_DCT){
1549 int progressive_score, interlaced_score;
1550
1551 s->interlaced_dct=0;
1552 progressive_score= s->dsp.ildct_cmp[4](s, ptr_y , NULL, wrap_y, 8)
1553 +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;
1554
1555 if(progressive_score > 0){
1556 interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y , NULL, wrap_y*2, 8)
1557 +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y , NULL, wrap_y*2, 8);
1558 if(progressive_score > interlaced_score){
1559 s->interlaced_dct=1;
1560
1561 dct_offset= wrap_y;
1562 wrap_y<<=1;
1563 if (s->chroma_format == CHROMA_422)
1564 wrap_c<<=1;
1565 }
1566 }
1567 }
1568
1569 s->dsp.get_pixels(s->block[0], ptr_y , wrap_y);
1570 s->dsp.get_pixels(s->block[1], ptr_y + 8, wrap_y);
1571 s->dsp.get_pixels(s->block[2], ptr_y + dct_offset , wrap_y);
1572 s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
1573
1574 if(s->flags&CODEC_FLAG_GRAY){
1575 skip_dct[4]= 1;
1576 skip_dct[5]= 1;
1577 }else{
1578 s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
1579 s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
1580 if(!s->chroma_y_shift){ /* 422 */
1581 s->dsp.get_pixels(s->block[6], ptr_cb + (dct_offset>>1), wrap_c);
1582 s->dsp.get_pixels(s->block[7], ptr_cr + (dct_offset>>1), wrap_c);
1583 }
1584 }
1585 }else{
1586 op_pixels_func (*op_pix)[4];
1587 qpel_mc_func (*op_qpix)[16];
1588 uint8_t *dest_y, *dest_cb, *dest_cr;
1589
1590 dest_y = s->dest[0];
1591 dest_cb = s->dest[1];
1592 dest_cr = s->dest[2];
1593
975a1447 1594 if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
3ada94ba
BF
1595 op_pix = s->dsp.put_pixels_tab;
1596 op_qpix= s->dsp.put_qpel_pixels_tab;
1597 }else{
1598 op_pix = s->dsp.put_no_rnd_pixels_tab;
1599 op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
1600 }
1601
1602 if (s->mv_dir & MV_DIR_FORWARD) {
1603 MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
1604 op_pix = s->dsp.avg_pixels_tab;
1605 op_qpix= s->dsp.avg_qpel_pixels_tab;
1606 }
1607 if (s->mv_dir & MV_DIR_BACKWARD) {
1608 MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
1609 }
1610
1611 if(s->flags&CODEC_FLAG_INTERLACED_DCT){
1612 int progressive_score, interlaced_score;
1613
1614 s->interlaced_dct=0;
1615 progressive_score= s->dsp.ildct_cmp[0](s, dest_y , ptr_y , wrap_y, 8)
1616 +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;
1617
1618 if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;
1619
1620 if(progressive_score>0){
1621 interlaced_score = s->dsp.ildct_cmp[0](s, dest_y , ptr_y , wrap_y*2, 8)
1622 +s->dsp.ildct_cmp[0](s, dest_y + wrap_y , ptr_y + wrap_y , wrap_y*2, 8);
1623
1624 if(progressive_score > interlaced_score){
1625 s->interlaced_dct=1;
1626
1627 dct_offset= wrap_y;
1628 wrap_y<<=1;
1629 if (s->chroma_format == CHROMA_422)
1630 wrap_c<<=1;
1631 }
1632 }
1633 }
1634
1635 s->dsp.diff_pixels(s->block[0], ptr_y , dest_y , wrap_y);
1636 s->dsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
1637 s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset , dest_y + dct_offset , wrap_y);
1638 s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
1639
1640 if(s->flags&CODEC_FLAG_GRAY){
1641 skip_dct[4]= 1;
1642 skip_dct[5]= 1;
1643 }else{
1644 s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
1645 s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
1646 if(!s->chroma_y_shift){ /* 422 */
1647 s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset>>1), dest_cb + (dct_offset>>1), wrap_c);
1648 s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset>>1), dest_cr + (dct_offset>>1), wrap_c);
1649 }
1650 }
1651 /* pre quantization */
1652 if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
1653 //FIXME optimize
1654 if(s->dsp.sad[1](NULL, ptr_y , dest_y , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;
1655 if(s->dsp.sad[1](NULL, ptr_y + 8, dest_y + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;
1656 if(s->dsp.sad[1](NULL, ptr_y +dct_offset , dest_y +dct_offset , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;
1657 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;
1658 if(s->dsp.sad[1](NULL, ptr_cb , dest_cb , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;
1659 if(s->dsp.sad[1](NULL, ptr_cr , dest_cr , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;
1660 if(!s->chroma_y_shift){ /* 422 */
1661 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;
1662 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;
1663 }
1664 }
1665 }
1666
1667 if(s->avctx->quantizer_noise_shaping){
f073a393
DB
1668 if(!skip_dct[0]) get_visual_weight(weight[0], ptr_y , wrap_y);
1669 if(!skip_dct[1]) get_visual_weight(weight[1], ptr_y + 8, wrap_y);
1670 if(!skip_dct[2]) get_visual_weight(weight[2], ptr_y + dct_offset , wrap_y);
1671 if(!skip_dct[3]) get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
1672 if(!skip_dct[4]) get_visual_weight(weight[4], ptr_cb , wrap_c);
1673 if(!skip_dct[5]) get_visual_weight(weight[5], ptr_cr , wrap_c);
3ada94ba 1674 if(!s->chroma_y_shift){ /* 422 */
f073a393
DB
1675 if(!skip_dct[6]) get_visual_weight(weight[6], ptr_cb + (dct_offset>>1), wrap_c);
1676 if(!skip_dct[7]) get_visual_weight(weight[7], ptr_cr + (dct_offset>>1), wrap_c);
3ada94ba
BF
1677 }
1678 memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*mb_block_count);
1679 }
1680
1681 /* DCT & quantize */
1682 assert(s->out_format!=FMT_MJPEG || s->qscale==8);
1683 {
1684 for(i=0;i<mb_block_count;i++) {
1685 if(!skip_dct[i]){
1686 int overflow;
1687 s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
1688 // FIXME we could decide to change to quantizer instead of clipping
1689 // JS: I don't think that would be a good idea it could lower quality instead
1690 // of improve it. Just INTRADC clipping deserves changes in quantizer
1691 if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
1692 }else
1693 s->block_last_index[i]= -1;
1694 }
1695 if(s->avctx->quantizer_noise_shaping){
1696 for(i=0;i<mb_block_count;i++) {
1697 if(!skip_dct[i]){
1698 s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);
1699 }
1700 }
1701 }
1702
1703 if(s->luma_elim_threshold && !s->mb_intra)
1704 for(i=0; i<4; i++)
1705 dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
1706 if(s->chroma_elim_threshold && !s->mb_intra)
1707 for(i=4; i<mb_block_count; i++)
1708 dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
1709
1710 if(s->flags & CODEC_FLAG_CBP_RD){
1711 for(i=0;i<mb_block_count;i++) {
1712 if(s->block_last_index[i] == -1)
1713 s->coded_score[i]= INT_MAX/256;
1714 }
1715 }
1716 }
1717
1718 if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
1719 s->block_last_index[4]=
1720 s->block_last_index[5]= 0;
1721 s->block[4][0]=
1722 s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
1723 }
1724
1725 //non c quantize code returns incorrect block_last_index FIXME
1726 if(s->alternate_scan && s->dct_quantize != dct_quantize_c){
1727 for(i=0; i<mb_block_count; i++){
1728 int j;
1729 if(s->block_last_index[i]>0){
1730 for(j=63; j>0; j--){
1731 if(s->block[i][ s->intra_scantable.permutated[j] ]) break;
1732 }
1733 s->block_last_index[i]= j;
1734 }
1735 }
1736 }
1737
1738 /* huffman encode */
1739 switch(s->codec_id){ //FIXME funct ptr could be slightly faster
1740 case CODEC_ID_MPEG1VIDEO:
1741 case CODEC_ID_MPEG2VIDEO:
49fb20cb 1742 if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
56be950a
AJ
1743 mpeg1_encode_mb(s, s->block, motion_x, motion_y);
1744 break;
3ada94ba 1745 case CODEC_ID_MPEG4:
49fb20cb 1746 if (CONFIG_MPEG4_ENCODER)
674eeb5f
AJ
1747 mpeg4_encode_mb(s, s->block, motion_x, motion_y);
1748 break;
3ada94ba
BF
1749 case CODEC_ID_MSMPEG4V2:
1750 case CODEC_ID_MSMPEG4V3:
1751 case CODEC_ID_WMV1:
49fb20cb 1752 if (CONFIG_MSMPEG4_ENCODER)
3ada94ba
BF
1753 msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
1754 break;
1755 case CODEC_ID_WMV2:
49fb20cb 1756 if (CONFIG_WMV2_ENCODER)
3ada94ba
BF
1757 ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
1758 break;
1759 case CODEC_ID_H261:
49fb20cb 1760 if (CONFIG_H261_ENCODER)
3ada94ba
BF
1761 ff_h261_encode_mb(s, s->block, motion_x, motion_y);
1762 break;
1763 case CODEC_ID_H263:
1764 case CODEC_ID_H263P:
1765 case CODEC_ID_FLV1:
1766 case CODEC_ID_RV10:
1767 case CODEC_ID_RV20:
0bd48530 1768 if (CONFIG_H263_ENCODER)
674eeb5f
AJ
1769 h263_encode_mb(s, s->block, motion_x, motion_y);
1770 break;
3ada94ba 1771 case CODEC_ID_MJPEG:
49fb20cb 1772 if (CONFIG_MJPEG_ENCODER)
3ada94ba
BF
1773 ff_mjpeg_encode_mb(s, s->block);
1774 break;
1775 default:
1776 assert(0);
1777 }
1778}
1779
1780static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
1781{
1782 if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y, 8, 6);
1783 else encode_mb_internal(s, motion_x, motion_y, 16, 8);
1784}
1785
3ada94ba
BF
1786static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
1787 int i;
1788
1789 memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
1790
1791 /* mpeg1 */
1792 d->mb_skip_run= s->mb_skip_run;
1793 for(i=0; i<3; i++)
1794 d->last_dc[i]= s->last_dc[i];
1795
1796 /* statistics */
1797 d->mv_bits= s->mv_bits;
1798 d->i_tex_bits= s->i_tex_bits;
1799 d->p_tex_bits= s->p_tex_bits;
1800 d->i_count= s->i_count;
1801 d->f_count= s->f_count;
1802 d->b_count= s->b_count;
1803 d->skip_count= s->skip_count;
1804 d->misc_bits= s->misc_bits;
1805 d->last_bits= 0;
1806
1807 d->mb_skipped= 0;
1808 d->qscale= s->qscale;
1809 d->dquant= s->dquant;
9f175aa0
MN
1810
1811 d->esc3_level_length= s->esc3_level_length;
3ada94ba
BF
1812}
1813
1814static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
1815 int i;
1816
1817 memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
1818 memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
1819
1820 /* mpeg1 */
1821 d->mb_skip_run= s->mb_skip_run;
1822 for(i=0; i<3; i++)
1823 d->last_dc[i]= s->last_dc[i];
1824
1825 /* statistics */
1826 d->mv_bits= s->mv_bits;
1827 d->i_tex_bits= s->i_tex_bits;
1828 d->p_tex_bits= s->p_tex_bits;
1829 d->i_count= s->i_count;
1830 d->f_count= s->f_count;
1831 d->b_count= s->b_count;
1832 d->skip_count= s->skip_count;
1833 d->misc_bits= s->misc_bits;
1834
1835 d->mb_intra= s->mb_intra;
1836 d->mb_skipped= s->mb_skipped;
1837 d->mv_type= s->mv_type;
1838 d->mv_dir= s->mv_dir;
1839 d->pb= s->pb;
1840 if(s->data_partitioning){
1841 d->pb2= s->pb2;
1842 d->tex_pb= s->tex_pb;
1843 }
1844 d->block= s->block;
1845 for(i=0; i<8; i++)
1846 d->block_last_index[i]= s->block_last_index[i];
1847 d->interlaced_dct= s->interlaced_dct;
1848 d->qscale= s->qscale;
9f175aa0
MN
1849
1850 d->esc3_level_length= s->esc3_level_length;
3ada94ba
BF
1851}
1852
1853static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
1854 PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
1855 int *dmin, int *next_block, int motion_x, int motion_y)
1856{
1857 int score;
1858 uint8_t *dest_backup[3];
1859
1860 copy_context_before_encode(s, backup, type);
1861
1862 s->block= s->blocks[*next_block];
1863 s->pb= pb[*next_block];
1864 if(s->data_partitioning){
1865 s->pb2 = pb2 [*next_block];
1866 s->tex_pb= tex_pb[*next_block];
1867 }
1868
1869 if(*next_block){
1870 memcpy(dest_backup, s->dest, sizeof(s->dest));
1871 s->dest[0] = s->rd_scratchpad;
1872 s->dest[1] = s->rd_scratchpad + 16*s->linesize;
1873 s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
1874 assert(s->linesize >= 32); //FIXME
1875 }
1876
1877 encode_mb(s, motion_x, motion_y);
1878
1879 score= put_bits_count(&s->pb);
1880 if(s->data_partitioning){
1881 score+= put_bits_count(&s->pb2);
1882 score+= put_bits_count(&s->tex_pb);
1883 }
1884
1885 if(s->avctx->mb_decision == FF_MB_DECISION_RD){
1886 MPV_decode_mb(s, s->block);
1887
1888 score *= s->lambda2;
1889 score += sse_mb(s) << FF_LAMBDA_SHIFT;
1890 }
1891
1892 if(*next_block){
1893 memcpy(s->dest, dest_backup, sizeof(s->dest));
1894 }
1895
1896 if(score<*dmin){
1897 *dmin= score;
1898 *next_block^=1;
1899
1900 copy_context_after_encode(best, s, type);
1901 }
1902}
1903
1904static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
1905 uint32_t *sq = ff_squareTbl + 256;
1906 int acc=0;
1907 int x,y;
1908
1909 if(w==16 && h==16)
1910 return s->dsp.sse[0](NULL, src1, src2, stride, 16);
1911 else if(w==8 && h==8)
1912 return s->dsp.sse[1](NULL, src1, src2, stride, 8);
1913
1914 for(y=0; y<h; y++){
1915 for(x=0; x<w; x++){
1916 acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
1917 }
1918 }
1919
1920 assert(acc>=0);
1921
1922 return acc;
1923}
1924
1925static int sse_mb(MpegEncContext *s){
1926 int w= 16;
1927 int h= 16;
1928
1929 if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
1930 if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
1931
1932 if(w==16 && h==16)
1933 if(s->avctx->mb_cmp == FF_CMP_NSSE){
1934 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)
1935 +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)
1936 +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);
1937 }else{
1938 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)
1939 +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)
1940 +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);
1941 }
1942 else
1943 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)
1944 +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)
1945 +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);
1946}
1947
1948static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
3a84713a 1949 MpegEncContext *s= *(void**)arg;
3ada94ba
BF
1950
1951
1952 s->me.pre_pass=1;
1953 s->me.dia_size= s->avctx->pre_dia_size;
1954 s->first_slice_line=1;
1955 for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
1956 for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
1957 ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
1958 }
1959 s->first_slice_line=0;
1960 }
1961
1962 s->me.pre_pass=0;
1963
1964 return 0;
1965}
1966
1967static int estimate_motion_thread(AVCodecContext *c, void *arg){
3a84713a 1968 MpegEncContext *s= *(void**)arg;
3ada94ba
BF
1969
1970 ff_check_alignment();
1971
1972 s->me.dia_size= s->avctx->dia_size;
1973 s->first_slice_line=1;
1974 for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
1975 s->mb_x=0; //for block init below
1976 ff_init_block_index(s);
1977 for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
1978 s->block_index[0]+=2;
1979 s->block_index[1]+=2;
1980 s->block_index[2]+=2;
1981 s->block_index[3]+=2;
1982
1983 /* compute motion vector & mb_type and store in context */
975a1447 1984 if(s->pict_type==AV_PICTURE_TYPE_B)
3ada94ba
BF
1985 ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
1986 else
1987 ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
1988 }
1989 s->first_slice_line=0;
1990 }
1991 return 0;
1992}
1993
1994static int mb_var_thread(AVCodecContext *c, void *arg){
3a84713a 1995 MpegEncContext *s= *(void**)arg;
3ada94ba
BF
1996 int mb_x, mb_y;
1997
1998 ff_check_alignment();
1999
2000 for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
2001 for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2002 int xx = mb_x * 16;
2003 int yy = mb_y * 16;
2004 uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
2005 int varc;
2006 int sum = s->dsp.pix_sum(pix, s->linesize);
2007
2008 varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
2009
2010 s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
2011 s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
2012 s->me.mb_var_sum_temp += varc;
2013 }
2014 }
2015 return 0;
2016}
2017
2018static void write_slice_end(MpegEncContext *s){
49fb20cb 2019 if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4){
3ada94ba
BF
2020 if(s->partitioned_frame){
2021 ff_mpeg4_merge_partitions(s);
2022 }
2023
2024 ff_mpeg4_stuffing(&s->pb);
49fb20cb 2025 }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
3ada94ba
BF
2026 ff_mjpeg_encode_stuffing(&s->pb);
2027 }
2028
2029 align_put_bits(&s->pb);
2030 flush_put_bits(&s->pb);
2031
2032 if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
2033 s->misc_bits+= get_bits_diff(s);
2034}
2035
2036static int encode_thread(AVCodecContext *c, void *arg){
3a84713a 2037 MpegEncContext *s= *(void**)arg;
3ada94ba 2038 int mb_x, mb_y, pdif = 0;
ec7e2582 2039 int chr_h= 16>>s->chroma_y_shift;
3ada94ba
BF
2040 int i, j;
2041 MpegEncContext best_s, backup_s;
2042 uint8_t bit_buf[2][MAX_MB_BYTES];
2043 uint8_t bit_buf2[2][MAX_MB_BYTES];
2044 uint8_t bit_buf_tex[2][MAX_MB_BYTES];
2045 PutBitContext pb[2], pb2[2], tex_pb[2];
2046//printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
2047
2048 ff_check_alignment();
2049
2050 for(i=0; i<2; i++){
2051 init_put_bits(&pb [i], bit_buf [i], MAX_MB_BYTES);
2052 init_put_bits(&pb2 [i], bit_buf2 [i], MAX_MB_BYTES);
2053 init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
2054 }
2055
2056 s->last_bits= put_bits_count(&s->pb);
2057 s->mv_bits=0;
2058 s->misc_bits=0;
2059 s->i_tex_bits=0;
2060 s->p_tex_bits=0;
2061 s->i_count=0;
2062 s->f_count=0;
2063 s->b_count=0;
2064 s->skip_count=0;
2065
2066 for(i=0; i<3; i++){
2067 /* init last dc values */
2068 /* note: quant matrix value (8) is implied here */
2069 s->last_dc[i] = 128 << s->intra_dc_precision;
2070
2071 s->current_picture.error[i] = 0;
2072 }
2073 s->mb_skip_run = 0;
2074 memset(s->last_mv, 0, sizeof(s->last_mv));
2075
2076 s->last_mv_dir = 0;
2077
2078 switch(s->codec_id){
2079 case CODEC_ID_H263:
2080 case CODEC_ID_H263P:
2081 case CODEC_ID_FLV1:
0bd48530 2082 if (CONFIG_H263_ENCODER)
674eeb5f 2083 s->gob_index = ff_h263_get_gob_height(s);
3ada94ba
BF
2084 break;
2085 case CODEC_ID_MPEG4:
49fb20cb 2086 if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
3ada94ba
BF
2087 ff_mpeg4_init_partitions(s);
2088 break;
2089 }
2090
2091 s->resync_mb_x=0;
2092 s->resync_mb_y=0;
2093 s->first_slice_line = 1;
2094 s->ptr_lastgob = s->pb.buf;
2095 for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
2096// printf("row %d at %X\n", s->mb_y, (int)s);
2097 s->mb_x=0;
2098 s->mb_y= mb_y;
2099
2100 ff_set_qscale(s, s->qscale);
2101 ff_init_block_index(s);
2102
2103 for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2104 int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
2105 int mb_type= s->mb_type[xy];
2106// int d;
2107 int dmin= INT_MAX;
2108 int dir;
2109
2110 if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
2111 av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
2112 return -1;
2113 }
2114 if(s->data_partitioning){
2115 if( s->pb2 .buf_end - s->pb2 .buf - (put_bits_count(&s-> pb2)>>3) < MAX_MB_BYTES
2116 || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
2117 av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
2118 return -1;
2119 }
2120 }
2121
2122 s->mb_x = mb_x;
2123 s->mb_y = mb_y; // moved into loop, can get changed by H.261
2124 ff_update_block_index(s);
2125
49fb20cb 2126 if(CONFIG_H261_ENCODER && s->codec_id == CODEC_ID_H261){
3ada94ba
BF
2127 ff_h261_reorder_mb_index(s);
2128 xy= s->mb_y*s->mb_stride + s->mb_x;
2129 mb_type= s->mb_type[xy];
2130 }
2131
2132 /* write gob / video packet header */
2133 if(s->rtp_mode){
2134 int current_packet_size, is_gob_start;
2135
2136 current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
2137
2138 is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
2139
2140 if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
2141
2142 switch(s->codec_id){
2143 case CODEC_ID_H263:
2144 case CODEC_ID_H263P:
2145 if(!s->h263_slice_structured)
2146 if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
2147 break;
2148 case CODEC_ID_MPEG2VIDEO:
2149 if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
2150 case CODEC_ID_MPEG1VIDEO:
2151 if(s->mb_skip_run) is_gob_start=0;
2152 break;
2153 }
2154
2155 if(is_gob_start){
2156 if(s->start_mb_y != mb_y || mb_x!=0){
2157 write_slice_end(s);
2158
49fb20cb 2159 if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
3ada94ba
BF
2160 ff_mpeg4_init_partitions(s);
2161 }
2162 }
2163
2164 assert((put_bits_count(&s->pb)&7) == 0);
fb53b4a0 2165 current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
3ada94ba
BF
2166
2167 if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
2168 int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
2169 int d= 100 / s->avctx->error_rate;
2170 if(r % d == 0){
2171 current_packet_size=0;
2172#ifndef ALT_BITSTREAM_WRITER
2173 s->pb.buf_ptr= s->ptr_lastgob;
2174#endif
fb53b4a0 2175 assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
3ada94ba
BF
2176 }
2177 }
2178
2179 if (s->avctx->rtp_callback){
2180 int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
2181 s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
2182 }
2183
2184 switch(s->codec_id){
2185 case CODEC_ID_MPEG4:
49fb20cb 2186 if (CONFIG_MPEG4_ENCODER) {
674eeb5f
AJ
2187 ff_mpeg4_encode_video_packet_header(s);
2188 ff_mpeg4_clean_buffers(s);
eb75a698 2189 }
3ada94ba
BF
2190 break;
2191 case CODEC_ID_MPEG1VIDEO:
2192 case CODEC_ID_MPEG2VIDEO:
49fb20cb 2193 if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
56be950a
AJ
2194 ff_mpeg1_encode_slice_header(s);
2195 ff_mpeg1_clean_buffers(s);
a6bc5731 2196 }
3ada94ba
BF
2197 break;
2198 case CODEC_ID_H263:
2199 case CODEC_ID_H263P:
965424da 2200 if (CONFIG_H263_ENCODER)
674eeb5f 2201 h263_encode_gob_header(s, mb_y);
3ada94ba
BF
2202 break;
2203 }
2204
2205 if(s->flags&CODEC_FLAG_PASS1){
2206 int bits= put_bits_count(&s->pb);
2207 s->misc_bits+= bits - s->last_bits;
2208 s->last_bits= bits;
2209 }
2210
2211 s->ptr_lastgob += current_packet_size;
2212 s->first_slice_line=1;
2213 s->resync_mb_x=mb_x;
2214 s->resync_mb_y=mb_y;
2215 }
2216 }
2217
2218 if( (s->resync_mb_x == s->mb_x)
2219 && s->resync_mb_y+1 == s->mb_y){
2220 s->first_slice_line=0;
2221 }
2222
2223 s->mb_skipped=0;
2224 s->dquant=0; //only for QP_RD
2225
2226 if(mb_type & (mb_type-1) || (s->flags & CODEC_FLAG_QP_RD)){ // more than 1 MB type possible or CODEC_FLAG_QP_RD
2227 int next_block=0;
2228 int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
2229
2230 copy_context_before_encode(&backup_s, s, -1);
2231 backup_s.pb= s->pb;
2232 best_s.data_partitioning= s->data_partitioning;
2233 best_s.partitioned_frame= s->partitioned_frame;
2234 if(s->data_partitioning){
2235 backup_s.pb2= s->pb2;
2236 backup_s.tex_pb= s->tex_pb;
2237 }
2238
2239 if(mb_type&CANDIDATE_MB_TYPE_INTER){
2240 s->mv_dir = MV_DIR_FORWARD;
2241 s->mv_type = MV_TYPE_16X16;
2242 s->mb_intra= 0;
2243 s->mv[0][0][0] = s->p_mv_table[xy][0];
2244 s->mv[0][0][1] = s->p_mv_table[xy][1];
2245 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
2246 &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2247 }
2248 if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
2249 s->mv_dir = MV_DIR_FORWARD;
2250 s->mv_type = MV_TYPE_FIELD;
2251 s->mb_intra= 0;
2252 for(i=0; i<2; i++){
2253 j= s->field_select[0][i] = s->p_field_select_table[i][xy];
2254 s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
2255 s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
2256 }
2257 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
2258 &dmin, &next_block, 0, 0);
2259 }
2260 if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
2261 s->mv_dir = MV_DIR_FORWARD;
2262 s->mv_type = MV_TYPE_16X16;
2263 s->mb_intra= 0;
2264 s->mv[0][0][0] = 0;
2265 s->mv[0][0][1] = 0;
2266 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
2267 &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2268 }
2269 if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
2270 s->mv_dir = MV_DIR_FORWARD;
2271 s->mv_type = MV_TYPE_8X8;
2272 s->mb_intra= 0;
2273 for(i=0; i<4; i++){
2274 s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
2275 s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
2276 }
2277 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
2278 &dmin, &next_block, 0, 0);
2279 }
2280 if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
2281 s->mv_dir = MV_DIR_FORWARD;
2282 s->mv_type = MV_TYPE_16X16;
2283 s->mb_intra= 0;
2284 s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
2285 s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
2286 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
2287 &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2288 }
2289 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
2290 s->mv_dir = MV_DIR_BACKWARD;
2291 s->mv_type = MV_TYPE_16X16;
2292 s->mb_intra= 0;
2293 s->mv[1][0][0] = s->b_back_mv_table[xy][0];
2294 s->mv[1][0][1] = s->b_back_mv_table[xy][1];
2295 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
2296 &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
2297 }
2298 if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
2299 s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2300 s->mv_type = MV_TYPE_16X16;
2301 s->mb_intra= 0;
2302 s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
2303 s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
2304 s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
2305 s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
2306 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
2307 &dmin, &next_block, 0, 0);
2308 }
2309 if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
2310 s->mv_dir = MV_DIR_FORWARD;
2311 s->mv_type = MV_TYPE_FIELD;
2312 s->mb_intra= 0;
2313 for(i=0; i<2; i++){
2314 j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
2315 s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
2316 s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
2317 }
2318 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
2319 &dmin, &next_block, 0, 0);
2320 }
2321 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
2322 s->mv_dir = MV_DIR_BACKWARD;
2323 s->mv_type = MV_TYPE_FIELD;
2324 s->mb_intra= 0;
2325 for(i=0; i<2; i++){
2326 j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
2327 s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
2328 s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
2329 }
2330 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
2331 &dmin, &next_block, 0, 0);
2332 }
2333 if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
2334 s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2335 s->mv_type = MV_TYPE_FIELD;
2336 s->mb_intra= 0;
2337 for(dir=0; dir<2; dir++){
2338 for(i=0; i<2; i++){
2339 j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
2340 s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
2341 s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
2342 }
2343 }
2344 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
2345 &dmin, &next_block, 0, 0);
2346 }
2347 if(mb_type&CANDIDATE_MB_TYPE_INTRA){
2348 s->mv_dir = 0;
2349 s->mv_type = MV_TYPE_16X16;
2350 s->mb_intra= 1;
2351 s->mv[0][0][0] = 0;
2352 s->mv[0][0][1] = 0;
2353 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
2354 &dmin, &next_block, 0, 0);
2355 if(s->h263_pred || s->h263_aic){
2356 if(best_s.mb_intra)
2357 s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
2358 else
2359 ff_clean_intra_table_entries(s); //old mode?
2360 }
2361 }
2362
2363 if((s->flags & CODEC_FLAG_QP_RD) && dmin < INT_MAX){
2364 if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
2365 const int last_qp= backup_s.qscale;
2366 int qpi, qp, dc[6];
2367 DCTELEM ac[6][16];
2368 const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
2369 static const int dquant_tab[4]={-1,1,-2,2};
2370
2371 assert(backup_s.dquant == 0);
2372
2373 //FIXME intra
2374 s->mv_dir= best_s.mv_dir;
2375 s->mv_type = MV_TYPE_16X16;
2376 s->mb_intra= best_s.mb_intra;
2377 s->mv[0][0][0] = best_s.mv[0][0][0];
2378 s->mv[0][0][1] = best_s.mv[0][0][1];
2379 s->mv[1][0][0] = best_s.mv[1][0][0];
2380 s->mv[1][0][1] = best_s.mv[1][0][1];
2381
975a1447 2382 qpi = s->pict_type == AV_PICTURE_TYPE_B ? 2 : 0;
3ada94ba
BF
2383 for(; qpi<4; qpi++){
2384 int dquant= dquant_tab[qpi];
2385 qp= last_qp + dquant;
2386 if(qp < s->avctx->qmin || qp > s->avctx->qmax)
2387 continue;
2388 backup_s.dquant= dquant;
2389 if(s->mb_intra && s->dc_val[0]){
2390 for(i=0; i<6; i++){
2391 dc[i]= s->dc_val[0][ s->block_index[i] ];
2392 memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(DCTELEM)*16);
2393 }
2394 }
2395
2396 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
2397 &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
2398 if(best_s.qscale != qp){
2399 if(s->mb_intra && s->dc_val[0]){
2400 for(i=0; i<6; i++){
2401 s->dc_val[0][ s->block_index[i] ]= dc[i];
2402 memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(DCTELEM)*16);
2403 }
2404 }
2405 }
2406 }
2407 }
2408 }
49fb20cb 2409 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
3ada94ba
BF
2410 int mx= s->b_direct_mv_table[xy][0];
2411 int my= s->b_direct_mv_table[xy][1];
2412
2413 backup_s.dquant = 0;
2414 s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2415 s->mb_intra= 0;
2416 ff_mpeg4_set_direct_mv(s, mx, my);
2417 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
2418 &dmin, &next_block, mx, my);
2419 }
49fb20cb 2420 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
3ada94ba
BF
2421 backup_s.dquant = 0;
2422 s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2423 s->mb_intra= 0;
2424 ff_mpeg4_set_direct_mv(s, 0, 0);
2425 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
2426 &dmin, &next_block, 0, 0);
2427 }
2428 if(!best_s.mb_intra && s->flags2&CODEC_FLAG2_SKIP_RD){
2429 int coded=0;
2430 for(i=0; i<6; i++)
2431 coded |= s->block_last_index[i];
2432 if(coded){
2433 int mx,my;
2434 memcpy(s->mv, best_s.mv, sizeof(s->mv));
49fb20cb 2435 if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
3ada94ba
BF
2436 mx=my=0; //FIXME find the one we actually used
2437 ff_mpeg4_set_direct_mv(s, mx, my);
2438 }else if(best_s.mv_dir&MV_DIR_BACKWARD){
2439 mx= s->mv[1][0][0];
2440 my= s->mv[1][0][1];
2441 }else{
2442 mx= s->mv[0][0][0];
2443 my= s->mv[0][0][1];
2444 }
2445
2446 s->mv_dir= best_s.mv_dir;
2447 s->mv_type = best_s.mv_type;
2448 s->mb_intra= 0;
2449/* s->mv[0][0][0] = best_s.mv[0][0][0];
2450 s->mv[0][0][1] = best_s.mv[0][0][1];
2451 s->mv[1][0][0] = best_s.mv[1][0][0];
2452 s->mv[1][0][1] = best_s.mv[1][0][1];*/
2453 backup_s.dquant= 0;
2454 s->skipdct=1;
2455 encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
2456 &dmin, &next_block, mx, my);
2457 s->skipdct=0;
2458 }
2459 }
2460
2461 s->current_picture.qscale_table[xy]= best_s.qscale;
2462
2463 copy_context_after_encode(s, &best_s, -1);
2464
2465 pb_bits_count= put_bits_count(&s->pb);
2466 flush_put_bits(&s->pb);
2467 ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
2468 s->pb= backup_s.pb;
2469
2470 if(s->data_partitioning){
2471 pb2_bits_count= put_bits_count(&s->pb2);
2472 flush_put_bits(&s->pb2);
2473 ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
2474 s->pb2= backup_s.pb2;
2475
2476 tex_pb_bits_count= put_bits_count(&s->tex_pb);
2477 flush_put_bits(&s->tex_pb);
2478 ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
2479 s->tex_pb= backup_s.tex_pb;
2480 }
2481 s->last_bits= put_bits_count(&s->pb);
2482
f34121f3 2483 if (CONFIG_H263_ENCODER &&
975a1447 2484 s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
3ada94ba
BF
2485 ff_h263_update_motion_val(s);
2486
2487 if(next_block==0){ //FIXME 16 vs linesize16
2488 s->dsp.put_pixels_tab[0][0](s->dest[0], s->rd_scratchpad , s->linesize ,16);
2489 s->dsp.put_pixels_tab[1][0](s->dest[1], s->rd_scratchpad + 16*s->linesize , s->uvlinesize, 8);
2490 s->dsp.put_pixels_tab[1][0](s->dest[2], s->rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
2491 }
2492
2493 if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
2494 MPV_decode_mb(s, s->block);
2495 } else {
2496 int motion_x = 0, motion_y = 0;
2497 s->mv_type=MV_TYPE_16X16;
2498 // only one MB-Type possible
2499
2500 switch(mb_type){
2501 case CANDIDATE_MB_TYPE_INTRA:
2502 s->mv_dir = 0;
2503 s->mb_intra= 1;
2504 motion_x= s->mv[0][0][0] = 0;
2505 motion_y= s->mv[0][0][1] = 0;
2506 break;
2507 case CANDIDATE_MB_TYPE_INTER:
2508 s->mv_dir = MV_DIR_FORWARD;
2509 s->mb_intra= 0;
2510 motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
2511 motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
2512 break;
2513 case CANDIDATE_MB_TYPE_INTER_I:
2514 s->mv_dir = MV_DIR_FORWARD;
2515 s->mv_type = MV_TYPE_FIELD;
2516 s->mb_intra= 0;
2517 for(i=0; i<2; i++){
2518 j= s->field_select[0][i] = s->p_field_select_table[i][xy];
2519 s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
2520 s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
2521 }
2522 break;
2523 case CANDIDATE_MB_TYPE_INTER4V:
2524 s->mv_dir = MV_DIR_FORWARD;
2525 s->mv_type = MV_TYPE_8X8;
2526 s->mb_intra= 0;
2527 for(i=0; i<4; i++){
2528 s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
2529 s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
2530 }
2531 break;
2532 case CANDIDATE_MB_TYPE_DIRECT:
49fb20cb 2533 if (CONFIG_MPEG4_ENCODER) {
674eeb5f
AJ
2534 s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
2535 s->mb_intra= 0;
2536 motion_x=s->b_direct_mv_table[xy][0];
2537 motion_y=s->b_direct_mv_table[xy][1];
2538 ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
eb75a698 2539 }
3ada94ba
BF
2540 break;
2541 case CANDIDATE_MB_TYPE_DIRECT0:
49fb20cb 2542 if (CONFIG_MPEG4_ENCODER) {
674eeb5f
AJ
2543 s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
2544 s->mb_intra= 0;
2545 ff_mpeg4_set_direct_mv(s, 0, 0);
eb75a698 2546 }
3ada94ba
BF
2547 break;
2548 case CANDIDATE_MB_TYPE_BIDIR:
2549 s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2550 s->mb_intra= 0;
2551 s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
2552 s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
2553 s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
2554 s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
2555 break;
2556 case CANDIDATE_MB_TYPE_BACKWARD:
2557 s->mv_dir = MV_DIR_BACKWARD;
2558 s->mb_intra= 0;
2559 motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
2560 motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
2561 break;
2562 case CANDIDATE_MB_TYPE_FORWARD:
2563 s->mv_dir = MV_DIR_FORWARD;
2564 s->mb_intra= 0;
2565 motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
2566 motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
2567// printf(" %d %d ", motion_x, motion_y);
2568 break;
2569 case CANDIDATE_MB_TYPE_FORWARD_I:
2570 s->mv_dir = MV_DIR_FORWARD;
2571 s->mv_type = MV_TYPE_FIELD;
2572 s->mb_intra= 0;
2573 for(i=0; i<2; i++){
2574 j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
2575 s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
2576 s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
2577 }
2578 break;
2579 case CANDIDATE_MB_TYPE_BACKWARD_I:
2580 s->mv_dir = MV_DIR_BACKWARD;
2581 s->mv_type = MV_TYPE_FIELD;
2582 s->mb_intra= 0;
2583 for(i=0; i<2; i++){
2584 j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
2585 s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
2586 s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
2587 }
2588 break;
2589 case CANDIDATE_MB_TYPE_BIDIR_I:
2590 s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2591 s->mv_type = MV_TYPE_FIELD;
2592 s->mb_intra= 0;
2593 for(dir=0; dir<2; dir++){
2594 for(i=0; i<2; i++){
2595 j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
2596 s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
2597 s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
2598 }
2599 }
2600 break;
2601 default:
2602 av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
2603 }
2604
2605 encode_mb(s, motion_x, motion_y);
2606
2607 // RAL: Update last macroblock type
2608 s->last_mv_dir = s->mv_dir;
2609
f34121f3 2610 if (CONFIG_H263_ENCODER &&
975a1447 2611 s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
3ada94ba
BF
2612 ff_h263_update_motion_val(s);
2613
2614 MPV_decode_mb(s, s->block);
2615 }
2616
2617 /* clean the MV table in IPS frames for direct mode in B frames */
2618 if(s->mb_intra /* && I,P,S_TYPE */){
2619 s->p_mv_table[xy][0]=0;
2620 s->p_mv_table[xy][1]=0;
2621 }
2622
2623 if(s->flags&CODEC_FLAG_PSNR){
2624 int w= 16;
2625 int h= 16;
2626
2627 if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
2628 if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
2629
2630 s->current_picture.error[0] += sse(
2631 s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
2632 s->dest[0], w, h, s->linesize);
2633 s->current_picture.error[1] += sse(
ec7e2582
BC
2634 s, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
2635 s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
3ada94ba 2636 s->current_picture.error[2] += sse(
ec7e2582
BC
2637 s, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
2638 s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
3ada94ba
BF
2639 }
2640 if(s->loop_filter){
f34121f3 2641 if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
3ada94ba
BF
2642 ff_h263_loop_filter(s);
2643 }
2644//printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, put_bits_count(&s->pb));
2645 }
2646 }
2647
2648 //not beautiful here but we must write it before flushing so it has to be here
975a1447 2649 if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == AV_PICTURE_TYPE_I)
3ada94ba
BF
2650 msmpeg4_encode_ext_header(s);
2651
2652 write_slice_end(s);
2653
2654 /* Send the last GOB if RTP */
2655 if (s->avctx->rtp_callback) {
2656 int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
fb53b4a0 2657 pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
3ada94ba
BF
2658 /* Call the RTP callback to send the last GOB */
2659 emms_c();
2660 s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
2661 }
2662
2663 return 0;
2664}
2665
2666#define MERGE(field) dst->field += src->field; src->field=0
2667static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
2668 MERGE(me.scene_change_score);
2669 MERGE(me.mc_mb_var_sum_temp);
2670 MERGE(me.mb_var_sum_temp);
2671}
2672
2673static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
2674 int i;
2675
2676 MERGE(dct_count[0]); //note, the other dct vars are not part of the context
2677 MERGE(dct_count[1]);
2678 MERGE(mv_bits);
2679 MERGE(i_tex_bits);
2680 MERGE(p_tex_bits);
2681 MERGE(i_count);
2682 MERGE(f_count);
2683 MERGE(b_count);
2684 MERGE(skip_count);
2685 MERGE(misc_bits);
2686 MERGE(error_count);
2687 MERGE(padding_bug_score);
2688 MERGE(current_picture.error[0]);
2689 MERGE(current_picture.error[1]);
2690 MERGE(current_picture.error[2]);
2691
2692 if(dst->avctx->noise_reduction){
2693 for(i=0; i<64; i++){
2694 MERGE(dct_error_sum[0][i]);
2695 MERGE(dct_error_sum[1][i]);
2696 }
2697 }
2698
2699 assert(put_bits_count(&src->pb) % 8 ==0);
2700 assert(put_bits_count(&dst->pb) % 8 ==0);
2701 ff_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
2702 flush_put_bits(&dst->pb);
2703}
2704
2705static int estimate_qp(MpegEncContext *s, int dry_run){
2706 if (s->next_lambda){
2707 s->current_picture_ptr->quality=
2708 s->current_picture.quality = s->next_lambda;
2709 if(!dry_run) s->next_lambda= 0;
2710 } else if (!s->fixed_qscale) {
2711 s->current_picture_ptr->quality=
2712 s->current_picture.quality = ff_rate_estimate_qscale(s, dry_run);
2713 if (s->current_picture.quality < 0)
2714 return -1;
2715 }
2716
2717 if(s->adaptive_quant){
2718 switch(s->codec_id){
2719 case CODEC_ID_MPEG4:
49fb20cb 2720 if (CONFIG_MPEG4_ENCODER)
674eeb5f 2721 ff_clean_mpeg4_qscales(s);
3ada94ba
BF
2722 break;
2723 case CODEC_ID_H263:
2724 case CODEC_ID_H263P:
2725 case CODEC_ID_FLV1:
0bd48530 2726 if (CONFIG_H263_ENCODER)
674eeb5f 2727 ff_clean_h263_qscales(s);
3ada94ba 2728 break;
ccc4b918
MN
2729 default:
2730 ff_init_qscale_tab(s);
3ada94ba
BF
2731 }
2732
2733 s->lambda= s->lambda_table[0];
2734 //FIXME broken
2735 }else
2736 s->lambda= s->current_picture.quality;
2737//printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
2738 update_qscale(s);
2739 return 0;
2740}
2741
7da31a80
AJ
2742/* must be called before writing the header */
2743static void set_frame_distances(MpegEncContext * s){
2744 assert(s->current_picture_ptr->pts != AV_NOPTS_VALUE);
2745 s->time= s->current_picture_ptr->pts*s->avctx->time_base.num;
2746
975a1447 2747 if(s->pict_type==AV_PICTURE_TYPE_B){
7da31a80
AJ
2748 s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
2749 assert(s->pb_time > 0 && s->pb_time < s->pp_time);
2750 }else{
2751 s->pp_time= s->time - s->last_non_b_time;
2752 s->last_non_b_time= s->time;
2753 assert(s->picture_number==0 || s->pp_time > 0);
2754 }
2755}
2756
3ada94ba
BF
2757static int encode_picture(MpegEncContext *s, int picture_number)
2758{
2759 int i;
2760 int bits;
2761
2762 s->picture_number = picture_number;
2763
2764 /* Reset the average MB variance */
2765 s->me.mb_var_sum_temp =
2766 s->me.mc_mb_var_sum_temp = 0;
2767
2768 /* we need to initialize some time vars before we can encode b-frames */
2769 // RAL: Condition added for MPEG1VIDEO
8c51620f 2770 if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->msmpeg4_version))
7da31a80 2771 set_frame_distances(s);
49fb20cb 2772 if(CONFIG_MPEG4_ENCODER && s->codec_id == CODEC_ID_MPEG4)
7da31a80 2773 ff_set_mpeg4_time(s);
3ada94ba
BF
2774
2775 s->me.scene_change_score=0;
2776
e6dba5df 2777// s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
3ada94ba 2778
975a1447 2779 if(s->pict_type==AV_PICTURE_TYPE_I){
3ada94ba
BF
2780 if(s->msmpeg4_version >= 3) s->no_rounding=1;
2781 else s->no_rounding=0;
975a1447 2782 }else if(s->pict_type!=AV_PICTURE_TYPE_B){
3ada94ba
BF
2783 if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
2784 s->no_rounding ^= 1;
2785 }
2786
2787 if(s->flags & CODEC_FLAG_PASS2){
2788 if (estimate_qp(s,1) < 0)
2789 return -1;
2790 ff_get_2pass_fcode(s);
2791 }else if(!(s->flags & CODEC_FLAG_QSCALE)){
975a1447 2792 if(s->pict_type==AV_PICTURE_TYPE_B)
3ada94ba
BF
2793 s->lambda= s->last_lambda_for[s->pict_type];
2794 else
2795 s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
2796 update_qscale(s);
2797 }
2798
2799 s->mb_intra=0; //for the rate distortion & bit compare functions
2800 for(i=1; i<s->avctx->thread_count; i++){
2801 ff_update_duplicate_context(s->thread_context[i], s);
2802 }
2803
719f3702
MN
2804 if(ff_init_me(s)<0)
2805 return -1;
3ada94ba
BF
2806
2807 /* Estimate motion for every MB */
975a1447 2808 if(s->pict_type != AV_PICTURE_TYPE_I){
3ada94ba
BF
2809 s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
2810 s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
975a1447
SS
2811 if(s->pict_type != AV_PICTURE_TYPE_B && s->avctx->me_threshold==0){
2812 if((s->avctx->pre_me && s->last_non_b_pict_type==AV_PICTURE_TYPE_I) || s->avctx->pre_me==2){
01418506 2813 s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
3ada94ba
BF
2814 }
2815 }
2816
01418506 2817 s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
975a1447 2818 }else /* if(s->pict_type == AV_PICTURE_TYPE_I) */{
3ada94ba
BF
2819 /* I-Frame */
2820 for(i=0; i<s->mb_stride*s->mb_height; i++)
2821 s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
2822
2823 if(!s->fixed_qscale){
2824 /* finding spatial complexity for I-frame rate control */
01418506 2825 s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
3ada94ba
BF
2826 }
2827 }
2828 for(i=1; i<s->avctx->thread_count; i++){
2829 merge_context_after_me(s, s->thread_context[i]);
2830 }
2831 s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
2832 s->current_picture. mb_var_sum= s->current_picture_ptr-> mb_var_sum= s->me. mb_var_sum_temp;
2833 emms_c();
2834
975a1447
SS
2835 if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == AV_PICTURE_TYPE_P){
2836 s->pict_type= AV_PICTURE_TYPE_I;
3ada94ba
BF
2837 for(i=0; i<s->mb_stride*s->mb_height; i++)
2838 s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
2839//printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
2840 }
2841
2842 if(!s->umvplus){
975a1447 2843 if(s->pict_type==AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
3ada94ba
BF
2844 s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
2845
2846 if(s->flags & CODEC_FLAG_INTERLACED_ME){
2847 int a,b;
2848 a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
2849 b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
159ef4b0 2850 s->f_code= FFMAX3(s->f_code, a, b);
3ada94ba
BF
2851 }
2852
2853 ff_fix_long_p_mvs(s);
2854 ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
2855 if(s->flags & CODEC_FLAG_INTERLACED_ME){
2856 int j;
2857 for(i=0; i<2; i++){
2858 for(j=0; j<2; j++)
2859 ff_fix_long_mvs(s, s->p_field_select_table[i], j,
2860 s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
2861 }
2862 }
2863 }
2864
975a1447 2865 if(s->pict_type==AV_PICTURE_TYPE_B){
3ada94ba
BF
2866 int a, b;
2867
2868 a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
2869 b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
2870 s->f_code = FFMAX(a, b);
2871
2872 a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
2873 b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
2874 s->b_code = FFMAX(a, b);
2875
2876 ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
2877 ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
2878 ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
2879 ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
2880 if(s->flags & CODEC_FLAG_INTERLACED_ME){
2881 int dir, j;
2882 for(dir=0; dir<2; dir++){
2883 for(i=0; i<2; i++){
2884 for(j=0; j<2; j++){
2885 int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
2886 : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
2887 ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
2888 s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
2889 }
2890 }
2891 }
2892 }
2893 }
2894 }
2895
2896 if (estimate_qp(s, 0) < 0)
2897 return -1;
2898
975a1447 2899 if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==AV_PICTURE_TYPE_I && !(s->flags & CODEC_FLAG_QSCALE))
3ada94ba
BF
2900 s->qscale= 3; //reduce clipping problems
2901
2902 if (s->out_format == FMT_MJPEG) {
2903 /* for mjpeg, we do include qscale in the matrix */
3ada94ba
BF
2904 for(i=1;i<64;i++){
2905 int j= s->dsp.idct_permutation[i];
2906
2907 s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
2908 }
6506c3d2 2909 s->y_dc_scale_table=
53f66cee
MN
2910 s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];
2911 s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];
69cea75f 2912 ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
3ada94ba
BF
2913 s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
2914 s->qscale= 8;
2915 }
2916
2917 //FIXME var duplication
2918 s->current_picture_ptr->key_frame=
975a1447 2919 s->current_picture.key_frame= s->pict_type == AV_PICTURE_TYPE_I; //FIXME pic_ptr
3ada94ba
BF
2920 s->current_picture_ptr->pict_type=
2921 s->current_picture.pict_type= s->pict_type;
2922
2923 if(s->current_picture.key_frame)
2924 s->picture_in_gop_number=0;
2925
2926 s->last_bits= put_bits_count(&s->pb);
2927 switch(s->out_format) {
2928 case FMT_MJPEG:
49fb20cb 2929 if (CONFIG_MJPEG_ENCODER)
3ada94ba
BF
2930 ff_mjpeg_encode_picture_header(s);
2931 break;
2932 case FMT_H261:
49fb20cb 2933 if (CONFIG_H261_ENCODER)
3ada94ba
BF
2934 ff_h261_encode_picture_header(s, picture_number);
2935 break;
2936 case FMT_H263:
49fb20cb 2937 if (CONFIG_WMV2_ENCODER && s->codec_id == CODEC_ID_WMV2)
3ada94ba 2938 ff_wmv2_encode_picture_header(s, picture_number);
8c51620f 2939 else if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
3ada94ba 2940 msmpeg4_encode_picture_header(s, picture_number);
49fb20cb 2941 else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
3ada94ba 2942 mpeg4_encode_picture_header(s, picture_number);
49fb20cb 2943 else if (CONFIG_RV10_ENCODER && s->codec_id == CODEC_ID_RV10)
3ada94ba 2944 rv10_encode_picture_header(s, picture_number);
49fb20cb 2945 else if (CONFIG_RV20_ENCODER && s->codec_id == CODEC_ID_RV20)
3ada94ba 2946 rv20_encode_picture_header(s, picture_number);
49fb20cb 2947 else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
3ada94ba 2948 ff_flv_encode_picture_header(s, picture_number);
f34121f3 2949 else if (CONFIG_H263_ENCODER)
3ada94ba
BF
2950 h263_encode_picture_header(s, picture_number);
2951 break;
2952 case FMT_MPEG1:
49fb20cb 2953 if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
56be950a 2954 mpeg1_encode_picture_header(s, picture_number);
3ada94ba
BF
2955 break;
2956 case FMT_H264:
2957 break;
2958 default:
2959 assert(0);
2960 }
2961 bits= put_bits_count(&s->pb);
2962 s->header_bits= bits - s->last_bits;
2963
2964 for(i=1; i<s->avctx->thread_count; i++){
2965 update_duplicate_context_after_me(s->thread_context[i], s);
2966 }
01418506 2967 s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
3ada94ba
BF
2968 for(i=1; i<s->avctx->thread_count; i++){
2969 merge_context_after_encode(s, s->thread_context[i]);
2970 }
2971 emms_c();
2972 return 0;
2973}
2974
aa61e39e 2975static void denoise_dct_c(MpegEncContext *s, DCTELEM *block){
3ada94ba
BF
2976 const int intra= s->mb_intra;
2977 int i;
2978
2979 s->dct_count[intra]++;
2980
2981 for(i=0; i<64; i++){
2982 int level= block[i];
2983
2984 if(level){
2985 if(level>0){
2986 s->dct_error_sum[intra][i] += level;
2987 level -= s->dct_offset[intra][i];
2988 if(level<0) level=0;
2989 }else{
2990 s->dct_error_sum[intra][i] -= level;
2991 level += s->dct_offset[intra][i];
2992 if(level>0) level=0;
2993 }
2994 block[i]= level;
2995 }
2996 }
2997}
2998
aa61e39e
MR
2999static int dct_quantize_trellis_c(MpegEncContext *s,
3000 DCTELEM *block, int n,
3001 int qscale, int *overflow){
3ada94ba
BF
3002 const int *qmat;
3003 const uint8_t *scantable= s->intra_scantable.scantable;
3004 const uint8_t *perm_scantable= s->intra_scantable.permutated;
3005 int max=0;
3006 unsigned int threshold1, threshold2;
3007 int bias=0;
3008 int run_tab[65];
3009 int level_tab[65];
3010 int score_tab[65];
3011 int survivor[65];
3012 int survivor_count;
3013 int last_run=0;
3014 int last_level=0;
3015 int last_score= 0;
3016 int last_i;
3017 int coeff[2][64];
3018 int coeff_count[64];
3019 int qmul, qadd, start_i, last_non_zero, i, dc;
3020 const int esc_length= s->ac_esc_length;
3021 uint8_t * length;
3022 uint8_t * last_length;
3023 const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
3024
3025 s->dsp.fdct (block);
3026
3027 if(s->dct_error_sum)
3028 s->denoise_dct(s, block);
3029 qmul= qscale*16;
3030 qadd= ((qscale-1)|1)*8;
3031
3032 if (s->mb_intra) {
3033 int q;
3034 if (!s->h263_aic) {
3035 if (n < 4)
3036 q = s->y_dc_scale;
3037 else
3038 q = s->c_dc_scale;
3039 q = q << 3;
3040 } else{
3041 /* For AIC we skip quant/dequant of INTRADC */
3042 q = 1 << 3;
3043 qadd=0;
3044 }
3045
3046 /* note: block[0] is assumed to be positive */
3047 block[0] = (block[0] + (q >> 1)) / q;
3048 start_i = 1;
3049 last_non_zero = 0;
3050 qmat = s->q_intra_matrix[qscale];
3051 if(s->mpeg_quant || s->out_format == FMT_MPEG1)
3052 bias= 1<<(QMAT_SHIFT-1);
3053 length = s->intra_ac_vlc_length;
3054 last_length= s->intra_ac_vlc_last_length;
3055 } else {
3056 start_i = 0;
3057 last_non_zero = -1;
3058 qmat = s->q_inter_matrix[qscale];
3059 length = s->inter_ac_vlc_length;
3060 last_length= s->inter_ac_vlc_last_length;
3061 }
3062 last_i= start_i;
3063
3064 threshold1= (1<<QMAT_SHIFT) - bias - 1;
3065 threshold2= (threshold1<<1);
3066
3067 for(i=63; i>=start_i; i--) {
3068 const int j = scantable[i];
3069 int level = block[j] * qmat[j];
3070
3071 if(((unsigned)(level+threshold1))>threshold2){
3072 last_non_zero = i;
3073 break;
3074 }
3075 }
3076
3077 for(i=start_i; i<=last_non_zero; i++) {
3078 const int j = scantable[i];
3079 int level = block[j] * qmat[j];
3080
3081// if( bias+level >= (1<<(QMAT_SHIFT - 3))
3082// || bias-level >= (1<<(QMAT_SHIFT - 3))){
3083 if(((unsigned)(level+threshold1))>threshold2){
3084 if(level>0){
3085 level= (bias + level)>>QMAT_SHIFT;
3086 coeff[0][i]= level;
3087 coeff[1][i]= level-1;
3088// coeff[2][k]= level-2;
3089 }else{
3090 level= (bias - level)>>QMAT_SHIFT;
3091 coeff[0][i]= -level;
3092 coeff[1][i]= -level+1;
3093// coeff[2][k]= -level+2;
3094 }
3095 coeff_count[i]= FFMIN(level, 2);
3096 assert(coeff_count[i]);
3097 max |=level;
3098 }else{
3099 coeff[0][i]= (level>>31)|1;
3100 coeff_count[i]= 1;
3101 }
3102 }
3103
3104 *overflow= s->max_qcoeff < max; //overflow might have happened
3105
3106 if(last_non_zero < start_i){
3107 memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
3108 return last_non_zero;
3109 }
3110
3111 score_tab[start_i]= 0;
3112 survivor[0]= start_i;
3113 survivor_count= 1;
3114
3115 for(i=start_i; i<=last_non_zero; i++){
e6dba5df 3116 int level_index, j, zero_distortion;
b6bffc46 3117 int dct_coeff= FFABS(block[ scantable[i] ]);
3ada94ba 3118 int best_score=256*256*256*120;
b6bffc46
MN
3119
3120 if ( s->dsp.fdct == fdct_ifast
3121#ifndef FAAN_POSTSCALE
3122 || s->dsp.fdct == ff_faandct
3123#endif
3124 )
939e4e3a 3125 dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
e6dba5df 3126 zero_distortion= dct_coeff*dct_coeff;
b6bffc46 3127
3ada94ba 3128 for(level_index=0; level_index < coeff_count[i]; level_index++){
e6dba5df 3129 int distortion;
3ada94ba
BF
3130 int level= coeff[level_index][i];
3131 const int alevel= FFABS(level);
3132 int unquant_coeff;
3133
3134 assert(level);
3135
3136 if(s->out_format == FMT_H263){
3137 unquant_coeff= alevel*qmul + qadd;
3138 }else{ //MPEG1
3139 j= s->dsp.idct_permutation[ scantable[i] ]; //FIXME optimize
3140 if(s->mb_intra){
3141 unquant_coeff = (int)( alevel * qscale * s->intra_matrix[j]) >> 3;
3142 unquant_coeff = (unquant_coeff - 1) | 1;
3143 }else{
3144 unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
3145 unquant_coeff = (unquant_coeff - 1) | 1;
3146 }
3147 unquant_coeff<<= 3;
3148 }
3149
e6dba5df 3150 distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
3ada94ba
BF
3151 level+=64;
3152 if((level&(~127)) == 0){
3153 for(j=survivor_count-1; j>=0; j--){
3154 int run= i - survivor[j];
e6dba5df 3155 int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
3ada94ba
BF
3156 score += score_tab[i-run];
3157
3158 if(score < best_score){
3159 best_score= score;
3160 run_tab[i+1]= run;
3161 level_tab[i+1]= level-64;
3162 }
3163 }
3164
3165 if(s->out_format == FMT_H263){
3166 for(j=survivor_count-1; j>=0; j--){
3167 int run= i - survivor[j];
e6dba5df 3168 int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
3ada94ba
BF
3169 score += score_tab[i-run];
3170 if(score < last_score){
3171 last_score= score;
3172 last_run= run;
3173 last_level= level-64;
3174 last_i= i+1;
3175 }
3176 }
3177 }
3178 }else{
e6dba5df 3179 distortion += esc_length*lambda;
3ada94ba
BF
3180 for(j=survivor_count-1; j>=0; j--){
3181 int run= i - survivor[j];
e6dba5df 3182 int score= distortion + score_tab[i-run];
3ada94ba
BF
3183
3184 if(score < best_score){
3185 best_score= score;
3186 run_tab[i+1]= run;
3187 level_tab[i+1]= level-64;
3188 }
3189 }
3190
3191 if(s->out_format == FMT_H263){
3192 for(j=survivor_count-1; j>=0; j--){
3193 int run= i - survivor[j];
e6dba5df 3194 int score= distortion + score_tab[i-run];
3ada94ba
BF
3195 if(score < last_score){
3196 last_score= score;
3197 last_run= run;
3198 last_level= level-64;
3199 last_i= i+1;
3200 }
3201 }
3202 }
3203 }
3204 }
3205
3206 score_tab[i+1]= best_score;
3207
3208 //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
3209 if(last_non_zero <= 27){
3210 for(; survivor_count; survivor_count--){
3211 if(score_tab[ survivor[survivor_count-1] ] <= best_score)
3212 break;
3213 }
3214 }else{
3215 for(; survivor_count; survivor_count--){
3216 if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
3217 break;
3218 }
3219 }
3220
3221 survivor[ survivor_count++ ]= i+1;
3222 }
3223
3224 if(s->out_format != FMT_H263){
3225 last_score= 256*256*256*120;
3226 for(i= survivor[0]; i<=last_non_zero + 1; i++){
3227 int score= score_tab[i];
3228 if(i) score += lambda*2; //FIXME exacter?
3229
3230 if(score < last_score){
3231 last_score= score;
3232 last_i= i;
3233 last_level= level_tab[i];
3234 last_run= run_tab[i];
3235 }
3236 }
3237 }
3238
3239 s->coded_score[n] = last_score;
3240
3241 dc= FFABS(block[0]);
3242 last_non_zero= last_i - 1;
3243 memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
3244
3245 if(last_non_zero < start_i)
3246 return last_non_zero;
3247
3248 if(last_non_zero == 0 && start_i == 0){
3249 int best_level= 0;
3250 int best_score= dc * dc;
3251
3252 for(i=0; i<coeff_count[0]; i++){
3253 int level= coeff[i][0];
3254 int alevel= FFABS(level);
3255 int unquant_coeff, score, distortion;
3256
3257 if(s->out_format == FMT_H263){
3258 unquant_coeff= (alevel*qmul + qadd)>>3;
3259 }else{ //MPEG1
3260 unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
3261 unquant_coeff = (unquant_coeff - 1) | 1;
3262 }
3263 unquant_coeff = (unquant_coeff + 4) >> 3;
3264 unquant_coeff<<= 3 + 3;
3265
3266 distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
3267 level+=64;
3268 if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
3269 else score= distortion + esc_length*lambda;
3270
3271 if(score < best_score){
3272 best_score= score;
3273 best_level= level - 64;
3274 }
3275 }
3276 block[0]= best_level;
3277 s->coded_score[n] = best_score - dc*dc;
3278 if(best_level == 0) return -1;
3279 else return last_non_zero;
3280 }
3281
3282 i= last_i;
3283 assert(last_level);
3284
3285 block[ perm_scantable[last_non_zero] ]= last_level;
3286 i -= last_run + 1;
3287
3288 for(; i>start_i; i -= run_tab[i] + 1){
3289 block[ perm_scantable[i-1] ]= level_tab[i];
3290 }
3291
3292 return last_non_zero;
3293}
3294
3295//#define REFINE_STATS 1
3296static int16_t basis[64][64];
3297
3298static void build_basis(uint8_t *perm){
3299 int i, j, x, y;
3300 emms_c();
3301 for(i=0; i<8; i++){
3302 for(j=0; j<8; j++){
3303 for(y=0; y<8; y++){
3304 for(x=0; x<8; x++){
3305 double s= 0.25*(1<<BASIS_SHIFT);
3306 int index= 8*i + j;
3307 int perm_index= perm[index];
3308 if(i==0) s*= sqrt(0.5);
3309 if(j==0) s*= sqrt(0.5);
3310 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)));
3311 }
3312 }
3313 }
3314 }
3315}
3316
3317static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
3318 DCTELEM *block, int16_t *weight, DCTELEM *orig,
3319 int n, int qscale){
3320 int16_t rem[64];
40d11227 3321 LOCAL_ALIGNED_16(DCTELEM, d1, [64]);
3ada94ba
BF
3322 const uint8_t *scantable= s->intra_scantable.scantable;
3323 const uint8_t *perm_scantable= s->intra_scantable.permutated;
3324// unsigned int threshold1, threshold2;
3325// int bias=0;
3326 int run_tab[65];
3327 int prev_run=0;
3328 int prev_level=0;
3329 int qmul, qadd, start_i, last_non_zero, i, dc;
3330 uint8_t * length;
3331 uint8_t * last_length;
3332 int lambda;
3333 int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
3334#ifdef REFINE_STATS
3335static int count=0;
3336static int after_last=0;
3337static int to_zero=0;
3338static int from_zero=0;
3339static int raise=0;
3340static int lower=0;
3341static int messed_sign=0;
3342#endif
3343
3344 if(basis[0][0] == 0)
3345 build_basis(s->dsp.idct_permutation);
3346
3347 qmul= qscale*2;
3348 qadd= (qscale-1)|1;
3349 if (s->mb_intra) {
3350 if (!s->h263_aic) {
3351 if (n < 4)
3352 q = s->y_dc_scale;
3353 else
3354 q = s->c_dc_scale;
3355 } else{
3356 /* For AIC we skip quant/dequant of INTRADC */
3357 q = 1;
3358 qadd=0;
3359 }
3360 q <<= RECON_SHIFT-3;
3361 /* note: block[0] is assumed to be positive */
3362 dc= block[0]*q;
3363// block[0] = (block[0] + (q >> 1)) / q;
3364 start_i = 1;
3ada94ba
BF
3365// if(s->mpeg_quant || s->out_format == FMT_MPEG1)
3366// bias= 1<<(QMAT_SHIFT-1);
3367 length = s->intra_ac_vlc_length;
3368 last_length= s->intra_ac_vlc_last_length;
3369 } else {
3370 dc= 0;
3371 start_i = 0;
3ada94ba
BF
3372 length = s->inter_ac_vlc_length;
3373 last_length= s->inter_ac_vlc_last_length;
3374 }
3375 last_non_zero = s->block_last_index[n];
3376
3377#ifdef REFINE_STATS
3378{START_TIMER
3379#endif
3380 dc += (1<<(RECON_SHIFT-1));
3381 for(i=0; i<64; i++){
3382 rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME use orig dirrectly instead of copying to rem[]
3383 }
3384#ifdef REFINE_STATS
3385STOP_TIMER("memset rem[]")}
3386#endif
3387 sum=0;
3388 for(i=0; i<64; i++){
3389 int one= 36;
3390 int qns=4;
3391 int w;
3392
3393 w= FFABS(weight[i]) + qns*one;
3394 w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
3395
3396 weight[i] = w;
3397// w=weight[i] = (63*qns + (w/2)) / w;
3398
3399 assert(w>0);
3400 assert(w<(1<<6));
3401 sum += w*w;
3402 }
3403 lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
3404#ifdef REFINE_STATS
3405{START_TIMER
3406#endif
3407 run=0;
3408 rle_index=0;
3409 for(i=start_i; i<=last_non_zero; i++){
3410 int j= perm_scantable[i];
3411 const int level= block[j];
3412 int coeff;
3413
3414 if(level){
3415 if(level<0) coeff= qmul*level - qadd;
3416 else coeff= qmul*level + qadd;
3417 run_tab[rle_index++]=run;
3418 run=0;
3419
3420 s->dsp.add_8x8basis(rem, basis[j], coeff);
3421 }else{
3422 run++;
3423 }
3424 }
3425#ifdef REFINE_STATS
3426if(last_non_zero>0){
3427STOP_TIMER("init rem[]")
3428}
3429}
3430
3431{START_TIMER
3432#endif
3433 for(;;){
3434 int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
3435 int best_coeff=0;
3436 int best_change=0;
3437 int run2, best_unquant_change=0, analyze_gradient;
3438#ifdef REFINE_STATS
3439{START_TIMER
3440#endif
3441 analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
3442
3443 if(analyze_gradient){
3444#ifdef REFINE_STATS
3445{START_TIMER
3446#endif
3447 for(i=0; i<64; i++){
3448 int w= weight[i];
3449
3450 d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
3451 }
3452#ifdef REFINE_STATS
3453STOP_TIMER("rem*w*w")}
3454{START_TIMER
3455#endif
3456 s->dsp.fdct(d1);
3457#ifdef REFINE_STATS
3458STOP_TIMER("dct")}
3459#endif
3460 }
3461
3462 if(start_i){
3463 const int level= block[0];
3464 int change, old_coeff;
3465
3466 assert(s->mb_intra);
3467
3468 old_coeff= q*level;
3469
3470 for(change=-1; change<=1; change+=2){
3471 int new_level= level + change;
3472 int score, new_coeff;
3473
3474 new_coeff= q*new_level;
3475 if(new_coeff >= 2048 || new_coeff < 0)
3476 continue;
3477
3478 score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
3479 if(score<best_score){
3480 best_score= score;
3481 best_coeff= 0;
3482 best_change= change;
3483 best_unquant_change= new_coeff - old_coeff;
3484 }
3485 }
3486 }
3487
3488 run=0;
3489 rle_index=0;
3490 run2= run_tab[rle_index++];
3491 prev_level=0;
3492 prev_run=0;
3493
3494 for(i=start_i; i<64; i++){
3495 int j= perm_scantable[i];
3496 const int level= block[j];
3497 int change, old_coeff;
3498
3499 if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
3500 break;
3501
3502 if(level){
3503 if(level<0) old_coeff= qmul*level - qadd;
3504 else old_coeff= qmul*level + qadd;
3505 run2= run_tab[rle_index++]; //FIXME ! maybe after last
3506 }else{
3507 old_coeff=0;
3508 run2--;
3509 assert(run2>=0 || i >= last_non_zero );
3510 }
3511
3512 for(change=-1; change<=1; change+=2){
3513 int new_level= level + change;
3514 int score, new_coeff, unquant_change;
3515
3516 score=0;
3517 if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
3518 continue;
3519
3520 if(new_level){
3521 if(new_level<0) new_coeff= qmul*new_level - qadd;
3522 else new_coeff= qmul*new_level + qadd;
3523 if(new_coeff >= 2048 || new_coeff <= -2048)
3524 continue;
3525 //FIXME check for overflow
3526
3527 if(level){
3528 if(level < 63 && level > -63){
3529 if(i < last_non_zero)
3530 score += length[UNI_AC_ENC_INDEX(run, new_level+64)]
3531 - length[UNI_AC_ENC_INDEX(run, level+64)];
3532 else
3533 score += last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
3534 - last_length[UNI_AC_ENC_INDEX(run, level+64)];
3535 }
3536 }else{
3537 assert(FFABS(new_level)==1);
3538
3539 if(analyze_gradient){
3540 int g= d1[ scantable[i] ];
3541 if(g && (g^new_level) >= 0)
3542 continue;
3543 }
3544
3545 if(i < last_non_zero){
3546 int next_i= i + run2 + 1;
3547 int next_level= block[ perm_scantable[next_i] ] + 64;
3548
3549 if(next_level&(~127))
3550 next_level= 0;
3551
3552 if(next_i < last_non_zero)
3553 score += length[UNI_AC_ENC_INDEX(run, 65)]
3554 + length[UNI_AC_ENC_INDEX(run2, next_level)]
3555 - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
3556 else
3557 score += length[UNI_AC_ENC_INDEX(run, 65)]
3558 + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
3559 - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
3560 }else{
3561 score += last_length[UNI_AC_ENC_INDEX(run, 65)];
3562 if(prev_level){
3563 score += length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
3564 - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
3565 }
3566 }
3567 }
3568 }else{
3569 new_coeff=0;
3570 assert(FFABS(level)==1);
3571
3572 if(i < last_non_zero){
3573 int next_i= i + run2 + 1;
3574 int next_level= block[ perm_scantable[next_i] ] + 64;
3575
3576 if(next_level&(~127))
3577 next_level= 0;
3578
3579 if(next_i < last_non_zero)
3580 score += length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
3581 - length[UNI_AC_ENC_INDEX(run2, next_level)]
3582 - length[UNI_AC_ENC_INDEX(run, 65)];
3583 else
3584 score += last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
3585 - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
3586 - length[UNI_AC_ENC_INDEX(run, 65)];
3587 }else{
3588 score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
3589 if(prev_level){
3590 score += last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
3591 - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
3592 }
3593 }
3594 }
3595
3596 score *= lambda;
3597
3598 unquant_change= new_coeff - old_coeff;
3599 assert((score < 100*lambda && score > -100*lambda) || lambda==0);
3600
3601 score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
3602 if(score<best_score){
3603 best_score= score;
3604 best_coeff= i;
3605 best_change= change;
3606 best_unquant_change= unquant_change;
3607 }
3608 }
3609 if(level){
3610 prev_level= level + 64;
3611 if(prev_level&(~127))
3612 prev_level= 0;
3613 prev_run= run;
3614 run=0;
3615 }else{
3616 run++;
3617 }
3618 }
3619#ifdef REFINE_STATS
3620STOP_TIMER("iterative step")}
3621#endif
3622
3623 if(best_change){
3624 int j= perm_scantable[ best_coeff ];
3625
3626 block[j] += best_change;
3627
3628 if(best_coeff > last_non_zero){
3629 last_non_zero= best_coeff;
3630 assert(block[j]);
3631#ifdef REFINE_STATS
3632after_last++;
3633#endif
3634 }else{
3635#ifdef REFINE_STATS
3636if(block[j]){
3637 if(block[j] - best_change){
3638 if(FFABS(block[j]) > FFABS(block[j] - best_change)){
3639