FFmpeg
Loading...
Searching...
No Matches
mpegvideo_enc.c
Go to the documentation of this file.
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 * non linear quantizers with large QPs and VBV with restrictive qmin fixes sponsored by NOA GmbH
27 */
28
29/**
30 * @file
31 * The simplest mpeg encoder (well, it was the simplest!).
32 */
33
34#include "config_components.h"
35
36#include <assert.h>
37#include <stdint.h>
38
40#include "libavutil/emms.h"
41#include "libavutil/internal.h"
42#include "libavutil/intmath.h"
44#include "libavutil/mem.h"
46#include "libavutil/opt.h"
47#include "libavutil/thread.h"
48#include "avcodec.h"
49#include "encode.h"
50#include "idctdsp.h"
51#include "mpeg12data.h"
52#include "mpeg12enc.h"
53#include "mpegvideo.h"
54#include "mpegvideodata.h"
55#include "mpegvideoenc.h"
56#include "h261enc.h"
57#include "h263.h"
58#include "h263data.h"
59#include "h263enc.h"
60#include "mjpegenc_common.h"
61#include "mathops.h"
62#include "mpegutils.h"
64#include "mjpegenc.h"
65#include "speedhqenc.h"
66#include "msmpeg4enc.h"
67#include "pixblockdsp.h"
68#include "qpeldsp.h"
69#include "faandct.h"
70#include "aandcttab.h"
71#include "mpeg4video.h"
72#include "mpeg4videodata.h"
73#include "mpeg4videoenc.h"
74#include "internal.h"
75#include "bytestream.h"
76#include "rv20enc.h"
77#include "libavutil/refstruct.h"
78#include <limits.h>
79#include "sp5x.h"
80
81#define QUANT_BIAS_SHIFT 8
82
83#define QMAT_SHIFT_MMX 16
84#define QMAT_SHIFT 21
85
86static int encode_picture(MPVMainEncContext *const s, const AVPacket *pkt);
87static int dct_quantize_refine(MPVEncContext *const s, int16_t *block, int16_t *weight, int16_t *orig, int n, int qscale);
88static int sse_mb(MPVEncContext *const s);
89static int dct_quantize_c(MPVEncContext *const s,
90 int16_t *block, int n,
91 int qscale, int *overflow);
92static int dct_quantize_trellis_c(MPVEncContext *const s, int16_t *block, int n, int qscale, int *overflow);
93
94static uint8_t default_fcode_tab[MAX_MV * 2 + 1];
95
101
103 .class_name = "generic mpegvideo encoder",
104 .item_name = av_default_item_name,
105 .option = mpv_generic_options,
106 .version = LIBAVUTIL_VERSION_INT,
107};
108
109void ff_convert_matrix(MPVEncContext *const s, int (*qmat)[64],
110 uint16_t (*qmat16)[2][64],
111 const uint16_t *quant_matrix,
112 int bias, int qmin, int qmax, int intra)
113{
114 FDCTDSPContext *fdsp = &s->fdsp;
115 int qscale;
116 int shift = 0;
117
118 for (qscale = qmin; qscale <= qmax; qscale++) {
119 int i;
120 int qscale2;
121
122 if (s->c.q_scale_type) qscale2 = ff_mpeg2_non_linear_qscale[qscale];
123 else qscale2 = qscale << 1;
124
125 if (fdsp->fdct == ff_jpeg_fdct_islow_8 ||
126#if CONFIG_FAANDCT
127 fdsp->fdct == ff_faandct ||
128#endif /* CONFIG_FAANDCT */
129 fdsp->fdct == ff_jpeg_fdct_islow_10) {
130 for (i = 0; i < 64; i++) {
131 const int j = s->c.idsp.idct_permutation[i];
132 int64_t den = (int64_t) qscale2 * quant_matrix[j];
133 /* 1 * 1 <= qscale2 * quant_matrix[j] <= 112 * 255
134 * Assume x = qscale2 * quant_matrix[j]
135 * 1 <= x <= 28560
136 * (1 << 22) / 1 >= (1 << 22) / (x) >= (1 << 22) / 28560
137 * 4194304 >= (1 << 22) / (x) >= 146 */
138
139 qmat[qscale][i] = (int)((UINT64_C(2) << QMAT_SHIFT) / den);
140 }
141 } else if (fdsp->fdct == ff_fdct_ifast) {
142 for (i = 0; i < 64; i++) {
143 const int j = s->c.idsp.idct_permutation[i];
144 int64_t den = ff_aanscales[i] * (int64_t) qscale2 * quant_matrix[j];
145 /* 1247 * 1 * 1 <= ff_aanscales[i] * qscale2 * quant_matrix[j] <= 31521 * 112 * 255
146 * Assume x = ff_aanscales[i] * qscale2 * quant_matrix[j]
147 * 1247 <= x <= 900239760
148 * (1 << 36) / 1247 >= (1 << 36) / (x) >= (1 << 36) / 900239760
149 * 55107840 >= (1 << 36) / (x) >= 76 */
150
151 qmat[qscale][i] = (int)((UINT64_C(2) << (QMAT_SHIFT + 14)) / den);
152 }
153 } else {
154 for (i = 0; i < 64; i++) {
155 const int j = s->c.idsp.idct_permutation[i];
156 int64_t den = (int64_t) qscale2 * quant_matrix[j];
157 /* 1 * 1 <= qscale2 * quant_matrix[j] <= 112 * 255
158 * Assume x = qscale2 * quant_matrix[j]
159 * 1 <= x <= 28560
160 * (1 << 22) / 1 >= (1 << 22) / (x) >= (1 << 22) / 28560
161 * 4194304 >= (1 << 22) / (x) >= 146
162 *
163 * 1 <= x <= 28560
164 * (1 << 17) / 1 >= (1 << 17) / (x) >= (1 << 17) / 28560
165 * 131072 >= (1 << 17) / (x) >= 4 */
166
167 qmat[qscale][i] = (int)((UINT64_C(2) << QMAT_SHIFT) / den);
168 qmat16[qscale][0][i] = (2 << QMAT_SHIFT_MMX) / den;
169
170 if (qmat16[qscale][0][i] == 0 ||
171 qmat16[qscale][0][i] == 128 * 256)
172 qmat16[qscale][0][i] = 128 * 256 - 1;
173 qmat16[qscale][1][i] =
174 ROUNDED_DIV(bias * (1<<(16 - QUANT_BIAS_SHIFT)),
175 qmat16[qscale][0][i]);
176 }
177 }
178
179 for (i = intra; i < 64; i++) {
180 int64_t max = 8191;
181 if (fdsp->fdct == ff_fdct_ifast) {
182 max = (8191LL * ff_aanscales[i]) >> 14;
183 }
184 while (((max * qmat[qscale][i]) >> shift) > INT_MAX) {
185 shift++;
186 }
187 }
188 }
189 if (shift) {
190 av_log(s->c.avctx, AV_LOG_INFO,
191 "Warning, QMAT_SHIFT is larger than %d, overflows possible\n",
192 QMAT_SHIFT - shift);
193 }
194}
195
196static inline void update_qscale(MPVMainEncContext *const m)
197{
198 MPVEncContext *const s = &m->s;
199
200 if (s->c.q_scale_type == 1 && 0) {
201 int i;
202 int bestdiff=INT_MAX;
203 int best = 1;
204
206 int diff = FFABS((ff_mpeg2_non_linear_qscale[i]<<(FF_LAMBDA_SHIFT + 6)) - (int)s->lambda * 139);
207 if (ff_mpeg2_non_linear_qscale[i] < s->c.avctx->qmin ||
208 (ff_mpeg2_non_linear_qscale[i] > s->c.avctx->qmax && !m->vbv_ignore_qmax))
209 continue;
210 if (diff < bestdiff) {
211 bestdiff = diff;
212 best = i;
213 }
214 }
215 s->c.qscale = best;
216 } else {
217 s->c.qscale = (s->lambda * 139 + FF_LAMBDA_SCALE * 64) >>
218 (FF_LAMBDA_SHIFT + 7);
219 s->c.qscale = av_clip(s->c.qscale, s->c.avctx->qmin, m->vbv_ignore_qmax ? 31 : s->c.avctx->qmax);
220 }
221
222 s->lambda2 = (s->lambda * s->lambda + FF_LAMBDA_SCALE / 2) >>
224}
225
227{
228 int i;
229
230 if (matrix) {
231 put_bits(pb, 1, 1);
232 for (i = 0; i < 64; i++) {
234 }
235 } else
236 put_bits(pb, 1, 0);
237}
238
239/**
240 * init s->c.cur_pic.qscale_table from s->lambda_table
241 */
242static void init_qscale_tab(MPVEncContext *const s)
243{
244 int8_t *const qscale_table = s->c.cur_pic.qscale_table;
245
246 for (int i = 0; i < s->c.mb_num; i++) {
247 unsigned int lam = s->lambda_table[s->c.mb_index2xy[i]];
248 int qp = (lam * 139 + FF_LAMBDA_SCALE * 64) >> (FF_LAMBDA_SHIFT + 7);
249 qscale_table[s->c.mb_index2xy[i]] = av_clip(qp, s->c.avctx->qmin,
250 s->c.avctx->qmax);
251 }
252}
253
255 const MPVEncContext *const src)
256{
257#define COPY(a) dst->a = src->a
258 COPY(c.pict_type);
259 COPY(f_code);
260 COPY(b_code);
261 COPY(c.qscale);
262 COPY(lambda);
263 COPY(lambda2);
264 COPY(c.frame_pred_frame_dct); // FIXME don't set in encode_header
265 COPY(c.progressive_frame); // FIXME don't set in encode_header
266 COPY(partitioned_frame); // FIXME don't set in encode_header
267#undef COPY
268}
269
271{
272 for (int i = -16; i < 16; i++)
274}
275
276/**
277 * Set the given MPVEncContext to defaults for encoding.
278 */
280{
281 MPVEncContext *const s = &m->s;
282 static AVOnce init_static_once = AV_ONCE_INIT;
283
285
286 s->f_code = 1;
287 s->b_code = 1;
288
289 if (!m->fcode_tab) {
291 ff_thread_once(&init_static_once, mpv_encode_init_static);
292 }
293 if (!s->c.y_dc_scale_table) {
294 s->c.y_dc_scale_table =
295 s->c.c_dc_scale_table = ff_mpeg1_dc_scale_table;
296 }
297}
298
300{
301 s->dct_quantize = dct_quantize_c;
302
303#if ARCH_X86
305#endif
306
307 if (s->c.avctx->trellis)
308 s->dct_quantize = dct_quantize_trellis_c;
309}
310
312{
313 MpegEncContext *const s = &s2->c;
314 MPVUnquantDSPContext unquant_dsp_ctx;
315
316 ff_mpv_unquantize_init(&unquant_dsp_ctx,
317 avctx->flags & AV_CODEC_FLAG_BITEXACT, s->q_scale_type);
318
319 if (s2->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
320 s->dct_unquantize_intra = unquant_dsp_ctx.dct_unquantize_mpeg2_intra;
321 s->dct_unquantize_inter = unquant_dsp_ctx.dct_unquantize_mpeg2_inter;
322 } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {
323 s->dct_unquantize_intra = unquant_dsp_ctx.dct_unquantize_h263_intra;
324 s->dct_unquantize_inter = unquant_dsp_ctx.dct_unquantize_h263_inter;
325 } else {
326 s->dct_unquantize_intra = unquant_dsp_ctx.dct_unquantize_mpeg1_intra;
327 s->dct_unquantize_inter = unquant_dsp_ctx.dct_unquantize_mpeg1_inter;
328 }
329}
330
332{
333 MPVEncContext *const s = &m->s;
334 MECmpContext mecc;
335 me_cmp_func me_cmp[6];
336 int ret;
337
338 ff_me_cmp_init(&mecc, avctx);
339 ret = ff_me_init(&s->me, avctx, &mecc, 1);
340 if (ret < 0)
341 return ret;
342 ret = ff_set_cmp(&mecc, me_cmp, m->frame_skip_cmp, 1);
343 if (ret < 0)
344 return ret;
345 m->frame_skip_cmp_fn = me_cmp[1];
346 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
347 ret = ff_set_cmp(&mecc, me_cmp, avctx->ildct_cmp, 1);
348 if (ret < 0)
349 return ret;
350 if (!me_cmp[0] || !me_cmp[4])
351 return AVERROR(EINVAL);
352 s->ildct_cmp[0] = me_cmp[0];
353 s->ildct_cmp[1] = me_cmp[4];
354 }
355
356 s->sum_abs_dctelem = mecc.sum_abs_dctelem;
357
358 s->sse_cmp[0] = mecc.sse[0];
359 s->sse_cmp[1] = mecc.sse[1];
360 s->sad_cmp[0] = mecc.sad[0];
361 s->sad_cmp[1] = mecc.sad[1];
362 if (avctx->mb_cmp == FF_CMP_NSSE) {
363 s->n_sse_cmp[0] = mecc.nsse[0];
364 s->n_sse_cmp[1] = mecc.nsse[1];
365 } else {
366 s->n_sse_cmp[0] = mecc.sse[0];
367 s->n_sse_cmp[1] = mecc.sse[1];
368 }
369
370 return 0;
371}
372
373#define ALLOCZ_ARRAYS(p, mult, numb) ((p) = av_calloc(numb, mult * sizeof(*(p))))
375{
376 MPVEncContext *const s = &m->s;
377 const int nb_matrices = 1 + (s->c.out_format == FMT_MJPEG) + !m->intra_only;
378 const uint16_t *intra_matrix, *inter_matrix;
379 int ret;
380
381 if (!ALLOCZ_ARRAYS(s->q_intra_matrix, 32, nb_matrices) ||
382 !ALLOCZ_ARRAYS(s->q_intra_matrix16, 32, nb_matrices))
383 return AVERROR(ENOMEM);
384
385 if (s->c.out_format == FMT_MJPEG) {
386 s->q_chroma_intra_matrix = s->q_intra_matrix + 32;
387 s->q_chroma_intra_matrix16 = s->q_intra_matrix16 + 32;
388 // No need to set q_inter_matrix
390 // intra_matrix, chroma_intra_matrix will be set later for MJPEG.
391 return 0;
392 } else {
393 s->q_chroma_intra_matrix = s->q_intra_matrix;
394 s->q_chroma_intra_matrix16 = s->q_intra_matrix16;
395 }
396 if (!m->intra_only) {
397 s->q_inter_matrix = s->q_intra_matrix + 32;
398 s->q_inter_matrix16 = s->q_intra_matrix16 + 32;
399 }
400
401 if (CONFIG_MPEG4_ENCODER && s->c.codec_id == AV_CODEC_ID_MPEG4 &&
402 s->mpeg_quant) {
403 intra_matrix = ff_mpeg4_default_intra_matrix;
405 } else if (s->c.out_format == FMT_H263 || s->c.out_format == FMT_H261) {
406 intra_matrix =
408 } else {
409 /* MPEG-1/2, SpeedHQ */
410 intra_matrix = ff_mpeg1_default_intra_matrix;
412 }
413 if (avctx->intra_matrix)
414 intra_matrix = avctx->intra_matrix;
415 if (avctx->inter_matrix)
416 inter_matrix = avctx->inter_matrix;
417
418 /* init q matrix */
419 for (int i = 0; i < 64; i++) {
420 int j = s->c.idsp.idct_permutation[i];
421
422 s->c.intra_matrix[j] = s->c.chroma_intra_matrix[j] = intra_matrix[i];
423 s->c.inter_matrix[j] = inter_matrix[i];
424 }
425
426 /* precompute matrix */
428 if (ret < 0)
429 return ret;
430
431 ff_convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16,
432 s->c.intra_matrix, s->intra_quant_bias, avctx->qmin,
433 31, 1);
434 if (s->q_inter_matrix)
435 ff_convert_matrix(s, s->q_inter_matrix, s->q_inter_matrix16,
436 s->c.inter_matrix, s->inter_quant_bias, avctx->qmin,
437 31, 0);
438
439 return 0;
440}
441
443{
444 MPVEncContext *const s = &m->s;
445 int has_b_frames = !!m->max_b_frames;
446 int16_t (*mv_table)[2];
447
448 /* Allocate MB type table */
449 unsigned mb_array_size = s->c.mb_stride * s->c.mb_height;
450 s->mb_type = av_calloc(mb_array_size, 3 * sizeof(*s->mb_type) + sizeof(*s->mb_mean));
451 if (!s->mb_type)
452 return AVERROR(ENOMEM);
453 s->mc_mb_var = s->mb_type + mb_array_size;
454 s->mb_var = s->mc_mb_var + mb_array_size;
455 s->mb_mean = (uint8_t*)(s->mb_var + mb_array_size);
456
457 if (!FF_ALLOCZ_TYPED_ARRAY(s->lambda_table, mb_array_size))
458 return AVERROR(ENOMEM);
459
460 unsigned mv_table_size = (s->c.mb_height + 2) * s->c.mb_stride + 1;
461 unsigned nb_mv_tables = 1 + 5 * has_b_frames;
462 if (s->c.codec_id == AV_CODEC_ID_MPEG4 ||
463 (s->c.avctx->flags & AV_CODEC_FLAG_INTERLACED_ME)) {
464 nb_mv_tables += 8 * has_b_frames;
465 s->p_field_select_table[0] = av_calloc(mv_table_size, 2 * (2 + 4 * has_b_frames));
466 if (!s->p_field_select_table[0])
467 return AVERROR(ENOMEM);
468 s->p_field_select_table[1] = s->p_field_select_table[0] + 2 * mv_table_size;
469 }
470
471 mv_table = av_calloc(mv_table_size, nb_mv_tables * sizeof(*mv_table));
472 if (!mv_table)
473 return AVERROR(ENOMEM);
474 m->mv_table_base = mv_table;
475 mv_table += s->c.mb_stride + 1;
476
477 s->p_mv_table = mv_table;
478 if (has_b_frames) {
479 s->b_forw_mv_table = mv_table += mv_table_size;
480 s->b_back_mv_table = mv_table += mv_table_size;
481 s->b_bidir_forw_mv_table = mv_table += mv_table_size;
482 s->b_bidir_back_mv_table = mv_table += mv_table_size;
483 s->b_direct_mv_table = mv_table += mv_table_size;
484
485 if (s->p_field_select_table[1]) { // MPEG-4 or INTERLACED_ME above
486 uint8_t *field_select = s->p_field_select_table[1];
487 for (int j = 0; j < 2; j++) {
488 for (int k = 0; k < 2; k++) {
489 for (int l = 0; l < 2; l++)
490 s->b_field_mv_table[j][k][l] = mv_table += mv_table_size;
491 s->b_field_select_table[j][k] = field_select += 2 * mv_table_size;
492 }
493 }
494 }
495 }
496
497 return 0;
498}
499
501{
502 MPVEncContext *const s = &m->s;
503 // Align the following per-thread buffers to avoid false sharing.
504 enum {
505#ifndef _MSC_VER
506 /// The number is supposed to match/exceed the cache-line size.
507 ALIGN = FFMAX(128, _Alignof(max_align_t)),
508#else
509 ALIGN = 128,
510#endif
511 DCT_ERROR_SIZE = FFALIGN(2 * sizeof(*s->dct_error_sum), ALIGN),
512 };
513 static_assert(DCT_ERROR_SIZE * MAX_THREADS + ALIGN - 1 <= SIZE_MAX,
514 "Need checks for potential overflow.");
515 unsigned nb_slices = s->c.slice_context_count;
516 char *dct_error = NULL;
517
518 if (m->noise_reduction) {
519 if (!FF_ALLOCZ_TYPED_ARRAY(s->dct_offset, 2))
520 return AVERROR(ENOMEM);
521 dct_error = av_mallocz(ALIGN - 1 + nb_slices * DCT_ERROR_SIZE);
522 if (!dct_error)
523 return AVERROR(ENOMEM);
525 dct_error += FFALIGN((uintptr_t)dct_error, ALIGN) - (uintptr_t)dct_error;
526 }
527
528 const int y_size = s->c.b8_stride * (2 * s->c.mb_height + 1);
529 const int c_size = s->c.mb_stride * (s->c.mb_height + 1);
530 const int yc_size = y_size + 2 * c_size;
531 ptrdiff_t offset = 0;
532
533 for (unsigned i = 0; i < nb_slices; ++i) {
534 MPVEncContext *const s2 = s->c.enc_contexts[i];
535
536 s2->block = s2->blocks[0];
537
538 if (dct_error) {
539 s2->dct_offset = s->dct_offset;
540 s2->dct_error_sum = (void*)dct_error;
541 dct_error += DCT_ERROR_SIZE;
542 }
543
544 if (s2->c.ac_val) {
545 s2->c.dc_val += offset + i;
546 s2->c.ac_val += offset;
547 offset += yc_size;
548 }
549 }
550 return 0;
551}
552
553/* init video encoder */
555{
556 MPVMainEncContext *const m = avctx->priv_data;
557 MPVEncContext *const s = &m->s;
558 AVCPBProperties *cpb_props;
559 int gcd, ret;
560
562
563 switch (avctx->pix_fmt) {
566 s->c.chroma_format = CHROMA_444;
567 break;
570 s->c.chroma_format = CHROMA_422;
571 break;
572 default:
573 av_unreachable("Already checked via CODEC_PIXFMTS");
576 s->c.chroma_format = CHROMA_420;
577 break;
578 }
579
580 avctx->bits_per_raw_sample = av_clip(avctx->bits_per_raw_sample, 0, 8);
581
582 m->bit_rate = avctx->bit_rate;
583 s->c.width = avctx->width;
584 s->c.height = avctx->height;
585 if (avctx->gop_size > 600 &&
587 av_log(avctx, AV_LOG_WARNING,
588 "keyframe interval too large!, reducing it from %d to %d\n",
589 avctx->gop_size, 600);
590 avctx->gop_size = 600;
591 }
592 m->gop_size = avctx->gop_size;
593 s->c.avctx = avctx;
594 if (avctx->max_b_frames > MPVENC_MAX_B_FRAMES) {
595 av_log(avctx, AV_LOG_ERROR, "Too many B-frames requested, maximum "
596 "is " AV_STRINGIFY(MPVENC_MAX_B_FRAMES) ".\n");
598 } else if (avctx->max_b_frames < 0) {
599 av_log(avctx, AV_LOG_ERROR,
600 "max b frames must be 0 or positive for mpegvideo based encoders\n");
601 return AVERROR(EINVAL);
602 }
603 m->max_b_frames = avctx->max_b_frames;
604 s->c.codec_id = avctx->codec->id;
605 if (m->max_b_frames && !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) {
606 av_log(avctx, AV_LOG_ERROR, "B-frames not supported by codec\n");
607 return AVERROR(EINVAL);
608 }
609
610 s->c.quarter_sample = (avctx->flags & AV_CODEC_FLAG_QPEL) != 0;
611 s->rtp_mode = !!s->rtp_payload_size;
613
614 if (m->gop_size <= 1) {
615 m->intra_only = 1;
616 m->gop_size = 12;
617 } else {
618 m->intra_only = 0;
619 }
620
621 /* Fixed QSCALE */
622 m->fixed_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);
623
624 s->adaptive_quant = (avctx->lumi_masking ||
625 avctx->dark_masking ||
626 avctx->temporal_cplx_masking ||
627 avctx->spatial_cplx_masking ||
628 avctx->p_masking ||
629 m->border_masking ||
630 (s->mpv_flags & FF_MPV_FLAG_QP_RD)) &&
631 !m->fixed_qscale;
632
633 s->loop_filter = !!(avctx->flags & AV_CODEC_FLAG_LOOP_FILTER);
634
635 if (avctx->rc_max_rate && !avctx->rc_buffer_size) {
636 switch(avctx->codec_id) {
639 avctx->rc_buffer_size = FFMAX(avctx->rc_max_rate, 15000000) * 112LL / 15000000 * 16384;
640 break;
645 if (avctx->rc_max_rate >= 15000000) {
646 avctx->rc_buffer_size = 320 + (avctx->rc_max_rate - 15000000LL) * (760-320) / (38400000 - 15000000);
647 } else if(avctx->rc_max_rate >= 2000000) {
648 avctx->rc_buffer_size = 80 + (avctx->rc_max_rate - 2000000LL) * (320- 80) / (15000000 - 2000000);
649 } else if(avctx->rc_max_rate >= 384000) {
650 avctx->rc_buffer_size = 40 + (avctx->rc_max_rate - 384000LL) * ( 80- 40) / ( 2000000 - 384000);
651 } else
652 avctx->rc_buffer_size = 40;
653 avctx->rc_buffer_size *= 16384;
654 break;
655 }
656 if (avctx->rc_buffer_size) {
657 av_log(avctx, AV_LOG_INFO, "Automatically choosing VBV buffer size of %d kbyte\n", avctx->rc_buffer_size/8192);
658 }
659 }
660
661 if ((!avctx->rc_max_rate) != (!avctx->rc_buffer_size)) {
662 av_log(avctx, AV_LOG_ERROR, "Either both buffer size and max rate or neither must be specified\n");
663 return AVERROR(EINVAL);
664 }
665
666 if (avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate) {
667 av_log(avctx, AV_LOG_INFO,
668 "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");
669 }
670
671 if (avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate) {
672 av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");
673 return AVERROR(EINVAL);
674 }
675
676 if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {
677 av_log(avctx, AV_LOG_ERROR, "bitrate above max bitrate\n");
678 return AVERROR(EINVAL);
679 }
680
681 if (avctx->rc_max_rate &&
682 avctx->rc_max_rate == avctx->bit_rate &&
683 avctx->rc_max_rate != avctx->rc_min_rate) {
684 av_log(avctx, AV_LOG_INFO,
685 "impossible bitrate constraints, this will fail\n");
686 }
687
688 if (avctx->rc_buffer_size &&
689 avctx->bit_rate * (int64_t)avctx->time_base.num >
690 avctx->rc_buffer_size * (int64_t)avctx->time_base.den) {
691 av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");
692 return AVERROR(EINVAL);
693 }
694
695 if (!m->fixed_qscale &&
696 avctx->bit_rate * av_q2d(avctx->time_base) >
697 avctx->bit_rate_tolerance) {
698 double nbt = avctx->bit_rate * av_q2d(avctx->time_base) * 5;
699 av_log(avctx, AV_LOG_WARNING,
700 "bitrate tolerance %d too small for bitrate %"PRId64", overriding\n", avctx->bit_rate_tolerance, avctx->bit_rate);
701 if (nbt <= INT_MAX) {
702 avctx->bit_rate_tolerance = nbt;
703 } else
704 avctx->bit_rate_tolerance = INT_MAX;
705 }
706
707 if ((avctx->flags & AV_CODEC_FLAG_4MV) && s->c.codec_id != AV_CODEC_ID_MPEG4 &&
708 s->c.codec_id != AV_CODEC_ID_H263 && s->c.codec_id != AV_CODEC_ID_H263P &&
709 s->c.codec_id != AV_CODEC_ID_FLV1) {
710 av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
711 return AVERROR(EINVAL);
712 }
713
714 if (s->c.obmc && avctx->mb_decision != FF_MB_DECISION_SIMPLE) {
715 av_log(avctx, AV_LOG_ERROR,
716 "OBMC is only supported with simple mb decision\n");
717 return AVERROR(EINVAL);
718 }
719
720 if (s->c.quarter_sample && s->c.codec_id != AV_CODEC_ID_MPEG4) {
721 av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
722 return AVERROR(EINVAL);
723 }
724
725 if ((s->c.codec_id == AV_CODEC_ID_MPEG4 ||
726 s->c.codec_id == AV_CODEC_ID_H263 ||
727 s->c.codec_id == AV_CODEC_ID_H263P) &&
728 (avctx->sample_aspect_ratio.num > 255 ||
729 avctx->sample_aspect_ratio.den > 255)) {
730 av_log(avctx, AV_LOG_WARNING,
731 "Invalid pixel aspect ratio %i/%i, limit is 255/255 reducing\n",
734 avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den, 255);
735 }
736
737 if ((s->c.codec_id == AV_CODEC_ID_H263 ||
738 s->c.codec_id == AV_CODEC_ID_H263P) &&
739 (avctx->width > 2048 ||
740 avctx->height > 1152 )) {
741 av_log(avctx, AV_LOG_ERROR, "H.263 does not support resolutions above 2048x1152\n");
742 return AVERROR(EINVAL);
743 }
744 if (s->c.codec_id == AV_CODEC_ID_FLV1 &&
745 (avctx->width > 65535 ||
746 avctx->height > 65535 )) {
747 av_log(avctx, AV_LOG_ERROR, "FLV does not support resolutions above 16bit\n");
748 return AVERROR(EINVAL);
749 }
750 if ((s->c.codec_id == AV_CODEC_ID_H263 ||
751 s->c.codec_id == AV_CODEC_ID_H263P ||
752 s->c.codec_id == AV_CODEC_ID_RV20) &&
753 ((avctx->width &3) ||
754 (avctx->height&3) )) {
755 av_log(avctx, AV_LOG_ERROR, "width and height must be a multiple of 4\n");
756 return AVERROR(EINVAL);
757 }
758
759 if ((s->c.codec_id == AV_CODEC_ID_WMV1 ||
760 s->c.codec_id == AV_CODEC_ID_WMV2) &&
761 avctx->width & 1) {
762 av_log(avctx, AV_LOG_ERROR, "width must be multiple of 2\n");
763 return AVERROR(EINVAL);
764 }
765
767 s->c.codec_id != AV_CODEC_ID_MPEG4 && s->c.codec_id != AV_CODEC_ID_MPEG2VIDEO) {
768 av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");
769 return AVERROR(EINVAL);
770 }
771
772 if ((s->mpv_flags & FF_MPV_FLAG_CBP_RD) && !avctx->trellis) {
773 av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
774 return AVERROR(EINVAL);
775 }
776
777 if ((s->mpv_flags & FF_MPV_FLAG_QP_RD) &&
778 avctx->mb_decision != FF_MB_DECISION_RD) {
779 av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=rd\n");
780 return AVERROR(EINVAL);
781 }
782
783 if (m->scenechange_threshold < 1000000000 &&
784 (avctx->flags & AV_CODEC_FLAG_CLOSED_GOP)) {
785 av_log(avctx, AV_LOG_ERROR,
786 "closed gop with scene change detection are not supported yet, "
787 "set threshold to 1000000000\n");
789 }
790
791 if (avctx->flags & AV_CODEC_FLAG_LOW_DELAY) {
792 if (s->c.codec_id != AV_CODEC_ID_MPEG2VIDEO &&
794 av_log(avctx, AV_LOG_ERROR,
795 "low delay forcing is only available for mpeg2, "
796 "set strict_std_compliance to 'unofficial' or lower in order to allow it\n");
797 return AVERROR(EINVAL);
798 }
799 if (m->max_b_frames != 0) {
800 av_log(avctx, AV_LOG_ERROR,
801 "B-frames cannot be used with low delay\n");
802 return AVERROR(EINVAL);
803 }
804 }
805
806 if (avctx->slices > 1 &&
808 av_log(avctx, AV_LOG_ERROR, "Multiple slices are not supported by this codec\n");
809 return AVERROR(EINVAL);
810 }
811
812 if (m->b_frame_strategy && (avctx->flags & AV_CODEC_FLAG_PASS2)) {
813 av_log(avctx, AV_LOG_INFO,
814 "notice: b_frame_strategy only affects the first pass\n");
815 m->b_frame_strategy = 0;
816 }
817
818 gcd = av_gcd(avctx->time_base.den, avctx->time_base.num);
819 if (gcd > 1) {
820 av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");
821 avctx->time_base.den /= gcd;
822 avctx->time_base.num /= gcd;
823 //return -1;
824 }
825
826 if (s->mpeg_quant || s->c.codec_id == AV_CODEC_ID_MPEG1VIDEO || s->c.codec_id == AV_CODEC_ID_MPEG2VIDEO || s->c.codec_id == AV_CODEC_ID_MJPEG || s->c.codec_id == AV_CODEC_ID_AMV || s->c.codec_id == AV_CODEC_ID_SPEEDHQ) {
827 // (a + x * 3 / 8) / x
828 s->intra_quant_bias = 3 << (QUANT_BIAS_SHIFT - 3);
829 s->inter_quant_bias = 0;
830 } else {
831 s->intra_quant_bias = 0;
832 // (a - x / 4) / x
833 s->inter_quant_bias = -(1 << (QUANT_BIAS_SHIFT - 2));
834 }
835
836 if (avctx->qmin > avctx->qmax || avctx->qmin <= 0) {
837 av_log(avctx, AV_LOG_ERROR, "qmin and or qmax are invalid, they must be 0 < min <= max\n");
838 return AVERROR(EINVAL);
839 }
840
841 av_log(avctx, AV_LOG_DEBUG, "intra_quant_bias = %d inter_quant_bias = %d\n",s->intra_quant_bias,s->inter_quant_bias);
842
843 switch (avctx->codec->id) {
844#if CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER
846 s->rtp_mode = 1;
849 s->c.out_format = FMT_MPEG1;
850 s->c.low_delay = !!(avctx->flags & AV_CODEC_FLAG_LOW_DELAY);
851 avctx->delay = s->c.low_delay ? 0 : (m->max_b_frames + 1);
852 break;
853#endif
854#if CONFIG_MJPEG_ENCODER || CONFIG_AMV_ENCODER
856 case AV_CODEC_ID_AMV:
857 s->c.out_format = FMT_MJPEG;
858 m->intra_only = 1; /* force intra only for jpeg */
859 avctx->delay = 0;
860 s->c.low_delay = 1;
861 break;
862#endif
864 s->c.out_format = FMT_SPEEDHQ;
865 m->intra_only = 1; /* force intra only for SHQ */
866 avctx->delay = 0;
867 s->c.low_delay = 1;
868 break;
869 case AV_CODEC_ID_H261:
870 s->c.out_format = FMT_H261;
871 avctx->delay = 0;
872 s->c.low_delay = 1;
873 s->rtp_mode = 0; /* Sliced encoding not supported */
874 break;
875 case AV_CODEC_ID_H263:
876 if (!CONFIG_H263_ENCODER)
879 s->c.width, s->c.height) == 8) {
880 av_log(avctx, AV_LOG_ERROR,
881 "The specified picture size of %dx%d is not valid for "
882 "the H.263 codec.\nValid sizes are 128x96, 176x144, "
883 "352x288, 704x576, and 1408x1152. "
884 "Try H.263+.\n", s->c.width, s->c.height);
885 return AVERROR(EINVAL);
886 }
887 s->c.out_format = FMT_H263;
888 avctx->delay = 0;
889 s->c.low_delay = 1;
890 break;
892 s->c.out_format = FMT_H263;
893 /* Fx */
894 s->c.h263_aic = (avctx->flags & AV_CODEC_FLAG_AC_PRED) ? 1 : 0;
895 s->modified_quant = s->c.h263_aic;
896 s->loop_filter = !!(avctx->flags & AV_CODEC_FLAG_LOOP_FILTER);
897 s->me.unrestricted_mv = s->c.obmc || s->loop_filter || s->umvplus;
898 s->flipflop_rounding = 1;
899
900 /* /Fx */
901 /* These are just to be sure */
902 avctx->delay = 0;
903 s->c.low_delay = 1;
904 break;
905 case AV_CODEC_ID_FLV1:
906 s->c.out_format = FMT_H263;
907 s->me.unrestricted_mv = 1;
908 s->rtp_mode = 0; /* don't allow GOB */
909 avctx->delay = 0;
910 s->c.low_delay = 1;
911 break;
912#if CONFIG_RV10_ENCODER
913 case AV_CODEC_ID_RV10:
914 s->c.out_format = FMT_H263;
915 avctx->delay = 0;
916 s->c.low_delay = 1;
917 break;
918#endif
919#if CONFIG_RV20_ENCODER
920 case AV_CODEC_ID_RV20:
922 s->c.out_format = FMT_H263;
923 avctx->delay = 0;
924 s->c.low_delay = 1;
925 s->modified_quant = 1;
926 // Set here to force allocation of dc_val;
927 // will be set later on a per-frame basis.
928 s->c.h263_aic = 1;
929 s->loop_filter = 1;
930 s->me.unrestricted_mv = 0;
931 break;
932#endif
934 s->c.out_format = FMT_H263;
935 s->c.h263_pred = 1;
936 s->me.unrestricted_mv = 1;
937 s->flipflop_rounding = 1;
938 s->c.low_delay = m->max_b_frames ? 0 : 1;
939 avctx->delay = s->c.low_delay ? 0 : (m->max_b_frames + 1);
940 break;
942 s->c.out_format = FMT_H263;
943 s->c.h263_pred = 1;
944 s->me.unrestricted_mv = 1;
945 s->c.msmpeg4_version = MSMP4_V2;
946 avctx->delay = 0;
947 s->c.low_delay = 1;
948 break;
950 s->c.out_format = FMT_H263;
951 s->c.h263_pred = 1;
952 s->me.unrestricted_mv = 1;
953 s->c.msmpeg4_version = MSMP4_V3;
954 s->flipflop_rounding = 1;
955 avctx->delay = 0;
956 s->c.low_delay = 1;
957 break;
958 case AV_CODEC_ID_WMV1:
959 s->c.out_format = FMT_H263;
960 s->c.h263_pred = 1;
961 s->me.unrestricted_mv = 1;
962 s->c.msmpeg4_version = MSMP4_WMV1;
963 s->flipflop_rounding = 1;
964 avctx->delay = 0;
965 s->c.low_delay = 1;
966 break;
967 case AV_CODEC_ID_WMV2:
968 s->c.out_format = FMT_H263;
969 s->c.h263_pred = 1;
970 s->me.unrestricted_mv = 1;
971 s->c.msmpeg4_version = MSMP4_WMV2;
972 s->flipflop_rounding = 1;
973 avctx->delay = 0;
974 s->c.low_delay = 1;
975 break;
976 default:
977 av_unreachable("List contains all codecs using ff_mpv_encode_init()");
978 }
979
980 avctx->has_b_frames = !s->c.low_delay;
981
982 s->c.encoding = 1;
983
984 s->c.progressive_frame =
985 s->c.progressive_sequence = !(avctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT |
987 s->c.alternate_scan);
988
989 if (avctx->flags & AV_CODEC_FLAG_PSNR || avctx->mb_decision == FF_MB_DECISION_RD ||
991 s->frame_reconstruction_bitfield = (1 << AV_PICTURE_TYPE_I) |
992 (1 << AV_PICTURE_TYPE_P) |
993 (1 << AV_PICTURE_TYPE_B);
994 } else if (!m->intra_only) {
995 s->frame_reconstruction_bitfield = (1 << AV_PICTURE_TYPE_I) |
996 (1 << AV_PICTURE_TYPE_P);
997 } else {
998 s->frame_reconstruction_bitfield = 0;
999 }
1000
1001 if (m->lmin > m->lmax) {
1002 av_log(avctx, AV_LOG_WARNING, "Clipping lmin value to %d\n", m->lmax);
1003 m->lmin = m->lmax;
1004 }
1005
1006 /* ff_mpv_init_duplicate_contexts() will copy (memdup) the contents of the
1007 * main slice to the slice contexts, so we initialize various fields of it
1008 * before calling ff_mpv_init_duplicate_contexts(). */
1009 s->parent = m;
1010 ff_mpv_idct_init(&s->c);
1011 init_unquantize(s, avctx);
1012 ff_fdctdsp_init(&s->fdsp, avctx);
1013 ff_mpegvideoencdsp_init(&s->mpvencdsp, avctx);
1014 ff_pixblockdsp_init(&s->pdsp, 8);
1015 ret = me_cmp_init(m, avctx);
1016 if (ret < 0)
1017 return ret;
1018
1019 if (!(avctx->stats_out = av_mallocz(256)) ||
1020 !(s->new_pic = av_frame_alloc()) ||
1021 !(s->c.picture_pool = ff_mpv_alloc_pic_pool(0)))
1022 return AVERROR(ENOMEM);
1023
1024 ret = init_matrices(m, avctx);
1025 if (ret < 0)
1026 return ret;
1027
1029
1030 if (CONFIG_H263_ENCODER && s->c.out_format == FMT_H263) {
1032#if CONFIG_MSMPEG4ENC
1033 if (s->c.msmpeg4_version != MSMP4_UNUSED)
1035#endif
1036 }
1037
1038 s->c.slice_ctx_size = sizeof(*s);
1039 ret = ff_mpv_common_init(&s->c);
1040 if (ret < 0)
1041 return ret;
1042 ret = init_buffers(m);
1043 if (ret < 0)
1044 return ret;
1045 if (s->c.slice_context_count > 1) {
1046 s->rtp_mode = 1;
1047 if (avctx->codec_id == AV_CODEC_ID_H263P)
1048 s->h263_slice_structured = 1;
1049 }
1051 if (ret < 0)
1052 return ret;
1053
1054 ret = init_slice_buffers(m);
1055 if (ret < 0)
1056 return ret;
1057
1058 ret = ff_rate_control_init(m);
1059 if (ret < 0)
1060 return ret;
1061
1062 if (m->b_frame_strategy == 2) {
1063 for (int i = 0; i < m->max_b_frames + 2; i++) {
1064 m->tmp_frames[i] = av_frame_alloc();
1065 if (!m->tmp_frames[i])
1066 return AVERROR(ENOMEM);
1067
1069 m->tmp_frames[i]->width = s->c.width >> m->brd_scale;
1070 m->tmp_frames[i]->height = s->c.height >> m->brd_scale;
1071
1072 ret = av_frame_get_buffer(m->tmp_frames[i], 0);
1073 if (ret < 0)
1074 return ret;
1075 }
1076 }
1077
1078 cpb_props = ff_encode_add_cpb_side_data(avctx);
1079 if (!cpb_props)
1080 return AVERROR(ENOMEM);
1081 cpb_props->max_bitrate = avctx->rc_max_rate;
1082 cpb_props->min_bitrate = avctx->rc_min_rate;
1083 cpb_props->avg_bitrate = avctx->bit_rate;
1084 cpb_props->buffer_size = avctx->rc_buffer_size;
1085
1086 return 0;
1087}
1088
1090{
1091 MPVMainEncContext *const m = avctx->priv_data;
1092 MPVEncContext *const s = &m->s;
1093
1095
1096 ff_mpv_common_end(&s->c);
1097 av_refstruct_pool_uninit(&s->c.picture_pool);
1098
1099 for (int i = 0; i < MPVENC_MAX_B_FRAMES + 1; i++) {
1102 }
1103 for (int i = 0; i < FF_ARRAY_ELEMS(m->tmp_frames); i++)
1105
1106 av_frame_free(&s->new_pic);
1107
1108 av_freep(&avctx->stats_out);
1109
1111 av_freep(&s->p_field_select_table[0]);
1113
1114 av_freep(&s->mb_type);
1115 av_freep(&s->lambda_table);
1116
1117 av_freep(&s->q_intra_matrix);
1118 av_freep(&s->q_intra_matrix16);
1119 av_freep(&s->dct_offset);
1120
1121 return 0;
1122}
1123
1124/* put block[] to dest[] */
1125static inline void put_dct(MPVEncContext *const s,
1126 int16_t *block, int i, uint8_t *dest, int line_size, int qscale)
1127{
1128 s->c.dct_unquantize_intra(&s->c, block, i, qscale);
1129 s->c.idsp.idct_put(dest, line_size, block);
1130}
1131
1132static inline void add_dequant_dct(MPVEncContext *const s,
1133 int16_t *block, int i, uint8_t *dest, int line_size, int qscale)
1134{
1135 if (s->c.block_last_index[i] >= 0) {
1136 s->c.dct_unquantize_inter(&s->c, block, i, qscale);
1137
1138 s->c.idsp.idct_add(dest, line_size, block);
1139 }
1140}
1141
1142/**
1143 * Performs dequantization and IDCT (if necessary)
1144 */
1145static void mpv_reconstruct_mb(MPVEncContext *const s, int16_t block[12][64])
1146{
1147 if (s->c.avctx->debug & FF_DEBUG_DCT_COEFF) {
1148 /* print DCT coefficients */
1149 av_log(s->c.avctx, AV_LOG_DEBUG, "DCT coeffs of MB at %dx%d:\n", s->c.mb_x, s->c.mb_y);
1150 for (int i = 0; i < 6; i++) {
1151 for (int j = 0; j < 64; j++) {
1152 av_log(s->c.avctx, AV_LOG_DEBUG, "%5d",
1153 block[i][s->c.idsp.idct_permutation[j]]);
1154 }
1155 av_log(s->c.avctx, AV_LOG_DEBUG, "\n");
1156 }
1157 }
1158
1159 if ((1 << s->c.pict_type) & s->frame_reconstruction_bitfield) {
1160 uint8_t *dest_y = s->c.dest[0], *dest_cb = s->c.dest[1], *dest_cr = s->c.dest[2];
1161 int dct_linesize, dct_offset;
1162 const int linesize = s->c.cur_pic.linesize[0];
1163 const int uvlinesize = s->c.cur_pic.linesize[1];
1164 const int block_size = 8;
1165
1166 dct_linesize = linesize << s->c.interlaced_dct;
1167 dct_offset = s->c.interlaced_dct ? linesize : linesize * block_size;
1168
1169 if (!s->c.mb_intra) {
1170 /* No MC, as that was already done otherwise */
1171 add_dequant_dct(s, block[0], 0, dest_y , dct_linesize, s->c.qscale);
1172 add_dequant_dct(s, block[1], 1, dest_y + block_size, dct_linesize, s->c.qscale);
1173 add_dequant_dct(s, block[2], 2, dest_y + dct_offset , dct_linesize, s->c.qscale);
1174 add_dequant_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->c.qscale);
1175
1176 if (!CONFIG_GRAY || !(s->c.avctx->flags & AV_CODEC_FLAG_GRAY)) {
1177 if (s->c.chroma_y_shift) {
1178 add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize, s->c.chroma_qscale);
1179 add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize, s->c.chroma_qscale);
1180 } else {
1181 dct_linesize >>= 1;
1182 dct_offset >>= 1;
1183 add_dequant_dct(s, block[4], 4, dest_cb, dct_linesize, s->c.chroma_qscale);
1184 add_dequant_dct(s, block[5], 5, dest_cr, dct_linesize, s->c.chroma_qscale);
1185 add_dequant_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->c.chroma_qscale);
1186 add_dequant_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->c.chroma_qscale);
1187 }
1188 }
1189 } else {
1190 /* dct only in intra block */
1191 put_dct(s, block[0], 0, dest_y , dct_linesize, s->c.qscale);
1192 put_dct(s, block[1], 1, dest_y + block_size, dct_linesize, s->c.qscale);
1193 put_dct(s, block[2], 2, dest_y + dct_offset , dct_linesize, s->c.qscale);
1194 put_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->c.qscale);
1195
1196 if (!CONFIG_GRAY || !(s->c.avctx->flags & AV_CODEC_FLAG_GRAY)) {
1197 if (s->c.chroma_y_shift) {
1198 put_dct(s, block[4], 4, dest_cb, uvlinesize, s->c.chroma_qscale);
1199 put_dct(s, block[5], 5, dest_cr, uvlinesize, s->c.chroma_qscale);
1200 } else {
1201 dct_offset >>= 1;
1202 dct_linesize >>= 1;
1203 put_dct(s, block[4], 4, dest_cb, dct_linesize, s->c.chroma_qscale);
1204 put_dct(s, block[5], 5, dest_cr, dct_linesize, s->c.chroma_qscale);
1205 put_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->c.chroma_qscale);
1206 put_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->c.chroma_qscale);
1207 }
1208 }
1209 }
1210 }
1211}
1212
1213static int get_sae(const uint8_t *src, int ref, int stride)
1214{
1215 int x,y;
1216 int acc = 0;
1217
1218 for (y = 0; y < 16; y++) {
1219 for (x = 0; x < 16; x++) {
1220 acc += FFABS(src[x + y * stride] - ref);
1221 }
1222 }
1223
1224 return acc;
1225}
1226
1227static int get_intra_count(MPVEncContext *const s, const uint8_t *src,
1228 const uint8_t *ref, int stride)
1229{
1230 int x, y, w, h;
1231 int acc = 0;
1232
1233 w = s->c.width & ~15;
1234 h = s->c.height & ~15;
1235
1236 for (y = 0; y < h; y += 16) {
1237 for (x = 0; x < w; x += 16) {
1238 int offset = x + y * stride;
1239 int sad = s->sad_cmp[0](NULL, src + offset, ref + offset,
1240 stride, 16);
1241 int mean = (s->mpvencdsp.pix_sum(src + offset, stride) + 128) >> 8;
1242 int sae = get_sae(src + offset, mean, stride);
1243
1244 acc += sae + 500 < sad;
1245 }
1246 }
1247 return acc;
1248}
1249
1250/**
1251 * Allocates new buffers for an AVFrame and copies the properties
1252 * from another AVFrame.
1253 */
1254static int prepare_picture(MPVEncContext *const s, AVFrame *f, const AVFrame *props_frame)
1255{
1256 AVCodecContext *avctx = s->c.avctx;
1257 int ret;
1258
1259 f->width = avctx->width + 2 * EDGE_WIDTH;
1260 f->height = avctx->height + 2 * EDGE_WIDTH;
1261
1262 ret = ff_encode_alloc_frame(avctx, f);
1263 if (ret < 0)
1264 return ret;
1265
1266 ret = ff_mpv_pic_check_linesize(avctx, f, &s->c.linesize, &s->c.uvlinesize);
1267 if (ret < 0)
1268 return ret;
1269
1270 for (int i = 0; f->data[i]; i++) {
1271 int offset = (EDGE_WIDTH >> (i ? s->c.chroma_y_shift : 0)) *
1272 f->linesize[i] +
1273 (EDGE_WIDTH >> (i ? s->c.chroma_x_shift : 0));
1274 f->data[i] += offset;
1275 }
1276 f->width = avctx->width;
1277 f->height = avctx->height;
1278
1279 ret = av_frame_copy_props(f, props_frame);
1280 if (ret < 0)
1281 return ret;
1282
1283 return 0;
1284}
1285
1286static int load_input_picture(MPVMainEncContext *const m, const AVFrame *pic_arg)
1287{
1288 MPVEncContext *const s = &m->s;
1289 MPVPicture *pic = NULL;
1290 int64_t pts;
1291 int display_picture_number = 0, ret;
1292 int encoding_delay = m->max_b_frames ? m->max_b_frames
1293 : (s->c.low_delay ? 0 : 1);
1294 int flush_offset = 1;
1295 int direct = 1;
1296
1297 av_assert1(!m->input_picture[0]);
1298
1299 if (pic_arg) {
1300 pts = pic_arg->pts;
1301 display_picture_number = m->input_picture_number++;
1302
1303 if (pts != AV_NOPTS_VALUE) {
1304 if (s->c.codec_id == AV_CODEC_ID_MPEG4 &&
1305 (pts > INT64_MAX / 2 / s->c.avctx->time_base.num ||
1306 pts < INT64_MIN / 2 / s->c.avctx->time_base.num)) {
1307 av_log(s->c.avctx, AV_LOG_ERROR, "pts %"PRId64" is out of the supported range\n", pts);
1308 return AVERROR_PATCHWELCOME;
1309 }
1310
1312 int64_t last = m->user_specified_pts;
1313
1314 if (pts <= last) {
1315 av_log(s->c.avctx, AV_LOG_ERROR,
1316 "Invalid pts (%"PRId64") <= last (%"PRId64")\n",
1317 pts, last);
1318 return AVERROR(EINVAL);
1319 }
1320
1321 if (!s->c.low_delay && display_picture_number == 1)
1322 m->dts_delta = pts - last;
1323 }
1325 } else {
1328 pts = m->user_specified_pts + 1;
1329 av_log(s->c.avctx, AV_LOG_INFO,
1330 "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n",
1331 pts);
1332 } else {
1333 pts = display_picture_number;
1334 }
1335 }
1336
1337 if (pic_arg->linesize[0] != s->c.linesize ||
1338 pic_arg->linesize[1] != s->c.uvlinesize ||
1339 pic_arg->linesize[2] != s->c.uvlinesize)
1340 direct = 0;
1341 if ((s->c.width & 15) || (s->c.height & 15))
1342 direct = 0;
1343 if (((intptr_t)(pic_arg->data[0])) & (STRIDE_ALIGN-1))
1344 direct = 0;
1345 if (s->c.linesize & (STRIDE_ALIGN-1))
1346 direct = 0;
1347
1348 ff_dlog(s->c.avctx, "%d %d %td %td\n", pic_arg->linesize[0],
1349 pic_arg->linesize[1], s->c.linesize, s->c.uvlinesize);
1350
1351 pic = av_refstruct_pool_get(s->c.picture_pool);
1352 if (!pic)
1353 return AVERROR(ENOMEM);
1354
1355 if (direct) {
1356 if ((ret = av_frame_ref(pic->f, pic_arg)) < 0)
1357 goto fail;
1358 pic->shared = 1;
1359 } else {
1360 ret = prepare_picture(s, pic->f, pic_arg);
1361 if (ret < 0)
1362 goto fail;
1363
1364 for (int i = 0; i < 3; i++) {
1365 ptrdiff_t src_stride = pic_arg->linesize[i];
1366 ptrdiff_t dst_stride = i ? s->c.uvlinesize : s->c.linesize;
1367 int h_shift = i ? s->c.chroma_x_shift : 0;
1368 int v_shift = i ? s->c.chroma_y_shift : 0;
1369 int w = AV_CEIL_RSHIFT(s->c.width , h_shift);
1370 int h = AV_CEIL_RSHIFT(s->c.height, v_shift);
1371 const uint8_t *src = pic_arg->data[i];
1372 int vpad = 16;
1373
1374 if ( s->c.codec_id == AV_CODEC_ID_MPEG2VIDEO
1375 && !s->c.progressive_sequence
1376 && FFALIGN(s->c.height, 32) - s->c.height > 16)
1377 vpad = 32;
1378
1379 if (!s->c.avctx->rc_buffer_size)
1380 pic->f->data[i] += INPLACE_OFFSET;
1381 uint8_t *dst = pic->f->data[i];
1382
1383 if (src_stride == dst_stride)
1384 memcpy(dst, src, src_stride * h - src_stride + w);
1385 else {
1386 int h2 = h;
1387 uint8_t *dst2 = dst;
1388 while (h2--) {
1389 memcpy(dst2, src, w);
1390 dst2 += dst_stride;
1391 src += src_stride;
1392 }
1393 }
1394 if ((s->c.width & 15) || (s->c.height & (vpad-1))) {
1395 s->mpvencdsp.draw_edges(dst, dst_stride,
1396 w, h,
1397 16 >> h_shift,
1398 vpad >> v_shift,
1399 EDGE_BOTTOM);
1400 }
1401 }
1402 }
1403
1404 pic->display_picture_number = display_picture_number;
1405 pic->f->pts = pts; // we set this here to avoid modifying pic_arg
1406 } else if (!m->reordered_input_picture[1]) {
1407 /* Flushing: When the above check is true, the encoder is about to run
1408 * out of frames to encode. Check if there are input_pictures left;
1409 * if so, ensure m->input_picture[0] contains the first picture.
1410 * A flush_offset != 1 will only happen if we did not receive enough
1411 * input frames. */
1412 for (flush_offset = 0; flush_offset < encoding_delay + 1; flush_offset++)
1413 if (m->input_picture[flush_offset])
1414 break;
1415
1416 encoding_delay -= flush_offset - 1;
1417 }
1418
1419 /* shift buffer entries */
1420 for (int i = flush_offset; i <= MPVENC_MAX_B_FRAMES; i++)
1421 m->input_picture[i - flush_offset] = m->input_picture[i];
1422 for (int i = MPVENC_MAX_B_FRAMES + 1 - flush_offset; i <= MPVENC_MAX_B_FRAMES; i++)
1423 m->input_picture[i] = NULL;
1424
1425 m->input_picture[encoding_delay] = pic;
1426
1427 return 0;
1428fail:
1429 av_refstruct_unref(&pic);
1430 return ret;
1431}
1432
1433static int skip_check(MPVMainEncContext *const m,
1434 const MPVPicture *p, const MPVPicture *ref)
1435{
1436 MPVEncContext *const s = &m->s;
1437 int score = 0;
1438 int64_t score64 = 0;
1439
1440 for (int plane = 0; plane < 3; plane++) {
1441 const int stride = p->f->linesize[plane];
1442 const int bw = plane ? 1 : 2;
1443 for (int y = 0; y < s->c.mb_height * bw; y++) {
1444 for (int x = 0; x < s->c.mb_width * bw; x++) {
1445 const uint8_t *dptr = p->f->data[plane] + 8 * (x + y * stride);
1446 const uint8_t *rptr = ref->f->data[plane] + 8 * (x + y * stride);
1447 int v = m->frame_skip_cmp_fn(s, dptr, rptr, stride, 8);
1448
1449 switch (FFABS(m->frame_skip_exp)) {
1450 case 0: score = FFMAX(score, v); break;
1451 case 1: score += FFABS(v); break;
1452 case 2: score64 += v * (int64_t)v; break;
1453 case 3: score64 += FFABS(v * (int64_t)v * v); break;
1454 case 4: score64 += (v * (int64_t)v) * (v * (int64_t)v); break;
1455 }
1456 }
1457 }
1458 }
1459 emms_c();
1460
1461 if (score)
1462 score64 = score;
1463 if (m->frame_skip_exp < 0)
1464 score64 = pow(score64 / (double)(s->c.mb_width * s->c.mb_height),
1465 -1.0/m->frame_skip_exp);
1466
1467 if (score64 < m->frame_skip_threshold)
1468 return 1;
1469 if (score64 < ((m->frame_skip_factor * (int64_t) s->lambda) >> 8))
1470 return 1;
1471 return 0;
1472}
1473
1475{
1476 int ret;
1477 int size = 0;
1478
1479 ret = avcodec_send_frame(c, frame);
1480 if (ret < 0)
1481 return ret;
1482
1483 do {
1485 if (ret >= 0) {
1486 size += pkt->size;
1488 } else if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
1489 return ret;
1490 } while (ret >= 0);
1491
1492 return size;
1493}
1494
1496{
1497 MPVEncContext *const s = &m->s;
1498 AVPacket *pkt;
1499 const int scale = m->brd_scale;
1500 int width = s->c.width >> scale;
1501 int height = s->c.height >> scale;
1502 int out_size, p_lambda, b_lambda, lambda2;
1503 int64_t best_rd = INT64_MAX;
1504 int best_b_count = -1;
1505 int ret = 0;
1506
1507 av_assert0(scale >= 0 && scale <= 3);
1508
1509 pkt = av_packet_alloc();
1510 if (!pkt)
1511 return AVERROR(ENOMEM);
1512
1513 p_lambda = m->last_lambda_for[AV_PICTURE_TYPE_P];
1514 //p_lambda * FFABS(s->c.avctx->b_quant_factor) + s->c.avctx->b_quant_offset;
1515 b_lambda = m->last_lambda_for[AV_PICTURE_TYPE_B];
1516 if (!b_lambda) // FIXME we should do this somewhere else
1517 b_lambda = p_lambda;
1518 lambda2 = (b_lambda * b_lambda + (1 << FF_LAMBDA_SHIFT) / 2) >>
1520
1521 for (int i = 0; i < m->max_b_frames + 2; i++) {
1522 const MPVPicture *pre_input_ptr = i ? m->input_picture[i - 1] :
1523 s->c.next_pic.ptr;
1524
1525 if (pre_input_ptr) {
1526 const AVFrame *const pre_input = pre_input_ptr->f;
1527
1528 s->mpvencdsp.shrink[scale](m->tmp_frames[i]->data[0],
1529 m->tmp_frames[i]->linesize[0],
1530 pre_input->data[0],
1531 pre_input->linesize[0],
1532 width, height);
1533 s->mpvencdsp.shrink[scale](m->tmp_frames[i]->data[1],
1534 m->tmp_frames[i]->linesize[1],
1535 pre_input->data[1],
1536 pre_input->linesize[1],
1537 width >> 1, height >> 1);
1538 s->mpvencdsp.shrink[scale](m->tmp_frames[i]->data[2],
1539 m->tmp_frames[i]->linesize[2],
1540 pre_input->data[2],
1541 pre_input->linesize[2],
1542 width >> 1, height >> 1);
1543 }
1544 }
1545
1546 for (int j = 0; j < m->max_b_frames + 1; j++) {
1548 int64_t rd = 0;
1549
1550 if (!m->input_picture[j])
1551 break;
1552
1554 if (!c) {
1555 ret = AVERROR(ENOMEM);
1556 goto fail;
1557 }
1558
1559 c->width = width;
1560 c->height = height;
1562 c->flags |= s->c.avctx->flags & AV_CODEC_FLAG_QPEL;
1563 c->mb_decision = s->c.avctx->mb_decision;
1564 c->me_cmp = s->c.avctx->me_cmp;
1565 c->mb_cmp = s->c.avctx->mb_cmp;
1566 c->me_sub_cmp = s->c.avctx->me_sub_cmp;
1567 c->pix_fmt = AV_PIX_FMT_YUV420P;
1568 c->time_base = s->c.avctx->time_base;
1569 c->max_b_frames = m->max_b_frames;
1570
1571 ret = avcodec_open2(c, s->c.avctx->codec, NULL);
1572 if (ret < 0)
1573 goto fail;
1574
1575
1577 m->tmp_frames[0]->quality = 1 * FF_QP2LAMBDA;
1578
1580 if (out_size < 0) {
1581 ret = out_size;
1582 goto fail;
1583 }
1584
1585 //rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
1586
1587 for (int i = 0; i < m->max_b_frames + 1; i++) {
1588 int is_p = i % (j + 1) == j || i == m->max_b_frames;
1589
1590 m->tmp_frames[i + 1]->pict_type = is_p ?
1592 m->tmp_frames[i + 1]->quality = is_p ? p_lambda : b_lambda;
1593
1594 out_size = encode_frame(c, m->tmp_frames[i + 1], pkt);
1595 if (out_size < 0) {
1596 ret = out_size;
1597 goto fail;
1598 }
1599
1600 rd += (out_size * (uint64_t)lambda2) >> (FF_LAMBDA_SHIFT - 3);
1601 }
1602
1603 /* get the delayed frames */
1605 if (out_size < 0) {
1606 ret = out_size;
1607 goto fail;
1608 }
1609 rd += (out_size * (uint64_t)lambda2) >> (FF_LAMBDA_SHIFT - 3);
1610
1611 rd += c->error[0] + c->error[1] + c->error[2];
1612
1613 if (rd < best_rd) {
1614 best_rd = rd;
1615 best_b_count = j;
1616 }
1617
1618fail:
1621 if (ret < 0) {
1622 best_b_count = ret;
1623 break;
1624 }
1625 }
1626
1628
1629 return best_b_count;
1630}
1631
1632/**
1633 * Determines whether an input picture is discarded or not
1634 * and if not determines the length of the next chain of B frames
1635 * and moves these pictures (including the P frame) into
1636 * reordered_input_picture.
1637 * input_picture[0] is always NULL when exiting this function, even on error;
1638 * reordered_input_picture[0] is always NULL when exiting this function on error.
1639 */
1641{
1642 MPVEncContext *const s = &m->s;
1643
1644 /* Either nothing to do or can't do anything */
1645 if (m->reordered_input_picture[0] || !m->input_picture[0])
1646 return 0;
1647
1648 /* set next picture type & ordering */
1650 if (m->picture_in_gop_number < m->gop_size &&
1651 s->c.next_pic.ptr &&
1652 skip_check(m, m->input_picture[0], s->c.next_pic.ptr)) {
1653 // FIXME check that the gop check above is +-1 correct
1655
1656 ff_vbv_update(m, 0);
1657
1658 return 0;
1659 }
1660 }
1661
1662 if (/* m->picture_in_gop_number >= m->gop_size || */
1663 !s->c.next_pic.ptr || m->intra_only) {
1665 m->input_picture[0] = NULL;
1669 } else {
1670 int b_frames = 0;
1671
1672 if (s->c.avctx->flags & AV_CODEC_FLAG_PASS2) {
1673 for (int i = 0; i < m->max_b_frames + 1; i++) {
1674 int pict_num = m->input_picture[0]->display_picture_number + i;
1675
1676 if (pict_num >= m->rc_context.num_entries)
1677 break;
1678 if (!m->input_picture[i]) {
1680 break;
1681 }
1682
1683 m->input_picture[i]->f->pict_type =
1684 m->rc_context.entry[pict_num].new_pict_type;
1685 }
1686 }
1687
1688 if (m->b_frame_strategy == 0) {
1689 b_frames = m->max_b_frames;
1690 while (b_frames && !m->input_picture[b_frames])
1691 b_frames--;
1692 } else if (m->b_frame_strategy == 1) {
1693 for (int i = 1; i < m->max_b_frames + 1; i++) {
1694 if (m->input_picture[i] &&
1695 m->input_picture[i]->b_frame_score == 0) {
1698 m->input_picture[i ]->f->data[0],
1699 m->input_picture[i - 1]->f->data[0],
1700 s->c.linesize) + 1;
1701 }
1702 }
1703 for (int i = 0;; i++) {
1704 if (i >= m->max_b_frames + 1 ||
1705 !m->input_picture[i] ||
1706 m->input_picture[i]->b_frame_score - 1 >
1707 s->c.mb_num / m->b_sensitivity) {
1708 b_frames = FFMAX(0, i - 1);
1709 break;
1710 }
1711 }
1712
1713 /* reset scores */
1714 for (int i = 0; i < b_frames + 1; i++)
1715 m->input_picture[i]->b_frame_score = 0;
1716 } else if (m->b_frame_strategy == 2) {
1717 b_frames = estimate_best_b_count(m);
1718 if (b_frames < 0) {
1720 return b_frames;
1721 }
1722 }
1723
1724 if (s->c.codec_id == AV_CODEC_ID_MPEG4)
1725 while (b_frames &&
1726 m->input_picture[b_frames]->f->pts * s->c.avctx->time_base.num -
1727 s->c.last_non_b_time > UINT16_MAX)
1728 b_frames--;
1729
1730 for (int i = b_frames - 1; i >= 0; i--) {
1731 int type = m->input_picture[i]->f->pict_type;
1732 if (type && type != AV_PICTURE_TYPE_B)
1733 b_frames = i;
1734 }
1735 if (m->input_picture[b_frames]->f->pict_type == AV_PICTURE_TYPE_B &&
1736 b_frames == m->max_b_frames) {
1737 av_log(s->c.avctx, AV_LOG_ERROR,
1738 "warning, too many B-frames in a row\n");
1739 }
1740
1741 if (m->picture_in_gop_number + b_frames >= m->gop_size) {
1742 if ((s->mpv_flags & FF_MPV_FLAG_STRICT_GOP) &&
1744 b_frames = m->gop_size - m->picture_in_gop_number - 1;
1745 } else {
1746 if (s->c.avctx->flags & AV_CODEC_FLAG_CLOSED_GOP)
1747 b_frames = 0;
1748 m->input_picture[b_frames]->f->pict_type = AV_PICTURE_TYPE_I;
1749 }
1750 }
1751
1752 if ((s->c.avctx->flags & AV_CODEC_FLAG_CLOSED_GOP) && b_frames &&
1753 m->input_picture[b_frames]->f->pict_type == AV_PICTURE_TYPE_I)
1754 b_frames--;
1755
1756 m->reordered_input_picture[0] = m->input_picture[b_frames];
1757 m->input_picture[b_frames] = NULL;
1762 for (int i = 0; i < b_frames; i++) {
1764 m->input_picture[i] = NULL;
1769 }
1770 }
1771
1772 return 0;
1773}
1774
1776{
1777 MPVEncContext *const s = &m->s;
1778 int ret;
1779
1781
1782 for (int i = 1; i <= MPVENC_MAX_B_FRAMES; i++)
1785
1786 ret = set_bframe_chain_length(m);
1787 av_assert1(!m->input_picture[0]);
1788 if (ret < 0)
1789 return ret;
1790
1791 av_frame_unref(s->new_pic);
1792
1793 if (m->reordered_input_picture[0]) {
1796
1797 if (m->reordered_input_picture[0]->shared || s->c.avctx->rc_buffer_size) {
1798 // input is a shared pix, so we can't modify it -> allocate a new
1799 // one & ensure that the shared one is reusable
1800 av_frame_move_ref(s->new_pic, m->reordered_input_picture[0]->f);
1801
1802 ret = prepare_picture(s, m->reordered_input_picture[0]->f, s->new_pic);
1803 if (ret < 0)
1804 goto fail;
1805 } else {
1806 // input is not a shared pix -> reuse buffer for current_pix
1807 ret = av_frame_ref(s->new_pic, m->reordered_input_picture[0]->f);
1808 if (ret < 0)
1809 goto fail;
1810 // The input was stored INPLACE_OFFSET into the buffer, which
1811 // new_pic now points at. Point the frame back at the start of
1812 // the buffer for the reconstruction.
1813 for (int i = 0; i < MPV_MAX_PLANES; i++)
1815 }
1816 s->c.cur_pic.ptr = m->reordered_input_picture[0];
1818 av_assert1(s->c.mb_width == s->c.buffer_pools.alloc_mb_width);
1819 av_assert1(s->c.mb_height == s->c.buffer_pools.alloc_mb_height);
1820 av_assert1(s->c.mb_stride == s->c.buffer_pools.alloc_mb_stride);
1821 ret = ff_mpv_alloc_pic_accessories(s->c.avctx, &s->c.cur_pic,
1822 &s->c.sc, &s->c.buffer_pools, s->c.mb_height);
1823 if (ret < 0) {
1824 ff_mpv_unref_picture(&s->c.cur_pic);
1825 return ret;
1826 }
1827 s->picture_number = s->c.cur_pic.ptr->display_picture_number;
1828
1829 }
1830 return 0;
1831fail:
1833 return ret;
1834}
1835
1836static void frame_end(MPVMainEncContext *const m)
1837{
1838 MPVEncContext *const s = &m->s;
1839
1840 if (s->me.unrestricted_mv &&
1841 s->c.cur_pic.reference &&
1842 !m->intra_only) {
1843 int hshift = s->c.chroma_x_shift;
1844 int vshift = s->c.chroma_y_shift;
1845 s->mpvencdsp.draw_edges(s->c.cur_pic.data[0],
1846 s->c.cur_pic.linesize[0],
1847 s->c.h_edge_pos, s->c.v_edge_pos,
1850 s->mpvencdsp.draw_edges(s->c.cur_pic.data[1],
1851 s->c.cur_pic.linesize[1],
1852 s->c.h_edge_pos >> hshift,
1853 s->c.v_edge_pos >> vshift,
1854 EDGE_WIDTH >> hshift,
1855 EDGE_WIDTH >> vshift,
1857 s->mpvencdsp.draw_edges(s->c.cur_pic.data[2],
1858 s->c.cur_pic.linesize[2],
1859 s->c.h_edge_pos >> hshift,
1860 s->c.v_edge_pos >> vshift,
1861 EDGE_WIDTH >> hshift,
1862 EDGE_WIDTH >> vshift,
1864 }
1865
1866 m->last_pict_type = s->c.pict_type;
1867 m->last_lambda_for[s->c.pict_type] = s->c.cur_pic.ptr->f->quality;
1868 if (s->c.pict_type != AV_PICTURE_TYPE_B)
1869 m->last_non_b_pict_type = s->c.pict_type;
1870}
1871
1873{
1874 MPVEncContext *const s = &m->s;
1875 int intra, i;
1876
1877 for (intra = 0; intra < 2; intra++) {
1878 if (s->dct_count[intra] > (1 << 16)) {
1879 for (i = 0; i < 64; i++) {
1880 s->dct_error_sum[intra][i] >>= 1;
1881 }
1882 s->dct_count[intra] >>= 1;
1883 }
1884
1885 for (i = 0; i < 64; i++) {
1886 s->dct_offset[intra][i] = (m->noise_reduction *
1887 s->dct_count[intra] +
1888 s->dct_error_sum[intra][i] / 2) /
1889 (s->dct_error_sum[intra][i] + 1);
1890 }
1891 }
1892}
1893
1894static void frame_start(MPVMainEncContext *const m)
1895{
1896 MPVEncContext *const s = &m->s;
1897
1898 s->c.cur_pic.ptr->f->pict_type = s->c.pict_type;
1899
1900 if (s->c.pict_type != AV_PICTURE_TYPE_B) {
1901 ff_mpv_replace_picture(&s->c.last_pic, &s->c.next_pic);
1902 ff_mpv_replace_picture(&s->c.next_pic, &s->c.cur_pic);
1903 }
1904
1905 av_assert2(!!m->noise_reduction == !!s->dct_error_sum);
1906 if (s->dct_error_sum) {
1908 }
1909}
1910
1912 const AVFrame *pic_arg, int *got_packet)
1913{
1914 MPVMainEncContext *const m = avctx->priv_data;
1915 MPVEncContext *const s = &m->s;
1916 int stuffing_count, ret;
1917 int context_count = s->c.slice_context_count;
1918
1919 ff_mpv_unref_picture(&s->c.cur_pic);
1920
1921 m->vbv_ignore_qmax = 0;
1922
1924
1925 ret = load_input_picture(m, pic_arg);
1926 if (ret < 0)
1927 return ret;
1928
1929 ret = select_input_picture(m);
1930 if (ret < 0)
1931 return ret;
1932
1933 /* output? */
1934 if (s->new_pic->data[0]) {
1935 int growing_buffer = context_count == 1 && !s->data_partitioning;
1936 size_t pkt_size = 10000 + s->c.mb_width * s->c.mb_height *
1937 (growing_buffer ? 64 : (MAX_MB_BYTES + 100));
1938 if (CONFIG_MJPEG_ENCODER && avctx->codec_id == AV_CODEC_ID_MJPEG) {
1939 ret = ff_mjpeg_add_icc_profile_size(avctx, s->new_pic, &pkt_size);
1940 if (ret < 0)
1941 return ret;
1942 ret = ff_mjpeg_add_gain_map_size(avctx, s->mjpeg_ctx, s->new_pic, &pkt_size);
1943 if (ret < 0)
1944 return ret;
1945 }
1946 if ((ret = ff_alloc_packet(avctx, pkt, pkt_size)) < 0)
1947 return ret;
1949 if (s->mb_info) {
1950 s->mb_info_ptr = av_packet_new_side_data(pkt,
1952 s->c.mb_width*s->c.mb_height*12);
1953 if (!s->mb_info_ptr)
1954 return AVERROR(ENOMEM);
1955 s->prev_mb_info = s->last_mb_info = s->mb_info_size = 0;
1956 }
1957
1958 s->c.pict_type = s->new_pic->pict_type;
1959 frame_start(m);
1960vbv_retry:
1961 ret = encode_picture(m, pkt);
1962 if (growing_buffer) {
1963 av_assert0(s->pb.buf == avctx->internal->byte_buffer);
1964 pkt->data = s->pb.buf;
1965 pkt->size = avctx->internal->byte_buffer_size;
1966 }
1967 if (ret < 0)
1968 return -1;
1969
1970 frame_end(m);
1971
1972 if ((CONFIG_MJPEG_ENCODER || CONFIG_AMV_ENCODER) && s->c.out_format == FMT_MJPEG)
1974
1975 if (avctx->rc_buffer_size) {
1976 RateControlContext *rcc = &m->rc_context;
1977 int max_size = FFMAX(rcc->buffer_index * avctx->rc_max_available_vbv_use, rcc->buffer_index - 500);
1978 int hq = (avctx->mb_decision == FF_MB_DECISION_RD || avctx->trellis);
1979 int min_step = hq ? 1 : (1<<(FF_LAMBDA_SHIFT + 7))/139;
1980
1981 if (put_bits_count(&s->pb) > max_size &&
1982 s->lambda < m->lmax) {
1983 m->next_lambda = FFMAX(s->lambda + min_step, s->lambda *
1984 (s->c.qscale + 1) / s->c.qscale);
1985 if (s->adaptive_quant) {
1986 for (int i = 0; i < s->c.mb_height * s->c.mb_stride; i++)
1987 s->lambda_table[i] =
1988 FFMAX(s->lambda_table[i] + min_step,
1989 s->lambda_table[i] * (s->c.qscale + 1) /
1990 s->c.qscale);
1991 }
1992 s->c.mb_skipped = 0; // done in frame_start()
1993 // done in encode_picture() so we must undo it
1994 if (s->c.pict_type == AV_PICTURE_TYPE_P) {
1995 s->c.no_rounding ^= s->flipflop_rounding;
1996 }
1997 if (s->c.pict_type != AV_PICTURE_TYPE_B) {
1998 s->c.time_base = s->c.last_time_base;
1999 s->c.last_non_b_time = s->c.time - s->c.pp_time;
2000 }
2001 m->vbv_ignore_qmax = 1;
2002 av_log(avctx, AV_LOG_VERBOSE, "reencoding frame due to VBV\n");
2003 goto vbv_retry;
2004 }
2005
2006 av_assert0(avctx->rc_max_rate);
2007 }
2008
2009 if (avctx->flags & AV_CODEC_FLAG_PASS1)
2011
2012 for (int i = 0; i < MPV_MAX_PLANES; i++)
2013 avctx->error[i] += s->encoding_error[i];
2014 ff_encode_add_stats_side_data(pkt, s->c.cur_pic.ptr->f->quality,
2015 s->encoding_error,
2017 s->c.pict_type);
2018
2019 if (avctx->flags & AV_CODEC_FLAG_PASS1)
2020 assert(put_bits_count(&s->pb) == m->header_bits + s->mv_bits +
2021 s->misc_bits + s->i_tex_bits +
2022 s->p_tex_bits);
2023 flush_put_bits(&s->pb);
2024 m->frame_bits = put_bits_count(&s->pb);
2025
2026 stuffing_count = ff_vbv_update(m, m->frame_bits);
2027 m->stuffing_bits = 8*stuffing_count;
2028 if (stuffing_count) {
2029 if (put_bytes_left(&s->pb, 0) < stuffing_count + 50) {
2030 av_log(avctx, AV_LOG_ERROR, "stuffing too large\n");
2031 return -1;
2032 }
2033
2034 switch (s->c.codec_id) {
2037 while (stuffing_count--) {
2038 put_bits(&s->pb, 8, 0);
2039 }
2040 break;
2041 case AV_CODEC_ID_MPEG4:
2042 put_bits(&s->pb, 16, 0);
2043 put_bits(&s->pb, 16, 0x1C3);
2044 stuffing_count -= 4;
2045 while (stuffing_count--) {
2046 put_bits(&s->pb, 8, 0xFF);
2047 }
2048 break;
2049 default:
2050 av_log(avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
2051 m->stuffing_bits = 0;
2052 }
2053 flush_put_bits(&s->pb);
2054 m->frame_bits = put_bits_count(&s->pb);
2055 }
2056
2057 /* update MPEG-1/2 vbv_delay for CBR */
2058 if (avctx->rc_max_rate &&
2059 avctx->rc_min_rate == avctx->rc_max_rate &&
2060 s->c.out_format == FMT_MPEG1 &&
2061 90000LL * (avctx->rc_buffer_size - 1) <=
2062 avctx->rc_max_rate * 0xFFFFLL) {
2063 AVCPBProperties *props;
2064 size_t props_size;
2065
2066 int vbv_delay, min_delay;
2067 double inbits = avctx->rc_max_rate *
2068 av_q2d(avctx->time_base);
2069 int minbits = m->frame_bits - 8 *
2070 (m->vbv_delay_pos - 1);
2071 double bits = m->rc_context.buffer_index + minbits - inbits;
2072 uint8_t *const vbv_delay_ptr = s->pb.buf + m->vbv_delay_pos;
2073
2074 if (bits < 0)
2075 av_log(avctx, AV_LOG_ERROR,
2076 "Internal error, negative bits\n");
2077
2078 av_assert1(s->c.repeat_first_field == 0);
2079
2080 vbv_delay = bits * 90000 / avctx->rc_max_rate;
2081 min_delay = (minbits * 90000LL + avctx->rc_max_rate - 1) /
2082 avctx->rc_max_rate;
2083
2084 vbv_delay = FFMAX(vbv_delay, min_delay);
2085
2086 av_assert0(vbv_delay < 0xFFFF);
2087
2088 vbv_delay_ptr[0] &= 0xF8;
2089 vbv_delay_ptr[0] |= vbv_delay >> 13;
2090 vbv_delay_ptr[1] = vbv_delay >> 5;
2091 vbv_delay_ptr[2] &= 0x07;
2092 vbv_delay_ptr[2] |= vbv_delay << 3;
2093
2094 props = av_cpb_properties_alloc(&props_size);
2095 if (!props)
2096 return AVERROR(ENOMEM);
2097 props->vbv_delay = vbv_delay * 300;
2098
2100 (uint8_t*)props, props_size);
2101 if (ret < 0) {
2102 av_freep(&props);
2103 return ret;
2104 }
2105 }
2106 m->total_bits += m->frame_bits;
2107
2108 pkt->pts = s->c.cur_pic.ptr->f->pts;
2109 pkt->duration = s->c.cur_pic.ptr->f->duration;
2110 if (!s->c.low_delay && s->c.pict_type != AV_PICTURE_TYPE_B) {
2111 if (!s->c.cur_pic.ptr->coded_picture_number)
2112 pkt->dts = pkt->pts - m->dts_delta;
2113 else
2114 pkt->dts = m->reordered_pts;
2115 m->reordered_pts = pkt->pts;
2116 } else
2117 pkt->dts = pkt->pts;
2118
2119 // the no-delay case is handled in generic code
2120 if (avctx->codec->capabilities & AV_CODEC_CAP_DELAY) {
2121 ret = ff_encode_reordered_opaque(avctx, pkt, s->c.cur_pic.ptr->f);
2122 if (ret < 0)
2123 return ret;
2124 }
2125
2126 if (s->c.cur_pic.ptr->f->flags & AV_FRAME_FLAG_KEY)
2127 pkt->flags |= AV_PKT_FLAG_KEY;
2128 if (s->mb_info)
2130 } else {
2131 m->frame_bits = 0;
2132 }
2133
2134 ff_mpv_unref_picture(&s->c.cur_pic);
2135
2136 av_assert1((m->frame_bits & 7) == 0);
2137
2138 pkt->size = m->frame_bits / 8;
2139 *got_packet = !!pkt->size;
2140 return 0;
2141}
2142
2144 int n, int threshold)
2145{
2146 static const char tab[64] = {
2147 3, 2, 2, 1, 1, 1, 1, 1,
2148 1, 1, 1, 1, 1, 1, 1, 1,
2149 1, 1, 1, 1, 1, 1, 1, 1,
2150 0, 0, 0, 0, 0, 0, 0, 0,
2151 0, 0, 0, 0, 0, 0, 0, 0,
2152 0, 0, 0, 0, 0, 0, 0, 0,
2153 0, 0, 0, 0, 0, 0, 0, 0,
2154 0, 0, 0, 0, 0, 0, 0, 0
2155 };
2156 int score = 0;
2157 int run = 0;
2158 int i;
2159 int16_t *block = s->block[n];
2160 const int last_index = s->c.block_last_index[n];
2161 int skip_dc;
2162
2163 if (threshold < 0) {
2164 skip_dc = 0;
2165 threshold = -threshold;
2166 } else
2167 skip_dc = 1;
2168
2169 /* Are all we could set to zero already zero? */
2170 if (last_index <= skip_dc - 1)
2171 return;
2172
2173 for (i = 0; i <= last_index; i++) {
2174 const int j = s->c.intra_scantable.permutated[i];
2175 const int level = FFABS(block[j]);
2176 if (level == 1) {
2177 if (skip_dc && i == 0)
2178 continue;
2179 score += tab[run];
2180 run = 0;
2181 } else if (level > 1) {
2182 return;
2183 } else {
2184 run++;
2185 }
2186 }
2187 if (score >= threshold)
2188 return;
2189 for (i = skip_dc; i <= last_index; i++) {
2190 const int j = s->c.intra_scantable.permutated[i];
2191 block[j] = 0;
2192 }
2193 if (block[0])
2194 s->c.block_last_index[n] = 0;
2195 else
2196 s->c.block_last_index[n] = -1;
2197}
2198
2199static inline void clip_coeffs(const MPVEncContext *const s, int16_t block[],
2200 int last_index)
2201{
2202 int i;
2203 const int maxlevel = s->max_qcoeff;
2204 const int minlevel = s->min_qcoeff;
2205 int overflow = 0;
2206
2207 if (s->c.mb_intra) {
2208 i = 1; // skip clipping of intra dc
2209 } else
2210 i = 0;
2211
2212 for (; i <= last_index; i++) {
2213 const int j = s->c.intra_scantable.permutated[i];
2214 int level = block[j];
2215
2216 if (level > maxlevel) {
2217 level = maxlevel;
2218 overflow++;
2219 } else if (level < minlevel) {
2220 level = minlevel;
2221 overflow++;
2222 }
2223
2224 block[j] = level;
2225 }
2226
2227 if (overflow && s->c.avctx->mb_decision == FF_MB_DECISION_SIMPLE)
2228 av_log(s->c.avctx, AV_LOG_INFO,
2229 "warning, clipping %d dct coefficients to %d..%d\n",
2230 overflow, minlevel, maxlevel);
2231}
2232
2233static void get_visual_weight(int16_t *weight, const uint8_t *ptr, int stride)
2234{
2235 int x, y;
2236 // FIXME optimize
2237 for (y = 0; y < 8; y++) {
2238 for (x = 0; x < 8; x++) {
2239 int x2, y2;
2240 int sum = 0;
2241 int sqr = 0;
2242 int count = 0;
2243
2244 for (y2 = FFMAX(y - 1, 0); y2 < FFMIN(8, y + 2); y2++) {
2245 for (x2= FFMAX(x - 1, 0); x2 < FFMIN(8, x + 2); x2++) {
2246 int v = ptr[x2 + y2 * stride];
2247 sum += v;
2248 sqr += v * v;
2249 count++;
2250 }
2251 }
2252 weight[x + 8 * y]= (36 * ff_sqrt(count * sqr - sum * sum)) / count;
2253 }
2254 }
2255}
2256
2258 int motion_x, int motion_y,
2259 int mb_block_height,
2260 int mb_block_width,
2261 int mb_block_count,
2262 int chroma_x_shift,
2263 int chroma_y_shift,
2264 int chroma_format)
2265{
2266/* Interlaced DCT is only possible with MPEG-2 and MPEG-4
2267 * and neither of these encoders currently supports 444. */
2268#define INTERLACED_DCT(s) ((chroma_format == CHROMA_420 || chroma_format == CHROMA_422) && \
2269 (s)->c.avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT)
2270 DECLARE_ALIGNED(16, int16_t, weight)[12][64];
2271 int16_t orig[12][64];
2272 const int mb_x = s->c.mb_x;
2273 const int mb_y = s->c.mb_y;
2274 int i;
2275 int skip_dct[12];
2276 int dct_offset = s->c.linesize * 8; // default for progressive frames
2277 int uv_dct_offset = s->c.uvlinesize * 8;
2278 const uint8_t *ptr_y, *ptr_cb, *ptr_cr;
2279 ptrdiff_t wrap_y, wrap_c;
2280
2281 for (i = 0; i < mb_block_count; i++)
2282 skip_dct[i] = s->skipdct;
2283
2284 if (s->adaptive_quant) {
2285 const int last_qp = s->c.qscale;
2286 const int mb_xy = mb_x + mb_y * s->c.mb_stride;
2287
2288 s->lambda = s->lambda_table[mb_xy];
2289 s->lambda2 = (s->lambda * s->lambda + FF_LAMBDA_SCALE / 2) >>
2291
2292 if (!(s->mpv_flags & FF_MPV_FLAG_QP_RD)) {
2293 s->dquant = s->c.cur_pic.qscale_table[mb_xy] - last_qp;
2294
2295 if (s->c.out_format == FMT_H263) {
2296 s->dquant = av_clip(s->dquant, -2, 2);
2297
2298 if (s->c.codec_id == AV_CODEC_ID_MPEG4) {
2299 if (!s->c.mb_intra) {
2300 if (s->c.pict_type == AV_PICTURE_TYPE_B) {
2301 if (s->dquant & 1 || s->c.mv_dir & MV_DIRECT)
2302 s->dquant = 0;
2303 }
2304 if (s->c.mv_type == MV_TYPE_8X8)
2305 s->dquant = 0;
2306 }
2307 }
2308 }
2309 }
2310 ff_set_qscale(&s->c, last_qp + s->dquant);
2311 } else if (s->mpv_flags & FF_MPV_FLAG_QP_RD)
2312 ff_set_qscale(&s->c, s->c.qscale + s->dquant);
2313
2314 wrap_y = s->c.linesize;
2315 wrap_c = s->c.uvlinesize;
2316 ptr_y = s->new_pic->data[0] +
2317 (mb_y * 16 * wrap_y) + mb_x * 16;
2318 ptr_cb = s->new_pic->data[1] +
2319 (mb_y * mb_block_height * wrap_c) + mb_x * mb_block_width;
2320 ptr_cr = s->new_pic->data[2] +
2321 (mb_y * mb_block_height * wrap_c) + mb_x * mb_block_width;
2322
2323 if ((mb_x * 16 + 16 > s->c.width || mb_y * 16 + 16 > s->c.height) &&
2324 s->c.codec_id != AV_CODEC_ID_AMV) {
2325 uint8_t *ebuf = s->c.sc.edge_emu_buffer + 38 * wrap_y;
2326 int cw = (s->c.width + chroma_x_shift) >> chroma_x_shift;
2327 int ch = (s->c.height + chroma_y_shift) >> chroma_y_shift;
2328 s->c.vdsp.emulated_edge_mc(ebuf, ptr_y,
2329 wrap_y, wrap_y,
2330 16, 16, mb_x * 16, mb_y * 16,
2331 s->c.width, s->c.height);
2332 ptr_y = ebuf;
2333 s->c.vdsp.emulated_edge_mc(ebuf + 16 * wrap_y, ptr_cb,
2334 wrap_c, wrap_c,
2335 mb_block_width, mb_block_height,
2336 mb_x * mb_block_width, mb_y * mb_block_height,
2337 cw, ch);
2338 ptr_cb = ebuf + 16 * wrap_y;
2339 s->c.vdsp.emulated_edge_mc(ebuf + 16 * wrap_y + 16, ptr_cr,
2340 wrap_c, wrap_c,
2341 mb_block_width, mb_block_height,
2342 mb_x * mb_block_width, mb_y * mb_block_height,
2343 cw, ch);
2344 ptr_cr = ebuf + 16 * wrap_y + 16;
2345 }
2346
2347 if (s->c.mb_intra) {
2348 if (INTERLACED_DCT(s)) {
2349 int progressive_score, interlaced_score;
2350
2351 s->c.interlaced_dct = 0;
2352 progressive_score = s->ildct_cmp[1](s, ptr_y, NULL, wrap_y, 8) +
2353 s->ildct_cmp[1](s, ptr_y + wrap_y * 8,
2354 NULL, wrap_y, 8) - 400;
2355
2356 if (progressive_score > 0) {
2357 interlaced_score = s->ildct_cmp[1](s, ptr_y,
2358 NULL, wrap_y * 2, 8) +
2359 s->ildct_cmp[1](s, ptr_y + wrap_y,
2360 NULL, wrap_y * 2, 8);
2361 if (progressive_score > interlaced_score) {
2362 s->c.interlaced_dct = 1;
2363
2364 dct_offset = wrap_y;
2365 uv_dct_offset = wrap_c;
2366 wrap_y <<= 1;
2367 if (chroma_format == CHROMA_422 ||
2368 chroma_format == CHROMA_444)
2369 wrap_c <<= 1;
2370 }
2371 }
2372 }
2373
2374 s->pdsp.get_pixels(s->block[0], ptr_y, wrap_y);
2375 s->pdsp.get_pixels(s->block[1], ptr_y + 8, wrap_y);
2376 s->pdsp.get_pixels(s->block[2], ptr_y + dct_offset, wrap_y);
2377 s->pdsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
2378
2379 if (s->c.avctx->flags & AV_CODEC_FLAG_GRAY) {
2380 skip_dct[4] = 1;
2381 skip_dct[5] = 1;
2382 } else {
2383 s->pdsp.get_pixels(s->block[4], ptr_cb, wrap_c);
2384 s->pdsp.get_pixels(s->block[5], ptr_cr, wrap_c);
2385 if (chroma_format == CHROMA_422) {
2386 s->pdsp.get_pixels(s->block[6], ptr_cb + uv_dct_offset, wrap_c);
2387 s->pdsp.get_pixels(s->block[7], ptr_cr + uv_dct_offset, wrap_c);
2388 } else if (chroma_format == CHROMA_444) {
2389 s->pdsp.get_pixels(s->block[ 6], ptr_cb + 8, wrap_c);
2390 s->pdsp.get_pixels(s->block[ 7], ptr_cr + 8, wrap_c);
2391 s->pdsp.get_pixels(s->block[ 8], ptr_cb + uv_dct_offset, wrap_c);
2392 s->pdsp.get_pixels(s->block[ 9], ptr_cr + uv_dct_offset, wrap_c);
2393 s->pdsp.get_pixels(s->block[10], ptr_cb + uv_dct_offset + 8, wrap_c);
2394 s->pdsp.get_pixels(s->block[11], ptr_cr + uv_dct_offset + 8, wrap_c);
2395 }
2396 }
2397 } else {
2398 op_pixels_func (*op_pix)[4];
2399 qpel_mc_func (*op_qpix)[16];
2400 uint8_t *dest_y, *dest_cb, *dest_cr;
2401
2402 dest_y = s->c.dest[0];
2403 dest_cb = s->c.dest[1];
2404 dest_cr = s->c.dest[2];
2405
2406 if ((!s->c.no_rounding) || s->c.pict_type == AV_PICTURE_TYPE_B) {
2407 op_pix = s->c.hdsp.put_pixels_tab;
2408 op_qpix = s->c.qdsp.put_qpel_pixels_tab;
2409 } else {
2410 op_pix = s->c.hdsp.put_no_rnd_pixels_tab;
2411 op_qpix = s->c.qdsp.put_no_rnd_qpel_pixels_tab;
2412 }
2413
2414 if (s->c.mv_dir & MV_DIR_FORWARD) {
2415 ff_mpv_motion(&s->c, dest_y, dest_cb, dest_cr, 0,
2416 s->c.last_pic.data,
2417 op_pix, op_qpix);
2418 op_pix = s->c.hdsp.avg_pixels_tab;
2419 op_qpix = s->c.qdsp.avg_qpel_pixels_tab;
2420 }
2421 if (s->c.mv_dir & MV_DIR_BACKWARD) {
2422 ff_mpv_motion(&s->c, dest_y, dest_cb, dest_cr, 1,
2423 s->c.next_pic.data,
2424 op_pix, op_qpix);
2425 }
2426
2427 if (INTERLACED_DCT(s)) {
2428 int progressive_score, interlaced_score;
2429
2430 s->c.interlaced_dct = 0;
2431 progressive_score = s->ildct_cmp[0](s, dest_y, ptr_y, wrap_y, 8) +
2432 s->ildct_cmp[0](s, dest_y + wrap_y * 8,
2433 ptr_y + wrap_y * 8,
2434 wrap_y, 8) - 400;
2435
2436 if (s->c.avctx->ildct_cmp == FF_CMP_VSSE)
2437 progressive_score -= 400;
2438
2439 if (progressive_score > 0) {
2440 interlaced_score = s->ildct_cmp[0](s, dest_y, ptr_y,
2441 wrap_y * 2, 8) +
2442 s->ildct_cmp[0](s, dest_y + wrap_y,
2443 ptr_y + wrap_y,
2444 wrap_y * 2, 8);
2445
2446 if (progressive_score > interlaced_score) {
2447 s->c.interlaced_dct = 1;
2448
2449 dct_offset = wrap_y;
2450 uv_dct_offset = wrap_c;
2451 wrap_y <<= 1;
2452 if (chroma_format == CHROMA_422)
2453 wrap_c <<= 1;
2454 }
2455 }
2456 }
2457
2458 s->pdsp.diff_pixels(s->block[0], ptr_y, dest_y, wrap_y);
2459 s->pdsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
2460 s->pdsp.diff_pixels(s->block[2], ptr_y + dct_offset,
2461 dest_y + dct_offset, wrap_y);
2462 s->pdsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8,
2463 dest_y + dct_offset + 8, wrap_y);
2464
2465 if (s->c.avctx->flags & AV_CODEC_FLAG_GRAY) {
2466 skip_dct[4] = 1;
2467 skip_dct[5] = 1;
2468 } else {
2469 s->pdsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
2470 s->pdsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
2471 if (!chroma_y_shift) { /* 422 */
2472 s->pdsp.diff_pixels(s->block[6], ptr_cb + uv_dct_offset,
2473 dest_cb + uv_dct_offset, wrap_c);
2474 s->pdsp.diff_pixels(s->block[7], ptr_cr + uv_dct_offset,
2475 dest_cr + uv_dct_offset, wrap_c);
2476 }
2477 }
2478 /* pre quantization */
2479 if (s->mc_mb_var[s->c.mb_stride * mb_y + mb_x] < 2 * s->c.qscale * s->c.qscale) {
2480 // FIXME optimize
2481 if (s->sad_cmp[1](NULL, ptr_y, dest_y, wrap_y, 8) < 20 * s->c.qscale)
2482 skip_dct[0] = 1;
2483 if (s->sad_cmp[1](NULL, ptr_y + 8, dest_y + 8, wrap_y, 8) < 20 * s->c.qscale)
2484 skip_dct[1] = 1;
2485 if (s->sad_cmp[1](NULL, ptr_y + dct_offset, dest_y + dct_offset,
2486 wrap_y, 8) < 20 * s->c.qscale)
2487 skip_dct[2] = 1;
2488 if (s->sad_cmp[1](NULL, ptr_y + dct_offset + 8, dest_y + dct_offset + 8,
2489 wrap_y, 8) < 20 * s->c.qscale)
2490 skip_dct[3] = 1;
2491 if (s->sad_cmp[1](NULL, ptr_cb, dest_cb, wrap_c, 8) < 20 * s->c.qscale)
2492 skip_dct[4] = 1;
2493 if (s->sad_cmp[1](NULL, ptr_cr, dest_cr, wrap_c, 8) < 20 * s->c.qscale)
2494 skip_dct[5] = 1;
2495 if (!chroma_y_shift) { /* 422 */
2496 if (s->sad_cmp[1](NULL, ptr_cb + uv_dct_offset,
2497 dest_cb + uv_dct_offset,
2498 wrap_c, 8) < 20 * s->c.qscale)
2499 skip_dct[6] = 1;
2500 if (s->sad_cmp[1](NULL, ptr_cr + uv_dct_offset,
2501 dest_cr + uv_dct_offset,
2502 wrap_c, 8) < 20 * s->c.qscale)
2503 skip_dct[7] = 1;
2504 }
2505 }
2506 }
2507
2508 if (s->quantizer_noise_shaping) {
2509 if (!skip_dct[0])
2510 get_visual_weight(weight[0], ptr_y , wrap_y);
2511 if (!skip_dct[1])
2512 get_visual_weight(weight[1], ptr_y + 8, wrap_y);
2513 if (!skip_dct[2])
2514 get_visual_weight(weight[2], ptr_y + dct_offset , wrap_y);
2515 if (!skip_dct[3])
2516 get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
2517 if (!skip_dct[4])
2518 get_visual_weight(weight[4], ptr_cb , wrap_c);
2519 if (!skip_dct[5])
2520 get_visual_weight(weight[5], ptr_cr , wrap_c);
2521 if (!chroma_y_shift) { /* 422 */
2522 if (!skip_dct[6])
2523 get_visual_weight(weight[6], ptr_cb + uv_dct_offset,
2524 wrap_c);
2525 if (!skip_dct[7])
2526 get_visual_weight(weight[7], ptr_cr + uv_dct_offset,
2527 wrap_c);
2528 }
2529 memcpy(orig[0], s->block[0], sizeof(int16_t) * 64 * mb_block_count);
2530 }
2531
2532 /* DCT & quantize */
2533 av_assert2(s->c.out_format != FMT_MJPEG || s->c.qscale == 8);
2534 {
2535 for (i = 0; i < mb_block_count; i++) {
2536 if (!skip_dct[i]) {
2537 int overflow;
2538 s->c.block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->c.qscale, &overflow);
2539 // FIXME we could decide to change to quantizer instead of
2540 // clipping
2541 // JS: I don't think that would be a good idea it could lower
2542 // quality instead of improve it. Just INTRADC clipping
2543 // deserves changes in quantizer
2544 if (overflow)
2545 clip_coeffs(s, s->block[i], s->c.block_last_index[i]);
2546 } else
2547 s->c.block_last_index[i] = -1;
2548 }
2549 if (s->quantizer_noise_shaping) {
2550 for (i = 0; i < mb_block_count; i++) {
2551 if (!skip_dct[i]) {
2552 s->c.block_last_index[i] =
2553 dct_quantize_refine(s, s->block[i], weight[i],
2554 orig[i], i, s->c.qscale);
2555 }
2556 }
2557 }
2558
2559 if (s->luma_elim_threshold && !s->c.mb_intra)
2560 for (i = 0; i < 4; i++)
2561 dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
2562 if (s->chroma_elim_threshold && !s->c.mb_intra)
2563 for (i = 4; i < mb_block_count; i++)
2564 dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
2565
2566 if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {
2567 for (i = 0; i < mb_block_count; i++) {
2568 if (s->c.block_last_index[i] == -1)
2569 s->coded_score[i] = INT_MAX / 256;
2570 }
2571 }
2572 }
2573
2574 if ((s->c.avctx->flags & AV_CODEC_FLAG_GRAY) && s->c.mb_intra) {
2575 s->c.block_last_index[4] =
2576 s->c.block_last_index[5] = 0;
2577 s->block[4][0] =
2578 s->block[5][0] = (1024 + s->c.c_dc_scale / 2) / s->c.c_dc_scale;
2579 if (!chroma_y_shift) { /* 422 / 444 */
2580 for (i=6; i<12; i++) {
2581 s->c.block_last_index[i] = 0;
2582 s->block[i][0] = s->block[4][0];
2583 }
2584 }
2585 }
2586
2587 // non c quantize code returns incorrect block_last_index FIXME
2588 if (s->c.alternate_scan && s->dct_quantize != dct_quantize_c) {
2589 for (i = 0; i < mb_block_count; i++) {
2590 int j;
2591 if (s->c.block_last_index[i] > 0) {
2592 for (j = 63; j > 0; j--) {
2593 if (s->block[i][s->c.intra_scantable.permutated[j]])
2594 break;
2595 }
2596 s->c.block_last_index[i] = j;
2597 }
2598 }
2599 }
2600
2601 s->encode_mb(s, s->block, motion_x, motion_y);
2602}
2603
2604static void encode_mb(MPVEncContext *const s, int motion_x, int motion_y)
2605{
2606 if (s->c.chroma_format == CHROMA_420)
2607 encode_mb_internal(s, motion_x, motion_y, 8, 8, 6, 1, 1, CHROMA_420);
2608 else if (s->c.chroma_format == CHROMA_422)
2609 encode_mb_internal(s, motion_x, motion_y, 16, 8, 8, 1, 0, CHROMA_422);
2610 else
2611 encode_mb_internal(s, motion_x, motion_y, 16, 16, 12, 0, 0, CHROMA_444);
2612}
2613
2632
2633#define COPY_CONTEXT(BEFORE, AFTER, DST_TYPE, SRC_TYPE) \
2634static inline void BEFORE ##_context_before_encode(DST_TYPE *const d, \
2635 const SRC_TYPE *const s) \
2636{ \
2637 /* FIXME is memcpy faster than a loop? */ \
2638 memcpy(d->c.last_mv, s->c.last_mv, 2*2*2*sizeof(int)); \
2639 \
2640 /* MPEG-1 */ \
2641 d->mb_skip_run = s->mb_skip_run; \
2642 for (int i = 0; i < 3; i++) \
2643 d->last_dc[i] = s->last_dc[i]; \
2644 \
2645 /* statistics */ \
2646 d->mv_bits = s->mv_bits; \
2647 d->i_tex_bits = s->i_tex_bits; \
2648 d->p_tex_bits = s->p_tex_bits; \
2649 d->i_count = s->i_count; \
2650 d->misc_bits = s->misc_bits; \
2651 d->last_bits = 0; \
2652 \
2653 d->c.mb_skipped = 0; \
2654 d->c.qscale = s->c.qscale; \
2655 d->dquant = s->dquant; \
2656 \
2657 d->esc3_level_length = s->esc3_level_length; \
2658} \
2659 \
2660static inline void AFTER ## _context_after_encode(DST_TYPE *const d, \
2661 const SRC_TYPE *const s, \
2662 int data_partitioning) \
2663{ \
2664 /* FIXME is memcpy faster than a loop? */ \
2665 memcpy(d->c.mv, s->c.mv, 2*4*2*sizeof(int)); \
2666 memcpy(d->c.last_mv, s->c.last_mv, 2*2*2*sizeof(int)); \
2667 \
2668 /* MPEG-1 */ \
2669 d->mb_skip_run = s->mb_skip_run; \
2670 for (int i = 0; i < 3; i++) \
2671 d->last_dc[i] = s->last_dc[i]; \
2672 \
2673 /* statistics */ \
2674 d->mv_bits = s->mv_bits; \
2675 d->i_tex_bits = s->i_tex_bits; \
2676 d->p_tex_bits = s->p_tex_bits; \
2677 d->i_count = s->i_count; \
2678 d->misc_bits = s->misc_bits; \
2679 \
2680 d->c.mb_intra = s->c.mb_intra; \
2681 d->c.mb_skipped = s->c.mb_skipped; \
2682 d->c.mv_type = s->c.mv_type; \
2683 d->c.mv_dir = s->c.mv_dir; \
2684 d->pb = s->pb; \
2685 if (data_partitioning) { \
2686 d->pb2 = s->pb2; \
2687 d->tex_pb = s->tex_pb; \
2688 } \
2689 d->block = s->block; \
2690 for (int i = 0; i < 8; i++) \
2691 d->c.block_last_index[i] = s->c.block_last_index[i]; \
2692 d->c.interlaced_dct = s->c.interlaced_dct; \
2693 d->c.qscale = s->c.qscale; \
2694 \
2695 d->esc3_level_length = s->esc3_level_length; \
2696}
2697
2698COPY_CONTEXT(backup, save, MBBackup, MPVEncContext)
2699COPY_CONTEXT(reset, store, MPVEncContext, MBBackup)
2700
2701static void encode_mb_hq(MPVEncContext *const s, MBBackup *const backup, MBBackup *const best,
2702 PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
2703 int *dmin, int *next_block, int motion_x, int motion_y)
2704{
2705 int score;
2706 uint8_t *dest_backup[3];
2707
2708 reset_context_before_encode(s, backup);
2709
2710 s->block = s->blocks[*next_block];
2711 s->pb = pb[*next_block];
2712 if (s->data_partitioning) {
2713 s->pb2 = pb2 [*next_block];
2714 s->tex_pb= tex_pb[*next_block];
2715 }
2716
2717 if(*next_block){
2718 memcpy(dest_backup, s->c.dest, sizeof(s->c.dest));
2719 s->c.dest[0] = s->c.sc.rd_scratchpad;
2720 s->c.dest[1] = s->c.sc.rd_scratchpad + 16*s->c.linesize;
2721 s->c.dest[2] = s->c.sc.rd_scratchpad + 16*s->c.linesize + 8;
2722 av_assert0(s->c.linesize >= 32); //FIXME
2723 }
2724
2725 encode_mb(s, motion_x, motion_y);
2726
2727 score= put_bits_count(&s->pb);
2728 if (s->data_partitioning) {
2729 score+= put_bits_count(&s->pb2);
2730 score+= put_bits_count(&s->tex_pb);
2731 }
2732
2733 if (s->c.avctx->mb_decision == FF_MB_DECISION_RD) {
2734 mpv_reconstruct_mb(s, s->block);
2735
2736 score *= s->lambda2;
2737 score += sse_mb(s) << FF_LAMBDA_SHIFT;
2738 }
2739
2740 if(*next_block){
2741 memcpy(s->c.dest, dest_backup, sizeof(s->c.dest));
2742 }
2743
2744 if(score<*dmin){
2745 *dmin= score;
2746 *next_block^=1;
2747
2748 save_context_after_encode(best, s, s->data_partitioning);
2749 }
2750}
2751
2752static int sse(const MPVEncContext *const s, const uint8_t *src1, const uint8_t *src2, int w, int h, int stride)
2753{
2754 const uint32_t *sq = ff_square_tab + 256;
2755 int acc=0;
2756 int x,y;
2757
2758 if(w==16 && h==16)
2759 return s->sse_cmp[0](NULL, src1, src2, stride, 16);
2760 else if(w==8 && h==8)
2761 return s->sse_cmp[1](NULL, src1, src2, stride, 8);
2762
2763 for(y=0; y<h; y++){
2764 for(x=0; x<w; x++){
2765 acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
2766 }
2767 }
2768
2769 av_assert2(acc>=0);
2770
2771 return acc;
2772}
2773
2774static int sse_mb(MPVEncContext *const s)
2775{
2776 int w= 16;
2777 int h= 16;
2778 int chroma_mb_w = w >> s->c.chroma_x_shift;
2779 int chroma_mb_h = h >> s->c.chroma_y_shift;
2780
2781 if (s->c.mb_x*16 + 16 > s->c.width ) w = s->c.width - s->c.mb_x*16;
2782 if (s->c.mb_y*16 + 16 > s->c.height) h = s->c.height- s->c.mb_y*16;
2783
2784 if(w==16 && h==16)
2785 return s->n_sse_cmp[0](s, s->new_pic->data[0] + s->c.mb_x * 16 + s->c.mb_y * s->c.linesize * 16,
2786 s->c.dest[0], s->c.linesize, 16) +
2787 s->n_sse_cmp[1](s, s->new_pic->data[1] + s->c.mb_x * chroma_mb_w + s->c.mb_y * s->c.uvlinesize * chroma_mb_h,
2788 s->c.dest[1], s->c.uvlinesize, chroma_mb_h) +
2789 s->n_sse_cmp[1](s, s->new_pic->data[2] + s->c.mb_x * chroma_mb_w + s->c.mb_y * s->c.uvlinesize * chroma_mb_h,
2790 s->c.dest[2], s->c.uvlinesize, chroma_mb_h);
2791 else
2792 return sse(s, s->new_pic->data[0] + s->c.mb_x * 16 + s->c.mb_y * s->c.linesize * 16,
2793 s->c.dest[0], w, h, s->c.linesize) +
2794 sse(s, s->new_pic->data[1] + s->c.mb_x * chroma_mb_w + s->c.mb_y * s->c.uvlinesize * chroma_mb_h,
2795 s->c.dest[1], w >> s->c.chroma_x_shift, h >> s->c.chroma_y_shift, s->c.uvlinesize) +
2796 sse(s, s->new_pic->data[2] + s->c.mb_x * chroma_mb_w + s->c.mb_y * s->c.uvlinesize * chroma_mb_h,
2797 s->c.dest[2], w >> s->c.chroma_x_shift, h >> s->c.chroma_y_shift, s->c.uvlinesize);
2798}
2799
2801 MPVEncContext *const s = *(void**)arg;
2802
2803
2804 s->me.pre_pass = 1;
2805 s->me.dia_size = s->c.avctx->pre_dia_size;
2806 s->c.first_slice_line = 1;
2807 for (s->c.mb_y = s->c.end_mb_y - 1; s->c.mb_y >= s->c.start_mb_y; s->c.mb_y--) {
2808 for (s->c.mb_x = s->c.mb_width - 1; s->c.mb_x >=0 ; s->c.mb_x--)
2809 ff_pre_estimate_p_frame_motion(s, s->c.mb_x, s->c.mb_y);
2810 s->c.first_slice_line = 0;
2811 }
2812
2813 s->me.pre_pass = 0;
2814
2815 return 0;
2816}
2817
2819 MPVEncContext *const s = *(void**)arg;
2820
2821 s->me.dia_size = s->c.avctx->dia_size;
2822 s->c.first_slice_line = 1;
2823 for (s->c.mb_y = s->c.start_mb_y; s->c.mb_y < s->c.end_mb_y; s->c.mb_y++) {
2824 s->c.mb_x = 0; //for block init below
2826 for (s->c.mb_x = 0; s->c.mb_x < s->c.mb_width; s->c.mb_x++) {
2827 s->c.block_index[0] += 2;
2828 s->c.block_index[1] += 2;
2829 s->c.block_index[2] += 2;
2830 s->c.block_index[3] += 2;
2831
2832 /* compute motion vector & mb_type and store in context */
2833 if (s->c.pict_type == AV_PICTURE_TYPE_B)
2834 ff_estimate_b_frame_motion(s, s->c.mb_x, s->c.mb_y);
2835 else
2836 ff_estimate_p_frame_motion(s, s->c.mb_x, s->c.mb_y);
2837 }
2838 s->c.first_slice_line = 0;
2839 }
2840 return 0;
2841}
2842
2843static int mb_var_thread(AVCodecContext *c, void *arg){
2844 MPVEncContext *const s = *(void**)arg;
2845
2846 for (int mb_y = s->c.start_mb_y; mb_y < s->c.end_mb_y; mb_y++) {
2847 for (int mb_x = 0; mb_x < s->c.mb_width; mb_x++) {
2848 int xx = mb_x * 16;
2849 int yy = mb_y * 16;
2850 const uint8_t *pix = s->new_pic->data[0] + (yy * s->c.linesize) + xx;
2851 int varc;
2852 int sum = s->mpvencdsp.pix_sum(pix, s->c.linesize);
2853
2854 varc = (s->mpvencdsp.pix_norm1(pix, s->c.linesize) -
2855 (((unsigned) sum * sum) >> 8) + 500 + 128) >> 8;
2856
2857 s->mb_var [s->c.mb_stride * mb_y + mb_x] = varc;
2858 s->mb_mean[s->c.mb_stride * mb_y + mb_x] = (sum+128)>>8;
2859 s->me.mb_var_sum_temp += varc;
2860 }
2861 }
2862 return 0;
2863}
2864
2866{
2867 if (CONFIG_MPEG4_ENCODER && s->c.codec_id == AV_CODEC_ID_MPEG4) {
2868 if (s->partitioned_frame)
2870
2871 ff_mpeg4_stuffing(&s->pb);
2872 } else if ((CONFIG_MJPEG_ENCODER || CONFIG_AMV_ENCODER) &&
2873 s->c.out_format == FMT_MJPEG) {
2875 } else if (CONFIG_SPEEDHQ_ENCODER && s->c.out_format == FMT_SPEEDHQ) {
2877 }
2878
2879 flush_put_bits(&s->pb);
2880
2881 if ((s->c.avctx->flags & AV_CODEC_FLAG_PASS1) && !s->partitioned_frame)
2882 s->misc_bits+= get_bits_diff(s);
2883}
2884
2885static void write_mb_info(MPVEncContext *const s)
2886{
2887 uint8_t *ptr = s->mb_info_ptr + s->mb_info_size - 12;
2888 int offset = put_bits_count(&s->pb);
2889 int mba = s->c.mb_x + s->c.mb_width * (s->c.mb_y % s->gob_index);
2890 int gobn = s->c.mb_y / s->gob_index;
2891 int pred_x, pred_y;
2892 if (CONFIG_H263_ENCODER)
2893 ff_h263_pred_motion(&s->c, 0, 0, &pred_x, &pred_y);
2894 bytestream_put_le32(&ptr, offset);
2895 bytestream_put_byte(&ptr, s->c.qscale);
2896 bytestream_put_byte(&ptr, gobn);
2897 bytestream_put_le16(&ptr, mba);
2898 bytestream_put_byte(&ptr, pred_x); /* hmv1 */
2899 bytestream_put_byte(&ptr, pred_y); /* vmv1 */
2900 /* 4MV not implemented */
2901 bytestream_put_byte(&ptr, 0); /* hmv2 */
2902 bytestream_put_byte(&ptr, 0); /* vmv2 */
2903}
2904
2905static void update_mb_info(MPVEncContext *const s)
2906{
2907 if (!s->mb_info)
2908 return;
2909 if (put_bytes_count(&s->pb, 0) - s->prev_mb_info >= s->mb_info) {
2910 s->mb_info_size += 12;
2911 s->prev_mb_info = s->last_mb_info;
2912 }
2913
2914 s->last_mb_info = put_bytes_count(&s->pb, 0);
2915 if (!s->mb_info_size)
2916 s->mb_info_size += 12;
2918}
2919
2920int ff_mpv_reallocate_putbitbuffer(MPVEncContext *const s, size_t threshold, size_t size_increase)
2921{
2922 if (put_bytes_left(&s->pb, 0) < threshold
2923 && s->c.slice_context_count == 1
2924 && s->pb.buf == s->c.avctx->internal->byte_buffer) {
2925 int lastgob_pos = s->ptr_lastgob - s->pb.buf;
2926
2927 uint8_t *new_buffer = NULL;
2928 int new_buffer_size = 0;
2929
2930 if ((s->c.avctx->internal->byte_buffer_size + size_increase) >= INT_MAX/8) {
2931 av_log(s->c.avctx, AV_LOG_ERROR, "Cannot reallocate putbit buffer\n");
2932 return AVERROR(ENOMEM);
2933 }
2934
2935 emms_c();
2936
2937 av_fast_padded_malloc(&new_buffer, &new_buffer_size,
2938 s->c.avctx->internal->byte_buffer_size + size_increase);
2939 if (!new_buffer)
2940 return AVERROR(ENOMEM);
2941
2942 memcpy(new_buffer, s->c.avctx->internal->byte_buffer, s->c.avctx->internal->byte_buffer_size);
2943 av_free(s->c.avctx->internal->byte_buffer);
2944 s->c.avctx->internal->byte_buffer = new_buffer;
2945 s->c.avctx->internal->byte_buffer_size = new_buffer_size;
2946 rebase_put_bits(&s->pb, new_buffer, new_buffer_size);
2947 s->ptr_lastgob = s->pb.buf + lastgob_pos;
2948 }
2949 if (put_bytes_left(&s->pb, 0) < threshold)
2950 return AVERROR(EINVAL);
2951 return 0;
2952}
2953
2954static int encode_thread(AVCodecContext *c, void *arg){
2955 MPVEncContext *const s = *(void**)arg;
2956 int chr_h = 16 >> s->c.chroma_y_shift;
2957 int i;
2958 MBBackup best_s = { 0 }, backup_s;
2959 uint8_t bit_buf[2][MAX_MB_BYTES];
2960 // + 2 because ff_copy_bits() overreads
2961 uint8_t bit_buf2[2][MAX_PB2_MB_SIZE + 2];
2962 uint8_t bit_buf_tex[2][MAX_AC_TEX_MB_SIZE + 2];
2963 PutBitContext pb[2], pb2[2], tex_pb[2];
2964
2965 for(i=0; i<2; i++){
2966 init_put_bits(&pb [i], bit_buf [i], MAX_MB_BYTES);
2967 init_put_bits(&pb2 [i], bit_buf2 [i], MAX_PB2_MB_SIZE);
2968 init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_AC_TEX_MB_SIZE);
2969 }
2970
2971 s->last_bits= put_bits_count(&s->pb);
2972 s->mv_bits=0;
2973 s->misc_bits=0;
2974 s->i_tex_bits=0;
2975 s->p_tex_bits=0;
2976 s->i_count=0;
2977
2978 for(i=0; i<3; i++){
2979 /* init last dc values */
2980 /* note: quant matrix value (8) is implied here */
2981 s->last_dc[i] = 128 << s->c.intra_dc_precision;
2982
2983 s->encoding_error[i] = 0;
2984 }
2985 if (s->c.codec_id == AV_CODEC_ID_AMV) {
2986 s->last_dc[0] = 128 * 8 / 13;
2987 s->last_dc[1] = 128 * 8 / 14;
2988 s->last_dc[2] = 128 * 8 / 14;
2989#if CONFIG_MPEG4_ENCODER
2990 } else if (s->partitioned_frame) {
2991 av_assert1(s->c.codec_id == AV_CODEC_ID_MPEG4);
2993#endif
2994 }
2995 s->mb_skip_run = 0;
2996 memset(s->c.last_mv, 0, sizeof(s->c.last_mv));
2997
2998 s->last_mv_dir = 0;
2999
3000 s->c.resync_mb_x = 0;
3001 s->c.resync_mb_y = 0;
3002 s->c.first_slice_line = 1;
3003 s->ptr_lastgob = s->pb.buf;
3004 for (int mb_y_order = s->c.start_mb_y; mb_y_order < s->c.end_mb_y; mb_y_order++) {
3005 int mb_y;
3006 if (CONFIG_SPEEDHQ_ENCODER && s->c.codec_id == AV_CODEC_ID_SPEEDHQ) {
3007 int first_in_slice;
3008 mb_y = ff_speedhq_mb_y_order_to_mb(mb_y_order, s->c.mb_height, &first_in_slice);
3009 if (first_in_slice && mb_y_order != s->c.start_mb_y)
3011 s->last_dc[0] = s->last_dc[1] = s->last_dc[2] = 1024;
3012 } else {
3013 mb_y = mb_y_order;
3014 }
3015 s->c.mb_x = 0;
3016 s->c.mb_y = mb_y;
3017
3018 ff_set_qscale(&s->c, s->c.qscale);
3020
3021 for (int mb_x = 0; mb_x < s->c.mb_width; mb_x++) {
3022 int mb_type, xy;
3023// int d;
3024 int dmin= INT_MAX;
3025 int dir;
3026 int size_increase = s->c.avctx->internal->byte_buffer_size/4
3027 + s->c.mb_width*MAX_MB_BYTES;
3028
3030 if (put_bytes_left(&s->pb, 0) < MAX_MB_BYTES){
3031 av_log(s->c.avctx, AV_LOG_ERROR, "encoded frame too large\n");
3032 return -1;
3033 }
3034 if (s->data_partitioning) {
3035 if (put_bytes_left(&s->pb2, 0) < MAX_MB_BYTES ||
3036 put_bytes_left(&s->tex_pb, 0) < MAX_MB_BYTES) {
3037 av_log(s->c.avctx, AV_LOG_ERROR, "encoded partitioned frame too large\n");
3038 return -1;
3039 }
3040 }
3041
3042 s->c.mb_x = mb_x;
3043 s->c.mb_y = mb_y; // moved into loop, can get changed by H.261
3044 ff_update_block_index(&s->c, 8, 0, s->c.chroma_x_shift);
3045
3046 if (CONFIG_H261_ENCODER && s->c.codec_id == AV_CODEC_ID_H261)
3048 xy = s->c.mb_y * s->c.mb_stride + s->c.mb_x;
3049 mb_type = s->mb_type[xy];
3050
3051 /* write gob / video packet header */
3052 if(s->rtp_mode){
3053 int current_packet_size, is_gob_start;
3054
3055 current_packet_size = put_bytes_count(&s->pb, 1)
3056 - (s->ptr_lastgob - s->pb.buf);
3057
3058 is_gob_start = s->rtp_payload_size &&
3059 current_packet_size >= s->rtp_payload_size &&
3060 mb_y + mb_x > 0;
3061
3062 if (s->c.start_mb_y == mb_y && mb_y > 0 && mb_x == 0) is_gob_start = 1;
3063
3064 switch (s->c.codec_id) {
3065 case AV_CODEC_ID_H263:
3066 case AV_CODEC_ID_H263P:
3067 if (!s->h263_slice_structured)
3068 if (s->c.mb_x || s->c.mb_y % s->gob_index) is_gob_start = 0;
3069 break;
3071 if (s->c.mb_x == 0 && s->c.mb_y != 0) is_gob_start = 1;
3074 if (s->c.codec_id == AV_CODEC_ID_MPEG1VIDEO && s->c.mb_y >= 175 ||
3075 s->mb_skip_run)
3076 is_gob_start=0;
3077 break;
3078 case AV_CODEC_ID_MJPEG:
3079 if (s->c.mb_x == 0 && s->c.mb_y != 0) is_gob_start = 1;
3080 break;
3081 }
3082
3083 if(is_gob_start){
3084 if (s->c.start_mb_y != mb_y || mb_x != 0) {
3086
3087 if (CONFIG_MPEG4_ENCODER && s->c.codec_id == AV_CODEC_ID_MPEG4 && s->partitioned_frame)
3089 }
3090
3091 av_assert2((put_bits_count(&s->pb)&7) == 0);
3092 current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
3093
3094 if (s->error_rate && s->c.resync_mb_x + s->c.resync_mb_y > 0) {
3095 int r = put_bytes_count(&s->pb, 0) + s->picture_number + 16 + s->c.mb_x + s->c.mb_y;
3096 int d = 100 / s->error_rate;
3097 if(r % d == 0){
3098 current_packet_size=0;
3099 s->pb.buf_ptr= s->ptr_lastgob;
3100 av_assert1(put_bits_ptr(&s->pb) == s->ptr_lastgob);
3101 }
3102 }
3103
3104 switch (s->c.codec_id) {
3105 case AV_CODEC_ID_MPEG4:
3106 if (CONFIG_MPEG4_ENCODER) {
3110 }
3111 break;
3114 if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
3117 }
3118 break;
3119#if CONFIG_H263P_ENCODER
3120 case AV_CODEC_ID_H263P:
3121 if (s->c.dc_val)
3124#endif
3125 case AV_CODEC_ID_H263:
3126 if (CONFIG_H263_ENCODER) {
3127 if (s->mb_info && put_bytes_count(&s->pb, 0) - s->prev_mb_info >= s->mb_info)
3128 s->mb_info_size += 12;
3129
3131 s->prev_mb_info = put_bits_count(&s->pb)/8;
3132 }
3133 break;
3134 }
3135
3136 if (s->c.avctx->flags & AV_CODEC_FLAG_PASS1) {
3137 int bits= put_bits_count(&s->pb);
3138 s->misc_bits+= bits - s->last_bits;
3139 s->last_bits= bits;
3140 }
3141
3142 s->ptr_lastgob += current_packet_size;
3143 s->c.first_slice_line = 1;
3144 s->c.resync_mb_x = mb_x;
3145 s->c.resync_mb_y = mb_y;
3146 }
3147 }
3148
3149 if (s->c.resync_mb_x == s->c.mb_x &&
3150 s->c.resync_mb_y+1 == s->c.mb_y)
3151 s->c.first_slice_line = 0;
3152
3153 s->c.mb_skipped = 0;
3154 s->dquant=0; //only for QP_RD
3155
3157
3158 if (mb_type & (mb_type-1) || (s->mpv_flags & FF_MPV_FLAG_QP_RD)) { // more than 1 MB type possible or FF_MPV_FLAG_QP_RD
3159 int next_block=0;
3160 int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
3161
3162 backup_context_before_encode(&backup_s, s);
3163 backup_s.pb= s->pb;
3164 if (s->data_partitioning) {
3165 backup_s.pb2= s->pb2;
3166 backup_s.tex_pb= s->tex_pb;
3167 }
3168
3169 if(mb_type&CANDIDATE_MB_TYPE_INTER){
3170 s->c.mv_dir = MV_DIR_FORWARD;
3171 s->c.mv_type = MV_TYPE_16X16;
3172 s->c.mb_intra = 0;
3173 s->c.mv[0][0][0] = s->p_mv_table[xy][0];
3174 s->c.mv[0][0][1] = s->p_mv_table[xy][1];
3175 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3176 &dmin, &next_block, s->c.mv[0][0][0], s->c.mv[0][0][1]);
3177 }
3178 if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
3179 s->c.mv_dir = MV_DIR_FORWARD;
3180 s->c.mv_type = MV_TYPE_FIELD;
3181 s->c.mb_intra = 0;
3182 for(i=0; i<2; i++){
3183 int j = s->c.field_select[0][i] = s->p_field_select_table[i][xy];
3184 s->c.mv[0][i][0] = s->c.p_field_mv_table[i][j][xy][0];
3185 s->c.mv[0][i][1] = s->c.p_field_mv_table[i][j][xy][1];
3186 }
3187 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3188 &dmin, &next_block, 0, 0);
3189 }
3190 if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
3191 s->c.mv_dir = MV_DIR_FORWARD;
3192 s->c.mv_type = MV_TYPE_16X16;
3193 s->c.mb_intra = 0;
3194 s->c.mv[0][0][0] = 0;
3195 s->c.mv[0][0][1] = 0;
3196 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3197 &dmin, &next_block, s->c.mv[0][0][0], s->c.mv[0][0][1]);
3198 }
3199 if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
3200 s->c.mv_dir = MV_DIR_FORWARD;
3201 s->c.mv_type = MV_TYPE_8X8;
3202 s->c.mb_intra = 0;
3203 for(i=0; i<4; i++){
3204 s->c.mv[0][i][0] = s->c.cur_pic.motion_val[0][s->c.block_index[i]][0];
3205 s->c.mv[0][i][1] = s->c.cur_pic.motion_val[0][s->c.block_index[i]][1];
3206 }
3207 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3208 &dmin, &next_block, 0, 0);
3209 }
3210 if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
3211 s->c.mv_dir = MV_DIR_FORWARD;
3212 s->c.mv_type = MV_TYPE_16X16;
3213 s->c.mb_intra = 0;
3214 s->c.mv[0][0][0] = s->b_forw_mv_table[xy][0];
3215 s->c.mv[0][0][1] = s->b_forw_mv_table[xy][1];
3216 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3217 &dmin, &next_block, s->c.mv[0][0][0], s->c.mv[0][0][1]);
3218 }
3219 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
3220 s->c.mv_dir = MV_DIR_BACKWARD;
3221 s->c.mv_type = MV_TYPE_16X16;
3222 s->c.mb_intra = 0;
3223 s->c.mv[1][0][0] = s->b_back_mv_table[xy][0];
3224 s->c.mv[1][0][1] = s->b_back_mv_table[xy][1];
3225 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3226 &dmin, &next_block, s->c.mv[1][0][0], s->c.mv[1][0][1]);
3227 }
3228 if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
3229 s->c.mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
3230 s->c.mv_type = MV_TYPE_16X16;
3231 s->c.mb_intra = 0;
3232 s->c.mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
3233 s->c.mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
3234 s->c.mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
3235 s->c.mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
3236 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3237 &dmin, &next_block, 0, 0);
3238 }
3239 if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
3240 s->c.mv_dir = MV_DIR_FORWARD;
3241 s->c.mv_type = MV_TYPE_FIELD;
3242 s->c.mb_intra = 0;
3243 for(i=0; i<2; i++){
3244 int j = s->c.field_select[0][i] = s->b_field_select_table[0][i][xy];
3245 s->c.mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
3246 s->c.mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
3247 }
3248 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3249 &dmin, &next_block, 0, 0);
3250 }
3251 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
3252 s->c.mv_dir = MV_DIR_BACKWARD;
3253 s->c.mv_type = MV_TYPE_FIELD;
3254 s->c.mb_intra = 0;
3255 for(i=0; i<2; i++){
3256 int j = s->c.field_select[1][i] = s->b_field_select_table[1][i][xy];
3257 s->c.mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
3258 s->c.mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
3259 }
3260 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3261 &dmin, &next_block, 0, 0);
3262 }
3263 if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
3264 s->c.mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
3265 s->c.mv_type = MV_TYPE_FIELD;
3266 s->c.mb_intra = 0;
3267 for(dir=0; dir<2; dir++){
3268 for(i=0; i<2; i++){
3269 int j = s->c.field_select[dir][i] = s->b_field_select_table[dir][i][xy];
3270 s->c.mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
3271 s->c.mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
3272 }
3273 }
3274 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3275 &dmin, &next_block, 0, 0);
3276 }
3277 if(mb_type&CANDIDATE_MB_TYPE_INTRA){
3278 s->c.mv_dir = 0;
3279 s->c.mv_type = MV_TYPE_16X16;
3280 s->c.mb_intra = 1;
3281 s->c.mv[0][0][0] = 0;
3282 s->c.mv[0][0][1] = 0;
3283 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3284 &dmin, &next_block, 0, 0);
3285 s->c.mbintra_table[xy] = 1;
3286 }
3287
3288 if ((s->mpv_flags & FF_MPV_FLAG_QP_RD) && dmin < INT_MAX) {
3289 if (best_s.c.mv_type == MV_TYPE_16X16) { //FIXME move 4mv after QPRD
3290 const int last_qp = backup_s.c.qscale;
3291 int qpi, qp, dc[6];
3292 int16_t ac[6][16];
3293 const int mvdir = (best_s.c.mv_dir & MV_DIR_BACKWARD) ? 1 : 0;
3294 static const int dquant_tab[4]={-1,1,-2,2};
3295 int storecoefs = s->c.mb_intra && s->c.dc_val;
3296
3297 av_assert2(backup_s.dquant == 0);
3298
3299 //FIXME intra
3300 s->c.mv_dir = best_s.c.mv_dir;
3301 s->c.mv_type = MV_TYPE_16X16;
3302 s->c.mb_intra = best_s.c.mb_intra;
3303 s->c.mv[0][0][0] = best_s.c.mv[0][0][0];
3304 s->c.mv[0][0][1] = best_s.c.mv[0][0][1];
3305 s->c.mv[1][0][0] = best_s.c.mv[1][0][0];
3306 s->c.mv[1][0][1] = best_s.c.mv[1][0][1];
3307
3308 qpi = s->c.pict_type == AV_PICTURE_TYPE_B ? 2 : 0;
3309 for(; qpi<4; qpi++){
3310 int dquant= dquant_tab[qpi];
3311 qp= last_qp + dquant;
3312 if (qp < s->c.avctx->qmin || qp > s->c.avctx->qmax)
3313 continue;
3314 backup_s.dquant= dquant;
3315 if(storecoefs){
3316 for(i=0; i<6; i++){
3317 dc[i] = s->c.dc_val[s->c.block_index[i]];
3318 memcpy(ac[i], s->c.ac_val[s->c.block_index[i]], sizeof(*s->c.ac_val));
3319 }
3320 }
3321
3322 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3323 &dmin, &next_block, s->c.mv[mvdir][0][0], s->c.mv[mvdir][0][1]);
3324 if (best_s.c.qscale != qp) {
3325 if(storecoefs){
3326 for(i=0; i<6; i++){
3327 s->c.dc_val[s->c.block_index[i]] = dc[i];
3328 memcpy(s->c.ac_val[s->c.block_index[i]], ac[i], sizeof(*s->c.ac_val));
3329 }
3330 }
3331 }
3332 }
3333 }
3334 }
3335 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
3336 int mx= s->b_direct_mv_table[xy][0];
3337 int my= s->b_direct_mv_table[xy][1];
3338
3339 backup_s.dquant = 0;
3340 s->c.mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3341 s->c.mb_intra = 0;
3343 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3344 &dmin, &next_block, mx, my);
3345 }
3346 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
3347 backup_s.dquant = 0;
3348 s->c.mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
3349 s->c.mb_intra = 0;
3350 ff_mpeg4_set_direct_mv(&s->c, 0, 0);
3351 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3352 &dmin, &next_block, 0, 0);
3353 }
3354 if (!best_s.c.mb_intra && s->mpv_flags & FF_MPV_FLAG_SKIP_RD) {
3355 int coded=0;
3356 for(i=0; i<6; i++)
3357 coded |= s->c.block_last_index[i];
3358 if(coded){
3359 int mx,my;
3360 memcpy(s->c.mv, best_s.c.mv, sizeof(s->c.mv));
3361 if (CONFIG_MPEG4_ENCODER && best_s.c.mv_dir & MV_DIRECT) {
3362 mx=my=0; //FIXME find the one we actually used
3364 } else if (best_s.c.mv_dir & MV_DIR_BACKWARD) {
3365 mx = s->c.mv[1][0][0];
3366 my = s->c.mv[1][0][1];
3367 }else{
3368 mx = s->c.mv[0][0][0];
3369 my = s->c.mv[0][0][1];
3370 }
3371
3372 s->c.mv_dir = best_s.c.mv_dir;
3373 s->c.mv_type = best_s.c.mv_type;
3374 s->c.mb_intra = 0;
3375/* s->c.mv[0][0][0] = best_s.mv[0][0][0];
3376 s->c.mv[0][0][1] = best_s.mv[0][0][1];
3377 s->c.mv[1][0][0] = best_s.mv[1][0][0];
3378 s->c.mv[1][0][1] = best_s.mv[1][0][1];*/
3379 backup_s.dquant= 0;
3380 s->skipdct=1;
3381 encode_mb_hq(s, &backup_s, &best_s, pb, pb2, tex_pb,
3382 &dmin, &next_block, mx, my);
3383 s->skipdct=0;
3384 }
3385 }
3386
3387 store_context_after_encode(s, &best_s, s->data_partitioning);
3388
3389 pb_bits_count= put_bits_count(&s->pb);
3390 flush_put_bits(&s->pb);
3391 ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
3392 s->pb= backup_s.pb;
3393
3394 if (s->data_partitioning) {
3395 pb2_bits_count= put_bits_count(&s->pb2);
3396 flush_put_bits(&s->pb2);
3397 ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
3398 s->pb2= backup_s.pb2;
3399
3400 tex_pb_bits_count= put_bits_count(&s->tex_pb);
3401 flush_put_bits(&s->tex_pb);
3402 ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
3403 s->tex_pb= backup_s.tex_pb;
3404 }
3405 s->last_bits= put_bits_count(&s->pb);
3406
3407 if (CONFIG_H263_ENCODER &&
3408 s->c.out_format == FMT_H263 && s->c.pict_type != AV_PICTURE_TYPE_B)
3410
3411 if(next_block==0){ //FIXME 16 vs linesize16
3412 s->c.hdsp.put_pixels_tab[0][0](s->c.dest[0], s->c.sc.rd_scratchpad , s->c.linesize ,16);
3413 s->c.hdsp.put_pixels_tab[1][0](s->c.dest[1], s->c.sc.rd_scratchpad + 16*s->c.linesize , s->c.uvlinesize, 8);
3414 s->c.hdsp.put_pixels_tab[1][0](s->c.dest[2], s->c.sc.rd_scratchpad + 16*s->c.linesize + 8, s->c.uvlinesize, 8);
3415 }
3416
3417 if (s->c.avctx->mb_decision == FF_MB_DECISION_BITS)
3418 mpv_reconstruct_mb(s, s->block);
3419 } else {
3420 int motion_x = 0, motion_y = 0;
3421 s->c.mv_type = MV_TYPE_16X16;
3422 // only one MB-Type possible
3423
3424 switch(mb_type){
3426 s->c.mv_dir = 0;
3427 s->c.mb_intra = 1;
3428 motion_x= s->c.mv[0][0][0] = 0;
3429 motion_y= s->c.mv[0][0][1] = 0;
3430 s->c.mbintra_table[xy] = 1;
3431 break;
3433 s->c.mv_dir = MV_DIR_FORWARD;
3434 s->c.mb_intra = 0;
3435 motion_x= s->c.mv[0][0][0] = s->p_mv_table[xy][0];
3436 motion_y= s->c.mv[0][0][1] = s->p_mv_table[xy][1];
3437 break;
3439 s->c.mv_dir = MV_DIR_FORWARD;
3440 s->c.mv_type = MV_TYPE_FIELD;
3441 s->c.mb_intra = 0;
3442 for(i=0; i<2; i++){
3443 int j = s->c.field_select[0][i] = s->p_field_select_table[i][xy];
3444 s->c.mv[0][i][0] = s->c.p_field_mv_table[i][j][xy][0];
3445 s->c.mv[0][i][1] = s->c.p_field_mv_table[i][j][xy][1];
3446 }
3447 break;
3449 s->c.mv_dir = MV_DIR_FORWARD;
3450 s->c.mv_type = MV_TYPE_8X8;
3451 s->c.mb_intra = 0;
3452 for(i=0; i<4; i++){
3453 s->c.mv[0][i][0] = s->c.cur_pic.motion_val[0][s->c.block_index[i]][0];
3454 s->c.mv[0][i][1] = s->c.cur_pic.motion_val[0][s->c.block_index[i]][1];
3455 }
3456 break;
3458 if (CONFIG_MPEG4_ENCODER) {
3460 s->c.mb_intra = 0;
3461 motion_x=s->b_direct_mv_table[xy][0];
3462 motion_y=s->b_direct_mv_table[xy][1];
3463 ff_mpeg4_set_direct_mv(&s->c, motion_x, motion_y);
3464 }
3465 break;
3467 if (CONFIG_MPEG4_ENCODER) {
3469 s->c.mb_intra = 0;
3470 ff_mpeg4_set_direct_mv(&s->c, 0, 0);
3471 }
3472 break;
3474 s->c.mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
3475 s->c.mb_intra = 0;
3476 s->c.mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
3477 s->c.mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
3478 s->c.mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
3479 s->c.mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
3480 break;
3482 s->c.mv_dir = MV_DIR_BACKWARD;
3483 s->c.mb_intra = 0;
3484 motion_x= s->c.mv[1][0][0] = s->b_back_mv_table[xy][0];
3485 motion_y= s->c.mv[1][0][1] = s->b_back_mv_table[xy][1];
3486 break;
3488 s->c.mv_dir = MV_DIR_FORWARD;
3489 s->c.mb_intra = 0;
3490 motion_x= s->c.mv[0][0][0] = s->b_forw_mv_table[xy][0];
3491 motion_y= s->c.mv[0][0][1] = s->b_forw_mv_table[xy][1];
3492 break;
3494 s->c.mv_dir = MV_DIR_FORWARD;
3495 s->c.mv_type = MV_TYPE_FIELD;
3496 s->c.mb_intra = 0;
3497 for(i=0; i<2; i++){
3498 int j = s->c.field_select[0][i] = s->b_field_select_table[0][i][xy];
3499 s->c.mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
3500 s->c.mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
3501 }
3502 break;
3504 s->c.mv_dir = MV_DIR_BACKWARD;
3505 s->c.mv_type = MV_TYPE_FIELD;
3506 s->c.mb_intra = 0;
3507 for(i=0; i<2; i++){
3508 int j = s->c.field_select[1][i] = s->b_field_select_table[1][i][xy];
3509 s->c.mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
3510 s->c.mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
3511 }
3512 break;
3514 s->c.mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
3515 s->c.mv_type = MV_TYPE_FIELD;
3516 s->c.mb_intra = 0;
3517 for(dir=0; dir<2; dir++){
3518 for(i=0; i<2; i++){
3519 int j = s->c.field_select[dir][i] = s->b_field_select_table[dir][i][xy];
3520 s->c.mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
3521 s->c.mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
3522 }
3523 }
3524 break;
3525 default:
3526 av_unreachable("There is a case for every CANDIDATE_MB_TYPE_* "
3527 "except CANDIDATE_MB_TYPE_SKIPPED which is never "
3528 "the only candidate (always coupled with INTER) "
3529 "so that it never reaches this switch");
3530 }
3531
3532 encode_mb(s, motion_x, motion_y);
3533
3534 // RAL: Update last macroblock type
3535 s->last_mv_dir = s->c.mv_dir;
3536
3537 if (CONFIG_H263_ENCODER &&
3538 s->c.out_format == FMT_H263 && s->c.pict_type != AV_PICTURE_TYPE_B)
3540
3541 mpv_reconstruct_mb(s, s->block);
3542 }
3543
3544 s->c.cur_pic.qscale_table[xy] = s->c.qscale;
3545
3546 /* clean the MV table in IPS frames for direct mode in B-frames */
3547 if (s->c.mb_intra /* && I,P,S_TYPE */) {
3548 s->p_mv_table[xy][0]=0;
3549 s->p_mv_table[xy][1]=0;
3550#if CONFIG_H263_ENCODER
3551 } else if (s->c.h263_pred || s->c.h263_aic) {
3553#endif
3554 }
3555
3556 if (s->c.avctx->flags & AV_CODEC_FLAG_PSNR) {
3557 int w= 16;
3558 int h= 16;
3559
3560 if (s->c.mb_x*16 + 16 > s->c.width ) w = s->c.width - s->c.mb_x*16;
3561 if (s->c.mb_y*16 + 16 > s->c.height) h = s->c.height- s->c.mb_y*16;
3562
3563 s->encoding_error[0] += sse(
3564 s, s->new_pic->data[0] + s->c.mb_x*16 + s->c.mb_y*s->c.linesize*16,
3565 s->c.dest[0], w, h, s->c.linesize);
3566 s->encoding_error[1] += sse(
3567 s, s->new_pic->data[1] + s->c.mb_x*8 + s->c.mb_y*s->c.uvlinesize*chr_h,
3568 s->c.dest[1], w>>1, h>>s->c.chroma_y_shift, s->c.uvlinesize);
3569 s->encoding_error[2] += sse(
3570 s, s->new_pic->data[2] + s->c.mb_x*8 + s->c.mb_y*s->c.uvlinesize*chr_h,
3571 s->c.dest[2], w>>1, h>>s->c.chroma_y_shift, s->c.uvlinesize);
3572 }
3573 if (s->loop_filter) {
3574 if (CONFIG_H263_ENCODER && s->c.out_format == FMT_H263)
3576 }
3577 ff_dlog(s->c.avctx, "MB %d %d bits\n",
3578 s->c.mb_x + s->c.mb_y * s->c.mb_stride, put_bits_count(&s->pb));
3579 }
3580 }
3581
3582#if CONFIG_MSMPEG4ENC
3583 //not beautiful here but we must write it before flushing so it has to be here
3584 if (s->c.msmpeg4_version != MSMP4_UNUSED && s->c.msmpeg4_version < MSMP4_WMV1 &&
3585 s->c.pict_type == AV_PICTURE_TYPE_I)
3587#endif
3588
3590
3591 return 0;
3592}
3593
3594#define ADD(field) dst->field += src->field;
3595#define MERGE(field) dst->field += src->field; src->field=0
3597{
3598 ADD(me.scene_change_score);
3599 ADD(me.mc_mb_var_sum_temp);
3600 ADD(me.mb_var_sum_temp);
3601}
3602
3604{
3605 int i;
3606
3607 MERGE(dct_count[0]); //note, the other dct vars are not part of the context
3608 MERGE(dct_count[1]);
3609 ADD(mv_bits);
3610 ADD(i_tex_bits);
3611 ADD(p_tex_bits);
3612 ADD(i_count);
3613 ADD(misc_bits);
3614 ADD(encoding_error[0]);
3615 ADD(encoding_error[1]);
3616 ADD(encoding_error[2]);
3617
3618 if (dst->dct_error_sum) {
3619 for(i=0; i<64; i++){
3620 MERGE(dct_error_sum[0][i]);
3621 MERGE(dct_error_sum[1][i]);
3622 }
3623 }
3624
3625 av_assert1(put_bits_count(&src->pb) % 8 ==0);
3626 av_assert1(put_bits_count(&dst->pb) % 8 ==0);
3627 ff_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
3628 flush_put_bits(&dst->pb);
3629}
3630
3631static int estimate_qp(MPVMainEncContext *const m, int dry_run)
3632{
3633 MPVEncContext *const s = &m->s;
3634
3635 if (m->next_lambda){
3636 s->c.cur_pic.ptr->f->quality = m->next_lambda;
3637 if(!dry_run) m->next_lambda= 0;
3638 } else if (!m->fixed_qscale) {
3639 int quality = ff_rate_estimate_qscale(m, dry_run);
3640 s->c.cur_pic.ptr->f->quality = quality;
3641 if (s->c.cur_pic.ptr->f->quality < 0)
3642 return -1;
3643 }
3644
3645 if(s->adaptive_quant){
3647
3648 switch (s->c.codec_id) {
3649 case AV_CODEC_ID_MPEG4:
3650 if (CONFIG_MPEG4_ENCODER)
3652 break;
3653 case AV_CODEC_ID_H263:
3654 case AV_CODEC_ID_H263P:
3655 case AV_CODEC_ID_FLV1:
3656 if (CONFIG_H263_ENCODER)
3658 break;
3659 }
3660
3661 s->lambda = s->lambda_table[0];
3662 //FIXME broken
3663 }else
3664 s->lambda = s->c.cur_pic.ptr->f->quality;
3665 update_qscale(m);
3666 return 0;
3667}
3668
3669/* must be called before writing the header */
3671{
3672 av_assert1(s->c.cur_pic.ptr->f->pts != AV_NOPTS_VALUE);
3673 s->c.time = s->c.cur_pic.ptr->f->pts * s->c.avctx->time_base.num;
3674
3675 if (s->c.pict_type == AV_PICTURE_TYPE_B) {
3676 s->c.pb_time = s->c.pp_time - (s->c.last_non_b_time - s->c.time);
3677 av_assert1(s->c.pb_time > 0 && s->c.pb_time < s->c.pp_time);
3678 }else{
3679 av_assert1(s->picture_number == 0 || s->c.time > s->c.last_non_b_time);
3680 s->c.pp_time = s->c.time - s->c.last_non_b_time;
3681 s->c.last_non_b_time = s->c.time;
3682 }
3683}
3684
3685static int encode_picture(MPVMainEncContext *const m, const AVPacket *pkt)
3686{
3687 MPVEncContext *const s = &m->s;
3688 int ret;
3689 int bits;
3690 int context_count = s->c.slice_context_count;
3691
3692 if (CONFIG_MPEG4_ENCODER && s->c.codec_id == AV_CODEC_ID_MPEG4) {
3695 }
3696
3697// s->lambda = s->c.cur_pic.ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
3698
3699 if (s->c.pict_type == AV_PICTURE_TYPE_I) {
3700 s->c.no_rounding = s->c.msmpeg4_version >= MSMP4_V3;
3701 } else if (s->c.pict_type != AV_PICTURE_TYPE_B) {
3702 s->c.no_rounding ^= s->flipflop_rounding;
3703 }
3704
3705 if (s->c.avctx->flags & AV_CODEC_FLAG_PASS2) {
3706 ret = estimate_qp(m, 1);
3707 if (ret < 0)
3708 return ret;
3710 } else if (!(s->c.avctx->flags & AV_CODEC_FLAG_QSCALE)) {
3711 if (s->c.pict_type == AV_PICTURE_TYPE_B)
3712 s->lambda = m->last_lambda_for[s->c.pict_type];
3713 else
3714 s->lambda = m->last_lambda_for[m->last_non_b_pict_type];
3715 update_qscale(m);
3716 }
3717
3718 s->c.mb_intra = 0; //for the rate distortion & bit compare functions
3719 for (int i = 0; i < context_count; i++) {
3720 MPVEncContext *const slice = s->c.enc_contexts[i];
3721 int h = s->c.mb_height;
3722 uint8_t *start = pkt->data + (int64_t)pkt->size * slice->c.start_mb_y / h;
3723 uint8_t *end = pkt->data + (int64_t)pkt->size * slice->c. end_mb_y / h;
3724
3725 init_put_bits(&slice->pb, start, end - start);
3726
3727 if (i) {
3728 ret = ff_update_duplicate_context(&slice->c, &s->c);
3729 if (ret < 0)
3730 return ret;
3731 slice->lambda = s->lambda;
3732 slice->lambda2 = s->lambda2;
3733 }
3734 slice->me.temp = slice->me.scratchpad = slice->c.sc.scratchpad_buf;
3735 ff_me_init_pic(slice);
3736 }
3737
3738 /* Estimate motion for every MB */
3739 if (s->c.pict_type != AV_PICTURE_TYPE_I) {
3740 s->lambda = (s->lambda * m->me_penalty_compensation + 128) >> 8;
3741 s->lambda2 = (s->lambda2 * (int64_t) m->me_penalty_compensation + 128) >> 8;
3742 if (s->c.pict_type != AV_PICTURE_TYPE_B) {
3743 if ((m->me_pre && m->last_non_b_pict_type == AV_PICTURE_TYPE_I) ||
3744 m->me_pre == 2) {
3745 s->c.avctx->execute(s->c.avctx, pre_estimate_motion_thread,
3746 &s->c.enc_contexts[0], NULL,
3747 context_count, sizeof(void*));
3748 }
3749 }
3750
3751 s->c.avctx->execute(s->c.avctx, estimate_motion_thread, &s->c.enc_contexts[0],
3752 NULL, context_count, sizeof(void*));
3753 }else /* if (s->c.pict_type == AV_PICTURE_TYPE_I) */{
3754 /* I-Frame */
3755 for (int i = 0; i < s->c.mb_stride * s->c.mb_height; i++)
3756 s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
3757
3758 if (!m->fixed_qscale) {
3759 /* finding spatial complexity for I-frame rate control */
3760 s->c.avctx->execute(s->c.avctx, mb_var_thread, &s->c.enc_contexts[0],
3761 NULL, context_count, sizeof(void*));
3762 }
3763 }
3764 for (int i = 1; i < context_count; i++)
3765 merge_context_after_me(s, s->c.enc_contexts[i]);
3766 m->mc_mb_var_sum = s->me.mc_mb_var_sum_temp;
3767 m->mb_var_sum = s->me. mb_var_sum_temp;
3768 emms_c();
3769
3770 if (s->me.scene_change_score > m->scenechange_threshold &&
3771 s->c.pict_type == AV_PICTURE_TYPE_P) {
3772 s->c.pict_type = AV_PICTURE_TYPE_I;
3773 for (int i = 0; i < s->c.mb_stride * s->c.mb_height; i++)
3774 s->mb_type[i] = CANDIDATE_MB_TYPE_INTRA;
3775 if (s->c.msmpeg4_version >= MSMP4_V3)
3776 s->c.no_rounding = 1;
3777 ff_dlog(s->c.avctx, "Scene change detected, encoding as I Frame %"PRId64" %"PRId64"\n",
3778 m->mb_var_sum, m->mc_mb_var_sum);
3779 }
3780
3781 if (!s->umvplus) {
3782 if (s->c.pict_type == AV_PICTURE_TYPE_P || s->c.pict_type == AV_PICTURE_TYPE_S) {
3783 s->f_code = ff_get_best_fcode(m, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
3784
3785 if (s->c.avctx->flags & AV_CODEC_FLAG_INTERLACED_ME) {
3786 int a,b;
3787 a = ff_get_best_fcode(m, s->c.p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
3788 b = ff_get_best_fcode(m, s->c.p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
3789 s->f_code = FFMAX3(s->f_code, a, b);
3790 }
3791
3793 ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, !!s->intra_penalty);
3794 if (s->c.avctx->flags & AV_CODEC_FLAG_INTERLACED_ME) {
3795 int j;
3796 for (int i = 0; i < 2; i++) {
3797 for(j=0; j<2; j++)
3798 ff_fix_long_mvs(s, s->p_field_select_table[i], j,
3799 s->c.p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, !!s->intra_penalty);
3800 }
3801 }
3802 } else if (s->c.pict_type == AV_PICTURE_TYPE_B) {
3803 int a, b;
3804
3805 a = ff_get_best_fcode(m, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
3806 b = ff_get_best_fcode(m, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
3807 s->f_code = FFMAX(a, b);
3808
3809 a = ff_get_best_fcode(m, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
3810 b = ff_get_best_fcode(m, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
3811 s->b_code = FFMAX(a, b);
3812
3813 ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
3814 ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
3815 ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
3816 ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
3817 if (s->c.avctx->flags & AV_CODEC_FLAG_INTERLACED_ME) {
3818 int dir, j;
3819 for(dir=0; dir<2; dir++){
3820 for (int i = 0; i < 2; i++) {
3821 for(j=0; j<2; j++){
3824 ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
3825 s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
3826 }
3827 }
3828 }
3829 }
3830 }
3831 }
3832
3833 ret = estimate_qp(m, 0);
3834 if (ret < 0)
3835 return ret;
3836
3837 if (s->c.qscale < 3 && s->max_qcoeff <= 128 &&
3838 s->c.pict_type == AV_PICTURE_TYPE_I &&
3839 !(s->c.avctx->flags & AV_CODEC_FLAG_QSCALE))
3840 s->c.qscale = 3; //reduce clipping problems
3841
3842 if (s->c.out_format == FMT_MJPEG) {
3844 (7 + s->c.qscale) / s->c.qscale, 65535);
3845 if (ret < 0)
3846 return ret;
3847
3848 if (s->c.codec_id != AV_CODEC_ID_AMV) {
3849 const uint16_t * luma_matrix = ff_mpeg1_default_intra_matrix;
3850 const uint16_t *chroma_matrix = ff_mpeg1_default_intra_matrix;
3851
3852 if (s->c.avctx->intra_matrix) {
3853 chroma_matrix =
3854 luma_matrix = s->c.avctx->intra_matrix;
3855 }
3856 if (s->c.avctx->chroma_intra_matrix)
3857 chroma_matrix = s->c.avctx->chroma_intra_matrix;
3858
3859 /* for mjpeg, we do include qscale in the matrix */
3860 for (int i = 1; i < 64; i++) {
3861 int j = s->c.idsp.idct_permutation[i];
3862
3863 s->c.chroma_intra_matrix[j] = av_clip_uint8((chroma_matrix[i] * s->c.qscale) >> 3);
3864 s->c. intra_matrix[j] = av_clip_uint8(( luma_matrix[i] * s->c.qscale) >> 3);
3865 }
3866 s->c.y_dc_scale_table =
3867 s->c.c_dc_scale_table = ff_mpeg12_dc_scale_table[0];
3868 s->c.chroma_intra_matrix[0] = s->c.intra_matrix[0] = 8;
3869 } else {
3870 static const uint8_t y[32] = {13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13};
3871 static const uint8_t c[32] = {14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14};
3872 for (int i = 1; i < 64; i++) {
3873 int j = s->c.idsp.idct_permutation[ff_zigzag_direct[i]];
3874
3875 s->c.intra_matrix[j] = sp5x_qscale_five_quant_table[0][i];
3876 s->c.chroma_intra_matrix[j] = sp5x_qscale_five_quant_table[1][i];
3877 }
3878 s->c.y_dc_scale_table = y;
3879 s->c.c_dc_scale_table = c;
3880 s->c.intra_matrix[0] = 13;
3881 s->c.chroma_intra_matrix[0] = 14;
3882 }
3883 ff_convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16,
3884 s->c.intra_matrix, s->intra_quant_bias, 8, 8, 1);
3885 ff_convert_matrix(s, s->q_chroma_intra_matrix, s->q_chroma_intra_matrix16,
3886 s->c.chroma_intra_matrix, s->intra_quant_bias, 8, 8, 1);
3887 s->c.qscale = 8;
3888 }
3889
3890 if (s->c.pict_type == AV_PICTURE_TYPE_I) {
3891 s->c.cur_pic.ptr->f->flags |= AV_FRAME_FLAG_KEY;
3892 } else {
3893 s->c.cur_pic.ptr->f->flags &= ~AV_FRAME_FLAG_KEY;
3894 }
3895 s->c.cur_pic.ptr->f->pict_type = s->c.pict_type;
3896
3897 if (s->c.cur_pic.ptr->f->flags & AV_FRAME_FLAG_KEY)
3898 m->picture_in_gop_number = 0;
3899
3900 s->c.mb_x = s->c.mb_y = 0;
3901 s->last_bits= put_bits_count(&s->pb);
3902 ret = m->encode_picture_header(m);
3903 if (ret < 0)
3904 return ret;
3905 bits= put_bits_count(&s->pb);
3906 m->header_bits = bits - s->last_bits;
3907
3908 for (int i = 1; i < context_count; i++)
3909 update_duplicate_context_after_me(s->c.enc_contexts[i], s);
3910 s->c.avctx->execute(s->c.avctx, encode_thread, &s->c.enc_contexts[0],
3911 NULL, context_count, sizeof(void*));
3912 for (int i = 1; i < context_count; i++) {
3913 if (s->pb.buf_end == s->c.enc_contexts[i]->pb.buf)
3914 set_put_bits_buffer_size(&s->pb, FFMIN(s->c.enc_contexts[i]->pb.buf_end - s->pb.buf, INT_MAX/8-BUF_BITS));
3915 merge_context_after_encode(s, s->c.enc_contexts[i]);
3916 }
3917 emms_c();
3918 return 0;
3919}
3920
3921static inline void denoise_dct(MPVEncContext *const s, int16_t block[])
3922{
3923 if (!s->dct_error_sum)
3924 return;
3925
3926 const int intra = s->c.mb_intra;
3927 s->dct_count[intra]++;
3928 s->mpvencdsp.denoise_dct(block, s->dct_error_sum[intra], s->dct_offset[intra]);
3929}
3930
3932 int16_t *block, int n,
3933 int qscale, int *overflow){
3934 const int *qmat;
3935 const uint16_t *matrix;
3936 const uint8_t *scantable;
3937 const uint8_t *perm_scantable;
3938 int max=0;
3939 unsigned int threshold1, threshold2;
3940 int bias=0;
3941 int run_tab[65];
3942 int level_tab[65];
3943 int score_tab[65];
3944 int survivor[65];
3945 int survivor_count;
3946 int last_run=0;
3947 int last_level=0;
3948 int last_score= 0;
3949 int last_i;
3950 int coeff[2][64];
3951 int coeff_count[64];
3952 int qmul, qadd, start_i, last_non_zero, i, dc;
3953 const int esc_length= s->ac_esc_length;
3954 const uint8_t *length, *last_length;
3955 const int lambda = s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
3956 int mpeg2_qscale;
3957
3958 s->fdsp.fdct(block);
3959
3961
3962 qmul= qscale*16;
3963 qadd= ((qscale-1)|1)*8;
3964
3965 if (s->c.q_scale_type) mpeg2_qscale = ff_mpeg2_non_linear_qscale[qscale];
3966 else mpeg2_qscale = qscale << 1;
3967
3968 if (s->c.mb_intra) {
3969 int q;
3970 scantable = s->c.intra_scantable.scantable;
3971 perm_scantable = s->c.intra_scantable.permutated;
3972 if (!s->c.h263_aic) {
3973 if (n < 4)
3974 q = s->c.y_dc_scale;
3975 else
3976 q = s->c.c_dc_scale;
3977 q = q << 3;
3978 } else{
3979 /* For AIC we skip quant/dequant of INTRADC */
3980 q = 1 << 3;
3981 qadd=0;
3982 }
3983
3984 /* note: block[0] is assumed to be positive */
3985 block[0] = (block[0] + (q >> 1)) / q;
3986 start_i = 1;
3987 last_non_zero = 0;
3988 qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
3989 matrix = n < 4 ? s->c.intra_matrix : s->c.chroma_intra_matrix;
3990 if (s->mpeg_quant || s->c.out_format == FMT_MPEG1 || s->c.out_format == FMT_MJPEG)
3991 bias= 1<<(QMAT_SHIFT-1);
3992
3993 if (n > 3 && s->intra_chroma_ac_vlc_length) {
3994 length = s->intra_chroma_ac_vlc_length;
3995 last_length= s->intra_chroma_ac_vlc_last_length;
3996 } else {
3997 length = s->intra_ac_vlc_length;
3998 last_length= s->intra_ac_vlc_last_length;
3999 }
4000 } else {
4001 scantable = s->c.inter_scantable.scantable;
4002 perm_scantable = s->c.inter_scantable.permutated;
4003 start_i = 0;
4004 last_non_zero = -1;
4005 qmat = s->q_inter_matrix[qscale];
4006 matrix = s->c.inter_matrix;
4007 length = s->inter_ac_vlc_length;
4008 last_length= s->inter_ac_vlc_last_length;
4009 }
4010 last_i= start_i;
4011
4012 threshold1= (1<<QMAT_SHIFT) - bias - 1;
4013 threshold2= (threshold1<<1);
4014
4015 for(i=63; i>=start_i; i--) {
4016 const int j = scantable[i];
4017 int64_t level = (int64_t)block[j] * qmat[j];
4018
4019 if(((uint64_t)(level+threshold1))>threshold2){
4020 last_non_zero = i;
4021 break;
4022 }
4023 }
4024
4025 for(i=start_i; i<=last_non_zero; i++) {
4026 const int j = scantable[i];
4027 int64_t level = (int64_t)block[j] * qmat[j];
4028
4029// if( bias+level >= (1<<(QMAT_SHIFT - 3))
4030// || bias-level >= (1<<(QMAT_SHIFT - 3))){
4031 if(((uint64_t)(level+threshold1))>threshold2){
4032 if(level>0){
4033 level= (bias + level)>>QMAT_SHIFT;
4034 coeff[0][i]= level;
4035 coeff[1][i]= level-1;
4036// coeff[2][k]= level-2;
4037 }else{
4038 level= (bias - level)>>QMAT_SHIFT;
4039 coeff[0][i]= -level;
4040 coeff[1][i]= -level+1;
4041// coeff[2][k]= -level+2;
4042 }
4043 coeff_count[i]= FFMIN(level, 2);
4044 av_assert2(coeff_count[i]);
4045 max |=level;
4046 }else{
4047 coeff[0][i]= (level>>31)|1;
4048 coeff_count[i]= 1;
4049 }
4050 }
4051
4052 *overflow= s->max_qcoeff < max; //overflow might have happened
4053
4054 if(last_non_zero < start_i){
4055 memset(block + start_i, 0, (64-start_i)*sizeof(int16_t));
4056 return last_non_zero;
4057 }
4058
4059 score_tab[start_i]= 0;
4060 survivor[0]= start_i;
4061 survivor_count= 1;
4062
4063 for(i=start_i; i<=last_non_zero; i++){
4064 int level_index, j, zero_distortion;
4065 int dct_coeff= FFABS(block[ scantable[i] ]);
4066 int best_score=256*256*256*120;
4067
4068 if (s->fdsp.fdct == ff_fdct_ifast)
4069 dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
4070 zero_distortion= dct_coeff*dct_coeff;
4071
4072 for(level_index=0; level_index < coeff_count[i]; level_index++){
4073 int distortion;
4074 int level= coeff[level_index][i];
4075 const int alevel= FFABS(level);
4076 int unquant_coeff;
4077
4079
4080 if (s->c.out_format == FMT_H263 || s->c.out_format == FMT_H261) {
4081 unquant_coeff= alevel*qmul + qadd;
4082 } else if (s->c.out_format == FMT_MJPEG) {
4083 j = s->c.idsp.idct_permutation[scantable[i]];
4084 unquant_coeff = alevel * matrix[j] * 8;
4085 }else{ // MPEG-1
4086 j = s->c.idsp.idct_permutation[scantable[i]]; // FIXME: optimize
4087 if (s->c.mb_intra) {
4088 unquant_coeff = (int)( alevel * mpeg2_qscale * matrix[j]) >> 4;
4089 unquant_coeff = (unquant_coeff - 1) | 1;
4090 }else{
4091 unquant_coeff = ((( alevel << 1) + 1) * mpeg2_qscale * ((int) matrix[j])) >> 5;
4092 unquant_coeff = (unquant_coeff - 1) | 1;
4093 }
4094 unquant_coeff<<= 3;
4095 }
4096
4097 distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
4098 level+=64;
4099 if((level&(~127)) == 0){
4100 for(j=survivor_count-1; j>=0; j--){
4101 int run= i - survivor[j];
4102 int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
4103 score += score_tab[i-run];
4104
4105 if(score < best_score){
4106 best_score= score;
4107 run_tab[i+1]= run;
4108 level_tab[i+1]= level-64;
4109 }
4110 }
4111
4112 if (s->c.out_format == FMT_H263 || s->c.out_format == FMT_H261) {
4113 for(j=survivor_count-1; j>=0; j--){
4114 int run= i - survivor[j];
4115 int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
4116 score += score_tab[i-run];
4117 if(score < last_score){
4118 last_score= score;
4119 last_run= run;
4120 last_level= level-64;
4121 last_i= i+1;
4122 }
4123 }
4124 }
4125 }else{
4126 distortion += esc_length*lambda;
4127 for(j=survivor_count-1; j>=0; j--){
4128 int run= i - survivor[j];
4129 int score= distortion + score_tab[i-run];
4130
4131 if(score < best_score){
4132 best_score= score;
4133 run_tab[i+1]= run;
4134 level_tab[i+1]= level-64;
4135 }
4136 }
4137
4138 if (s->c.out_format == FMT_H263 || s->c.out_format == FMT_H261) {
4139 for(j=survivor_count-1; j>=0; j--){
4140 int run= i - survivor[j];
4141 int score= distortion + score_tab[i-run];
4142 if(score < last_score){
4143 last_score= score;
4144 last_run= run;
4145 last_level= level-64;
4146 last_i= i+1;
4147 }
4148 }
4149 }
4150 }
4151 }
4152
4153 score_tab[i+1]= best_score;
4154
4155 // Note: there is a vlc code in MPEG-4 which is 1 bit shorter then another one with a shorter run and the same level
4156 if(last_non_zero <= 27){
4157 for(; survivor_count; survivor_count--){
4158 if(score_tab[ survivor[survivor_count-1] ] <= best_score)
4159 break;
4160 }
4161 }else{
4162 for(; survivor_count; survivor_count--){
4163 if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
4164 break;
4165 }
4166 }
4167
4168 survivor[ survivor_count++ ]= i+1;
4169 }
4170
4171 if (s->c.out_format != FMT_H263 && s->c.out_format != FMT_H261) {
4172 last_score= 256*256*256*120;
4173 for(i= survivor[0]; i<=last_non_zero + 1; i++){
4174 int score= score_tab[i];
4175 if (i)
4176 score += lambda * 2; // FIXME more exact?
4177
4178 if(score < last_score){
4179 last_score= score;
4180 last_i= i;
4181 last_level= level_tab[i];
4182 last_run= run_tab[i];
4183 }
4184 }
4185 }
4186
4187 s->coded_score[n] = last_score;
4188
4189 dc= FFABS(block[0]);
4190 last_non_zero= last_i - 1;
4191 memset(block + start_i, 0, (64-start_i)*sizeof(int16_t));
4192
4193 if(last_non_zero < start_i)
4194 return last_non_zero;
4195
4196 if(last_non_zero == 0 && start_i == 0){
4197 int best_level= 0;
4198 int best_score= dc * dc;
4199
4200 for(i=0; i<coeff_count[0]; i++){
4201 int level= coeff[i][0];
4202 int alevel= FFABS(level);
4203 int unquant_coeff, score, distortion;
4204
4205 if (s->c.out_format == FMT_H263 || s->c.out_format == FMT_H261) {
4206 unquant_coeff= (alevel*qmul + qadd)>>3;
4207 } else{ // MPEG-1
4208 unquant_coeff = ((( alevel << 1) + 1) * mpeg2_qscale * ((int) matrix[0])) >> 5;
4209 unquant_coeff = (unquant_coeff - 1) | 1;
4210 }
4211 unquant_coeff = (unquant_coeff + 4) >> 3;
4212 unquant_coeff<<= 3 + 3;
4213
4214 distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
4215 level+=64;
4216 if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
4217 else score= distortion + esc_length*lambda;
4218
4219 if(score < best_score){
4220 best_score= score;
4221 best_level= level - 64;
4222 }
4223 }
4224 block[0]= best_level;
4225 s->coded_score[n] = best_score - dc*dc;
4226 if(best_level == 0) return -1;
4227 else return last_non_zero;
4228 }
4229
4230 i= last_i;
4231 av_assert2(last_level);
4232
4233 block[ perm_scantable[last_non_zero] ]= last_level;
4234 i -= last_run + 1;
4235
4236 for(; i>start_i; i -= run_tab[i] + 1){
4237 block[ perm_scantable[i-1] ]= level_tab[i];
4238 }
4239
4240 return last_non_zero;
4241}
4242
4243static DECLARE_ALIGNED(16, int16_t, basis)[64][64];
4244
4245static void build_basis(uint8_t *perm){
4246 int i, j, x, y;
4247 emms_c();
4248 for(i=0; i<8; i++){
4249 for(j=0; j<8; j++){
4250 for(y=0; y<8; y++){
4251 for(x=0; x<8; x++){
4252 double s= 0.25*(1<<BASIS_SHIFT);
4253 int index= 8*i + j;
4254 int perm_index= perm[index];
4255 if(i==0) s*= sqrt(0.5);
4256 if(j==0) s*= sqrt(0.5);
4257 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)));
4258 }
4259 }
4260 }
4261 }
4262}
4263
4264static int dct_quantize_refine(MPVEncContext *const s, //FIXME breaks denoise?
4265 int16_t *block, int16_t *weight, int16_t *orig,
4266 int n, int qscale){
4267 DECLARE_ALIGNED(16, int16_t, rem)[64];
4268 LOCAL_ALIGNED_16(int16_t, d1, [64]);
4269 const uint8_t *scantable;
4270 const uint8_t *perm_scantable;
4271// unsigned int threshold1, threshold2;
4272// int bias=0;
4273 int run_tab[65];
4274 int prev_run=0;
4275 int prev_level=0;
4276 int qmul, qadd, start_i, last_non_zero, i, dc;
4277 const uint8_t *length;
4278 const uint8_t *last_length;
4279 int lambda;
4280 int rle_index, run, q = 1, sum; //q is only used when s->c.mb_intra is true
4281
4282 if(basis[0][0] == 0)
4283 build_basis(s->c.idsp.idct_permutation);
4284
4285 qmul= qscale*2;
4286 qadd= (qscale-1)|1;
4287 if (s->c.mb_intra) {
4288 scantable = s->c.intra_scantable.scantable;
4289 perm_scantable = s->c.intra_scantable.permutated;
4290 if (!s->c.h263_aic) {
4291 if (n < 4)
4292 q = s->c.y_dc_scale;
4293 else
4294 q = s->c.c_dc_scale;
4295 } else{
4296 /* For AIC we skip quant/dequant of INTRADC */
4297 q = 1;
4298 qadd=0;
4299 }
4300 q <<= RECON_SHIFT-3;
4301 /* note: block[0] is assumed to be positive */
4302 dc= block[0]*q;
4303// block[0] = (block[0] + (q >> 1)) / q;
4304 start_i = 1;
4305// if (s->mpeg_quant || s->c.out_format == FMT_MPEG1)
4306// bias= 1<<(QMAT_SHIFT-1);
4307 if (n > 3 && s->intra_chroma_ac_vlc_length) {
4308 length = s->intra_chroma_ac_vlc_length;
4309 last_length= s->intra_chroma_ac_vlc_last_length;
4310 } else {
4311 length = s->intra_ac_vlc_length;
4312 last_length= s->intra_ac_vlc_last_length;
4313 }
4314 } else {
4315 scantable = s->c.inter_scantable.scantable;
4316 perm_scantable = s->c.inter_scantable.permutated;
4317 dc= 0;
4318 start_i = 0;
4319 length = s->inter_ac_vlc_length;
4320 last_length= s->inter_ac_vlc_last_length;
4321 }
4322 last_non_zero = s->c.block_last_index[n];
4323
4324 dc += (1<<(RECON_SHIFT-1));
4325 for(i=0; i<64; i++){
4326 rem[i] = dc - (orig[i] << RECON_SHIFT); // FIXME use orig directly instead of copying to rem[]
4327 }
4328
4329 sum=0;
4330 for(i=0; i<64; i++){
4331 int one= 36;
4332 int qns=4;
4333 int w;
4334
4335 w= FFABS(weight[i]) + qns*one;
4336 w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
4337
4338 weight[i] = w;
4339// w=weight[i] = (63*qns + (w/2)) / w;
4340
4341 av_assert2(w>0);
4342 av_assert2(w<(1<<6));
4343 sum += w*w;
4344 }
4345 lambda = sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
4346
4347 run=0;
4348 rle_index=0;
4349 for(i=start_i; i<=last_non_zero; i++){
4350 int j= perm_scantable[i];
4351 const int level= block[j];
4352 int coeff;
4353
4354 if(level){
4355 if(level<0) coeff= qmul*level - qadd;
4356 else coeff= qmul*level + qadd;
4357 run_tab[rle_index++]=run;
4358 run=0;
4359
4360 s->mpvencdsp.add_8x8basis(rem, basis[j], coeff);
4361 }else{
4362 run++;
4363 }
4364 }
4365
4366 for(;;){
4367 int best_score = s->mpvencdsp.try_8x8basis(rem, weight, basis[0], 0);
4368 int best_coeff=0;
4369 int best_change=0;
4370 int run2, best_unquant_change=0, analyze_gradient;
4371 analyze_gradient = last_non_zero > 2 || s->quantizer_noise_shaping >= 3;
4372
4373 if(analyze_gradient){
4374 for(i=0; i<64; i++){
4375 int w= weight[i];
4376
4377 d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
4378 }
4379 s->fdsp.fdct(d1);
4380 }
4381
4382 if(start_i){
4383 const int level= block[0];
4384 int change, old_coeff;
4385
4386 av_assert2(s->c.mb_intra);
4387
4388 old_coeff= q*level;
4389
4390 for(change=-1; change<=1; change+=2){
4391 int new_level= level + change;
4392 int score, new_coeff;
4393
4394 new_coeff= q*new_level;
4395 if(new_coeff >= 2048 || new_coeff < 0)
4396 continue;
4397
4398 score = s->mpvencdsp.try_8x8basis(rem, weight, basis[0],
4399 new_coeff - old_coeff);
4400 if(score<best_score){
4401 best_score= score;
4402 best_coeff= 0;
4403 best_change= change;
4404 best_unquant_change= new_coeff - old_coeff;
4405 }
4406 }
4407 }
4408
4409 run=0;
4410 rle_index=0;
4411 run2= run_tab[rle_index++];
4412 prev_level=0;
4413 prev_run=0;
4414
4415 for(i=start_i; i<64; i++){
4416 int j= perm_scantable[i];
4417 const int level= block[j];
4418 int change, old_coeff;
4419
4420 if(s->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
4421 break;
4422
4423 if(level){
4424 if(level<0) old_coeff= qmul*level - qadd;
4425 else old_coeff= qmul*level + qadd;
4426 run2= run_tab[rle_index++]; //FIXME ! maybe after last
4427 }else{
4428 old_coeff=0;
4429 run2--;
4430 av_assert2(run2>=0 || i >= last_non_zero );
4431 }
4432
4433 for(change=-1; change<=1; change+=2){
4434 int new_level= level + change;
4435 int score, new_coeff, unquant_change;
4436
4437 score=0;
4438 if(s->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
4439 continue;
4440
4441 if(new_level){
4442 if(new_level<0) new_coeff= qmul*new_level - qadd;
4443 else new_coeff= qmul*new_level + qadd;
4444 if(new_coeff >= 2048 || new_coeff <= -2048)
4445 continue;
4446 //FIXME check for overflow
4447
4448 if(level){
4449 if(level < 63 && level > -63){
4450 if(i < last_non_zero)
4451 score += length[UNI_AC_ENC_INDEX(run, new_level+64)]
4452 - length[UNI_AC_ENC_INDEX(run, level+64)];
4453 else
4454 score += last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
4455 - last_length[UNI_AC_ENC_INDEX(run, level+64)];
4456 }
4457 }else{
4458 av_assert2(FFABS(new_level)==1);
4459
4460 if(analyze_gradient){
4461 int g= d1[ scantable[i] ];
4462 if(g && (g^new_level) >= 0)
4463 continue;
4464 }
4465
4466 if(i < last_non_zero){
4467 int next_i= i + run2 + 1;
4468 int next_level= block[ perm_scantable[next_i] ] + 64;
4469
4470 if(next_level&(~127))
4471 next_level= 0;
4472
4473 if(next_i < last_non_zero)
4474 score += length[UNI_AC_ENC_INDEX(run, 65)]
4475 + length[UNI_AC_ENC_INDEX(run2, next_level)]
4476 - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
4477 else
4478 score += length[UNI_AC_ENC_INDEX(run, 65)]
4479 + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
4480 - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
4481 }else{
4482 score += last_length[UNI_AC_ENC_INDEX(run, 65)];
4483 if(prev_level){
4484 score += length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
4485 - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
4486 }
4487 }
4488 }
4489 }else{
4490 new_coeff=0;
4491 av_assert2(FFABS(level)==1);
4492
4493 if(i < last_non_zero){
4494 int next_i= i + run2 + 1;
4495 int next_level= block[ perm_scantable[next_i] ] + 64;
4496
4497 if(next_level&(~127))
4498 next_level= 0;
4499
4500 if(next_i < last_non_zero)
4501 score += length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
4502 - length[UNI_AC_ENC_INDEX(run2, next_level)]
4503 - length[UNI_AC_ENC_INDEX(run, 65)];
4504 else
4505 score += last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
4506 - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
4507 - length[UNI_AC_ENC_INDEX(run, 65)];
4508 }else{
4509 score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
4510 if(prev_level){
4511 score += last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
4512 - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
4513 }
4514 }
4515 }
4516
4517 score *= lambda;
4518
4519 unquant_change= new_coeff - old_coeff;
4520 av_assert2((score < 100*lambda && score > -100*lambda) || lambda==0);
4521
4522 score += s->mpvencdsp.try_8x8basis(rem, weight, basis[j],
4523 unquant_change);
4524 if(score<best_score){
4525 best_score= score;
4526 best_coeff= i;
4527 best_change= change;
4528 best_unquant_change= unquant_change;
4529 }
4530 }
4531 if(level){
4532 prev_level= level + 64;
4533 if(prev_level&(~127))
4534 prev_level= 0;
4535 prev_run= run;
4536 run=0;
4537 }else{
4538 run++;
4539 }
4540 }
4541
4542 if(best_change){
4543 int j= perm_scantable[ best_coeff ];
4544
4545 block[j] += best_change;
4546
4547 if(best_coeff > last_non_zero){
4548 last_non_zero= best_coeff;
4549 av_assert2(block[j]);
4550 }else{
4551 for(; last_non_zero>=start_i; last_non_zero--){
4552 if(block[perm_scantable[last_non_zero]])
4553 break;
4554 }
4555 }
4556
4557 run=0;
4558 rle_index=0;
4559 for(i=start_i; i<=last_non_zero; i++){
4560 const int level = block[perm_scantable[i]];
4561
4562 if(level){
4563 run_tab[rle_index++]=run;
4564 run=0;
4565 }else{
4566 run++;
4567 }
4568 }
4569
4570 s->mpvencdsp.add_8x8basis(rem, basis[j], best_unquant_change);
4571 }else{
4572 break;
4573 }
4574 }
4575
4576 return last_non_zero;
4577}
4578
4579/**
4580 * Permute an 8x8 block according to permutation.
4581 * @param block the block which will be permuted according to
4582 * the given permutation vector
4583 * @param permutation the permutation vector
4584 * @param last the last non zero coefficient in scantable order, used to
4585 * speed the permutation up
4586 * @param scantable the used scantable, this is only used to speed the
4587 * permutation up, the block is not (inverse) permutated
4588 * to scantable order!
4589 */
4590void ff_block_permute(int16_t *block, const uint8_t *permutation,
4591 const uint8_t *scantable, int last)
4592{
4593 int i;
4594 int16_t temp[64];
4595
4596 if (last <= 0)
4597 return;
4598 //FIXME it is ok but not clean and might fail for some permutations
4599 // if (permutation[1] == 1)
4600 // return;
4601
4602 for (i = 0; i <= last; i++) {
4603 const int j = scantable[i];
4604 temp[j] = block[j];
4605 block[j] = 0;
4606 }
4607
4608 for (i = 0; i <= last; i++) {
4609 const int j = scantable[i];
4610 const int perm_j = permutation[j];
4611 block[perm_j] = temp[j];
4612 }
4613}
4614
4616 int16_t *block, int n,
4617 int qscale, int *overflow)
4618{
4619 int i, last_non_zero, q, start_i;
4620 const int *qmat;
4621 const uint8_t *scantable;
4622 int bias;
4623 int max=0;
4624 unsigned int threshold1, threshold2;
4625
4626 s->fdsp.fdct(block);
4627
4629
4630 if (s->c.mb_intra) {
4631 scantable = s->c.intra_scantable.scantable;
4632 if (!s->c.h263_aic) {
4633 if (n < 4)
4634 q = s->c.y_dc_scale;
4635 else
4636 q = s->c.c_dc_scale;
4637 q = q << 3;
4638 } else
4639 /* For AIC we skip quant/dequant of INTRADC */
4640 q = 1 << 3;
4641
4642 /* note: block[0] is assumed to be positive */
4643 block[0] = (block[0] + (q >> 1)) / q;
4644 start_i = 1;
4645 last_non_zero = 0;
4646 qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
4647 bias= s->intra_quant_bias*(1<<(QMAT_SHIFT - QUANT_BIAS_SHIFT));
4648 } else {
4649 scantable = s->c.inter_scantable.scantable;
4650 start_i = 0;
4651 last_non_zero = -1;
4652 qmat = s->q_inter_matrix[qscale];
4653 bias= s->inter_quant_bias*(1<<(QMAT_SHIFT - QUANT_BIAS_SHIFT));
4654 }
4655 threshold1= (1<<QMAT_SHIFT) - bias - 1;
4656 threshold2= (threshold1<<1);
4657 for(i=63;i>=start_i;i--) {
4658 const int j = scantable[i];
4659 int64_t level = (int64_t)block[j] * qmat[j];
4660
4661 if(((uint64_t)(level+threshold1))>threshold2){
4662 last_non_zero = i;
4663 break;
4664 }else{
4665 block[j]=0;
4666 }
4667 }
4668 for(i=start_i; i<=last_non_zero; i++) {
4669 const int j = scantable[i];
4670 int64_t level = (int64_t)block[j] * qmat[j];
4671
4672// if( bias+level >= (1<<QMAT_SHIFT)
4673// || bias-level >= (1<<QMAT_SHIFT)){
4674 if(((uint64_t)(level+threshold1))>threshold2){
4675 if(level>0){
4676 level= (bias + level)>>QMAT_SHIFT;
4677 block[j]= level;
4678 }else{
4679 level= (bias - level)>>QMAT_SHIFT;
4680 block[j]= -level;
4681 }
4682 max |=level;
4683 }else{
4684 block[j]=0;
4685 }
4686 }
4687 *overflow= s->max_qcoeff < max; //overflow might have happened
4688
4689 /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
4690 if (s->c.idsp.perm_type != FF_IDCT_PERM_NONE)
4691 ff_block_permute(block, s->c.idsp.idct_permutation,
4692 scantable, last_non_zero);
4693
4694 return last_non_zero;
4695}
const uint16_t ff_aanscales[64]
Definition aandcttab.c:26
const uint16_t ff_inv_aanscales[64]
Definition aandcttab.c:38
AAN (Arai, Agui and Nakajima) (I)DCT tables.
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t my
Definition dsp.h:57
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t mx
Definition dsp.h:57
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition dsp.h:87
static double sqr(double in)
Definition af_afwtdn.c:872
static int out_size
#define av_assert2(cond)
assert() equivalent, that does lie in speed critical code.
Definition avassert.h:68
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition avassert.h:58
#define av_unreachable(msg)
Asserts that are used as compiler optimization hints depending upon ASSERT_LEVEL and NBDEBUG.
Definition avassert.h:109
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
Libavcodec external API header.
#define FF_CMP_VSSE
Definition avcodec.h:890
#define FF_CMP_NSSE
Definition avcodec.h:891
#define FF_MB_DECISION_RD
rate distortion
Definition avcodec.h:951
#define FF_DEBUG_DCT_COEFF
Definition avcodec.h:1399
#define FF_MB_DECISION_BITS
chooses the one which needs the fewest bits
Definition avcodec.h:950
#define FF_MB_DECISION_SIMPLE
uses mb_cmp
Definition avcodec.h:949
void ff_copy_bits(PutBitContext *pb, const uint8_t *src, int length)
Copy the content of src to the bitstream.
Definition bitstream.c:49
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define f(width, name)
Definition cbs_vp8.c:236
#define s(width, name)
Definition cbs_vp9.c:198
#define AV_CEIL_RSHIFT(a, b)
Definition common.h:60
#define av_clip
Definition common.h:100
#define ROUNDED_DIV(a, b)
Definition common.h:58
#define av_clip_uint8
Definition common.h:106
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition common.h:74
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
#define max(a, b)
static int16_t block[64]
Definition dct.c:125
static int dct_error(const struct algo *dct, int test, int is_idct, int speed, const int bits)
Definition dct.c:188
#define FF_COMPLIANCE_EXPERIMENTAL
Allow nonstandardized experimental things.
Definition defs.h:62
#define FF_COMPLIANCE_NORMAL
Definition defs.h:60
AVCPBProperties * av_cpb_properties_alloc(size_t *size)
Allocate a CPB properties structure and initialize its fields to default values.
Definition utils.c:976
static AVPacket * pkt
static AVFrame * frame
#define emms_c()
Definition emms.h:88
int ff_alloc_packet(AVCodecContext *avctx, AVPacket *avpkt, int64_t size)
Check AVPacket size and allocate data.
Definition encode.c:62
AVCPBProperties * ff_encode_add_cpb_side_data(AVCodecContext *avctx)
Add a CPB properties side data to an encoding context.
Definition encode.c:1039
int ff_encode_add_stats_side_data(AVPacket *pkt, int quality, const int64_t error[], int error_count, enum AVPictureType pict_type)
Definition encode.c:1070
int ff_encode_reordered_opaque(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *frame)
Propagate user opaque values from the frame to avctx/pkt as needed.
Definition encode.c:280
int ff_encode_alloc_frame(AVCodecContext *avctx, AVFrame *frame)
Allocate buffers for a frame.
Definition encode.c:989
int ff_check_codec_matrices(AVCodecContext *avctx, unsigned types, uint16_t min, uint16_t max)
Definition encode.c:1095
#define FF_MATRIX_TYPE_INTER
Definition encode.h:122
#define FF_MATRIX_TYPE_CHROMA_INTRA
Definition encode.h:123
#define FF_MATRIX_TYPE_INTRA
Check if the elements of codec context matrices (intra_matrix, inter_matrix or chroma_intra_matrix) a...
Definition encode.h:121
perm
Definition f_perms.c:75
void ff_faandct(int16_t *data)
Definition faandct.c:117
Floating point AAN DCT.
static const uint8_t bits[8]
Definition fastaudio.c:100
void ff_fdct_ifast(int16_t *data)
Definition jfdctfst.c:207
void ff_jpeg_fdct_islow_10(int16_t *data)
void ff_jpeg_fdct_islow_8(int16_t *data)
#define MAX_THREADS
#define fail
Definition test.h:479
#define AV_CODEC_FLAG_QPEL
Use qpel MC.
Definition avcodec.h:225
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition avcodec.c:144
#define AV_CODEC_FLAG_BITEXACT
Use only bitexact stuff (except (I)DCT).
Definition avcodec.h:322
#define AV_CODEC_FLAG_PASS2
Use internal 2pass ratecontrol in second pass mode.
Definition avcodec.h:294
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition options.c:149
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition codec.h:79
#define AV_CODEC_FLAG_CLOSED_GOP
Definition avcodec.h:332
#define AV_CODEC_FLAG_INTERLACED_DCT
Use interlaced DCT.
Definition avcodec.h:310
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition avcodec.h:213
#define AV_CODEC_FLAG_GRAY
Only decode/encode grayscale.
Definition avcodec.h:302
#define AV_CODEC_FLAG_AC_PRED
H.263 advanced intra coding / MPEG-4 AC prediction.
Definition avcodec.h:327
#define AV_CODEC_CAP_SLICE_THREADS
Codec supports slice-based (or partition-based) multithreading.
Definition codec.h:102
#define AV_CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
Definition avcodec.h:290
#define AV_CODEC_FLAG_LOOP_FILTER
loop filter.
Definition avcodec.h:298
#define AV_CODEC_FLAG_INTERLACED_ME
interlaced motion estimation
Definition avcodec.h:331
#define AV_CODEC_FLAG_LOW_DELAY
Force low delay.
Definition avcodec.h:314
#define AV_CODEC_FLAG_PSNR
error[?
Definition avcodec.h:306
#define AV_CODEC_FLAG_4MV
4 MV per MB allowed / advanced prediction for H.263.
Definition avcodec.h:217
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
Definition options.c:164
@ AV_CODEC_ID_MSMPEG4V1
Definition codec_id.h:64
@ AV_CODEC_ID_H261
Definition codec_id.h:53
@ AV_CODEC_ID_FLV1
Definition codec_id.h:71
@ AV_CODEC_ID_WMV2
Definition codec_id.h:68
@ AV_CODEC_ID_MSMPEG4V2
Definition codec_id.h:65
@ AV_CODEC_ID_WMV1
Definition codec_id.h:67
@ AV_CODEC_ID_RV10
Definition codec_id.h:55
@ AV_CODEC_ID_SPEEDHQ
Definition codec_id.h:270
@ AV_CODEC_ID_RV20
Definition codec_id.h:56
@ AV_CODEC_ID_H263
Definition codec_id.h:54
@ AV_CODEC_ID_MPEG4
Definition codec_id.h:62
@ AV_CODEC_ID_MJPEG
Definition codec_id.h:57
@ AV_CODEC_ID_MPEG1VIDEO
Definition codec_id.h:51
@ AV_CODEC_ID_H263P
Definition codec_id.h:69
@ AV_CODEC_ID_MSMPEG4V3
Definition codec_id.h:66
@ AV_CODEC_ID_MPEG2VIDEO
preferred ID for MPEG-1/2 video decoding
Definition codec_id.h:52
@ AV_CODEC_ID_AMV
Definition codec_id.h:157
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
Read encoded data from the encoder.
Definition encode.c:578
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Supply a raw video or audio frame to the encoder.
Definition encode.c:545
void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size)
Same behaviour av_fast_malloc but the buffer has additional AV_INPUT_BUFFER_PADDING_SIZE at the end w...
Definition utils.c:53
@ AV_PKT_DATA_H263_MB_INFO
An AV_PKT_DATA_H263_MB_INFO side data packet contains a number of structures with info about macroblo...
Definition packet.h:90
@ AV_PKT_DATA_CPB_PROPERTIES
This side data corresponds to the AVCPBProperties struct.
Definition packet.h:142
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition packet.c:74
int av_packet_shrink_side_data(AVPacket *pkt, enum AVPacketSideDataType type, size_t size)
Shrink the already allocated side data buffer.
Definition packet.c:381
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:434
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, size_t size)
Allocate new information of a packet.
Definition packet.c:231
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:650
int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type, uint8_t *data, size_t size)
Wrap an existing array as a packet side data.
Definition packet.c:197
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition packet.c:63
#define FF_LAMBDA_SCALE
Definition avutil.h:225
#define FF_LAMBDA_SHIFT
Definition avutil.h:224
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition avutil.h:226
#define AVERROR_ENCODER_NOT_FOUND
Encoder not found.
Definition error.h:56
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition error.h:64
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_FRAME_FLAG_KEY
A flag to mark frames that are keyframes.
Definition frame.h:694
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition frame.c:496
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
Definition frame.c:206
void av_frame_move_ref(AVFrame *dst, AVFrame *src)
Move everything contained in src to dst and reset src.
Definition frame.c:523
int av_frame_ref(AVFrame *dst, const AVFrame *src)
Set up a new reference to the data described by the source frame.
Definition frame.c:278
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition frame.c:64
int av_frame_copy_props(AVFrame *dst, const AVFrame *src)
Copy only "metadata" fields from src to dst.
Definition frame.c:599
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition frame.c:52
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:241
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition rational.c:35
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition rational.h:104
int64_t av_gcd(int64_t a, int64_t b)
Compute the greatest common divisor of two integer operands.
Definition mathematics.c:37
@ AV_PICTURE_TYPE_I
Intra.
Definition avutil.h:278
@ AV_PICTURE_TYPE_P
Predicted.
Definition avutil.h:279
@ AV_PICTURE_TYPE_S
S(GMC)-VOP MPEG-4.
Definition avutil.h:281
@ AV_PICTURE_TYPE_B
Bi-dir predicted.
Definition avutil.h:280
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
#define AV_STRINGIFY(s)
Definition macros.h:66
int index
Definition gxfenc.c:90
void ff_h261_reorder_mb_index(MPVEncContext *const s)
Definition h261enc.c:118
H.261 encoder header.
int16_t * ff_h263_pred_motion(MpegEncContext *s, int block, int dir, int *px, int *py)
Definition h263.c:182
void ff_h263_loop_filter(MpegEncContext *s)
Definition h263.c:97
static void ff_h263_clean_intra_table_entries(MpegEncContext *s, int xy)
Definition h263.h:47
const uint16_t ff_h263_format[8][2]
Definition h263data.c:236
H.263 tables.
void ff_h263_mpeg4_reset_dc(MPVEncContext *s)
void ff_h263_encode_gob_header(MPVEncContext *s, int mb_line)
void ff_clean_h263_qscales(MPVEncContext *s)
void ff_h263_encode_init(MPVMainEncContext *m)
void ff_h263_update_mb(MPVEncContext *s)
int a
const pixel * src2
#define ALIGN
Definition hashtable.c:32
void(* op_pixels_func)(uint8_t *block, const uint8_t *pixels, ptrdiff_t line_size, int h)
Average and put pixel Widths can be 16, 8, 4 or 2.
Definition hpeldsp.h:39
@ FF_IDCT_PERM_NONE
Definition idctdsp.h:28
#define r
Definition input.c:42
#define b
Definition input.c:43
static void scale(int *out, const int *in, const int w, const int h, const int shift)
Definition intra.c:278
static void put_bits(Jpeg2000EncoderContext *s, int val, int n)
put n times val bit
Definition j2kenc.c:154
uint32_t type
Definition jpegmpfenc.c:80
unsigned offset
Definition libaomenc.c:763
static int shift(int a, int b)
Definition bonk.c:261
#define EDGE_WIDTH
Definition diracdec.c:47
av_cold void ff_fdctdsp_init(FDCTDSPContext *c, AVCodecContext *avctx)
Definition fdctdsp.c:25
common internal api header.
#define STRIDE_ALIGN
Definition internal.h:46
int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b)
Return the index into tab at which {a,b} match elements {[0],[1]} of tab.
Definition utils.c:851
const char * arg
Definition jacosubdec.c:65
av_cold void ff_mpegvideoencdsp_init(MpegvideoEncDSPContext *c, AVCodecContext *avctx)
av_cold void ff_pixblockdsp_init(PixblockDSPContext *c, int bits_per_raw_sample)
Definition pixblockdsp.c:87
Macro definitions for various function/variable attributes.
#define av_always_inline
Definition attributes.h:72
#define av_fallthrough
Definition attributes.h:67
#define av_cold
Definition attributes.h:117
common internal API header
#define FF_ALLOCZ_TYPED_ARRAY(p, nelem)
Definition internal.h:81
#define AVOnce
Definition thread.h:202
static int ff_thread_once(char *control, void(*routine)(void))
Definition thread.h:205
#define AV_ONCE_INIT
Definition thread.h:203
#define lrintf(x)
Definition libm_mips.h:74
uint8_t w
Definition llvidencdsp.c:39
#define FFMAX3(a, b, c)
Definition macros.h:48
#define FFMIN(a, b)
Definition macros.h:49
#define FFMAX(a, b)
Definition macros.h:47
#define FFALIGN(x, a)
Definition macros.h:78
#define M_PI
Definition mathematics.h:67
const uint8_t ff_zigzag_direct[64]
Definition mathtables.c:137
#define ff_sqrt
Definition mathops.h:220
EXTERN const uint32_t ff_square_tab[512]
Definition mathops.h:35
av_cold int ff_set_cmp(const MECmpContext *c, me_cmp_func *cmp, int type, int mpvenc)
Fill the function pointer array cmp[6] with me_cmp_funcs from c based upon type.
Definition me_cmp.c:443
av_cold void ff_me_cmp_init(MECmpContext *c, AVCodecContext *avctx)
Definition me_cmp.c:961
int(* me_cmp_func)(MPVEncContext *c, const uint8_t *blk1, const uint8_t *blk2, ptrdiff_t stride, int h)
Definition me_cmp.h:45
void * av_calloc(size_t nmemb, size_t size)
Definition mem.c:370
Memory handling functions.
#define DECLARE_ALIGNED(n, t, v)
Declare a variable that is aligned in memory.
#define LOCAL_ALIGNED_16(t, v,...)
int ff_mjpeg_encode_stuffing(MPVEncContext *const s)
Writes the complete JPEG frame when optimal huffman tables are enabled, otherwise writes the stuffing...
Definition mjpegenc.c:238
MJPEG encoder.
int ff_mjpeg_add_gain_map_size(AVCodecContext *avctx, struct MJpegContext *m, const AVFrame *frame, size_t *max_pkt_size)
int ff_mjpeg_add_icc_profile_size(AVCodecContext *avctx, const AVFrame *frame, size_t *max_pkt_size)
void ff_mjpeg_encode_picture_trailer(PutBitContext *pb, int header_bits)
static const uint8_t mv_bits[2][16][10]
Definition mobiclip.c:165
int ff_get_best_fcode(MPVMainEncContext *const m, const int16_t(*mv_table)[2], int type)
void ff_estimate_p_frame_motion(MPVEncContext *const s, int mb_x, int mb_y)
Definition motion_est.c:888
void ff_me_init_pic(MPVEncContext *const s)
Definition motion_est.c:371
void ff_fix_long_p_mvs(MPVEncContext *const s, int type)
void ff_estimate_b_frame_motion(MPVEncContext *const s, int mb_x, int mb_y)
int ff_pre_estimate_p_frame_motion(MPVEncContext *const s, int mb_x, int mb_y)
void ff_fix_long_mvs(MPVEncContext *const s, uint8_t *field_select_table, int field_select, int16_t(*mv_table)[2], int f_code, int type, int truncate)
av_cold int ff_me_init(MotionEstContext *c, AVCodecContext *avctx, const MECmpContext *mecc, int mpvenc)
Definition motion_est.c:309
#define MAX_MV
Definition motion_est.h:37
const uint16_t ff_mpeg1_default_intra_matrix[256]
Definition mpeg12data.c:31
const uint16_t ff_mpeg1_default_non_intra_matrix[64]
Definition mpeg12data.c:42
MPEG-1/2 tables.
static void ff_mpeg1_clean_buffers(MPVEncContext *s)
Definition mpeg12enc.h:29
void ff_mpeg1_encode_slice_header(MPVEncContext *s)
const int16_t ff_mpeg4_default_intra_matrix[64]
Definition mpeg4data.h:334
const int16_t ff_mpeg4_default_non_intra_matrix[64]
Definition mpeg4data.h:345
void ff_mpeg4_clean_buffers(MpegEncContext *s)
Definition mpeg4video.c:44
int ff_mpeg4_set_direct_mv(MpegEncContext *s, int mx, int my)
Definition mpeg4video.c:119
void ff_mpeg4_stuffing(PutBitContext *pbc)
add MPEG-4 stuffing bits (01...1)
void ff_mpeg4_init_partitions(MPVEncContext *const s)
void ff_clean_mpeg4_qscales(MPVEncContext *const s)
modify mb_type & qscale so that encoding is actually possible in MPEG-4
void ff_mpeg4_merge_partitions(MPVEncContext *const s)
void ff_set_mpeg4_time(MPVEncContext *const s)
void ff_mpeg4_encode_video_packet_header(MPVEncContext *const s)
@ MAX_PB2_MB_SIZE
@ MAX_AC_TEX_MB_SIZE
void ff_mpv_unref_picture(MPVWorkPicture *pic)
Definition mpegpicture.c:98
int ff_mpv_pic_check_linesize(void *logctx, const AVFrame *f, ptrdiff_t *linesizep, ptrdiff_t *uvlinesizep)
int ff_mpv_alloc_pic_accessories(AVCodecContext *avctx, MPVWorkPicture *wpic, ScratchpadContext *sc, BufferPoolContext *pools, int mb_height)
Allocate an MPVPicture's accessories (but not the AVFrame's buffer itself) and set the MPVWorkPicture...
av_cold AVRefStructPool * ff_mpv_alloc_pic_pool(int init_progress)
Allocate a pool of MPVPictures.
Definition mpegpicture.c:90
void ff_mpv_replace_picture(MPVWorkPicture *dst, const MPVWorkPicture *src)
#define MPV_MAX_PLANES
Definition mpegpicture.h:31
#define MAX_MB_BYTES
Definition mpegutils.h:35
av_cold int ff_mpv_common_init(MpegEncContext *s)
init common structure for both encoder and decoder.
Definition mpegvideo.c:359
av_cold int ff_mpv_init_duplicate_contexts(MpegEncContext *s)
Initialize an MpegEncContext's thread contexts.
Definition mpegvideo.c:99
av_cold void ff_mpv_idct_init(MpegEncContext *s)
Definition mpegvideo.c:81
av_cold void ff_mpv_common_end(MpegEncContext *s)
Definition mpegvideo.c:428
void ff_set_qscale(MpegEncContext *s, int qscale)
set qscale and update qscale dependent variables.
Definition mpegvideo.c:505
void ff_init_block_index(MpegEncContext *s)
Definition mpegvideo.c:472
av_cold void ff_mpv_common_defaults(MpegEncContext *s)
Set the given MpegEncContext to common defaults (same for encoding and decoding).
Definition mpegvideo.c:171
int ff_update_duplicate_context(MpegEncContext *dst, const MpegEncContext *src)
Definition mpegvideo.c:139
mpegvideo header.
void ff_mpv_motion(MpegEncContext *s, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr, int dir, uint8_t *const *ref_picture, const op_pixels_func(*pix_op)[4], const qpel_mc_func(*qpix_op)[16])
#define MV_DIR_BACKWARD
Definition mpegvideo.h:169
static void ff_update_block_index(MpegEncContext *s, int bits_per_raw_sample, int lowres, int chroma_x_shift)
Definition mpegvideo.h:335
#define MV_DIR_FORWARD
Definition mpegvideo.h:168
#define MV_TYPE_FIELD
2 vectors, one per field
Definition mpegvideo.h:175
#define MV_TYPE_8X8
4 vectors (H.263, MPEG-4 4MV)
Definition mpegvideo.h:173
#define CHROMA_420
Definition mpegvideo.h:264
#define CHROMA_444
Definition mpegvideo.h:266
#define MV_DIRECT
bidirectional mode where the difference equals the MV of the last P/S/I-Frame (MPEG-4)
Definition mpegvideo.h:170
#define MV_TYPE_16X16
1 vector for the whole mb
Definition mpegvideo.h:172
@ FMT_H261
Definition mpegvideo.h:56
@ FMT_MPEG1
Definition mpegvideo.h:55
@ FMT_SPEEDHQ
Definition mpegvideo.h:59
@ FMT_H263
Definition mpegvideo.h:57
@ FMT_MJPEG
Definition mpegvideo.h:58
#define CHROMA_422
Definition mpegvideo.h:265
static av_cold void mpv_encode_defaults(MPVMainEncContext *const m)
Set the given MPVEncContext to defaults for encoding.
static av_cold int init_matrices(MPVMainEncContext *const m, AVCodecContext *avctx)
static int sse(const MPVEncContext *const s, const uint8_t *src1, const uint8_t *src2, int w, int h, int stride)
static int encode_frame(AVCodecContext *c, const AVFrame *frame, AVPacket *pkt)
static int set_bframe_chain_length(MPVMainEncContext *const m)
Determines whether an input picture is discarded or not and if not determines the length of the next ...
static void merge_context_after_encode(MPVEncContext *const dst, MPVEncContext *const src)
#define QMAT_SHIFT_MMX
static int dct_quantize_c(MPVEncContext *const s, int16_t *block, int n, int qscale, int *overflow)
static void put_dct(MPVEncContext *const s, int16_t *block, int i, uint8_t *dest, int line_size, int qscale)
static av_cold void mpv_encode_init_static(void)
static const AVOption mpv_generic_options[]
void ff_block_permute(int16_t *block, const uint8_t *permutation, const uint8_t *scantable, int last)
Permute an 8x8 block according to permutation.
#define MERGE(field)
static av_cold void init_unquantize(MPVEncContext *const s2, AVCodecContext *avctx)
static void clip_coeffs(const MPVEncContext *const s, int16_t block[], int last_index)
static int dct_quantize_refine(MPVEncContext *const s, int16_t *block, int16_t *weight, int16_t *orig, int n, int qscale)
static int mb_var_thread(AVCodecContext *c, void *arg)
static int estimate_best_b_count(MPVMainEncContext *const m)
static void add_dequant_dct(MPVEncContext *const s, int16_t *block, int i, uint8_t *dest, int line_size, int qscale)
static int estimate_motion_thread(AVCodecContext *c, void *arg)
static int skip_check(MPVMainEncContext *const m, const MPVPicture *p, const MPVPicture *ref)
const AVClass ff_mpv_enc_class
int ff_mpv_reallocate_putbitbuffer(MPVEncContext *const s, size_t threshold, size_t size_increase)
static void merge_context_after_me(MPVEncContext *const dst, MPVEncContext *const src)
#define ALLOCZ_ARRAYS(p, mult, numb)
static void encode_mb_hq(MPVEncContext *const s, MBBackup *const backup, MBBackup *const best, PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2], int *dmin, int *next_block, int motion_x, int motion_y)
av_cold void ff_dct_encode_init(MPVEncContext *const s)
static int pre_estimate_motion_thread(AVCodecContext *c, void *arg)
static int prepare_picture(MPVEncContext *const s, AVFrame *f, const AVFrame *props_frame)
Allocates new buffers for an AVFrame and copies the properties from another AVFrame.
static void encode_mb(MPVEncContext *const s, int motion_x, int motion_y)
static uint8_t default_fcode_tab[MAX_MV *2+1]
static void build_basis(uint8_t *perm)
static int sse_mb(MPVEncContext *const s)
static void update_noise_reduction(MPVMainEncContext *const m)
#define QUANT_BIAS_SHIFT
static int get_intra_count(MPVEncContext *const s, const uint8_t *src, const uint8_t *ref, int stride)
static int dct_quantize_trellis_c(MPVEncContext *const s, int16_t *block, int n, int qscale, int *overflow)
#define ADD(field)
static void dct_single_coeff_elimination(MPVEncContext *const s, int n, int threshold)
static void update_duplicate_context_after_me(MPVEncContext *const dst, const MPVEncContext *const src)
static void write_slice_end(MPVEncContext *const s)
void ff_convert_matrix(MPVEncContext *const s, int(*qmat)[64], uint16_t(*qmat16)[2][64], const uint16_t *quant_matrix, int bias, int qmin, int qmax, int intra)
static void get_visual_weight(int16_t *weight, const uint8_t *ptr, int stride)
static void mpv_reconstruct_mb(MPVEncContext *const s, int16_t block[12][64])
Performs dequantization and IDCT (if necessary)
static int encode_picture(MPVMainEncContext *const s, const AVPacket *pkt)
av_cold int ff_mpv_encode_init(AVCodecContext *avctx)
static void update_mb_info(MPVEncContext *const s)
int ff_mpv_encode_picture(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *pic_arg, int *got_packet)
static int16_t basis[64][64]
static av_cold int me_cmp_init(MPVMainEncContext *const m, AVCodecContext *avctx)
#define COPY_CONTEXT(BEFORE, AFTER, DST_TYPE, SRC_TYPE)
static av_cold int init_buffers(MPVMainEncContext *const m)
static av_always_inline void encode_mb_internal(MPVEncContext *const s, int motion_x, int motion_y, int mb_block_height, int mb_block_width, int mb_block_count, int chroma_x_shift, int chroma_y_shift, int chroma_format)
static void write_mb_info(MPVEncContext *const s)
static void init_qscale_tab(MPVEncContext *const s)
init s->c.cur_pic.qscale_table from s->lambda_table
void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix)
static void frame_end(MPVMainEncContext *const m)
static int select_input_picture(MPVMainEncContext *const m)
#define COPY(a)
static int encode_thread(AVCodecContext *c, void *arg)
static void denoise_dct(MPVEncContext *const s, int16_t block[])
av_cold int ff_mpv_encode_end(AVCodecContext *avctx)
#define INTERLACED_DCT(s)
static int get_sae(const uint8_t *src, int ref, int stride)
static int estimate_qp(MPVMainEncContext *const m, int dry_run)
static void update_qscale(MPVMainEncContext *const m)
static int load_input_picture(MPVMainEncContext *const m, const AVFrame *pic_arg)
static av_cold int init_slice_buffers(MPVMainEncContext *const m)
static void frame_start(MPVMainEncContext *const m)
static void set_frame_distances(MPVEncContext *const s)
#define QMAT_SHIFT
#define ff_mpv_unquantize_init(s, bitexact, q_scale_type)
const uint8_t ff_mpeg2_non_linear_qscale[32]
const uint8_t ff_mpeg12_dc_scale_table[4][32]
static const uint8_t *const ff_mpeg1_dc_scale_table
mpegvideo header.
static int get_bits_diff(MPVEncContext *s)
#define CANDIDATE_MB_TYPE_INTRA
#define MPVENC_MAX_B_FRAMES
#define FF_MPV_FLAG_CBP_RD
#define CANDIDATE_MB_TYPE_BACKWARD
#define CANDIDATE_MB_TYPE_FORWARD_I
#define CANDIDATE_MB_TYPE_INTER_I
#define CANDIDATE_MB_TYPE_BIDIR_I
#define CANDIDATE_MB_TYPE_BACKWARD_I
#define CANDIDATE_MB_TYPE_SKIPPED
#define CANDIDATE_MB_TYPE_INTER
#define CANDIDATE_MB_TYPE_DIRECT
#define CANDIDATE_MB_TYPE_BIDIR
#define CANDIDATE_MB_TYPE_FORWARD
void ff_dct_encode_init_x86(MPVEncContext *s)
#define FF_MPV_FLAG_QP_RD
#define UNI_AC_ENC_INDEX(run, level)
#define CANDIDATE_MB_TYPE_INTER4V
#define FF_MPV_COMMON_OPTS
#define CANDIDATE_MB_TYPE_DIRECT0
#define INPLACE_OFFSET
#define FF_MPV_FLAG_SKIP_RD
#define FF_MPV_COMMON_MOTION_EST_OPTS
#define FF_MPV_FLAG_STRICT_GOP
#define BASIS_SHIFT
#define EDGE_BOTTOM
#define RECON_SHIFT
#define EDGE_TOP
void ff_msmpeg4_encode_ext_header(MPVEncContext *const s)
Definition msmpeg4enc.c:285
av_cold void ff_msmpeg4_encode_init(MPVMainEncContext *const m)
Definition msmpeg4enc.c:673
enum AVPixelFormat pix
Definition ohcodec.c:55
AVOptions.
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition pixfmt.h:73
@ AV_PIX_FMT_YUV422P
planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
Definition pixfmt.h:77
@ AV_PIX_FMT_YUV444P
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
Definition pixfmt.h:78
@ AV_PIX_FMT_YUVJ422P
planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV422P and setting col...
Definition pixfmt.h:86
@ AV_PIX_FMT_YUVJ444P
planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV444P and setting col...
Definition pixfmt.h:87
@ AV_PIX_FMT_YUVJ420P
planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV420P and setting col...
Definition pixfmt.h:85
static void init_put_bits(PutBitContext *s, uint8_t *buffer, int buffer_size)
Initialize the PutBitContext s.
Definition put_bits.h:62
static void rebase_put_bits(PutBitContext *s, uint8_t *buffer, int buffer_size)
Rebase the bit writer onto a reallocated buffer.
Definition put_bits.h:122
static void set_put_bits_buffer_size(PutBitContext *s, int size)
Change the end of the buffer.
Definition put_bits.h:436
static int put_bits_count(PutBitContext *s)
Definition put_bits.h:90
static uint8_t * put_bits_ptr(PutBitContext *s)
Return the pointer to the byte where the bitstream writer will put the next bit.
Definition put_bits.h:402
static int put_bytes_count(const PutBitContext *s, int round_up)
Definition put_bits.h:110
static int put_bytes_left(const PutBitContext *s, int round_up)
Definition put_bits.h:145
static void flush_put_bits(PutBitContext *s)
Pad the end of the output stream with zeros.
Definition put_bits.h:153
#define BUF_BITS
Definition put_bits.h:47
quarterpel DSP functions
void(* qpel_mc_func)(uint8_t *dst, const uint8_t *src, ptrdiff_t stride)
Definition qpeldsp.h:65
void ff_write_pass1_stats(MPVMainEncContext *const m)
Definition ratecontrol.c:37
void ff_get_2pass_fcode(MPVMainEncContext *const m)
av_cold void ff_rate_control_uninit(RateControlContext *rcc)
float ff_rate_estimate_qscale(MPVMainEncContext *const m, int dry_run)
int ff_vbv_update(MPVMainEncContext *m, int frame_size)
av_cold int ff_rate_control_init(MPVMainEncContext *const m)
void av_refstruct_unref(void *objp)
Decrement the reference count of the underlying object and automatically free the object if there are...
Definition refstruct.c:121
void * av_refstruct_pool_get(AVRefStructPool *pool)
Get an object from the pool, reusing an old one from the pool when available.
Definition refstruct.c:315
static void av_refstruct_pool_uninit(AVRefStructPool **poolp)
Mark the pool as being available for freeing.
Definition refstruct.h:292
const h264_weight_func weight
int ff_rv20_encode_picture_header(MPVMainEncContext *const m)
Definition rv20enc.c:37
#define FF_ARRAY_ELEMS(a)
static const uint8_t sp5x_qscale_five_quant_table[][64]
Definition sp5x.h:135
void ff_speedhq_end_slice(MPVEncContext *const s)
Definition speedhqenc.c:118
SpeedHQ encoder.
static int ff_speedhq_mb_y_order_to_mb(int mb_y_order, int mb_height, int *first_in_slice)
Definition speedhqenc.h:41
This structure describes the bitrate properties of an encoded bitstream.
Definition defs.h:296
int64_t avg_bitrate
Average bitrate of the stream, in bits per second.
Definition defs.h:311
int64_t max_bitrate
Maximum bitrate of the stream, in bits per second.
Definition defs.h:301
int64_t buffer_size
The size of the buffer to which the ratecontrol is applied, in bits.
Definition defs.h:317
uint64_t vbv_delay
The delay between the time the packet this structure is associated with is received and the time when...
Definition defs.h:326
int64_t min_bitrate
Minimum bitrate of the stream, in bits per second.
Definition defs.h:306
Describe the class of an AVClass context structure.
Definition log.h:76
main external API structure.
Definition avcodec.h:443
float rc_max_available_vbv_use
Ratecontrol attempt to use, at maximum, of what can be used without an underflow.
Definition avcodec.h:1302
int trellis
trellis RD quantization
Definition avcodec.h:1323
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition avcodec.h:643
int width
picture width / height.
Definition avcodec.h:604
char * stats_out
pass1 encoding statistics output buffer
Definition avcodec.h:1330
int rc_buffer_size
decoder bitstream buffer size
Definition avcodec.h:1273
int strict_std_compliance
strictly follow the standard (MPEG-4, ...).
Definition avcodec.h:1376
int max_b_frames
maximum number of B-frames between non-B-frames Note: The output will be delayed by max_b_frames+1 re...
Definition avcodec.h:781
int qmin
minimum quantizer
Definition avcodec.h:1252
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition avcodec.h:628
uint16_t * inter_matrix
custom inter quantization matrix Must be allocated with the av_malloc() family of functions,...
Definition avcodec.h:969
int bit_rate_tolerance
number of bits the bitstream is allowed to diverge from the reference.
Definition avcodec.h:1227
int mb_decision
macroblock decision mode
Definition avcodec.h:948
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition avcodec.h:709
int64_t bit_rate
the average bitrate
Definition avcodec.h:493
const struct AVCodec * codec
Definition avcodec.h:452
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition avcodec.h:1576
float temporal_cplx_masking
temporary complexity masking (0-> disabled)
Definition avcodec.h:827
float p_masking
p block masking (0-> disabled)
Definition avcodec.h:841
int delay
Codec delay.
Definition avcodec.h:587
float dark_masking
darkness masking (0-> disabled)
Definition avcodec.h:848
int mb_cmp
macroblock comparison function (not supported yet)
Definition avcodec.h:874
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
Definition avcodec.h:1021
int ildct_cmp
interlaced DCT comparison function
Definition avcodec.h:880
int64_t rc_max_rate
maximum bitrate
Definition avcodec.h:1288
int qmax
maximum quantizer
Definition avcodec.h:1259
uint16_t * intra_matrix
custom intra quantization matrix Must be allocated with the av_malloc() family of functions,...
Definition avcodec.h:960
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avcodec.h:547
int flags
AV_CODEC_FLAG_*.
Definition avcodec.h:500
int64_t rc_min_rate
minimum bitrate
Definition avcodec.h:1295
uint64_t error[AV_NUM_DATA_POINTERS]
error
Definition avcodec.h:1524
enum AVCodecID codec_id
Definition avcodec.h:453
float lumi_masking
luminance masking (0-> disabled)
Definition avcodec.h:820
struct AVCodecInternal * internal
Private context used for internal data.
Definition avcodec.h:478
void * priv_data
Definition avcodec.h:470
float spatial_cplx_masking
spatial complexity masking (0-> disabled)
Definition avcodec.h:834
int slices
Number of slices.
Definition avcodec.h:1037
unsigned int byte_buffer_size
Definition internal.h:96
uint8_t * byte_buffer
temporary buffer used for encoders to store their bitstream
Definition internal.h:95
enum AVCodecID id
Definition codec.h:189
int capabilities
Codec capabilities.
Definition codec.h:194
This structure describes decoded (raw) audio or video data.
Definition frame.h:479
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition frame.h:581
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition frame.h:500
int width
Definition frame.h:551
int height
Definition frame.h:551
int quality
quality (between 1 (good) and FF_LAMBDA_MAX (bad))
Definition frame.h:601
int linesize[AV_NUM_DATA_POINTERS]
For video, a positive or negative value, which is typically indicating the size in bytes of each pict...
Definition frame.h:524
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
Definition frame.h:566
enum AVPictureType pict_type
Picture type of the frame.
Definition frame.h:571
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:580
int num
Numerator.
Definition rational.h:59
int den
Denominator.
Definition rational.h:60
void(* fdct)(int16_t *block)
Definition fdctdsp.h:29
int block_last_index[8]
int last_dc[3]
int16_t(* block)[64]
int esc3_level_length
PutBitContext pb
int mv[2][4][2]
int last_mv[2][2][2]
PutBitContext tex_pb
struct MBBackup::@342113007365243263012337326261363212055053105164 c
PutBitContext pb2
int(* sum_abs_dctelem)(const int16_t *block)
Definition me_cmp.h:51
me_cmp_func sad[6]
Definition me_cmp.h:53
me_cmp_func sse[6]
Definition me_cmp.h:54
me_cmp_func nsse[6]
Definition me_cmp.h:62
int(* dct_error_sum)[64]
MotionEstContext me
PutBitContext pb
bit output
MpegEncContext c
the common base context
uint16_t(* dct_offset)[64]
unsigned int lambda
Lagrange multiplier used in rate distortion.
int16_t(* block)[64]
points into blocks below
unsigned int lambda2
(lambda*lambda) >> FF_LAMBDA_SHIFT
int max_b_frames
max number of B-frames
int frame_bits
bits used for the current frame
int stuffing_bits
bits used for stuffing
MPVEncContext s
The main slicecontext.
RateControlContext rc_context
contains stuff only accessed in ratecontrol.c
int16_t(* mv_table_base)[2]
int vbv_delay_pos
offset of vbv_delay in the bitstream
int last_non_b_pict_type
used for MPEG-4 gmc B-frames & ratecontrol
int64_t mc_mb_var_sum
motion compensated MB variance for current frame
int last_lambda_for[5]
last lambda for a specific pict type
int64_t dts_delta
pts difference between the first and second input frame, used for calculating dts of the first frame ...
const uint8_t * fcode_tab
smallest fcode needed for each MV
int64_t mb_var_sum
sum of MB variance for current frame
char * dct_error_sum_base
backs dct_error_sum
AVFrame * tmp_frames[MPVENC_MAX_B_FRAMES+2]
temporary frames used by b_frame_strategy = 2
int picture_in_gop_number
0-> first pic in gop, ...
int coded_picture_number
used to set pic->coded_picture_number
int fixed_qscale
fixed qscale if non zero
int next_lambda
next lambda used for retrying to encode a frame
int64_t user_specified_pts
last non-zero pts from user-supplied AVFrame
int input_picture_number
used to set pic->display_picture_number
int64_t reordered_pts
reordered pts to be used as dts for the next output frame when there's a delay
MPVPicture * reordered_input_picture[MPVENC_MAX_B_FRAMES+1]
next pictures in coded order
MPVPicture * input_picture[MPVENC_MAX_B_FRAMES+1]
next pictures in display order
me_cmp_func frame_skip_cmp_fn
int intra_only
if true, only intra pictures are generated
int me_pre
prepass for motion estimation
int(* encode_picture_header)(struct MPVMainEncContext *m)
MPVPicture.
Definition mpegpicture.h:58
int b_frame_score
Definition mpegpicture.h:84
struct AVFrame * f
Definition mpegpicture.h:59
int display_picture_number
Definition mpegpicture.h:89
int coded_picture_number
Definition mpegpicture.h:90
void(* dct_unquantize_mpeg2_intra)(const MPVContext *s, int16_t *block, int n, int qscale)
void(* dct_unquantize_mpeg1_intra)(const MPVContext *s, int16_t *block, int n, int qscale)
void(* dct_unquantize_mpeg2_inter)(const MPVContext *s, int16_t *block, int n, int qscale)
void(* dct_unquantize_h263_inter)(const MPVContext *s, int16_t *block, int n, int qscale)
void(* dct_unquantize_h263_intra)(const MPVContext *s, int16_t *block, int n, int qscale)
void(* dct_unquantize_mpeg1_inter)(const MPVContext *s, int16_t *block, int n, int qscale)
uint8_t * scratchpad
data area for the ME algo, so that the ME does not need to malloc/free.
Definition motion_est.h:55
uint8_t * temp
Definition motion_est.h:57
MpegEncContext.
Definition mpegvideo.h:67
int16_t * dc_val
used for H.263 AIC/MPEG-4 DC prediction and ER
Definition mpegvideo.h:141
ScratchpadContext sc
Definition mpegvideo.h:150
int start_mb_y
start mb_y of this thread (so current thread should process start_mb_y <= row < end_mb_y)
Definition mpegvideo.h:107
int16_t(* ac_val)[16]
used for H.263 AIC, MPEG-4 AC prediction
Definition mpegvideo.h:142
rate control context.
Definition ratecontrol.h:60
RateControlEntry * entry
Definition ratecontrol.h:62
double buffer_index
amount of bits in the video/audio buffer
Definition ratecontrol.h:63
int num_entries
number of RateControlEntries
Definition ratecontrol.h:61
uint8_t * scratchpad_buf
the other *_scratchpad point into this buffer
Definition mpegpicture.h:38
uint8_t run
Definition svq3.c:207
uint8_t level
Definition svq3.c:208
#define stride
#define av_free(p)
#define av_mallocz(s)
#define ff_dlog(a,...)
#define av_freep(p)
#define av_log(a,...)
#define src1
Definition h264pred.c:141
#define src
Definition vp8dsp.c:248
static int ref[MAX_W *MAX_W]
#define height
Definition dsp.h:89
#define width
Definition dsp.h:89
static int64_t pts
int size
static const struct twinvq_data tab
#define me
const char * g
Definition vf_curves.c:128
else temp
Definition vf_mcdeint.c:275
static float mean(const float *input, int size)
Definition vf_nnedi.c:861
static const double coeff[2][5]
static av_always_inline int diff(const struct color_info *a, const struct color_info *b, const int trans_thresh)
static const uint8_t quality[]
Definition vmixdec.c:58
static int bias(int x, int c)
Definition vqcdec.c:115
static double c[64]