Statistics
| Branch: | Revision:

ffmpeg / libavcodec / mpegvideo_enc.c @ c46eeae2

History | View | Annotate | Download (139 KB)

1
/*
2
 * The simplest mpeg encoder (well, it was the simplest!)
3
 * Copyright (c) 2000,2001 Fabrice Bellard
4
 * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5
 *
6
 * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
7
 *
8
 * This file is part of FFmpeg.
9
 *
10
 * FFmpeg is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public
12
 * License as published by the Free Software Foundation; either
13
 * version 2.1 of the License, or (at your option) any later version.
14
 *
15
 * FFmpeg is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with FFmpeg; if not, write to the Free Software
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23
 */
24

    
25
/**
26
 * @file libavcodec/mpegvideo_enc.c
27
 * The simplest mpeg encoder (well, it was the simplest!).
28
 */
29

    
30
#include "avcodec.h"
31
#include "dsputil.h"
32
#include "mpegvideo.h"
33
#include "mpegvideo_common.h"
34
#include "h263.h"
35
#include "mjpegenc.h"
36
#include "msmpeg4.h"
37
#include "faandct.h"
38
#include "aandcttab.h"
39
#include "flv.h"
40
#include "mpeg4video.h"
41
#include <limits.h>
42

    
43
//#undef NDEBUG
44
//#include <assert.h>
45

    
46
static int encode_picture(MpegEncContext *s, int picture_number);
47
static int dct_quantize_refine(MpegEncContext *s, DCTELEM *block, int16_t *weight, DCTELEM *orig, int n, int qscale);
48
static int sse_mb(MpegEncContext *s);
49

    
50
/* enable all paranoid tests for rounding, overflows, etc... */
51
//#define PARANOID
52

    
53
//#define DEBUG
54

    
55
static uint8_t default_mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
56
static uint8_t default_fcode_tab[MAX_MV*2+1];
57

    
58
void ff_convert_matrix(DSPContext *dsp, int (*qmat)[64], uint16_t (*qmat16)[2][64],
59
                           const uint16_t *quant_matrix, int bias, int qmin, int qmax, int intra)
60
{
61
    int qscale;
62
    int shift=0;
63

    
64
    for(qscale=qmin; qscale<=qmax; qscale++){
65
        int i;
66
        if (dsp->fdct == ff_jpeg_fdct_islow
67
#ifdef FAAN_POSTSCALE
68
            || dsp->fdct == ff_faandct
69
#endif
70
            ) {
71
            for(i=0;i<64;i++) {
72
                const int j= dsp->idct_permutation[i];
73
                /* 16 <= qscale * quant_matrix[i] <= 7905 */
74
                /* 19952             <= ff_aanscales[i] * qscale * quant_matrix[i]               <= 249205026 */
75
                /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1 << 36) / 249205026 */
76
                /* 3444240           >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
77

    
78
                qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) /
79
                                (qscale * quant_matrix[j]));
80
            }
81
        } else if (dsp->fdct == fdct_ifast
82
#ifndef FAAN_POSTSCALE
83
                   || dsp->fdct == ff_faandct
84
#endif
85
                   ) {
86
            for(i=0;i<64;i++) {
87
                const int j= dsp->idct_permutation[i];
88
                /* 16 <= qscale * quant_matrix[i] <= 7905 */
89
                /* 19952             <= ff_aanscales[i] * qscale * quant_matrix[i]               <= 249205026 */
90
                /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
91
                /* 3444240           >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
92

    
93
                qmat[qscale][i] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) /
94
                                (ff_aanscales[i] * qscale * quant_matrix[j]));
95
            }
96
        } else {
97
            for(i=0;i<64;i++) {
98
                const int j= dsp->idct_permutation[i];
99
                /* We can safely suppose that 16 <= quant_matrix[i] <= 255
100
                   So 16           <= qscale * quant_matrix[i]             <= 7905
101
                   so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
102
                   so 32768        >= (1<<19) / (qscale * quant_matrix[i]) >= 67
103
                */
104
                qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) / (qscale * quant_matrix[j]));
105
//                qmat  [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
106
                qmat16[qscale][0][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[j]);
107

    
108
                if(qmat16[qscale][0][i]==0 || qmat16[qscale][0][i]==128*256) qmat16[qscale][0][i]=128*256-1;
109
                qmat16[qscale][1][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][0][i]);
110
            }
111
        }
112

    
113
        for(i=intra; i<64; i++){
114
            int64_t max= 8191;
115
            if (dsp->fdct == fdct_ifast
116
#ifndef FAAN_POSTSCALE
117
                   || dsp->fdct == ff_faandct
118
#endif
119
                   ) {
120
                max = (8191LL*ff_aanscales[i]) >> 14;
121
            }
122
            while(((max * qmat[qscale][i]) >> shift) > INT_MAX){
123
                shift++;
124
            }
125
        }
126
    }
127
    if(shift){
128
        av_log(NULL, AV_LOG_INFO, "Warning, QMAT_SHIFT is larger than %d, overflows possible\n", QMAT_SHIFT - shift);
129
    }
130
}
131

    
132
static inline void update_qscale(MpegEncContext *s){
133
    s->qscale= (s->lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
134
    s->qscale= av_clip(s->qscale, s->avctx->qmin, s->avctx->qmax);
135

    
136
    s->lambda2= (s->lambda*s->lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
137
}
138

    
139
void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix){
140
    int i;
141

    
142
    if(matrix){
143
        put_bits(pb, 1, 1);
144
        for(i=0;i<64;i++) {
145
            put_bits(pb, 8, matrix[ ff_zigzag_direct[i] ]);
146
        }
147
    }else
148
        put_bits(pb, 1, 0);
149
}
150

    
151
/**
152
 * init s->current_picture.qscale_table from s->lambda_table
153
 */
154
void ff_init_qscale_tab(MpegEncContext *s){
155
    int8_t * const qscale_table= s->current_picture.qscale_table;
156
    int i;
157

    
158
    for(i=0; i<s->mb_num; i++){
159
        unsigned int lam= s->lambda_table[ s->mb_index2xy[i] ];
160
        int qp= (lam*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
161
        qscale_table[ s->mb_index2xy[i] ]= av_clip(qp, s->avctx->qmin, s->avctx->qmax);
162
    }
163
}
164

    
165
static void copy_picture_attributes(MpegEncContext *s, AVFrame *dst, AVFrame *src){
166
    int i;
167

    
168
    dst->pict_type              = src->pict_type;
169
    dst->quality                = src->quality;
170
    dst->coded_picture_number   = src->coded_picture_number;
171
    dst->display_picture_number = src->display_picture_number;
172
//    dst->reference              = src->reference;
173
    dst->pts                    = src->pts;
174
    dst->interlaced_frame       = src->interlaced_frame;
175
    dst->top_field_first        = src->top_field_first;
176

    
177
    if(s->avctx->me_threshold){
178
        if(!src->motion_val[0])
179
            av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_val not set!\n");
180
        if(!src->mb_type)
181
            av_log(s->avctx, AV_LOG_ERROR, "AVFrame.mb_type not set!\n");
182
        if(!src->ref_index[0])
183
            av_log(s->avctx, AV_LOG_ERROR, "AVFrame.ref_index not set!\n");
184
        if(src->motion_subsample_log2 != dst->motion_subsample_log2)
185
            av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_subsample_log2 doesn't match! (%d!=%d)\n",
186
            src->motion_subsample_log2, dst->motion_subsample_log2);
187

    
188
        memcpy(dst->mb_type, src->mb_type, s->mb_stride * s->mb_height * sizeof(dst->mb_type[0]));
189

    
190
        for(i=0; i<2; i++){
191
            int stride= ((16*s->mb_width )>>src->motion_subsample_log2) + 1;
192
            int height= ((16*s->mb_height)>>src->motion_subsample_log2);
193

    
194
            if(src->motion_val[i] && src->motion_val[i] != dst->motion_val[i]){
195
                memcpy(dst->motion_val[i], src->motion_val[i], 2*stride*height*sizeof(int16_t));
196
            }
197
            if(src->ref_index[i] && src->ref_index[i] != dst->ref_index[i]){
198
                memcpy(dst->ref_index[i], src->ref_index[i], s->b8_stride*2*s->mb_height*sizeof(int8_t));
199
            }
200
        }
201
    }
202
}
203

    
204
static void update_duplicate_context_after_me(MpegEncContext *dst, MpegEncContext *src){
205
#define COPY(a) dst->a= src->a
206
    COPY(pict_type);
207
    COPY(current_picture);
208
    COPY(f_code);
209
    COPY(b_code);
210
    COPY(qscale);
211
    COPY(lambda);
212
    COPY(lambda2);
213
    COPY(picture_in_gop_number);
214
    COPY(gop_picture_number);
215
    COPY(frame_pred_frame_dct); //FIXME don't set in encode_header
216
    COPY(progressive_frame); //FIXME don't set in encode_header
217
    COPY(partitioned_frame); //FIXME don't set in encode_header
218
#undef COPY
219
}
220

    
221
/**
222
 * sets the given MpegEncContext to defaults for encoding.
223
 * the changed fields will not depend upon the prior state of the MpegEncContext.
224
 */
225
static void MPV_encode_defaults(MpegEncContext *s){
226
    int i;
227
    MPV_common_defaults(s);
228

    
229
    for(i=-16; i<16; i++){
230
        default_fcode_tab[i + MAX_MV]= 1;
231
    }
232
    s->me.mv_penalty= default_mv_penalty;
233
    s->fcode_tab= default_fcode_tab;
234
}
235

    
236
/* init video encoder */
237
av_cold int MPV_encode_init(AVCodecContext *avctx)
238
{
239
    MpegEncContext *s = avctx->priv_data;
240
    int i;
241
    int chroma_h_shift, chroma_v_shift;
242

    
243
    MPV_encode_defaults(s);
244

    
245
    switch (avctx->codec_id) {
246
    case CODEC_ID_MPEG2VIDEO:
247
        if(avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P){
248
            av_log(avctx, AV_LOG_ERROR, "only YUV420 and YUV422 are supported\n");
249
            return -1;
250
        }
251
        break;
252
    case CODEC_ID_LJPEG:
253
    case CODEC_ID_MJPEG:
254
        if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P && avctx->pix_fmt != PIX_FMT_RGB32 &&
255
           ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P) || avctx->strict_std_compliance>FF_COMPLIANCE_INOFFICIAL)){
256
            av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");
257
            return -1;
258
        }
259
        break;
260
    default:
261
        if(avctx->pix_fmt != PIX_FMT_YUV420P){
262
            av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");
263
            return -1;
264
        }
265
    }
266

    
267
    switch (avctx->pix_fmt) {
268
    case PIX_FMT_YUVJ422P:
269
    case PIX_FMT_YUV422P:
270
        s->chroma_format = CHROMA_422;
271
        break;
272
    case PIX_FMT_YUVJ420P:
273
    case PIX_FMT_YUV420P:
274
    default:
275
        s->chroma_format = CHROMA_420;
276
        break;
277
    }
278

    
279
    s->bit_rate = avctx->bit_rate;
280
    s->width = avctx->width;
281
    s->height = avctx->height;
282
    if(avctx->gop_size > 600 && avctx->strict_std_compliance>FF_COMPLIANCE_EXPERIMENTAL){
283
        av_log(avctx, AV_LOG_ERROR, "Warning keyframe interval too large! reducing it ...\n");
284
        avctx->gop_size=600;
285
    }
286
    s->gop_size = avctx->gop_size;
287
    s->avctx = avctx;
288
    s->flags= avctx->flags;
289
    s->flags2= avctx->flags2;
290
    s->max_b_frames= avctx->max_b_frames;
291
    s->codec_id= avctx->codec->id;
292
    s->luma_elim_threshold  = avctx->luma_elim_threshold;
293
    s->chroma_elim_threshold= avctx->chroma_elim_threshold;
294
    s->strict_std_compliance= avctx->strict_std_compliance;
295
    s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
296
    s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;
297
    s->mpeg_quant= avctx->mpeg_quant;
298
    s->rtp_mode= !!avctx->rtp_payload_size;
299
    s->intra_dc_precision= avctx->intra_dc_precision;
300
    s->user_specified_pts = AV_NOPTS_VALUE;
301

    
302
    if (s->gop_size <= 1) {
303
        s->intra_only = 1;
304
        s->gop_size = 12;
305
    } else {
306
        s->intra_only = 0;
307
    }
308

    
309
    s->me_method = avctx->me_method;
310

    
311
    /* Fixed QSCALE */
312
    s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);
313

    
314
    s->adaptive_quant= (   s->avctx->lumi_masking
315
                        || s->avctx->dark_masking
316
                        || s->avctx->temporal_cplx_masking
317
                        || s->avctx->spatial_cplx_masking
318
                        || s->avctx->p_masking
319
                        || s->avctx->border_masking
320
                        || (s->flags&CODEC_FLAG_QP_RD))
321
                       && !s->fixed_qscale;
322

    
323
    s->obmc= !!(s->flags & CODEC_FLAG_OBMC);
324
    s->loop_filter= !!(s->flags & CODEC_FLAG_LOOP_FILTER);
325
    s->alternate_scan= !!(s->flags & CODEC_FLAG_ALT_SCAN);
326
    s->intra_vlc_format= !!(s->flags2 & CODEC_FLAG2_INTRA_VLC);
327
    s->q_scale_type= !!(s->flags2 & CODEC_FLAG2_NON_LINEAR_QUANT);
328

    
329
    if(avctx->rc_max_rate && !avctx->rc_buffer_size){
330
        av_log(avctx, AV_LOG_ERROR, "a vbv buffer size is needed, for encoding with a maximum bitrate\n");
331
        return -1;
332
    }
333

    
334
    if(avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate){
335
        av_log(avctx, AV_LOG_INFO, "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");
336
    }
337

    
338
    if(avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate){
339
        av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");
340
        return -1;
341
    }
342

    
343
    if(avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate){
344
        av_log(avctx, AV_LOG_INFO, "bitrate above max bitrate\n");
345
        return -1;
346
    }
347

    
348
    if(avctx->rc_max_rate && avctx->rc_max_rate == avctx->bit_rate && avctx->rc_max_rate != avctx->rc_min_rate){
349
        av_log(avctx, AV_LOG_INFO, "impossible bitrate constraints, this will fail\n");
350
    }
351

    
352
    if(avctx->rc_buffer_size && avctx->bit_rate*av_q2d(avctx->time_base) > avctx->rc_buffer_size){
353
        av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");
354
        return -1;
355
    }
356

    
357
    if(avctx->bit_rate*av_q2d(avctx->time_base) > avctx->bit_rate_tolerance){
358
        av_log(avctx, AV_LOG_ERROR, "bitrate tolerance too small for bitrate\n");
359
        return -1;
360
    }
361

    
362
    if(   s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate
363
       && (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO)
364
       && 90000LL * (avctx->rc_buffer_size-1) > s->avctx->rc_max_rate*0xFFFFLL){
365

    
366
        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");
367
    }
368

    
369
    if((s->flags & CODEC_FLAG_4MV) && s->codec_id != CODEC_ID_MPEG4
370
       && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P && s->codec_id != CODEC_ID_FLV1){
371
        av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
372
        return -1;
373
    }
374

    
375
    if(s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE){
376
        av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with simple mb decision\n");
377
        return -1;
378
    }
379

    
380
    if(s->obmc && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P){
381
        av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with H263(+)\n");
382
        return -1;
383
    }
384

    
385
    if(s->quarter_sample && s->codec_id != CODEC_ID_MPEG4){
386
        av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
387
        return -1;
388
    }
389

    
390
    if(s->data_partitioning && s->codec_id != CODEC_ID_MPEG4){
391
        av_log(avctx, AV_LOG_ERROR, "data partitioning not supported by codec\n");
392
        return -1;
393
    }
394

    
395
    if(s->max_b_frames && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO){
396
        av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
397
        return -1;
398
    }
399

    
400
    if ((s->codec_id == CODEC_ID_MPEG4 || s->codec_id == CODEC_ID_H263 ||
401
         s->codec_id == CODEC_ID_H263P) &&
402
        (avctx->sample_aspect_ratio.num > 255 || avctx->sample_aspect_ratio.den > 255)) {
403
        av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i, limit is 255/255\n",
404
               avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
405
        return -1;
406
    }
407

    
408
    if((s->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN))
409
       && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG2VIDEO){
410
        av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");
411
        return -1;
412
    }
413

    
414
    if(s->mpeg_quant && s->codec_id != CODEC_ID_MPEG4){ //FIXME mpeg2 uses that too
415
        av_log(avctx, AV_LOG_ERROR, "mpeg2 style quantization not supported by codec\n");
416
        return -1;
417
    }
418

    
419
    if((s->flags & CODEC_FLAG_CBP_RD) && !avctx->trellis){
420
        av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
421
        return -1;
422
    }
423

    
424
    if((s->flags & CODEC_FLAG_QP_RD) && s->avctx->mb_decision != FF_MB_DECISION_RD){
425
        av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");
426
        return -1;
427
    }
428

    
429
    if(s->avctx->scenechange_threshold < 1000000000 && (s->flags & CODEC_FLAG_CLOSED_GOP)){
430
        av_log(avctx, AV_LOG_ERROR, "closed gop with scene change detection are not supported yet, set threshold to 1000000000\n");
431
        return -1;
432
    }
433

    
434
    if((s->flags2 & CODEC_FLAG2_INTRA_VLC) && s->codec_id != CODEC_ID_MPEG2VIDEO){
435
        av_log(avctx, AV_LOG_ERROR, "intra vlc table not supported by codec\n");
436
        return -1;
437
    }
438

    
439
    if(s->flags & CODEC_FLAG_LOW_DELAY){
440
        if (s->codec_id != CODEC_ID_MPEG2VIDEO){
441
            av_log(avctx, AV_LOG_ERROR, "low delay forcing is only available for mpeg2\n");
442
            return -1;
443
        }
444
        if (s->max_b_frames != 0){
445
            av_log(avctx, AV_LOG_ERROR, "b frames cannot be used with low delay\n");
446
            return -1;
447
        }
448
    }
449

    
450
    if(s->q_scale_type == 1){
451
        if(s->codec_id != CODEC_ID_MPEG2VIDEO){
452
            av_log(avctx, AV_LOG_ERROR, "non linear quant is only available for mpeg2\n");
453
            return -1;
454
        }
455
        if(avctx->qmax > 12){
456
            av_log(avctx, AV_LOG_ERROR, "non linear quant only supports qmax <= 12 currently\n");
457
            return -1;
458
        }
459
    }
460

    
461
    if(s->avctx->thread_count > 1 && s->codec_id != CODEC_ID_MPEG4
462
       && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO
463
       && (s->codec_id != CODEC_ID_H263P || !(s->flags & CODEC_FLAG_H263P_SLICE_STRUCT))){
464
        av_log(avctx, AV_LOG_ERROR, "multi threaded encoding not supported by codec\n");
465
        return -1;
466
    }
467

    
468
    if(s->avctx->thread_count < 1){
469
        av_log(avctx, AV_LOG_ERROR, "automatic thread number detection not supported by codec, patch welcome\n");
470
        return -1;
471
    }
472

    
473
    if(s->avctx->thread_count > 1)
474
        s->rtp_mode= 1;
475

    
476
    if(!avctx->time_base.den || !avctx->time_base.num){
477
        av_log(avctx, AV_LOG_ERROR, "framerate not set\n");
478
        return -1;
479
    }
480

    
481
    i= (INT_MAX/2+128)>>8;
482
    if(avctx->me_threshold >= i){
483
        av_log(avctx, AV_LOG_ERROR, "me_threshold too large, max is %d\n", i - 1);
484
        return -1;
485
    }
486
    if(avctx->mb_threshold >= i){
487
        av_log(avctx, AV_LOG_ERROR, "mb_threshold too large, max is %d\n", i - 1);
488
        return -1;
489
    }
490

    
491
    if(avctx->b_frame_strategy && (avctx->flags&CODEC_FLAG_PASS2)){
492
        av_log(avctx, AV_LOG_INFO, "notice: b_frame_strategy only affects the first pass\n");
493
        avctx->b_frame_strategy = 0;
494
    }
495

    
496
    i= av_gcd(avctx->time_base.den, avctx->time_base.num);
497
    if(i > 1){
498
        av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");
499
        avctx->time_base.den /= i;
500
        avctx->time_base.num /= i;
501
//        return -1;
502
    }
503

    
504
    if(s->codec_id==CODEC_ID_MJPEG){
505
        s->intra_quant_bias= 1<<(QUANT_BIAS_SHIFT-1); //(a + x/2)/x
506
        s->inter_quant_bias= 0;
507
    }else if(s->mpeg_quant || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO){
508
        s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
509
        s->inter_quant_bias= 0;
510
    }else{
511
        s->intra_quant_bias=0;
512
        s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
513
    }
514

    
515
    if(avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
516
        s->intra_quant_bias= avctx->intra_quant_bias;
517
    if(avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
518
        s->inter_quant_bias= avctx->inter_quant_bias;
519

    
520
    avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);
521

    
522
    if(avctx->codec_id == CODEC_ID_MPEG4 && s->avctx->time_base.den > (1<<16)-1){
523
        av_log(avctx, AV_LOG_ERROR, "timebase not supported by mpeg 4 standard\n");
524
        return -1;
525
    }
526
    s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
527

    
528
    switch(avctx->codec->id) {
529
    case CODEC_ID_MPEG1VIDEO:
530
        s->out_format = FMT_MPEG1;
531
        s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
532
        avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
533
        break;
534
    case CODEC_ID_MPEG2VIDEO:
535
        s->out_format = FMT_MPEG1;
536
        s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
537
        avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
538
        s->rtp_mode= 1;
539
        break;
540
    case CODEC_ID_LJPEG:
541
    case CODEC_ID_MJPEG:
542
        s->out_format = FMT_MJPEG;
543
        s->intra_only = 1; /* force intra only for jpeg */
544
        if(avctx->codec->id == CODEC_ID_LJPEG && avctx->pix_fmt == PIX_FMT_BGRA){
545
            s->mjpeg_vsample[0] = s->mjpeg_hsample[0] =
546
            s->mjpeg_vsample[1] = s->mjpeg_hsample[1] =
547
            s->mjpeg_vsample[2] = s->mjpeg_hsample[2] = 1;
548
        }else{
549
            s->mjpeg_vsample[0] = 2;
550
            s->mjpeg_vsample[1] = 2>>chroma_v_shift;
551
            s->mjpeg_vsample[2] = 2>>chroma_v_shift;
552
            s->mjpeg_hsample[0] = 2;
553
            s->mjpeg_hsample[1] = 2>>chroma_h_shift;
554
            s->mjpeg_hsample[2] = 2>>chroma_h_shift;
555
        }
556
        if (!(CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER)
557
            || ff_mjpeg_encode_init(s) < 0)
558
            return -1;
559
        avctx->delay=0;
560
        s->low_delay=1;
561
        break;
562
    case CODEC_ID_H261:
563
        if (!CONFIG_H261_ENCODER)  return -1;
564
        if (ff_h261_get_picture_format(s->width, s->height) < 0) {
565
            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);
566
            return -1;
567
        }
568
        s->out_format = FMT_H261;
569
        avctx->delay=0;
570
        s->low_delay=1;
571
        break;
572
    case CODEC_ID_H263:
573
        if (!CONFIG_H263_ENCODER)  return -1;
574
        if (ff_match_2uint16(h263_format, FF_ARRAY_ELEMS(h263_format), s->width, s->height) == 7) {
575
            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);
576
            return -1;
577
        }
578
        s->out_format = FMT_H263;
579
        s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
580
        avctx->delay=0;
581
        s->low_delay=1;
582
        break;
583
    case CODEC_ID_H263P:
584
        s->out_format = FMT_H263;
585
        s->h263_plus = 1;
586
        /* Fx */
587
        s->umvplus = (avctx->flags & CODEC_FLAG_H263P_UMV) ? 1:0;
588
        s->h263_aic= (avctx->flags & CODEC_FLAG_AC_PRED) ? 1:0;
589
        s->modified_quant= s->h263_aic;
590
        s->alt_inter_vlc= (avctx->flags & CODEC_FLAG_H263P_AIV) ? 1:0;
591
        s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
592
        s->loop_filter= (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1:0;
593
        s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;
594
        s->h263_slice_structured= (s->flags & CODEC_FLAG_H263P_SLICE_STRUCT) ? 1:0;
595

    
596
        /* /Fx */
597
        /* These are just to be sure */
598
        avctx->delay=0;
599
        s->low_delay=1;
600
        break;
601
    case CODEC_ID_FLV1:
602
        s->out_format = FMT_H263;
603
        s->h263_flv = 2; /* format = 1; 11-bit codes */
604
        s->unrestricted_mv = 1;
605
        s->rtp_mode=0; /* don't allow GOB */
606
        avctx->delay=0;
607
        s->low_delay=1;
608
        break;
609
    case CODEC_ID_RV10:
610
        s->out_format = FMT_H263;
611
        avctx->delay=0;
612
        s->low_delay=1;
613
        break;
614
    case CODEC_ID_RV20:
615
        s->out_format = FMT_H263;
616
        avctx->delay=0;
617
        s->low_delay=1;
618
        s->modified_quant=1;
619
        s->h263_aic=1;
620
        s->h263_plus=1;
621
        s->loop_filter=1;
622
        s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;
623
        break;
624
    case CODEC_ID_MPEG4:
625
        s->out_format = FMT_H263;
626
        s->h263_pred = 1;
627
        s->unrestricted_mv = 1;
628
        s->low_delay= s->max_b_frames ? 0 : 1;
629
        avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
630
        break;
631
    case CODEC_ID_MSMPEG4V1:
632
        s->out_format = FMT_H263;
633
        s->h263_msmpeg4 = 1;
634
        s->h263_pred = 1;
635
        s->unrestricted_mv = 1;
636
        s->msmpeg4_version= 1;
637
        avctx->delay=0;
638
        s->low_delay=1;
639
        break;
640
    case CODEC_ID_MSMPEG4V2:
641
        s->out_format = FMT_H263;
642
        s->h263_msmpeg4 = 1;
643
        s->h263_pred = 1;
644
        s->unrestricted_mv = 1;
645
        s->msmpeg4_version= 2;
646
        avctx->delay=0;
647
        s->low_delay=1;
648
        break;
649
    case CODEC_ID_MSMPEG4V3:
650
        s->out_format = FMT_H263;
651
        s->h263_msmpeg4 = 1;
652
        s->h263_pred = 1;
653
        s->unrestricted_mv = 1;
654
        s->msmpeg4_version= 3;
655
        s->flipflop_rounding=1;
656
        avctx->delay=0;
657
        s->low_delay=1;
658
        break;
659
    case CODEC_ID_WMV1:
660
        s->out_format = FMT_H263;
661
        s->h263_msmpeg4 = 1;
662
        s->h263_pred = 1;
663
        s->unrestricted_mv = 1;
664
        s->msmpeg4_version= 4;
665
        s->flipflop_rounding=1;
666
        avctx->delay=0;
667
        s->low_delay=1;
668
        break;
669
    case CODEC_ID_WMV2:
670
        s->out_format = FMT_H263;
671
        s->h263_msmpeg4 = 1;
672
        s->h263_pred = 1;
673
        s->unrestricted_mv = 1;
674
        s->msmpeg4_version= 5;
675
        s->flipflop_rounding=1;
676
        avctx->delay=0;
677
        s->low_delay=1;
678
        break;
679
    default:
680
        return -1;
681
    }
682

    
683
    avctx->has_b_frames= !s->low_delay;
684

    
685
    s->encoding = 1;
686

    
687
    s->progressive_frame=
688
    s->progressive_sequence= !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN));
689

    
690
    /* init */
691
    if (MPV_common_init(s) < 0)
692
        return -1;
693

    
694
    if(!s->dct_quantize)
695
        s->dct_quantize = dct_quantize_c;
696
    if(!s->denoise_dct)
697
        s->denoise_dct = denoise_dct_c;
698
    s->fast_dct_quantize = s->dct_quantize;
699
    if(avctx->trellis)
700
        s->dct_quantize = dct_quantize_trellis_c;
701

    
702
    if((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)
703
        s->chroma_qscale_table= ff_h263_chroma_qscale_table;
704

    
705
    s->quant_precision=5;
706

    
707
    ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);
708
    ff_set_cmp(&s->dsp, s->dsp.frame_skip_cmp, s->avctx->frame_skip_cmp);
709

    
710
    if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)
711
        ff_h261_encode_init(s);
712
    if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)
713
        h263_encode_init(s);
714
    if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
715
        ff_msmpeg4_encode_init(s);
716
    if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
717
        && s->out_format == FMT_MPEG1)
718
        ff_mpeg1_encode_init(s);
719

    
720
    /* init q matrix */
721
    for(i=0;i<64;i++) {
722
        int j= s->dsp.idct_permutation[i];
723
        if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
724
            s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
725
            s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
726
        }else if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
727
            s->intra_matrix[j] =
728
            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
729
        }else
730
        { /* mpeg1/2 */
731
            s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
732
            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
733
        }
734
        if(s->avctx->intra_matrix)
735
            s->intra_matrix[j] = s->avctx->intra_matrix[i];
736
        if(s->avctx->inter_matrix)
737
            s->inter_matrix[j] = s->avctx->inter_matrix[i];
738
    }
739

    
740
    /* precompute matrix */
741
    /* for mjpeg, we do include qscale in the matrix */
742
    if (s->out_format != FMT_MJPEG) {
743
        ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
744
                       s->intra_matrix, s->intra_quant_bias, avctx->qmin, 31, 1);
745
        ff_convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,
746
                       s->inter_matrix, s->inter_quant_bias, avctx->qmin, 31, 0);
747
    }
748

    
749
    if(ff_rate_control_init(s) < 0)
750
        return -1;
751

    
752
    return 0;
753
}
754

    
755
av_cold int MPV_encode_end(AVCodecContext *avctx)
756
{
757
    MpegEncContext *s = avctx->priv_data;
758

    
759
    ff_rate_control_uninit(s);
760

    
761
    MPV_common_end(s);
762
    if ((CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER) && s->out_format == FMT_MJPEG)
763
        ff_mjpeg_encode_close(s);
764

    
765
    av_freep(&avctx->extradata);
766

    
767
    return 0;
768
}
769

    
770
static int get_sae(uint8_t *src, int ref, int stride){
771
    int x,y;
772
    int acc=0;
773

    
774
    for(y=0; y<16; y++){
775
        for(x=0; x<16; x++){
776
            acc+= FFABS(src[x+y*stride] - ref);
777
        }
778
    }
779

    
780
    return acc;
781
}
782

    
783
static int get_intra_count(MpegEncContext *s, uint8_t *src, uint8_t *ref, int stride){
784
    int x, y, w, h;
785
    int acc=0;
786

    
787
    w= s->width &~15;
788
    h= s->height&~15;
789

    
790
    for(y=0; y<h; y+=16){
791
        for(x=0; x<w; x+=16){
792
            int offset= x + y*stride;
793
            int sad = s->dsp.sad[0](NULL, src + offset, ref + offset, stride, 16);
794
            int mean= (s->dsp.pix_sum(src + offset, stride) + 128)>>8;
795
            int sae = get_sae(src + offset, mean, stride);
796

    
797
            acc+= sae + 500 < sad;
798
        }
799
    }
800
    return acc;
801
}
802

    
803

    
804
static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
805
    AVFrame *pic=NULL;
806
    int64_t pts;
807
    int i;
808
    const int encoding_delay= s->max_b_frames;
809
    int direct=1;
810

    
811
    if(pic_arg){
812
        pts= pic_arg->pts;
813
        pic_arg->display_picture_number= s->input_picture_number++;
814

    
815
        if(pts != AV_NOPTS_VALUE){
816
            if(s->user_specified_pts != AV_NOPTS_VALUE){
817
                int64_t time= pts;
818
                int64_t last= s->user_specified_pts;
819

    
820
                if(time <= last){
821
                    av_log(s->avctx, AV_LOG_ERROR, "Error, Invalid timestamp=%"PRId64", last=%"PRId64"\n", pts, s->user_specified_pts);
822
                    return -1;
823
                }
824
            }
825
            s->user_specified_pts= pts;
826
        }else{
827
            if(s->user_specified_pts != AV_NOPTS_VALUE){
828
                s->user_specified_pts=
829
                pts= s->user_specified_pts + 1;
830
                av_log(s->avctx, AV_LOG_INFO, "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n", pts);
831
            }else{
832
                pts= pic_arg->display_picture_number;
833
            }
834
        }
835
    }
836

    
837
  if(pic_arg){
838
    if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
839
    if(pic_arg->linesize[0] != s->linesize) direct=0;
840
    if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
841
    if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
842

    
843
//    av_log(AV_LOG_DEBUG, "%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);
844

    
845
    if(direct){
846
        i= ff_find_unused_picture(s, 1);
847

    
848
        pic= (AVFrame*)&s->picture[i];
849
        pic->reference= 3;
850

    
851
        for(i=0; i<4; i++){
852
            pic->data[i]= pic_arg->data[i];
853
            pic->linesize[i]= pic_arg->linesize[i];
854
        }
855
        ff_alloc_picture(s, (Picture*)pic, 1);
856
    }else{
857
        i= ff_find_unused_picture(s, 0);
858

    
859
        pic= (AVFrame*)&s->picture[i];
860
        pic->reference= 3;
861

    
862
        ff_alloc_picture(s, (Picture*)pic, 0);
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

    
910
static 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

    
943
static 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();
957
    p_lambda= s->last_lambda_for[FF_P_TYPE]; //s->next_picture_ptr->quality;
958
    b_lambda= s->last_lambda_for[FF_B_TYPE]; //p_lambda *FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
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

    
1013
        input[0].pict_type= FF_I_TYPE;
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

    
1021
            input[i+1].pict_type= is_p ? FF_P_TYPE : FF_B_TYPE;
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

    
1052
static void select_input_picture(MpegEncContext *s){
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];
1063
            s->reordered_input_picture[0]->pict_type= FF_I_TYPE;
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]){
1098
                        s->rc_context.entry[pict_num-1].new_pict_type = FF_P_TYPE;
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;
1142
                if(type && type != FF_B_TYPE)
1143
                    b_frames= i;
1144
            }
1145
            if(s->input_picture[b_frames]->pict_type == FF_B_TYPE && b_frames == s->max_b_frames){
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;
1155
                s->input_picture[b_frames]->pict_type= FF_I_TYPE;
1156
              }
1157
            }
1158

    
1159
            if(   (s->flags & CODEC_FLAG_CLOSED_GOP)
1160
               && b_frames
1161
               && s->input_picture[b_frames]->pict_type== FF_I_TYPE)
1162
                b_frames--;
1163

    
1164
            s->reordered_input_picture[0]= s->input_picture[b_frames];
1165
            if(s->reordered_input_picture[0]->pict_type != FF_I_TYPE)
1166
                s->reordered_input_picture[0]->pict_type= FF_P_TYPE;
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];
1170
                s->reordered_input_picture[i+1]->pict_type= FF_B_TYPE;
1171
                s->reordered_input_picture[i+1]->coded_picture_number= s->coded_picture_number++;
1172
            }
1173
        }
1174
    }
1175
no_output_pic:
1176
    if(s->reordered_input_picture[0]){
1177
        s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=FF_B_TYPE ? 3 : 0;
1178

    
1179
        ff_copy_picture(&s->new_picture, s->reordered_input_picture[0]);
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;
1188
            ff_alloc_picture(s, pic, 0);
1189

    
1190
            /* mark us unused / free shared pic */
1191
            if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_INTERNAL)
1192
                s->avctx->release_buffer(s->avctx, (AVFrame*)s->reordered_input_picture[0]);
1193
            for(i=0; i<4; i++)
1194
                s->reordered_input_picture[0]->data[i]= NULL;
1195
            s->reordered_input_picture[0]->type= 0;
1196

    
1197
            copy_picture_attributes(s, (AVFrame*)pic, (AVFrame*)s->reordered_input_picture[0]);
1198

    
1199
            s->current_picture_ptr= pic;
1200
        }else{
1201
            // input is not a shared pix -> reuse buffer for current_pix
1202

    
1203
            assert(   s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER
1204
                   || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
1205

    
1206
            s->current_picture_ptr= s->reordered_input_picture[0];
1207
            for(i=0; i<4; i++){
1208
                s->new_picture.data[i]+= INPLACE_OFFSET;
1209
            }
1210
        }
1211
        ff_copy_picture(&s->current_picture, s->current_picture_ptr);
1212

    
1213
        s->picture_number= s->new_picture.display_picture_number;
1214
//printf("dpn:%d\n", s->picture_number);
1215
    }else{
1216
       memset(&s->new_picture, 0, sizeof(Picture));
1217
    }
1218
}
1219

    
1220
int MPV_encode_picture(AVCodecContext *avctx,
1221
                       unsigned char *buf, int buf_size, void *data)
1222
{
1223
    MpegEncContext *s = avctx->priv_data;
1224
    AVFrame *pic_arg = data;
1225
    int i, stuffing_count;
1226

    
1227
    for(i=0; i<avctx->thread_count; i++){
1228
        int start_y= s->thread_context[i]->start_mb_y;
1229
        int   end_y= s->thread_context[i]->  end_mb_y;
1230
        int h= s->mb_height;
1231
        uint8_t *start= buf + (size_t)(((int64_t) buf_size)*start_y/h);
1232
        uint8_t *end  = buf + (size_t)(((int64_t) buf_size)*  end_y/h);
1233

    
1234
        init_put_bits(&s->thread_context[i]->pb, start, end - start);
1235
    }
1236

    
1237
    s->picture_in_gop_number++;
1238

    
1239
    if(load_input_picture(s, pic_arg) < 0)
1240
        return -1;
1241

    
1242
    select_input_picture(s);
1243

    
1244
    /* output? */
1245
    if(s->new_picture.data[0]){
1246
        s->pict_type= s->new_picture.pict_type;
1247
//emms_c();
1248
//printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
1249
        MPV_frame_start(s, avctx);
1250
vbv_retry:
1251
        if (encode_picture(s, s->picture_number) < 0)
1252
            return -1;
1253

    
1254
        avctx->header_bits = s->header_bits;
1255
        avctx->mv_bits     = s->mv_bits;
1256
        avctx->misc_bits   = s->misc_bits;
1257
        avctx->i_tex_bits  = s->i_tex_bits;
1258
        avctx->p_tex_bits  = s->p_tex_bits;
1259
        avctx->i_count     = s->i_count;
1260
        avctx->p_count     = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
1261
        avctx->skip_count  = s->skip_count;
1262

    
1263
        MPV_frame_end(s);
1264

    
1265
        if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
1266
            ff_mjpeg_encode_picture_trailer(s);
1267

    
1268
        if(avctx->rc_buffer_size){
1269
            RateControlContext *rcc= &s->rc_context;
1270
            int max_size= rcc->buffer_index * avctx->rc_max_available_vbv_use;
1271

    
1272
            if(put_bits_count(&s->pb) > max_size && s->lambda < s->avctx->lmax){
1273
                s->next_lambda= FFMAX(s->lambda+1, s->lambda*(s->qscale+1) / s->qscale);
1274
                if(s->adaptive_quant){
1275
                    int i;
1276
                    for(i=0; i<s->mb_height*s->mb_stride; i++)
1277
                        s->lambda_table[i]= FFMAX(s->lambda_table[i]+1, s->lambda_table[i]*(s->qscale+1) / s->qscale);
1278
                }
1279
                s->mb_skipped = 0;        //done in MPV_frame_start()
1280
                if(s->pict_type==FF_P_TYPE){ //done in encode_picture() so we must undo it
1281
                    if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
1282
                        s->no_rounding ^= 1;
1283
                }
1284
                if(s->pict_type!=FF_B_TYPE){
1285
                    s->time_base= s->last_time_base;
1286
                    s->last_non_b_time= s->time - s->pp_time;
1287
                }
1288
//                av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);
1289
                for(i=0; i<avctx->thread_count; i++){
1290
                    PutBitContext *pb= &s->thread_context[i]->pb;
1291
                    init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
1292
                }
1293
                goto vbv_retry;
1294
            }
1295

    
1296
            assert(s->avctx->rc_max_rate);
1297
        }
1298

    
1299
        if(s->flags&CODEC_FLAG_PASS1)
1300
            ff_write_pass1_stats(s);
1301

    
1302
        for(i=0; i<4; i++){
1303
            s->current_picture_ptr->error[i]= s->current_picture.error[i];
1304
            avctx->error[i] += s->current_picture_ptr->error[i];
1305
        }
1306

    
1307
        if(s->flags&CODEC_FLAG_PASS1)
1308
            assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb));
1309
        flush_put_bits(&s->pb);
1310
        s->frame_bits  = put_bits_count(&s->pb);
1311

    
1312
        stuffing_count= ff_vbv_update(s, s->frame_bits);
1313
        if(stuffing_count){
1314
            if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){
1315
                av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
1316
                return -1;
1317
            }
1318

    
1319
            switch(s->codec_id){
1320
            case CODEC_ID_MPEG1VIDEO:
1321
            case CODEC_ID_MPEG2VIDEO:
1322
                while(stuffing_count--){
1323
                    put_bits(&s->pb, 8, 0);
1324
                }
1325
            break;
1326
            case CODEC_ID_MPEG4:
1327
                put_bits(&s->pb, 16, 0);
1328
                put_bits(&s->pb, 16, 0x1C3);
1329
                stuffing_count -= 4;
1330
                while(stuffing_count--){
1331
                    put_bits(&s->pb, 8, 0xFF);
1332
                }
1333
            break;
1334
            default:
1335
                av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
1336
            }
1337
            flush_put_bits(&s->pb);
1338
            s->frame_bits  = put_bits_count(&s->pb);
1339
        }
1340

    
1341
        /* update mpeg1/2 vbv_delay for CBR */
1342
        if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1
1343
           && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){
1344
            int vbv_delay, min_delay;
1345
            double inbits = s->avctx->rc_max_rate*av_q2d(s->avctx->time_base);
1346
            int    minbits= s->frame_bits - 8*(s->vbv_delay_ptr - s->pb.buf - 1);
1347
            double bits   = s->rc_context.buffer_index + minbits - inbits;
1348

    
1349
            if(bits<0)
1350
                av_log(s->avctx, AV_LOG_ERROR, "Internal error, negative bits\n");
1351

    
1352
            assert(s->repeat_first_field==0);
1353

    
1354
            vbv_delay=     bits * 90000                               / s->avctx->rc_max_rate;
1355
            min_delay= (minbits * 90000LL + s->avctx->rc_max_rate - 1)/ s->avctx->rc_max_rate;
1356

    
1357
            vbv_delay= FFMAX(vbv_delay, min_delay);
1358

    
1359
            assert(vbv_delay < 0xFFFF);
1360

    
1361
            s->vbv_delay_ptr[0] &= 0xF8;
1362
            s->vbv_delay_ptr[0] |= vbv_delay>>13;
1363
            s->vbv_delay_ptr[1]  = vbv_delay>>5;
1364
            s->vbv_delay_ptr[2] &= 0x07;
1365
            s->vbv_delay_ptr[2] |= vbv_delay<<3;
1366
        }
1367
        s->total_bits += s->frame_bits;
1368
        avctx->frame_bits  = s->frame_bits;
1369
    }else{
1370
        assert((put_bits_ptr(&s->pb) == s->pb.buf));
1371
        s->frame_bits=0;
1372
    }
1373
    assert((s->frame_bits&7)==0);
1374

    
1375
    return s->frame_bits/8;
1376
}
1377

    
1378
static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
1379
{
1380
    static const char tab[64]=
1381
        {3,2,2,1,1,1,1,1,
1382
         1,1,1,1,1,1,1,1,
1383
         1,1,1,1,1,1,1,1,
1384
         0,0,0,0,0,0,0,0,
1385
         0,0,0,0,0,0,0,0,
1386
         0,0,0,0,0,0,0,0,
1387
         0,0,0,0,0,0,0,0,
1388
         0,0,0,0,0,0,0,0};
1389
    int score=0;
1390
    int run=0;
1391
    int i;
1392
    DCTELEM *block= s->block[n];
1393
    const int last_index= s->block_last_index[n];
1394
    int skip_dc;
1395

    
1396
    if(threshold<0){
1397
        skip_dc=0;
1398
        threshold= -threshold;
1399
    }else
1400
        skip_dc=1;
1401

    
1402
    /* Are all we could set to zero already zero? */
1403
    if(last_index<=skip_dc - 1) return;
1404

    
1405
    for(i=0; i<=last_index; i++){
1406
        const int j = s->intra_scantable.permutated[i];
1407
        const int level = FFABS(block[j]);
1408
        if(level==1){
1409
            if(skip_dc && i==0) continue;
1410
            score+= tab[run];
1411
            run=0;
1412
        }else if(level>1){
1413
            return;
1414
        }else{
1415
            run++;
1416
        }
1417
    }
1418
    if(score >= threshold) return;
1419
    for(i=skip_dc; i<=last_index; i++){
1420
        const int j = s->intra_scantable.permutated[i];
1421
        block[j]=0;
1422
    }
1423
    if(block[0]) s->block_last_index[n]= 0;
1424
    else         s->block_last_index[n]= -1;
1425
}
1426

    
1427
static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
1428
{
1429
    int i;
1430
    const int maxlevel= s->max_qcoeff;
1431
    const int minlevel= s->min_qcoeff;
1432
    int overflow=0;
1433

    
1434
    if(s->mb_intra){
1435
        i=1; //skip clipping of intra dc
1436
    }else
1437
        i=0;
1438

    
1439
    for(;i<=last_index; i++){
1440
        const int j= s->intra_scantable.permutated[i];
1441
        int level = block[j];
1442

    
1443
        if     (level>maxlevel){
1444
            level=maxlevel;
1445
            overflow++;
1446
        }else if(level<minlevel){
1447
            level=minlevel;
1448
            overflow++;
1449
        }
1450

    
1451
        block[j]= level;
1452
    }
1453

    
1454
    if(overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
1455
        av_log(s->avctx, AV_LOG_INFO, "warning, clipping %d dct coefficients to %d..%d\n", overflow, minlevel, maxlevel);
1456
}
1457

    
1458
static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride){
1459
    int x, y;
1460
//FIXME optimize
1461
    for(y=0; y<8; y++){
1462
        for(x=0; x<8; x++){
1463
            int x2, y2;
1464
            int sum=0;
1465
            int sqr=0;
1466
            int count=0;
1467

    
1468
            for(y2= FFMAX(y-1, 0); y2 < FFMIN(8, y+2); y2++){
1469
                for(x2= FFMAX(x-1, 0); x2 < FFMIN(8, x+2); x2++){
1470
                    int v= ptr[x2 + y2*stride];
1471
                    sum += v;
1472
                    sqr += v*v;
1473
                    count++;
1474
                }
1475
            }
1476
            weight[x + 8*y]= (36*ff_sqrt(count*sqr - sum*sum)) / count;
1477
        }
1478
    }
1479
}
1480

    
1481
static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x, int motion_y, int mb_block_height, int mb_block_count)
1482
{
1483
    int16_t weight[8][64];
1484
    DCTELEM orig[8][64];
1485
    const int mb_x= s->mb_x;
1486
    const int mb_y= s->mb_y;
1487
    int i;
1488
    int skip_dct[8];
1489
    int dct_offset   = s->linesize*8; //default for progressive frames
1490
    uint8_t *ptr_y, *ptr_cb, *ptr_cr;
1491
    int wrap_y, wrap_c;
1492

    
1493
    for(i=0; i<mb_block_count; i++) skip_dct[i]=s->skipdct;
1494

    
1495
    if(s->adaptive_quant){
1496
        const int last_qp= s->qscale;
1497
        const int mb_xy= mb_x + mb_y*s->mb_stride;
1498

    
1499
        s->lambda= s->lambda_table[mb_xy];
1500
        update_qscale(s);
1501

    
1502
        if(!(s->flags&CODEC_FLAG_QP_RD)){
1503
            s->qscale= s->current_picture_ptr->qscale_table[mb_xy];
1504
            s->dquant= s->qscale - last_qp;
1505

    
1506
            if(s->out_format==FMT_H263){
1507
                s->dquant= av_clip(s->dquant, -2, 2);
1508

    
1509
                if(s->codec_id==CODEC_ID_MPEG4){
1510
                    if(!s->mb_intra){
1511
                        if(s->pict_type == FF_B_TYPE){
1512
                            if(s->dquant&1 || s->mv_dir&MV_DIRECT)
1513
                                s->dquant= 0;
1514
                        }
1515
                        if(s->mv_type==MV_TYPE_8X8)
1516
                            s->dquant=0;
1517
                    }
1518
                }
1519
            }
1520
        }
1521
        ff_set_qscale(s, last_qp + s->dquant);
1522
    }else if(s->flags&CODEC_FLAG_QP_RD)
1523
        ff_set_qscale(s, s->qscale + s->dquant);
1524

    
1525
    wrap_y = s->linesize;
1526
    wrap_c = s->uvlinesize;
1527
    ptr_y = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
1528
    ptr_cb = s->new_picture.data[1] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
1529
    ptr_cr = s->new_picture.data[2] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
1530

    
1531
    if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
1532
        uint8_t *ebuf= s->edge_emu_buffer + 32;
1533
        ff_emulated_edge_mc(ebuf            , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width   , s->height);
1534
        ptr_y= ebuf;
1535
        ff_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);
1536
        ptr_cb= ebuf+18*wrap_y;
1537
        ff_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);
1538
        ptr_cr= ebuf+18*wrap_y+8;
1539
    }
1540

    
1541
    if (s->mb_intra) {
1542
        if(s->flags&CODEC_FLAG_INTERLACED_DCT){
1543
            int progressive_score, interlaced_score;
1544

    
1545
            s->interlaced_dct=0;
1546
            progressive_score= s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y, 8)
1547
                              +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;
1548

    
1549
            if(progressive_score > 0){
1550
                interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y           , NULL, wrap_y*2, 8)
1551
                                  +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y  , NULL, wrap_y*2, 8);
1552
                if(progressive_score > interlaced_score){
1553
                    s->interlaced_dct=1;
1554

    
1555
                    dct_offset= wrap_y;
1556
                    wrap_y<<=1;
1557
                    if (s->chroma_format == CHROMA_422)
1558
                        wrap_c<<=1;
1559
                }
1560
            }
1561
        }
1562

    
1563
        s->dsp.get_pixels(s->block[0], ptr_y                 , wrap_y);
1564
        s->dsp.get_pixels(s->block[1], ptr_y              + 8, wrap_y);
1565
        s->dsp.get_pixels(s->block[2], ptr_y + dct_offset    , wrap_y);
1566
        s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
1567

    
1568
        if(s->flags&CODEC_FLAG_GRAY){
1569
            skip_dct[4]= 1;
1570
            skip_dct[5]= 1;
1571
        }else{
1572
            s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
1573
            s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
1574
            if(!s->chroma_y_shift){ /* 422 */
1575
                s->dsp.get_pixels(s->block[6], ptr_cb + (dct_offset>>1), wrap_c);
1576
                s->dsp.get_pixels(s->block[7], ptr_cr + (dct_offset>>1), wrap_c);
1577
            }
1578
        }
1579
    }else{
1580
        op_pixels_func (*op_pix)[4];
1581
        qpel_mc_func (*op_qpix)[16];
1582
        uint8_t *dest_y, *dest_cb, *dest_cr;
1583

    
1584
        dest_y  = s->dest[0];
1585
        dest_cb = s->dest[1];
1586
        dest_cr = s->dest[2];
1587

    
1588
        if ((!s->no_rounding) || s->pict_type==FF_B_TYPE){
1589
            op_pix = s->dsp.put_pixels_tab;
1590
            op_qpix= s->dsp.put_qpel_pixels_tab;
1591
        }else{
1592
            op_pix = s->dsp.put_no_rnd_pixels_tab;
1593
            op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
1594
        }
1595

    
1596
        if (s->mv_dir & MV_DIR_FORWARD) {
1597
            MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
1598
            op_pix = s->dsp.avg_pixels_tab;
1599
            op_qpix= s->dsp.avg_qpel_pixels_tab;
1600
        }
1601
        if (s->mv_dir & MV_DIR_BACKWARD) {
1602
            MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
1603
        }
1604

    
1605
        if(s->flags&CODEC_FLAG_INTERLACED_DCT){
1606
            int progressive_score, interlaced_score;
1607

    
1608
            s->interlaced_dct=0;
1609
            progressive_score= s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y, 8)
1610
                              +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;
1611

    
1612
            if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;
1613

    
1614
            if(progressive_score>0){
1615
                interlaced_score = s->dsp.ildct_cmp[0](s, dest_y           , ptr_y           , wrap_y*2, 8)
1616
                                  +s->dsp.ildct_cmp[0](s, dest_y + wrap_y  , ptr_y + wrap_y  , wrap_y*2, 8);
1617

    
1618
                if(progressive_score > interlaced_score){
1619
                    s->interlaced_dct=1;
1620

    
1621
                    dct_offset= wrap_y;
1622
                    wrap_y<<=1;
1623
                    if (s->chroma_format == CHROMA_422)
1624
                        wrap_c<<=1;
1625
                }
1626
            }
1627
        }
1628

    
1629
        s->dsp.diff_pixels(s->block[0], ptr_y                 , dest_y                 , wrap_y);
1630
        s->dsp.diff_pixels(s->block[1], ptr_y              + 8, dest_y              + 8, wrap_y);
1631
        s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset    , dest_y + dct_offset    , wrap_y);
1632
        s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
1633

    
1634
        if(s->flags&CODEC_FLAG_GRAY){
1635
            skip_dct[4]= 1;
1636
            skip_dct[5]= 1;
1637
        }else{
1638
            s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
1639
            s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
1640
            if(!s->chroma_y_shift){ /* 422 */
1641
                s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset>>1), dest_cb + (dct_offset>>1), wrap_c);
1642
                s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset>>1), dest_cr + (dct_offset>>1), wrap_c);
1643
            }
1644
        }
1645
        /* pre quantization */
1646
        if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
1647
            //FIXME optimize
1648
            if(s->dsp.sad[1](NULL, ptr_y               , dest_y               , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;
1649
            if(s->dsp.sad[1](NULL, ptr_y            + 8, dest_y            + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;
1650
            if(s->dsp.sad[1](NULL, ptr_y +dct_offset   , dest_y +dct_offset   , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;
1651
            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;
1652
            if(s->dsp.sad[1](NULL, ptr_cb              , dest_cb              , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;
1653
            if(s->dsp.sad[1](NULL, ptr_cr              , dest_cr              , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;
1654
            if(!s->chroma_y_shift){ /* 422 */
1655
                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;
1656
                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;
1657
            }
1658
        }
1659
    }
1660

    
1661
    if(s->avctx->quantizer_noise_shaping){
1662
        if(!skip_dct[0]) get_visual_weight(weight[0], ptr_y                 , wrap_y);
1663
        if(!skip_dct[1]) get_visual_weight(weight[1], ptr_y              + 8, wrap_y);
1664
        if(!skip_dct[2]) get_visual_weight(weight[2], ptr_y + dct_offset    , wrap_y);
1665
        if(!skip_dct[3]) get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
1666
        if(!skip_dct[4]) get_visual_weight(weight[4], ptr_cb                , wrap_c);
1667
        if(!skip_dct[5]) get_visual_weight(weight[5], ptr_cr                , wrap_c);
1668
        if(!s->chroma_y_shift){ /* 422 */
1669
            if(!skip_dct[6]) get_visual_weight(weight[6], ptr_cb + (dct_offset>>1), wrap_c);
1670
            if(!skip_dct[7]) get_visual_weight(weight[7], ptr_cr + (dct_offset>>1), wrap_c);
1671
        }
1672
        memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*mb_block_count);
1673
    }
1674

    
1675
    /* DCT & quantize */
1676
    assert(s->out_format!=FMT_MJPEG || s->qscale==8);
1677
    {
1678
        for(i=0;i<mb_block_count;i++) {
1679
            if(!skip_dct[i]){
1680
                int overflow;
1681
                s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
1682
            // FIXME we could decide to change to quantizer instead of clipping
1683
            // JS: I don't think that would be a good idea it could lower quality instead
1684
            //     of improve it. Just INTRADC clipping deserves changes in quantizer
1685
                if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
1686
            }else
1687
                s->block_last_index[i]= -1;
1688
        }
1689
        if(s->avctx->quantizer_noise_shaping){
1690
            for(i=0;i<mb_block_count;i++) {
1691
                if(!skip_dct[i]){
1692
                    s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);
1693
                }
1694
            }
1695
        }
1696

    
1697
        if(s->luma_elim_threshold && !s->mb_intra)
1698
            for(i=0; i<4; i++)
1699
                dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
1700
        if(s->chroma_elim_threshold && !s->mb_intra)
1701
            for(i=4; i<mb_block_count; i++)
1702
                dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
1703

    
1704
        if(s->flags & CODEC_FLAG_CBP_RD){
1705
            for(i=0;i<mb_block_count;i++) {
1706
                if(s->block_last_index[i] == -1)
1707
                    s->coded_score[i]= INT_MAX/256;
1708
            }
1709
        }
1710
    }
1711

    
1712
    if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
1713
        s->block_last_index[4]=
1714
        s->block_last_index[5]= 0;
1715
        s->block[4][0]=
1716
        s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
1717
    }
1718

    
1719
    //non c quantize code returns incorrect block_last_index FIXME
1720
    if(s->alternate_scan && s->dct_quantize != dct_quantize_c){
1721
        for(i=0; i<mb_block_count; i++){
1722
            int j;
1723
            if(s->block_last_index[i]>0){
1724
                for(j=63; j>0; j--){
1725
                    if(s->block[i][ s->intra_scantable.permutated[j] ]) break;
1726
                }
1727
                s->block_last_index[i]= j;
1728
            }
1729
        }
1730
    }
1731

    
1732
    /* huffman encode */
1733
    switch(s->codec_id){ //FIXME funct ptr could be slightly faster
1734
    case CODEC_ID_MPEG1VIDEO:
1735
    case CODEC_ID_MPEG2VIDEO:
1736
        if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
1737
            mpeg1_encode_mb(s, s->block, motion_x, motion_y);
1738
        break;
1739
    case CODEC_ID_MPEG4:
1740
        if (CONFIG_MPEG4_ENCODER)
1741
            mpeg4_encode_mb(s, s->block, motion_x, motion_y);
1742
        break;
1743
    case CODEC_ID_MSMPEG4V2:
1744
    case CODEC_ID_MSMPEG4V3:
1745
    case CODEC_ID_WMV1:
1746
        if (CONFIG_MSMPEG4_ENCODER)
1747
            msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
1748
        break;
1749
    case CODEC_ID_WMV2:
1750
        if (CONFIG_WMV2_ENCODER)
1751
            ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
1752
        break;
1753
    case CODEC_ID_H261:
1754
        if (CONFIG_H261_ENCODER)
1755
            ff_h261_encode_mb(s, s->block, motion_x, motion_y);
1756
        break;
1757
    case CODEC_ID_H263:
1758
    case CODEC_ID_H263P:
1759
    case CODEC_ID_FLV1:
1760
    case CODEC_ID_RV10:
1761
    case CODEC_ID_RV20:
1762
        if (CONFIG_H263_ENCODER)
1763
            h263_encode_mb(s, s->block, motion_x, motion_y);
1764
        break;
1765
    case CODEC_ID_MJPEG:
1766
        if (CONFIG_MJPEG_ENCODER)
1767
            ff_mjpeg_encode_mb(s, s->block);
1768
        break;
1769
    default:
1770
        assert(0);
1771
    }
1772
}
1773

    
1774
static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
1775
{
1776
    if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y,  8, 6);
1777
    else                                encode_mb_internal(s, motion_x, motion_y, 16, 8);
1778
}
1779

    
1780
static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
1781
    int i;
1782

    
1783
    memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
1784

    
1785
    /* mpeg1 */
1786
    d->mb_skip_run= s->mb_skip_run;
1787
    for(i=0; i<3; i++)
1788
        d->last_dc[i]= s->last_dc[i];
1789

    
1790
    /* statistics */
1791
    d->mv_bits= s->mv_bits;
1792
    d->i_tex_bits= s->i_tex_bits;
1793
    d->p_tex_bits= s->p_tex_bits;
1794
    d->i_count= s->i_count;
1795
    d->f_count= s->f_count;
1796
    d->b_count= s->b_count;
1797
    d->skip_count= s->skip_count;
1798
    d->misc_bits= s->misc_bits;
1799
    d->last_bits= 0;
1800

    
1801
    d->mb_skipped= 0;
1802
    d->qscale= s->qscale;
1803
    d->dquant= s->dquant;
1804

    
1805
    d->esc3_level_length= s->esc3_level_length;
1806
}
1807

    
1808
static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
1809
    int i;
1810

    
1811
    memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
1812
    memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
1813

    
1814
    /* mpeg1 */
1815
    d->mb_skip_run= s->mb_skip_run;
1816
    for(i=0; i<3; i++)
1817
        d->last_dc[i]= s->last_dc[i];
1818

    
1819
    /* statistics */
1820
    d->mv_bits= s->mv_bits;
1821
    d->i_tex_bits= s->i_tex_bits;
1822
    d->p_tex_bits= s->p_tex_bits;
1823
    d->i_count= s->i_count;
1824
    d->f_count= s->f_count;
1825
    d->b_count= s->b_count;
1826
    d->skip_count= s->skip_count;
1827
    d->misc_bits= s->misc_bits;
1828

    
1829
    d->mb_intra= s->mb_intra;
1830
    d->mb_skipped= s->mb_skipped;
1831
    d->mv_type= s->mv_type;
1832
    d->mv_dir= s->mv_dir;
1833
    d->pb= s->pb;
1834
    if(s->data_partitioning){
1835
        d->pb2= s->pb2;
1836
        d->tex_pb= s->tex_pb;
1837
    }
1838
    d->block= s->block;
1839
    for(i=0; i<8; i++)
1840
        d->block_last_index[i]= s->block_last_index[i];
1841
    d->interlaced_dct= s->interlaced_dct;
1842
    d->qscale= s->qscale;
1843

    
1844
    d->esc3_level_length= s->esc3_level_length;
1845
}
1846

    
1847
static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
1848
                           PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
1849
                           int *dmin, int *next_block, int motion_x, int motion_y)
1850
{
1851
    int score;
1852
    uint8_t *dest_backup[3];
1853

    
1854
    copy_context_before_encode(s, backup, type);
1855

    
1856
    s->block= s->blocks[*next_block];
1857
    s->pb= pb[*next_block];
1858
    if(s->data_partitioning){
1859
        s->pb2   = pb2   [*next_block];
1860
        s->tex_pb= tex_pb[*next_block];
1861
    }
1862

    
1863
    if(*next_block){
1864
        memcpy(dest_backup, s->dest, sizeof(s->dest));
1865
        s->dest[0] = s->rd_scratchpad;
1866
        s->dest[1] = s->rd_scratchpad + 16*s->linesize;
1867
        s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
1868
        assert(s->linesize >= 32); //FIXME
1869
    }
1870

    
1871
    encode_mb(s, motion_x, motion_y);
1872

    
1873
    score= put_bits_count(&s->pb);
1874
    if(s->data_partitioning){
1875
        score+= put_bits_count(&s->pb2);
1876
        score+= put_bits_count(&s->tex_pb);
1877
    }
1878

    
1879
    if(s->avctx->mb_decision == FF_MB_DECISION_RD){
1880
        MPV_decode_mb(s, s->block);
1881

    
1882
        score *= s->lambda2;
1883
        score += sse_mb(s) << FF_LAMBDA_SHIFT;
1884
    }
1885

    
1886
    if(*next_block){
1887
        memcpy(s->dest, dest_backup, sizeof(s->dest));
1888
    }
1889

    
1890
    if(score<*dmin){
1891
        *dmin= score;
1892
        *next_block^=1;
1893

    
1894
        copy_context_after_encode(best, s, type);
1895
    }
1896
}
1897

    
1898
static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
1899
    uint32_t *sq = ff_squareTbl + 256;
1900
    int acc=0;
1901
    int x,y;
1902

    
1903
    if(w==16 && h==16)
1904
        return s->dsp.sse[0](NULL, src1, src2, stride, 16);
1905
    else if(w==8 && h==8)
1906
        return s->dsp.sse[1](NULL, src1, src2, stride, 8);
1907

    
1908
    for(y=0; y<h; y++){
1909
        for(x=0; x<w; x++){
1910
            acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
1911
        }
1912
    }
1913

    
1914
    assert(acc>=0);
1915

    
1916
    return acc;
1917
}
1918

    
1919
static int sse_mb(MpegEncContext *s){
1920
    int w= 16;
1921
    int h= 16;
1922

    
1923
    if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
1924
    if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
1925

    
1926
    if(w==16 && h==16)
1927
      if(s->avctx->mb_cmp == FF_CMP_NSSE){
1928
        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)
1929
               +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)
1930
               +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);
1931
      }else{
1932
        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)
1933
               +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)
1934
               +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);
1935
      }
1936
    else
1937
        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)
1938
               +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)
1939
               +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);
1940
}
1941

    
1942
static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
1943
    MpegEncContext *s= *(void**)arg;
1944

    
1945

    
1946
    s->me.pre_pass=1;
1947
    s->me.dia_size= s->avctx->pre_dia_size;
1948
    s->first_slice_line=1;
1949
    for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
1950
        for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
1951
            ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
1952
        }
1953
        s->first_slice_line=0;
1954
    }
1955

    
1956
    s->me.pre_pass=0;
1957

    
1958
    return 0;
1959
}
1960

    
1961
static int estimate_motion_thread(AVCodecContext *c, void *arg){
1962
    MpegEncContext *s= *(void**)arg;
1963

    
1964
    ff_check_alignment();
1965

    
1966
    s->me.dia_size= s->avctx->dia_size;
1967
    s->first_slice_line=1;
1968
    for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
1969
        s->mb_x=0; //for block init below
1970
        ff_init_block_index(s);
1971
        for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
1972
            s->block_index[0]+=2;
1973
            s->block_index[1]+=2;
1974
            s->block_index[2]+=2;
1975
            s->block_index[3]+=2;
1976

    
1977
            /* compute motion vector & mb_type and store in context */
1978
            if(s->pict_type==FF_B_TYPE)
1979
                ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
1980
            else
1981
                ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
1982
        }
1983
        s->first_slice_line=0;
1984
    }
1985
    return 0;
1986
}
1987

    
1988
static int mb_var_thread(AVCodecContext *c, void *arg){
1989
    MpegEncContext *s= *(void**)arg;
1990
    int mb_x, mb_y;
1991

    
1992
    ff_check_alignment();
1993

    
1994
    for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
1995
        for(mb_x=0; mb_x < s->mb_width; mb_x++) {
1996
            int xx = mb_x * 16;
1997
            int yy = mb_y * 16;
1998
            uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
1999
            int varc;
2000
            int sum = s->dsp.pix_sum(pix, s->linesize);
2001

    
2002
            varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
2003

    
2004
            s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
2005
            s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
2006
            s->me.mb_var_sum_temp    += varc;
2007
        }
2008
    }
2009
    return 0;
2010
}
2011

    
2012
static void write_slice_end(MpegEncContext *s){
2013
    if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4){
2014
        if(s->partitioned_frame){
2015
            ff_mpeg4_merge_partitions(s);
2016
        }
2017

    
2018
        ff_mpeg4_stuffing(&s->pb);
2019
    }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
2020
        ff_mjpeg_encode_stuffing(&s->pb);
2021
    }
2022

    
2023
    align_put_bits(&s->pb);
2024
    flush_put_bits(&s->pb);
2025

    
2026
    if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
2027
        s->misc_bits+= get_bits_diff(s);
2028
}
2029

    
2030
static int encode_thread(AVCodecContext *c, void *arg){
2031
    MpegEncContext *s= *(void**)arg;
2032
    int mb_x, mb_y, pdif = 0;
2033
    int chr_h= 16>>s->chroma_y_shift;
2034
    int i, j;
2035
    MpegEncContext best_s, backup_s;
2036
    uint8_t bit_buf[2][MAX_MB_BYTES];
2037
    uint8_t bit_buf2[2][MAX_MB_BYTES];
2038
    uint8_t bit_buf_tex[2][MAX_MB_BYTES];
2039
    PutBitContext pb[2], pb2[2], tex_pb[2];
2040
//printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
2041

    
2042
    ff_check_alignment();
2043

    
2044
    for(i=0; i<2; i++){
2045
        init_put_bits(&pb    [i], bit_buf    [i], MAX_MB_BYTES);
2046
        init_put_bits(&pb2   [i], bit_buf2   [i], MAX_MB_BYTES);
2047
        init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
2048
    }
2049

    
2050
    s->last_bits= put_bits_count(&s->pb);
2051
    s->mv_bits=0;
2052
    s->misc_bits=0;
2053
    s->i_tex_bits=0;
2054
    s->p_tex_bits=0;
2055
    s->i_count=0;
2056
    s->f_count=0;
2057
    s->b_count=0;
2058
    s->skip_count=0;
2059

    
2060
    for(i=0; i<3; i++){
2061
        /* init last dc values */
2062
        /* note: quant matrix value (8) is implied here */
2063
        s->last_dc[i] = 128 << s->intra_dc_precision;
2064

    
2065
        s->current_picture.error[i] = 0;
2066
    }
2067
    s->mb_skip_run = 0;
2068
    memset(s->last_mv, 0, sizeof(s->last_mv));
2069

    
2070
    s->last_mv_dir = 0;
2071

    
2072
    switch(s->codec_id){
2073
    case CODEC_ID_H263:
2074
    case CODEC_ID_H263P:
2075
    case CODEC_ID_FLV1:
2076
        if (CONFIG_H263_ENCODER)
2077
            s->gob_index = ff_h263_get_gob_height(s);
2078
        break;
2079
    case CODEC_ID_MPEG4:
2080
        if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
2081
            ff_mpeg4_init_partitions(s);
2082
        break;
2083
    }
2084

    
2085
    s->resync_mb_x=0;
2086
    s->resync_mb_y=0;
2087
    s->first_slice_line = 1;
2088
    s->ptr_lastgob = s->pb.buf;
2089
    for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
2090
//    printf("row %d at %X\n", s->mb_y, (int)s);
2091
        s->mb_x=0;
2092
        s->mb_y= mb_y;
2093

    
2094
        ff_set_qscale(s, s->qscale);
2095
        ff_init_block_index(s);
2096

    
2097
        for(mb_x=0; mb_x < s->mb_width; mb_x++) {
2098
            int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
2099
            int mb_type= s->mb_type[xy];
2100
//            int d;
2101
            int dmin= INT_MAX;
2102
            int dir;
2103

    
2104
            if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
2105
                av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
2106
                return -1;
2107
            }
2108
            if(s->data_partitioning){
2109
                if(   s->pb2   .buf_end - s->pb2   .buf - (put_bits_count(&s->    pb2)>>3) < MAX_MB_BYTES
2110
                   || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
2111
                    av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
2112
                    return -1;
2113
                }
2114
            }
2115

    
2116
            s->mb_x = mb_x;
2117
            s->mb_y = mb_y;  // moved into loop, can get changed by H.261
2118
            ff_update_block_index(s);
2119

    
2120
            if(CONFIG_H261_ENCODER && s->codec_id == CODEC_ID_H261){
2121
                ff_h261_reorder_mb_index(s);
2122
                xy= s->mb_y*s->mb_stride + s->mb_x;
2123
                mb_type= s->mb_type[xy];
2124
            }
2125

    
2126
            /* write gob / video packet header  */
2127
            if(s->rtp_mode){
2128
                int current_packet_size, is_gob_start;
2129

    
2130
                current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
2131

    
2132
                is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
2133

    
2134
                if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
2135

    
2136
                switch(s->codec_id){
2137
                case CODEC_ID_H263:
2138
                case CODEC_ID_H263P:
2139
                    if(!s->h263_slice_structured)
2140
                        if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
2141
                    break;
2142
                case CODEC_ID_MPEG2VIDEO:
2143
                    if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
2144
                case CODEC_ID_MPEG1VIDEO:
2145
                    if(s->mb_skip_run) is_gob_start=0;
2146
                    break;
2147
                }
2148

    
2149
                if(is_gob_start){
2150
                    if(s->start_mb_y != mb_y || mb_x!=0){
2151
                        write_slice_end(s);
2152

    
2153
                        if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
2154
                            ff_mpeg4_init_partitions(s);
2155
                        }
2156
                    }
2157

    
2158
                    assert((put_bits_count(&s->pb)&7) == 0);
2159
                    current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
2160

    
2161
                    if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
2162
                        int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
2163
                        int d= 100 / s->avctx->error_rate;
2164
                        if(r % d == 0){
2165
                            current_packet_size=0;
2166
#ifndef ALT_BITSTREAM_WRITER
2167
                            s->pb.buf_ptr= s->ptr_lastgob;
2168
#endif
2169
                            assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
2170
                        }
2171
                    }
2172

    
2173
                    if (s->avctx->rtp_callback){
2174
                        int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
2175
                        s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
2176
                    }
2177

    
2178
                    switch(s->codec_id){
2179
                    case CODEC_ID_MPEG4:
2180
                        if (CONFIG_MPEG4_ENCODER) {
2181
                            ff_mpeg4_encode_video_packet_header(s);
2182
                            ff_mpeg4_clean_buffers(s);
2183
                        }
2184
                    break;
2185
                    case CODEC_ID_MPEG1VIDEO:
2186
                    case CODEC_ID_MPEG2VIDEO:
2187
                        if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
2188
                            ff_mpeg1_encode_slice_header(s);
2189
                            ff_mpeg1_clean_buffers(s);
2190
                        }
2191
                    break;
2192
                    case CODEC_ID_H263:
2193
                    case CODEC_ID_H263P:
2194
                        if (CONFIG_H263_ENCODER)
2195
                            h263_encode_gob_header(s, mb_y);
2196
                    break;
2197
                    }
2198

    
2199
                    if(s->flags&CODEC_FLAG_PASS1){
2200
                        int bits= put_bits_count(&s->pb);
2201
                        s->misc_bits+= bits - s->last_bits;
2202
                        s->last_bits= bits;
2203
                    }
2204

    
2205
                    s->ptr_lastgob += current_packet_size;
2206
                    s->first_slice_line=1;
2207
                    s->resync_mb_x=mb_x;
2208
                    s->resync_mb_y=mb_y;
2209
                }
2210
            }
2211

    
2212
            if(  (s->resync_mb_x   == s->mb_x)
2213
               && s->resync_mb_y+1 == s->mb_y){
2214
                s->first_slice_line=0;
2215
            }
2216

    
2217
            s->mb_skipped=0;
2218
            s->dquant=0; //only for QP_RD
2219

    
2220
            if(mb_type & (mb_type-1) || (s->flags & CODEC_FLAG_QP_RD)){ // more than 1 MB type possible or CODEC_FLAG_QP_RD
2221
                int next_block=0;
2222
                int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
2223

    
2224
                copy_context_before_encode(&backup_s, s, -1);
2225
                backup_s.pb= s->pb;
2226
                best_s.data_partitioning= s->data_partitioning;
2227
                best_s.partitioned_frame= s->partitioned_frame;
2228
                if(s->data_partitioning){
2229
                    backup_s.pb2= s->pb2;
2230
                    backup_s.tex_pb= s->tex_pb;
2231
                }
2232

    
2233
                if(mb_type&CANDIDATE_MB_TYPE_INTER){
2234
                    s->mv_dir = MV_DIR_FORWARD;
2235
                    s->mv_type = MV_TYPE_16X16;
2236
                    s->mb_intra= 0;
2237
                    s->mv[0][0][0] = s->p_mv_table[xy][0];
2238
                    s->mv[0][0][1] = s->p_mv_table[xy][1];
2239
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
2240
                                 &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2241
                }
2242
                if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
2243
                    s->mv_dir = MV_DIR_FORWARD;
2244
                    s->mv_type = MV_TYPE_FIELD;
2245
                    s->mb_intra= 0;
2246
                    for(i=0; i<2; i++){
2247
                        j= s->field_select[0][i] = s->p_field_select_table[i][xy];
2248
                        s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
2249
                        s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
2250
                    }
2251
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
2252
                                 &dmin, &next_block, 0, 0);
2253
                }
2254
                if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
2255
                    s->mv_dir = MV_DIR_FORWARD;
2256
                    s->mv_type = MV_TYPE_16X16;
2257
                    s->mb_intra= 0;
2258
                    s->mv[0][0][0] = 0;
2259
                    s->mv[0][0][1] = 0;
2260
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
2261
                                 &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2262
                }
2263
                if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
2264
                    s->mv_dir = MV_DIR_FORWARD;
2265
                    s->mv_type = MV_TYPE_8X8;
2266
                    s->mb_intra= 0;
2267
                    for(i=0; i<4; i++){
2268
                        s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
2269
                        s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
2270
                    }
2271
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
2272
                                 &dmin, &next_block, 0, 0);
2273
                }
2274
                if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
2275
                    s->mv_dir = MV_DIR_FORWARD;
2276
                    s->mv_type = MV_TYPE_16X16;
2277
                    s->mb_intra= 0;
2278
                    s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
2279
                    s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
2280
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
2281
                                 &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
2282
                }
2283
                if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
2284
                    s->mv_dir = MV_DIR_BACKWARD;
2285
                    s->mv_type = MV_TYPE_16X16;
2286
                    s->mb_intra= 0;
2287
                    s->mv[1][0][0] = s->b_back_mv_table[xy][0];
2288
                    s->mv[1][0][1] = s->b_back_mv_table[xy][1];
2289
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
2290
                                 &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
2291
                }
2292
                if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
2293
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2294
                    s->mv_type = MV_TYPE_16X16;
2295
                    s->mb_intra= 0;
2296
                    s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
2297
                    s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
2298
                    s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
2299
                    s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
2300
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
2301
                                 &dmin, &next_block, 0, 0);
2302
                }
2303
                if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
2304
                    s->mv_dir = MV_DIR_FORWARD;
2305
                    s->mv_type = MV_TYPE_FIELD;
2306
                    s->mb_intra= 0;
2307
                    for(i=0; i<2; i++){
2308
                        j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
2309
                        s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
2310
                        s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
2311
                    }
2312
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
2313
                                 &dmin, &next_block, 0, 0);
2314
                }
2315
                if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
2316
                    s->mv_dir = MV_DIR_BACKWARD;
2317
                    s->mv_type = MV_TYPE_FIELD;
2318
                    s->mb_intra= 0;
2319
                    for(i=0; i<2; i++){
2320
                        j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
2321
                        s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
2322
                        s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
2323
                    }
2324
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
2325
                                 &dmin, &next_block, 0, 0);
2326
                }
2327
                if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
2328
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2329
                    s->mv_type = MV_TYPE_FIELD;
2330
                    s->mb_intra= 0;
2331
                    for(dir=0; dir<2; dir++){
2332
                        for(i=0; i<2; i++){
2333
                            j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
2334
                            s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
2335
                            s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
2336
                        }
2337
                    }
2338
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
2339
                                 &dmin, &next_block, 0, 0);
2340
                }
2341
                if(mb_type&CANDIDATE_MB_TYPE_INTRA){
2342
                    s->mv_dir = 0;
2343
                    s->mv_type = MV_TYPE_16X16;
2344
                    s->mb_intra= 1;
2345
                    s->mv[0][0][0] = 0;
2346
                    s->mv[0][0][1] = 0;
2347
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
2348
                                 &dmin, &next_block, 0, 0);
2349
                    if(s->h263_pred || s->h263_aic){
2350
                        if(best_s.mb_intra)
2351
                            s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
2352
                        else
2353
                            ff_clean_intra_table_entries(s); //old mode?
2354
                    }
2355
                }
2356

    
2357
                if((s->flags & CODEC_FLAG_QP_RD) && dmin < INT_MAX){
2358
                    if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
2359
                        const int last_qp= backup_s.qscale;
2360
                        int qpi, qp, dc[6];
2361
                        DCTELEM ac[6][16];
2362
                        const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
2363
                        static const int dquant_tab[4]={-1,1,-2,2};
2364

    
2365
                        assert(backup_s.dquant == 0);
2366

    
2367
                        //FIXME intra
2368
                        s->mv_dir= best_s.mv_dir;
2369
                        s->mv_type = MV_TYPE_16X16;
2370
                        s->mb_intra= best_s.mb_intra;
2371
                        s->mv[0][0][0] = best_s.mv[0][0][0];
2372
                        s->mv[0][0][1] = best_s.mv[0][0][1];
2373
                        s->mv[1][0][0] = best_s.mv[1][0][0];
2374
                        s->mv[1][0][1] = best_s.mv[1][0][1];
2375

    
2376
                        qpi = s->pict_type == FF_B_TYPE ? 2 : 0;
2377
                        for(; qpi<4; qpi++){
2378
                            int dquant= dquant_tab[qpi];
2379
                            qp= last_qp + dquant;
2380
                            if(qp < s->avctx->qmin || qp > s->avctx->qmax)
2381
                                continue;
2382
                            backup_s.dquant= dquant;
2383
                            if(s->mb_intra && s->dc_val[0]){
2384
                                for(i=0; i<6; i++){
2385
                                    dc[i]= s->dc_val[0][ s->block_index[i] ];
2386
                                    memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(DCTELEM)*16);
2387
                                }
2388
                            }
2389

    
2390
                            encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
2391
                                         &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
2392
                            if(best_s.qscale != qp){
2393
                                if(s->mb_intra && s->dc_val[0]){
2394
                                    for(i=0; i<6; i++){
2395
                                        s->dc_val[0][ s->block_index[i] ]= dc[i];
2396
                                        memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(DCTELEM)*16);
2397
                                    }
2398
                                }
2399
                            }
2400
                        }
2401
                    }
2402
                }
2403
                if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
2404
                    int mx= s->b_direct_mv_table[xy][0];
2405
                    int my= s->b_direct_mv_table[xy][1];
2406

    
2407
                    backup_s.dquant = 0;
2408
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2409
                    s->mb_intra= 0;
2410
                    ff_mpeg4_set_direct_mv(s, mx, my);
2411
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
2412
                                 &dmin, &next_block, mx, my);
2413
                }
2414
                if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
2415
                    backup_s.dquant = 0;
2416
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
2417
                    s->mb_intra= 0;
2418
                    ff_mpeg4_set_direct_mv(s, 0, 0);
2419
                    encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
2420
                                 &dmin, &next_block, 0, 0);
2421
                }
2422
                if(!best_s.mb_intra && s->flags2&CODEC_FLAG2_SKIP_RD){
2423
                    int coded=0;
2424
                    for(i=0; i<6; i++)
2425
                        coded |= s->block_last_index[i];
2426
                    if(coded){
2427
                        int mx,my;
2428
                        memcpy(s->mv, best_s.mv, sizeof(s->mv));
2429
                        if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
2430
                            mx=my=0; //FIXME find the one we actually used
2431
                            ff_mpeg4_set_direct_mv(s, mx, my);
2432
                        }else if(best_s.mv_dir&MV_DIR_BACKWARD){
2433
                            mx= s->mv[1][0][0];
2434
                            my= s->mv[1][0][1];
2435
                        }else{
2436
                            mx= s->mv[0][0][0];
2437
                            my= s->mv[0][0][1];
2438
                        }
2439

    
2440
                        s->mv_dir= best_s.mv_dir;
2441
                        s->mv_type = best_s.mv_type;
2442
                        s->mb_intra= 0;
2443
/*                        s->mv[0][0][0] = best_s.mv[0][0][0];
2444
                        s->mv[0][0][1] = best_s.mv[0][0][1];
2445
                        s->mv[1][0][0] = best_s.mv[1][0][0];
2446
                        s->mv[1][0][1] = best_s.mv[1][0][1];*/
2447
                        backup_s.dquant= 0;
2448
                        s->skipdct=1;
2449
                        encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
2450
                                        &dmin, &next_block, mx, my);
2451
                        s->skipdct=0;
2452
                    }
2453
                }
2454

    
2455
                s->current_picture.qscale_table[xy]= best_s.qscale;
2456

    
2457
                copy_context_after_encode(s, &best_s, -1);
2458

    
2459
                pb_bits_count= put_bits_count(&s->pb);
2460
                flush_put_bits(&s->pb);
2461
                ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
2462
                s->pb= backup_s.pb;
2463

    
2464
                if(s->data_partitioning){
2465
                    pb2_bits_count= put_bits_count(&s->pb2);
2466
                    flush_put_bits(&s->pb2);
2467
                    ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
2468
                    s->pb2= backup_s.pb2;
2469

    
2470
                    tex_pb_bits_count= put_bits_count(&s->tex_pb);
2471
                    flush_put_bits(&s->tex_pb);
2472
                    ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
2473
                    s->tex_pb= backup_s.tex_pb;
2474
                }
2475
                s->last_bits= put_bits_count(&s->pb);
2476

    
2477
                if (CONFIG_H263_ENCODER &&
2478
                    s->out_format == FMT_H263 && s->pict_type!=FF_B_TYPE)
2479
                    ff_h263_update_motion_val(s);
2480

    
2481
                if(next_block==0){ //FIXME 16 vs linesize16
2482
                    s->dsp.put_pixels_tab[0][0](s->dest[0], s->rd_scratchpad                     , s->linesize  ,16);
2483
                    s->dsp.put_pixels_tab[1][0](s->dest[1], s->rd_scratchpad + 16*s->linesize    , s->uvlinesize, 8);
2484
                    s->dsp.put_pixels_tab[1][0](s->dest[2], s->rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
2485
                }
2486

    
2487
                if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
2488
                    MPV_decode_mb(s, s->block);
2489
            } else {
2490
                int motion_x = 0, motion_y = 0;
2491
                s->mv_type=MV_TYPE_16X16;
2492
                // only one MB-Type possible
2493

    
2494
                switch(mb_type){
2495
                case CANDIDATE_MB_TYPE_INTRA:
2496
                    s->mv_dir = 0;
2497
                    s->mb_intra= 1;
2498
                    motion_x= s->mv[0][0][0] = 0;
2499
                    motion_y= s->mv[0][0][1] = 0;
2500
                    break;
2501
                case CANDIDATE_MB_TYPE_INTER:
2502
                    s->mv_dir = MV_DIR_FORWARD;
2503
                    s->mb_intra= 0;
2504
                    motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
2505
                    motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
2506
                    break;
2507
                case CANDIDATE_MB_TYPE_INTER_I:
2508
                    s->mv_dir = MV_DIR_FORWARD;
2509
                    s->mv_type = MV_TYPE_FIELD;
2510
                    s->mb_intra= 0;
2511
                    for(i=0; i<2; i++){
2512
                        j= s->field_select[0][i] = s->p_field_select_table[i][xy];
2513
                        s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
2514
                        s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
2515
                    }
2516
                    break;
2517
                case CANDIDATE_MB_TYPE_INTER4V:
2518
                    s->mv_dir = MV_DIR_FORWARD;
2519
                    s->mv_type = MV_TYPE_8X8;
2520
                    s->mb_intra= 0;
2521
                    for(i=0; i<4; i++){
2522
                        s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
2523
                        s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
2524
                    }
2525
                    break;
2526
                case CANDIDATE_MB_TYPE_DIRECT:
2527
                    if (CONFIG_MPEG4_ENCODER) {
2528
                        s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
2529
                        s->mb_intra= 0;
2530
                        motion_x=s->b_direct_mv_table[xy][0];
2531
                        motion_y=s->b_direct_mv_table[xy][1];
2532
                        ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
2533
                    }
2534
                    break;
2535
                case CANDIDATE_MB_TYPE_DIRECT0:
2536
                    if (CONFIG_MPEG4_ENCODER) {
2537
                        s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
2538
                        s->mb_intra= 0;
2539
                        ff_mpeg4_set_direct_mv(s, 0, 0);
2540
                    }
2541
                    break;
2542
                case CANDIDATE_MB_TYPE_BIDIR:
2543
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2544
                    s->mb_intra= 0;
2545
                    s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
2546
                    s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
2547
                    s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
2548
                    s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
2549
                    break;
2550
                case CANDIDATE_MB_TYPE_BACKWARD:
2551
                    s->mv_dir = MV_DIR_BACKWARD;
2552
                    s->mb_intra= 0;
2553
                    motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
2554
                    motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
2555
                    break;
2556
                case CANDIDATE_MB_TYPE_FORWARD:
2557
                    s->mv_dir = MV_DIR_FORWARD;
2558
                    s->mb_intra= 0;
2559
                    motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
2560
                    motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
2561
//                    printf(" %d %d ", motion_x, motion_y);
2562
                    break;
2563
                case CANDIDATE_MB_TYPE_FORWARD_I:
2564
                    s->mv_dir = MV_DIR_FORWARD;
2565
                    s->mv_type = MV_TYPE_FIELD;
2566
                    s->mb_intra= 0;
2567
                    for(i=0; i<2; i++){
2568
                        j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
2569
                        s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
2570
                        s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
2571
                    }
2572
                    break;
2573
                case CANDIDATE_MB_TYPE_BACKWARD_I:
2574
                    s->mv_dir = MV_DIR_BACKWARD;
2575
                    s->mv_type = MV_TYPE_FIELD;
2576
                    s->mb_intra= 0;
2577
                    for(i=0; i<2; i++){
2578
                        j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
2579
                        s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
2580
                        s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
2581
                    }
2582
                    break;
2583
                case CANDIDATE_MB_TYPE_BIDIR_I:
2584
                    s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
2585
                    s->mv_type = MV_TYPE_FIELD;
2586
                    s->mb_intra= 0;
2587
                    for(dir=0; dir<2; dir++){
2588
                        for(i=0; i<2; i++){
2589
                            j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
2590
                            s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
2591
                            s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
2592
                        }
2593
                    }
2594
                    break;
2595
                default:
2596
                    av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
2597
                }
2598

    
2599
                encode_mb(s, motion_x, motion_y);
2600

    
2601
                // RAL: Update last macroblock type
2602
                s->last_mv_dir = s->mv_dir;
2603

    
2604
                if (CONFIG_H263_ENCODER &&
2605
                    s->out_format == FMT_H263 && s->pict_type!=FF_B_TYPE)
2606
                    ff_h263_update_motion_val(s);
2607

    
2608
                MPV_decode_mb(s, s->block);
2609
            }
2610

    
2611
            /* clean the MV table in IPS frames for direct mode in B frames */
2612
            if(s->mb_intra /* && I,P,S_TYPE */){
2613
                s->p_mv_table[xy][0]=0;
2614
                s->p_mv_table[xy][1]=0;
2615
            }
2616

    
2617
            if(s->flags&CODEC_FLAG_PSNR){
2618
                int w= 16;
2619
                int h= 16;
2620

    
2621
                if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
2622
                if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
2623

    
2624
                s->current_picture.error[0] += sse(
2625
                    s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
2626
                    s->dest[0], w, h, s->linesize);
2627
                s->current_picture.error[1] += sse(
2628
                    s, s->new_picture.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
2629
                    s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
2630
                s->current_picture.error[2] += sse(
2631
                    s, s->new_picture.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
2632
                    s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
2633
            }
2634
            if(s->loop_filter){
2635
                if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
2636
                    ff_h263_loop_filter(s);
2637
            }
2638
//printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, put_bits_count(&s->pb));
2639
        }
2640
    }
2641

    
2642
    //not beautiful here but we must write it before flushing so it has to be here
2643
    if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == FF_I_TYPE)
2644
        msmpeg4_encode_ext_header(s);
2645

    
2646
    write_slice_end(s);
2647

    
2648
    /* Send the last GOB if RTP */
2649
    if (s->avctx->rtp_callback) {
2650
        int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
2651
        pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
2652
        /* Call the RTP callback to send the last GOB */
2653
        emms_c();
2654
        s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
2655
    }
2656

    
2657
    return 0;
2658
}
2659

    
2660
#define MERGE(field) dst->field += src->field; src->field=0
2661
static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
2662
    MERGE(me.scene_change_score);
2663
    MERGE(me.mc_mb_var_sum_temp);
2664
    MERGE(me.mb_var_sum_temp);
2665
}
2666

    
2667
static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
2668
    int i;
2669

    
2670
    MERGE(dct_count[0]); //note, the other dct vars are not part of the context
2671
    MERGE(dct_count[1]);
2672
    MERGE(mv_bits);
2673
    MERGE(i_tex_bits);
2674
    MERGE(p_tex_bits);
2675
    MERGE(i_count);
2676
    MERGE(f_count);
2677
    MERGE(b_count);
2678
    MERGE(skip_count);
2679
    MERGE(misc_bits);
2680
    MERGE(error_count);
2681
    MERGE(padding_bug_score);
2682
    MERGE(current_picture.error[0]);
2683
    MERGE(current_picture.error[1]);
2684
    MERGE(current_picture.error[2]);
2685

    
2686
    if(dst->avctx->noise_reduction){
2687
        for(i=0; i<64; i++){
2688
            MERGE(dct_error_sum[0][i]);
2689
            MERGE(dct_error_sum[1][i]);
2690
        }
2691
    }
2692

    
2693
    assert(put_bits_count(&src->pb) % 8 ==0);
2694
    assert(put_bits_count(&dst->pb) % 8 ==0);
2695
    ff_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
2696
    flush_put_bits(&dst->pb);
2697
}
2698

    
2699
static int estimate_qp(MpegEncContext *s, int dry_run){
2700
    if (s->next_lambda){
2701
        s->current_picture_ptr->quality=
2702
        s->current_picture.quality = s->next_lambda;
2703
        if(!dry_run) s->next_lambda= 0;
2704
    } else if (!s->fixed_qscale) {
2705
        s->current_picture_ptr->quality=
2706
        s->current_picture.quality = ff_rate_estimate_qscale(s, dry_run);
2707
        if (s->current_picture.quality < 0)
2708
            return -1;
2709
    }
2710

    
2711
    if(s->adaptive_quant){
2712
        switch(s->codec_id){
2713
        case CODEC_ID_MPEG4:
2714
            if (CONFIG_MPEG4_ENCODER)
2715
                ff_clean_mpeg4_qscales(s);
2716
            break;
2717
        case CODEC_ID_H263:
2718
        case CODEC_ID_H263P:
2719
        case CODEC_ID_FLV1:
2720
            if (CONFIG_H263_ENCODER)
2721
                ff_clean_h263_qscales(s);
2722
            break;
2723
        default:
2724
            ff_init_qscale_tab(s);
2725
        }
2726

    
2727
        s->lambda= s->lambda_table[0];
2728
        //FIXME broken
2729
    }else
2730
        s->lambda= s->current_picture.quality;
2731
//printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
2732
    update_qscale(s);
2733
    return 0;
2734
}
2735

    
2736
/* must be called before writing the header */
2737
static void set_frame_distances(MpegEncContext * s){
2738
    assert(s->current_picture_ptr->pts != AV_NOPTS_VALUE);
2739
    s->time= s->current_picture_ptr->pts*s->avctx->time_base.num;
2740

    
2741
    if(s->pict_type==FF_B_TYPE){
2742
        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
2743
        assert(s->pb_time > 0 && s->pb_time < s->pp_time);
2744
    }else{
2745
        s->pp_time= s->time - s->last_non_b_time;
2746
        s->last_non_b_time= s->time;
2747
        assert(s->picture_number==0 || s->pp_time > 0);
2748
    }
2749
}
2750

    
2751
static int encode_picture(MpegEncContext *s, int picture_number)
2752
{
2753
    int i;
2754
    int bits;
2755

    
2756
    s->picture_number = picture_number;
2757

    
2758
    /* Reset the average MB variance */
2759
    s->me.mb_var_sum_temp    =
2760
    s->me.mc_mb_var_sum_temp = 0;
2761

    
2762
    /* we need to initialize some time vars before we can encode b-frames */
2763
    // RAL: Condition added for MPEG1VIDEO
2764
    if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->h263_msmpeg4))
2765
        set_frame_distances(s);
2766
    if(CONFIG_MPEG4_ENCODER && s->codec_id == CODEC_ID_MPEG4)
2767
        ff_set_mpeg4_time(s);
2768

    
2769
    s->me.scene_change_score=0;
2770

    
2771
//    s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
2772

    
2773
    if(s->pict_type==FF_I_TYPE){
2774
        if(s->msmpeg4_version >= 3) s->no_rounding=1;
2775
        else                        s->no_rounding=0;
2776
    }else if(s->pict_type!=FF_B_TYPE){
2777
        if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
2778
            s->no_rounding ^= 1;
2779
    }
2780

    
2781
    if(s->flags & CODEC_FLAG_PASS2){
2782
        if (estimate_qp(s,1) < 0)
2783
            return -1;
2784
        ff_get_2pass_fcode(s);
2785
    }else if(!(s->flags & CODEC_FLAG_QSCALE)){
2786
        if(s->pict_type==FF_B_TYPE)
2787
            s->lambda= s->last_lambda_for[s->pict_type];
2788
        else
2789
            s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
2790
        update_qscale(s);
2791
    }
2792

    
2793
    s->mb_intra=0; //for the rate distortion & bit compare functions
2794
    for(i=1; i<s->avctx->thread_count; i++){
2795
        ff_update_duplicate_context(s->thread_context[i], s);
2796
    }
2797

    
2798
    if(ff_init_me(s)<0)
2799
        return -1;
2800

    
2801
    /* Estimate motion for every MB */
2802
    if(s->pict_type != FF_I_TYPE){
2803
        s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
2804
        s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
2805
        if(s->pict_type != FF_B_TYPE && s->avctx->me_threshold==0){
2806
            if((s->avctx->pre_me && s->last_non_b_pict_type==FF_I_TYPE) || s->avctx->pre_me==2){
2807
                s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
2808
            }
2809
        }
2810

    
2811
        s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
2812
    }else /* if(s->pict_type == FF_I_TYPE) */{
2813
        /* I-Frame */
2814
        for(i=0; i<s->mb_stride*s->mb_height; i++)
2815
            s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
2816

    
2817
        if(!s->fixed_qscale){
2818
            /* finding spatial complexity for I-frame rate control */
2819
            s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
2820
        }
2821
    }
2822
    for(i=1; i<s->avctx->thread_count; i++){
2823
        merge_context_after_me(s, s->thread_context[i]);
2824
    }
2825
    s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
2826
    s->current_picture.   mb_var_sum= s->current_picture_ptr->   mb_var_sum= s->me.   mb_var_sum_temp;
2827
    emms_c();
2828

    
2829
    if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == FF_P_TYPE){
2830
        s->pict_type= FF_I_TYPE;
2831
        for(i=0; i<s->mb_stride*s->mb_height; i++)
2832
            s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
2833
//printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
2834
    }
2835

    
2836
    if(!s->umvplus){
2837
        if(s->pict_type==FF_P_TYPE || s->pict_type==FF_S_TYPE) {
2838
            s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
2839

    
2840
            if(s->flags & CODEC_FLAG_INTERLACED_ME){
2841
                int a,b;
2842
                a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
2843
                b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
2844
                s->f_code= FFMAX3(s->f_code, a, b);
2845
            }
2846

    
2847
            ff_fix_long_p_mvs(s);
2848
            ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
2849
            if(s->flags & CODEC_FLAG_INTERLACED_ME){
2850
                int j;
2851
                for(i=0; i<2; i++){
2852
                    for(j=0; j<2; j++)
2853
                        ff_fix_long_mvs(s, s->p_field_select_table[i], j,
2854
                                        s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
2855
                }
2856
            }
2857
        }
2858

    
2859
        if(s->pict_type==FF_B_TYPE){
2860
            int a, b;
2861

    
2862
            a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
2863
            b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
2864
            s->f_code = FFMAX(a, b);
2865

    
2866
            a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
2867
            b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
2868
            s->b_code = FFMAX(a, b);
2869

    
2870
            ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
2871
            ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
2872
            ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
2873
            ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
2874
            if(s->flags & CODEC_FLAG_INTERLACED_ME){
2875
                int dir, j;
2876
                for(dir=0; dir<2; dir++){
2877
                    for(i=0; i<2; i++){
2878
                        for(j=0; j<2; j++){
2879
                            int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
2880
                                          : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
2881
                            ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
2882
                                            s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
2883
                        }
2884
                    }
2885
                }
2886
            }
2887
        }
2888
    }
2889

    
2890
    if (estimate_qp(s, 0) < 0)
2891
        return -1;
2892

    
2893
    if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==FF_I_TYPE && !(s->flags & CODEC_FLAG_QSCALE))
2894
        s->qscale= 3; //reduce clipping problems
2895

    
2896
    if (s->out_format == FMT_MJPEG) {
2897
        /* for mjpeg, we do include qscale in the matrix */
2898
        s->intra_matrix[0] = ff_mpeg1_default_intra_matrix[0];
2899
        for(i=1;i<64;i++){
2900
            int j= s->dsp.idct_permutation[i];
2901

    
2902
            s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
2903
        }
2904
        ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
2905
                       s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
2906
        s->qscale= 8;
2907
    }
2908

    
2909
    //FIXME var duplication
2910
    s->current_picture_ptr->key_frame=
2911
    s->current_picture.key_frame= s->pict_type == FF_I_TYPE; //FIXME pic_ptr
2912
    s->current_picture_ptr->pict_type=
2913
    s->current_picture.pict_type= s->pict_type;
2914

    
2915
    if(s->current_picture.key_frame)
2916
        s->picture_in_gop_number=0;
2917

    
2918
    s->last_bits= put_bits_count(&s->pb);
2919
    switch(s->out_format) {
2920
    case FMT_MJPEG:
2921
        if (CONFIG_MJPEG_ENCODER)
2922
            ff_mjpeg_encode_picture_header(s);
2923
        break;
2924
    case FMT_H261:
2925
        if (CONFIG_H261_ENCODER)
2926
            ff_h261_encode_picture_header(s, picture_number);
2927
        break;
2928
    case FMT_H263:
2929
        if (CONFIG_WMV2_ENCODER && s->codec_id == CODEC_ID_WMV2)
2930
            ff_wmv2_encode_picture_header(s, picture_number);
2931
        else if (CONFIG_MSMPEG4_ENCODER && s->h263_msmpeg4)
2932
            msmpeg4_encode_picture_header(s, picture_number);
2933
        else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
2934
            mpeg4_encode_picture_header(s, picture_number);
2935
        else if (CONFIG_RV10_ENCODER && s->codec_id == CODEC_ID_RV10)
2936
            rv10_encode_picture_header(s, picture_number);
2937
        else if (CONFIG_RV20_ENCODER && s->codec_id == CODEC_ID_RV20)
2938
            rv20_encode_picture_header(s, picture_number);
2939
        else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
2940
            ff_flv_encode_picture_header(s, picture_number);
2941
        else if (CONFIG_H263_ENCODER)
2942
            h263_encode_picture_header(s, picture_number);
2943
        break;
2944
    case FMT_MPEG1:
2945
        if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
2946
            mpeg1_encode_picture_header(s, picture_number);
2947
        break;
2948
    case FMT_H264:
2949
        break;
2950
    default:
2951
        assert(0);
2952
    }
2953
    bits= put_bits_count(&s->pb);
2954
    s->header_bits= bits - s->last_bits;
2955

    
2956
    for(i=1; i<s->avctx->thread_count; i++){
2957
        update_duplicate_context_after_me(s->thread_context[i], s);
2958
    }
2959
    s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
2960
    for(i=1; i<s->avctx->thread_count; i++){
2961
        merge_context_after_encode(s, s->thread_context[i]);
2962
    }
2963
    emms_c();
2964
    return 0;
2965
}
2966

    
2967
void  denoise_dct_c(MpegEncContext *s, DCTELEM *block){
2968
    const int intra= s->mb_intra;
2969
    int i;
2970

    
2971
    s->dct_count[intra]++;
2972

    
2973
    for(i=0; i<64; i++){
2974
        int level= block[i];
2975

    
2976
        if(level){
2977
            if(level>0){
2978
                s->dct_error_sum[intra][i] += level;
2979
                level -= s->dct_offset[intra][i];
2980
                if(level<0) level=0;
2981
            }else{
2982
                s->dct_error_sum[intra][i] -= level;
2983
                level += s->dct_offset[intra][i];
2984
                if(level>0) level=0;
2985
            }
2986
            block[i]= level;
2987
        }
2988
    }
2989
}
2990

    
2991
int dct_quantize_trellis_c(MpegEncContext *s,
2992
                        DCTELEM *block, int n,
2993
                        int qscale, int *overflow){
2994
    const int *qmat;
2995
    const uint8_t *scantable= s->intra_scantable.scantable;
2996
    const uint8_t *perm_scantable= s->intra_scantable.permutated;
2997
    int max=0;
2998
    unsigned int threshold1, threshold2;
2999
    int bias=0;
3000
    int run_tab[65];
3001
    int level_tab[65];
3002
    int score_tab[65];
3003
    int survivor[65];
3004
    int survivor_count;
3005
    int last_run=0;
3006
    int last_level=0;
3007
    int last_score= 0;
3008
    int last_i;
3009
    int coeff[2][64];
3010
    int coeff_count[64];
3011
    int qmul, qadd, start_i, last_non_zero, i, dc;
3012
    const int esc_length= s->ac_esc_length;
3013
    uint8_t * length;
3014
    uint8_t * last_length;
3015
    const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
3016

    
3017
    s->dsp.fdct (block);
3018

    
3019
    if(s->dct_error_sum)
3020
        s->denoise_dct(s, block);
3021
    qmul= qscale*16;
3022
    qadd= ((qscale-1)|1)*8;
3023

    
3024
    if (s->mb_intra) {
3025
        int q;
3026
        if (!s->h263_aic) {
3027
            if (n < 4)
3028
                q = s->y_dc_scale;
3029
            else
3030
                q = s->c_dc_scale;
3031
            q = q << 3;
3032
        } else{
3033
            /* For AIC we skip quant/dequant of INTRADC */
3034
            q = 1 << 3;
3035
            qadd=0;
3036
        }
3037

    
3038
        /* note: block[0] is assumed to be positive */
3039
        block[0] = (block[0] + (q >> 1)) / q;
3040
        start_i = 1;
3041
        last_non_zero = 0;
3042
        qmat = s->q_intra_matrix[qscale];
3043
        if(s->mpeg_quant || s->out_format == FMT_MPEG1)
3044
            bias= 1<<(QMAT_SHIFT-1);
3045
        length     = s->intra_ac_vlc_length;
3046
        last_length= s->intra_ac_vlc_last_length;
3047
    } else {
3048
        start_i = 0;
3049
        last_non_zero = -1;
3050
        qmat = s->q_inter_matrix[qscale];
3051
        length     = s->inter_ac_vlc_length;
3052
        last_length= s->inter_ac_vlc_last_length;
3053
    }
3054
    last_i= start_i;
3055

    
3056
    threshold1= (1<<QMAT_SHIFT) - bias - 1;
3057
    threshold2= (threshold1<<1);
3058

    
3059
    for(i=63; i>=start_i; i--) {
3060
        const int j = scantable[i];
3061
        int level = block[j] * qmat[j];
3062

    
3063
        if(((unsigned)(level+threshold1))>threshold2){
3064
            last_non_zero = i;
3065
            break;
3066
        }
3067
    }
3068

    
3069
    for(i=start_i; i<=last_non_zero; i++) {
3070
        const int j = scantable[i];
3071
        int level = block[j] * qmat[j];
3072

    
3073
//        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
3074
//           || bias-level >= (1<<(QMAT_SHIFT - 3))){
3075
        if(((unsigned)(level+threshold1))>threshold2){
3076
            if(level>0){
3077
                level= (bias + level)>>QMAT_SHIFT;
3078
                coeff[0][i]= level;
3079
                coeff[1][i]= level-1;
3080
//                coeff[2][k]= level-2;
3081
            }else{
3082
                level= (bias - level)>>QMAT_SHIFT;
3083
                coeff[0][i]= -level;
3084
                coeff[1][i]= -level+1;
3085
//                coeff[2][k]= -level+2;
3086
            }
3087
            coeff_count[i]= FFMIN(level, 2);
3088
            assert(coeff_count[i]);
3089
            max |=level;
3090
        }else{
3091
            coeff[0][i]= (level>>31)|1;
3092
            coeff_count[i]= 1;
3093
        }
3094
    }
3095

    
3096
    *overflow= s->max_qcoeff < max; //overflow might have happened
3097

    
3098
    if(last_non_zero < start_i){
3099
        memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
3100
        return last_non_zero;
3101
    }
3102

    
3103
    score_tab[start_i]= 0;
3104
    survivor[0]= start_i;
3105
    survivor_count= 1;
3106

    
3107
    for(i=start_i; i<=last_non_zero; i++){
3108
        int level_index, j, zero_distortion;
3109
        int dct_coeff= FFABS(block[ scantable[i] ]);
3110
        int best_score=256*256*256*120;
3111

    
3112
        if (   s->dsp.fdct == fdct_ifast
3113
#ifndef FAAN_POSTSCALE
3114
            || s->dsp.fdct == ff_faandct
3115
#endif
3116
           )
3117
            dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
3118
        zero_distortion= dct_coeff*dct_coeff;
3119

    
3120
        for(level_index=0; level_index < coeff_count[i]; level_index++){
3121
            int distortion;
3122
            int level= coeff[level_index][i];
3123
            const int alevel= FFABS(level);
3124
            int unquant_coeff;
3125

    
3126
            assert(level);
3127

    
3128
            if(s->out_format == FMT_H263){
3129
                unquant_coeff= alevel*qmul + qadd;
3130
            }else{ //MPEG1
3131
                j= s->dsp.idct_permutation[ scantable[i] ]; //FIXME optimize
3132
                if(s->mb_intra){
3133
                        unquant_coeff = (int)(  alevel  * qscale * s->intra_matrix[j]) >> 3;
3134
                        unquant_coeff =   (unquant_coeff - 1) | 1;
3135
                }else{
3136
                        unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
3137
                        unquant_coeff =   (unquant_coeff - 1) | 1;
3138
                }
3139
                unquant_coeff<<= 3;
3140
            }
3141

    
3142
            distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
3143
            level+=64;
3144
            if((level&(~127)) == 0){
3145
                for(j=survivor_count-1; j>=0; j--){
3146
                    int run= i - survivor[j];
3147
                    int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
3148
                    score += score_tab[i-run];
3149

    
3150
                    if(score < best_score){
3151
                        best_score= score;
3152
                        run_tab[i+1]= run;
3153
                        level_tab[i+1]= level-64;
3154
                    }
3155
                }
3156

    
3157
                if(s->out_format == FMT_H263){
3158
                    for(j=survivor_count-1; j>=0; j--){
3159
                        int run= i - survivor[j];
3160
                        int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
3161
                        score += score_tab[i-run];
3162
                        if(score < last_score){
3163
                            last_score= score;
3164
                            last_run= run;
3165
                            last_level= level-64;
3166
                            last_i= i+1;
3167
                        }
3168
                    }
3169
                }
3170
            }else{
3171
                distortion += esc_length*lambda;
3172
                for(j=survivor_count-1; j>=0; j--){
3173
                    int run= i - survivor[j];
3174
                    int score= distortion + score_tab[i-run];
3175

    
3176
                    if(score < best_score){
3177
                        best_score= score;
3178
                        run_tab[i+1]= run;
3179
                        level_tab[i+1]= level-64;
3180
                    }
3181
                }
3182

    
3183
                if(s->out_format == FMT_H263){
3184
                  for(j=survivor_count-1; j>=0; j--){
3185
                        int run= i - survivor[j];
3186
                        int score= distortion + score_tab[i-run];
3187
                        if(score < last_score){
3188
                            last_score= score;
3189
                            last_run= run;
3190
                            last_level= level-64;
3191
                            last_i= i+1;
3192
                        }
3193
                    }
3194
                }
3195
            }
3196
        }
3197

    
3198
        score_tab[i+1]= best_score;
3199

    
3200
        //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
3201
        if(last_non_zero <= 27){
3202
            for(; survivor_count; survivor_count--){
3203
                if(score_tab[ survivor[survivor_count-1] ] <= best_score)
3204
                    break;
3205
            }
3206
        }else{
3207
            for(; survivor_count; survivor_count--){
3208
                if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
3209
                    break;
3210
            }
3211
        }
3212

    
3213
        survivor[ survivor_count++ ]= i+1;
3214
    }
3215

    
3216
    if(s->out_format != FMT_H263){
3217
        last_score= 256*256*256*120;
3218
        for(i= survivor[0]; i<=last_non_zero + 1; i++){
3219
            int score= score_tab[i];
3220
            if(i) score += lambda*2; //FIXME exacter?
3221

    
3222
            if(score < last_score){
3223
                last_score= score;
3224
                last_i= i;
3225
                last_level= level_tab[i];
3226
                last_run= run_tab[i];
3227
            }
3228
        }
3229
    }
3230

    
3231
    s->coded_score[n] = last_score;
3232

    
3233
    dc= FFABS(block[0]);
3234
    last_non_zero= last_i - 1;
3235
    memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
3236

    
3237
    if(last_non_zero < start_i)
3238
        return last_non_zero;
3239

    
3240
    if(last_non_zero == 0 && start_i == 0){
3241
        int best_level= 0;
3242
        int best_score= dc * dc;
3243

    
3244
        for(i=0; i<coeff_count[0]; i++){
3245
            int level= coeff[i][0];
3246
            int alevel= FFABS(level);
3247
            int unquant_coeff, score, distortion;
3248

    
3249
            if(s->out_format == FMT_H263){
3250
                    unquant_coeff= (alevel*qmul + qadd)>>3;
3251
            }else{ //MPEG1
3252
                    unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
3253
                    unquant_coeff =   (unquant_coeff - 1) | 1;
3254
            }
3255
            unquant_coeff = (unquant_coeff + 4) >> 3;
3256
            unquant_coeff<<= 3 + 3;
3257

    
3258
            distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
3259
            level+=64;
3260
            if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
3261
            else                    score= distortion + esc_length*lambda;
3262

    
3263
            if(score < best_score){
3264
                best_score= score;
3265
                best_level= level - 64;
3266
            }
3267
        }
3268
        block[0]= best_level;
3269
        s->coded_score[n] = best_score - dc*dc;
3270
        if(best_level == 0) return -1;
3271
        else                return last_non_zero;
3272
    }
3273

    
3274
    i= last_i;
3275
    assert(last_level);
3276

    
3277
    block[ perm_scantable[last_non_zero] ]= last_level;
3278
    i -= last_run + 1;
3279

    
3280
    for(; i>start_i; i -= run_tab[i] + 1){
3281
        block[ perm_scantable[i-1] ]= level_tab[i];
3282
    }
3283

    
3284
    return last_non_zero;
3285
}
3286

    
3287
//#define REFINE_STATS 1
3288
static int16_t basis[64][64];
3289

    
3290
static void build_basis(uint8_t *perm){
3291
    int i, j, x, y;
3292
    emms_c();
3293
    for(i=0; i<8; i++){
3294
        for(j=0; j<8; j++){
3295
            for(y=0; y<8; y++){
3296
                for(x=0; x<8; x++){
3297
                    double s= 0.25*(1<<BASIS_SHIFT);
3298
                    int index= 8*i + j;
3299
                    int perm_index= perm[index];
3300
                    if(i==0) s*= sqrt(0.5);
3301
                    if(j==0) s*= sqrt(0.5);
3302
                    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)));
3303
                }
3304
            }
3305
        }
3306
    }
3307
}
3308

    
3309
static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
3310
                        DCTELEM *block, int16_t *weight, DCTELEM *orig,
3311
                        int n, int qscale){
3312
    int16_t rem[64];
3313
    DECLARE_ALIGNED_16(DCTELEM, d1[64]);
3314
    const uint8_t *scantable= s->intra_scantable.scantable;
3315
    const uint8_t *perm_scantable= s->intra_scantable.permutated;
3316
//    unsigned int threshold1, threshold2;
3317
//    int bias=0;
3318
    int run_tab[65];
3319
    int prev_run=0;
3320
    int prev_level=0;
3321
    int qmul, qadd, start_i, last_non_zero, i, dc;
3322
    uint8_t * length;
3323
    uint8_t * last_length;
3324
    int lambda;
3325
    int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
3326
#ifdef REFINE_STATS
3327
static int count=0;
3328
static int after_last=0;
3329
static int to_zero=0;
3330
static int from_zero=0;
3331
static int raise=0;
3332
static int lower=0;
3333
static int messed_sign=0;
3334
#endif
3335

    
3336
    if(basis[0][0] == 0)
3337
        build_basis(s->dsp.idct_permutation);
3338

    
3339
    qmul= qscale*2;
3340
    qadd= (qscale-1)|1;
3341
    if (s->mb_intra) {
3342
        if (!s->h263_aic) {
3343
            if (n < 4)
3344
                q = s->y_dc_scale;
3345
            else
3346
                q = s->c_dc_scale;
3347
        } else{
3348
            /* For AIC we skip quant/dequant of INTRADC */
3349
            q = 1;
3350
            qadd=0;
3351
        }
3352
        q <<= RECON_SHIFT-3;
3353
        /* note: block[0] is assumed to be positive */
3354
        dc= block[0]*q;
3355
//        block[0] = (block[0] + (q >> 1)) / q;
3356
        start_i = 1;
3357
//        if(s->mpeg_quant || s->out_format == FMT_MPEG1)
3358
//            bias= 1<<(QMAT_SHIFT-1);
3359
        length     = s->intra_ac_vlc_length;
3360
        last_length= s->intra_ac_vlc_last_length;
3361
    } else {
3362
        dc= 0;
3363
        start_i = 0;
3364
        length     = s->inter_ac_vlc_length;
3365
        last_length= s->inter_ac_vlc_last_length;
3366
    }
3367
    last_non_zero = s->block_last_index[n];
3368

    
3369
#ifdef REFINE_STATS
3370
{START_TIMER
3371
#endif
3372
    dc += (1<<(RECON_SHIFT-1));
3373
    for(i=0; i<64; i++){
3374
        rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME  use orig dirrectly instead of copying to rem[]
3375
    }
3376
#ifdef REFINE_STATS
3377
STOP_TIMER("memset rem[]")}
3378
#endif
3379
    sum=0;
3380
    for(i=0; i<64; i++){
3381
        int one= 36;
3382
        int qns=4;
3383
        int w;
3384

    
3385
        w= FFABS(weight[i]) + qns*one;
3386
        w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
3387

    
3388
        weight[i] = w;
3389
//        w=weight[i] = (63*qns + (w/2)) / w;
3390

    
3391
        assert(w>0);
3392
        assert(w<(1<<6));
3393
        sum += w*w;
3394
    }
3395
    lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
3396
#ifdef REFINE_STATS
3397
{START_TIMER
3398
#endif
3399
    run=0;
3400
    rle_index=0;
3401
    for(i=start_i; i<=last_non_zero; i++){
3402
        int j= perm_scantable[i];
3403
        const int level= block[j];
3404
        int coeff;
3405

    
3406
        if(level){
3407
            if(level<0) coeff= qmul*level - qadd;
3408
            else        coeff= qmul*level + qadd;
3409
            run_tab[rle_index++]=run;
3410
            run=0;
3411

    
3412
            s->dsp.add_8x8basis(rem, basis[j], coeff);
3413
        }else{
3414
            run++;
3415
        }
3416
    }
3417
#ifdef REFINE_STATS
3418
if(last_non_zero>0){
3419
STOP_TIMER("init rem[]")
3420
}
3421
}
3422

    
3423
{START_TIMER
3424
#endif
3425
    for(;;){
3426
        int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
3427
        int best_coeff=0;
3428
        int best_change=0;
3429
        int run2, best_unquant_change=0, analyze_gradient;
3430
#ifdef REFINE_STATS
3431
{START_TIMER
3432
#endif
3433
        analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
3434

    
3435
        if(analyze_gradient){
3436
#ifdef REFINE_STATS
3437
{START_TIMER
3438
#endif
3439
            for(i=0; i<64; i++){
3440
                int w= weight[i];
3441

    
3442
                d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
3443
            }
3444
#ifdef REFINE_STATS
3445
STOP_TIMER("rem*w*w")}
3446
{START_TIMER
3447
#endif
3448
            s->dsp.fdct(d1);
3449
#ifdef REFINE_STATS
3450
STOP_TIMER("dct")}
3451
#endif
3452
        }
3453

    
3454
        if(start_i){
3455
            const int level= block[0];
3456
            int change, old_coeff;
3457

    
3458
            assert(s->mb_intra);
3459

    
3460
            old_coeff= q*level;
3461

    
3462
            for(change=-1; change<=1; change+=2){
3463
                int new_level= level + change;
3464
                int score, new_coeff;
3465

    
3466
                new_coeff= q*new_level;
3467
                if(new_coeff >= 2048 || new_coeff < 0)
3468
                    continue;
3469

    
3470
                score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
3471
                if(score<best_score){
3472
                    best_score= score;
3473
                    best_coeff= 0;
3474
                    best_change= change;
3475
                    best_unquant_change= new_coeff - old_coeff;
3476
                }
3477
            }
3478
        }
3479

    
3480
        run=0;
3481
        rle_index=0;
3482
        run2= run_tab[rle_index++];
3483
        prev_level=0;
3484
        prev_run=0;
3485

    
3486
        for(i=start_i; i<64; i++){
3487
            int j= perm_scantable[i];
3488
            const int level= block[j];
3489
            int change, old_coeff;
3490

    
3491
            if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
3492
                break;
3493

    
3494
            if(level){
3495
                if(level<0) old_coeff= qmul*level - qadd;
3496
                else        old_coeff= qmul*level + qadd;
3497
                run2= run_tab[rle_index++]; //FIXME ! maybe after last
3498
            }else{
3499
                old_coeff=0;
3500
                run2--;
3501
                assert(run2>=0 || i >= last_non_zero );
3502
            }
3503

    
3504
            for(change=-1; change<=1; change+=2){
3505
                int new_level= level + change;
3506
                int score, new_coeff, unquant_change;
3507

    
3508
                score=0;
3509
                if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
3510
                   continue;
3511

    
3512
                if(new_level){
3513
                    if(new_level<0) new_coeff= qmul*new_level - qadd;
3514
                    else            new_coeff= qmul*new_level + qadd;
3515
                    if(new_coeff >= 2048 || new_coeff <= -2048)
3516
                        continue;
3517
                    //FIXME check for overflow
3518

    
3519
                    if(level){
3520
                        if(level < 63 && level > -63){
3521
                            if(i < last_non_zero)
3522
                                score +=   length[UNI_AC_ENC_INDEX(run, new_level+64)]
3523
                                         - length[UNI_AC_ENC_INDEX(run, level+64)];
3524
                            else
3525
                                score +=   last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
3526
                                         - last_length[UNI_AC_ENC_INDEX(run, level+64)];
3527
                        }
3528
                    }else{
3529
                        assert(FFABS(new_level)==1);
3530

    
3531
                        if(analyze_gradient){
3532
                            int g= d1[ scantable[i] ];
3533
                            if(g && (g^new_level) >= 0)
3534
                                continue;
3535
                        }
3536

    
3537
                        if(i < last_non_zero){
3538
                            int next_i= i + run2 + 1;
3539
                            int next_level= block[ perm_scantable[next_i] ] + 64;
3540

    
3541
                            if(next_level&(~127))
3542
                                next_level= 0;
3543

    
3544
                            if(next_i < last_non_zero)
3545
                                score +=   length[UNI_AC_ENC_INDEX(run, 65)]
3546
                                         + length[UNI_AC_ENC_INDEX(run2, next_level)]
3547
                                         - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
3548
                            else
3549
                                score +=  length[UNI_AC_ENC_INDEX(run, 65)]
3550
                                        + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
3551
                                        - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
3552
                        }else{
3553
                            score += last_length[UNI_AC_ENC_INDEX(run, 65)];
3554
                            if(prev_level){
3555
                                score +=  length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
3556
                                        - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
3557
                            }
3558
                        }
3559
                    }
3560
                }else{
3561
                    new_coeff=0;
3562
                    assert(FFABS(level)==1);
3563

    
3564
                    if(i < last_non_zero){
3565
                        int next_i= i + run2 + 1;
3566
                        int next_level= block[ perm_scantable[next_i] ] + 64;
3567

    
3568
                        if(next_level&(~127))
3569
                            next_level= 0;
3570

    
3571
                        if(next_i < last_non_zero)
3572
                            score +=   length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
3573
                                     - length[UNI_AC_ENC_INDEX(run2, next_level)]
3574
                                     - length[UNI_AC_ENC_INDEX(run, 65)];
3575
                        else
3576
                            score +=   last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
3577
                                     - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
3578
                                     - length[UNI_AC_ENC_INDEX(run, 65)];
3579
                    }else{
3580
                        score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
3581
                        if(prev_level){
3582
                            score +=  last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
3583
                                    - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
3584
                        }
3585
                    }
3586
                }
3587

    
3588
                score *= lambda;
3589

    
3590
                unquant_change= new_coeff - old_coeff;
3591
                assert((score < 100*lambda && score > -100*lambda) || lambda==0);
3592

    
3593
                score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
3594
                if(score<best_score){
3595
                    best_score= score;
3596
                    best_coeff= i;
3597
                    best_change= change;
3598
                    best_unquant_change= unquant_change;
3599
                }
3600
            }
3601
            if(level){
3602
                prev_level= level + 64;
3603
                if(prev_level&(~127))
3604
                    prev_level= 0;
3605
                prev_run= run;
3606
                run=0;
3607
            }else{
3608
                run++;
3609
            }
3610
        }
3611
#ifdef REFINE_STATS
3612
STOP_TIMER("iterative step")}
3613
#endif
3614

    
3615
        if(best_change){
3616
            int j= perm_scantable[ best_coeff ];
3617

    
3618
            block[j] += best_change;
3619

    
3620
            if(best_coeff > last_non_zero){
3621
                last_non_zero= best_coeff;
3622
                assert(block[j]);
3623
#ifdef REFINE_STATS
3624
after_last++;
3625
#endif
3626
            }else{
3627
#ifdef REFINE_STATS
3628
if(block[j]){
3629
    if(block[j] - best_change){
3630
        if(FFABS(block[j]) > FFABS(block[j] - best_change)){
3631
            raise++;
3632
        }else{
3633
            lower++;
3634
        }
3635
    }else{
3636
        from_zero++;
3637
    }
3638
}else{
3639
    to_zero++;
3640
}
3641
#endif
3642
                for(; last_non_zero>=start_i; last_non_zero--){
3643
                    if(block[perm_scantable[last_non_zero]])
3644
                        break;
3645
                }
3646
            }
3647
#ifdef REFINE_STATS
3648
count++;
3649
if(256*256*256*64 % count == 0){
3650
    printf("after_last:%d to_zero:%d from_zero:%d raise:%d lower:%d sign:%d xyp:%d/%d/%d\n", after_last, to_zero, from_zero, raise, lower, messed_sign, s->mb_x, s->mb_y, s->picture_number);
3651
}
3652
#endif
3653
            run=0;
3654
            rle_index=0;
3655
            for(i=start_i; i<=last_non_zero; i++){
3656
                int j= perm_scantable[i];
3657
                const int level= block[j];
3658

    
3659
                 if(level){
3660
                     run_tab[rle_index++]=run;
3661
                     run=0;
3662
                 }else{
3663
                     run++;
3664
                 }
3665
            }
3666

    
3667
            s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);
3668
        }else{
3669
            break;
3670
        }
3671
    }
3672
#ifdef REFINE_STATS
3673
if(last_non_zero>0){
3674
STOP_TIMER("iterative search")
3675
}
3676
}
3677
#endif
3678

    
3679
    return last_non_zero;
3680
}
3681

    
3682
int dct_quantize_c(MpegEncContext *s,
3683
                        DCTELEM *block, int n,
3684
                        int qscale, int *overflow)
3685
{
3686
    int i, j, level, last_non_zero, q, start_i;
3687
    const int *qmat;
3688
    const uint8_t *scantable= s->intra_scantable.scantable;
3689
    int bias;
3690
    int max=0;
3691
    unsigned int threshold1, threshold2;
3692

    
3693
    s->dsp.fdct (block);
3694

    
3695
    if(s->dct_error_sum)
3696
        s->denoise_dct(s, block);
3697

    
3698
    if (s->mb_intra) {
3699
        if (!s->h263_aic) {
3700
            if (n < 4)
3701
                q = s->y_dc_scale;
3702
            else
3703
                q = s->c_dc_scale;
3704
            q = q << 3;
3705
        } else
3706
            /* For AIC we skip quant/dequant of INTRADC */
3707
            q = 1 << 3;
3708

    
3709
        /* note: block[0] is assumed to be positive */
3710
        block[0] = (block[0] + (q >> 1)) / q;
3711
        start_i = 1;
3712
        last_non_zero = 0;
3713
        qmat = s->q_intra_matrix[qscale];
3714
        bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
3715
    } else {
3716
        start_i = 0;
3717
        last_non_zero = -1;
3718
        qmat = s->q_inter_matrix[qscale];
3719
        bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
3720
    }
3721
    threshold1= (1<<QMAT_SHIFT) - bias - 1;
3722
    threshold2= (threshold1<<1);
3723
    for(i=63;i>=start_i;i--) {
3724
        j = scantable[i];
3725
        level = block[j] * qmat[j];
3726

    
3727
        if(((unsigned)(level+threshold1))>threshold2){
3728
            last_non_zero = i;
3729
            break;
3730
        }else{
3731
            block[j]=0;
3732
        }
3733
    }
3734
    for(i=start_i; i<=last_non_zero; i++) {
3735
        j = scantable[i];
3736
        level = block[j] * qmat[j];
3737

    
3738
//        if(   bias+level >= (1<<QMAT_SHIFT)
3739
//           || bias-level >= (1<<QMAT_SHIFT)){
3740
        if(((unsigned)(level+threshold1))>threshold2){
3741
            if(level>0){
3742
                level= (bias + level)>>QMAT_SHIFT;
3743
                block[j]= level;
3744
            }else{
3745
                level= (bias - level)>>QMAT_SHIFT;
3746
                block[j]= -level;
3747
            }
3748
            max |=level;
3749
        }else{
3750
            block[j]=0;
3751
        }
3752
    }
3753
    *overflow= s->max_qcoeff < max; //overflow might have happened
3754

    
3755
    /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
3756
    if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
3757
        ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
3758

    
3759
    return last_non_zero;
3760
}
3761

    
3762
AVCodec h263_encoder = {
3763
    "h263",
3764
    CODEC_TYPE_VIDEO,
3765
    CODEC_ID_H263,
3766
    sizeof(MpegEncContext),
3767
    MPV_encode_init,
3768
    MPV_encode_picture,
3769
    MPV_encode_end,
3770
    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3771
    .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
3772
};
3773

    
3774
AVCodec h263p_encoder = {
3775
    "h263p",
3776
    CODEC_TYPE_VIDEO,
3777
    CODEC_ID_H263P,
3778
    sizeof(MpegEncContext),
3779
    MPV_encode_init,
3780
    MPV_encode_picture,
3781
    MPV_encode_end,
3782
    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3783
    .long_name= NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
3784
};
3785

    
3786
AVCodec msmpeg4v1_encoder = {
3787
    "msmpeg4v1",
3788
    CODEC_TYPE_VIDEO,
3789
    CODEC_ID_MSMPEG4V1,
3790
    sizeof(MpegEncContext),
3791
    MPV_encode_init,
3792
    MPV_encode_picture,
3793
    MPV_encode_end,
3794
    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3795
    .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 1"),
3796
};
3797

    
3798
AVCodec msmpeg4v2_encoder = {
3799
    "msmpeg4v2",
3800
    CODEC_TYPE_VIDEO,
3801
    CODEC_ID_MSMPEG4V2,
3802
    sizeof(MpegEncContext),
3803
    MPV_encode_init,
3804
    MPV_encode_picture,
3805
    MPV_encode_end,
3806
    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3807
    .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
3808
};
3809

    
3810
AVCodec msmpeg4v3_encoder = {
3811
    "msmpeg4",
3812
    CODEC_TYPE_VIDEO,
3813
    CODEC_ID_MSMPEG4V3,
3814
    sizeof(MpegEncContext),
3815
    MPV_encode_init,
3816
    MPV_encode_picture,
3817
    MPV_encode_end,
3818
    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3819
    .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
3820
};
3821

    
3822
AVCodec wmv1_encoder = {
3823
    "wmv1",
3824
    CODEC_TYPE_VIDEO,
3825
    CODEC_ID_WMV1,
3826
    sizeof(MpegEncContext),
3827
    MPV_encode_init,
3828
    MPV_encode_picture,
3829
    MPV_encode_end,
3830
    .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
3831
    .long_name= NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
3832
};