Coverage Report

Created: 2025-08-28 07:12

/src/libvpx/vp8/encoder/encodeframe.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5
 *  that can be found in the LICENSE file in the root of the source
6
 *  tree. An additional intellectual property rights grant can be found
7
 *  in the file PATENTS.  All contributing project authors may
8
 *  be found in the AUTHORS file in the root of the source tree.
9
 */
10
#include <limits.h>
11
#include <stdio.h>
12
13
#include "vpx_config.h"
14
15
#include "vp8/common/common.h"
16
#include "vp8/common/entropymode.h"
17
#include "vp8/common/extend.h"
18
#include "vp8/common/invtrans.h"
19
#include "vp8/common/quant_common.h"
20
#include "vp8/common/reconinter.h"
21
#include "vp8/common/setupintrarecon.h"
22
#include "vp8/common/threading.h"
23
#include "vp8/encoder/bitstream.h"
24
#include "vp8/encoder/encodeframe.h"
25
#include "vp8/encoder/encodeintra.h"
26
#include "vp8/encoder/encodemb.h"
27
#include "vp8/encoder/onyx_int.h"
28
#include "vp8/encoder/pickinter.h"
29
#include "vp8/encoder/rdopt.h"
30
#include "vp8_rtcd.h"
31
#include "vpx/internal/vpx_codec_internal.h"
32
#include "vpx_dsp_rtcd.h"
33
#include "vpx_mem/vpx_mem.h"
34
#include "vpx_ports/vpx_timer.h"
35
36
#if CONFIG_MULTITHREAD
37
#include "vp8/encoder/ethreading.h"
38
#endif
39
40
extern void vp8_stuff_mb(VP8_COMP *cpi, MACROBLOCK *x, TOKENEXTRA **t);
41
static void adjust_act_zbin(VP8_COMP *cpi, MACROBLOCK *x);
42
43
#ifdef MODE_STATS
44
unsigned int inter_y_modes[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
45
unsigned int inter_uv_modes[4] = { 0, 0, 0, 0 };
46
unsigned int inter_b_modes[15] = {
47
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
48
};
49
unsigned int y_modes[5] = { 0, 0, 0, 0, 0 };
50
unsigned int uv_modes[4] = { 0, 0, 0, 0 };
51
unsigned int b_modes[14] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
52
#endif
53
54
/* activity_avg must be positive, or flat regions could get a zero weight
55
 *  (infinite lambda), which confounds analysis.
56
 * This also avoids the need for divide by zero checks in
57
 *  vp8_activity_masking().
58
 */
59
0
#define VP8_ACTIVITY_AVG_MIN (64)
60
61
/* This is used as a reference when computing the source variance for the
62
 *  purposes of activity masking.
63
 * Eventually this should be replaced by custom no-reference routines,
64
 *  which will be faster.
65
 */
66
static const unsigned char VP8_VAR_OFFS[16] = { 128, 128, 128, 128, 128, 128,
67
                                                128, 128, 128, 128, 128, 128,
68
                                                128, 128, 128, 128 };
69
70
/* Original activity measure from Tim T's code. */
71
0
static unsigned int tt_activity_measure(MACROBLOCK *x) {
72
0
  unsigned int act;
73
0
  unsigned int sse;
74
0
  /* TODO: This could also be done over smaller areas (8x8), but that would
75
0
   *  require extensive changes elsewhere, as lambda is assumed to be fixed
76
0
   *  over an entire MB in most of the code.
77
0
   * Another option is to compute four 8x8 variances, and pick a single
78
0
   *  lambda using a non-linear combination (e.g., the smallest, or second
79
0
   *  smallest, etc.).
80
0
   */
81
0
  act = vpx_variance16x16(x->src.y_buffer, x->src.y_stride, VP8_VAR_OFFS, 0,
82
0
                          &sse);
83
0
  act = act << 4;
84
0
85
0
  /* If the region is flat, lower the activity some more. */
86
0
  if (act < 8 << 12) act = act < 5 << 12 ? act : 5 << 12;
87
0
88
0
  return act;
89
0
}
90
91
/* Measure the activity of the current macroblock
92
 * What we measure here is TBD so abstracted to this function
93
 */
94
0
#define ALT_ACT_MEASURE 1
95
0
static unsigned int mb_activity_measure(MACROBLOCK *x, int mb_row, int mb_col) {
96
0
  unsigned int mb_activity;
97
98
0
  if (ALT_ACT_MEASURE) {
99
0
    int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
100
101
    /* Or use an alternative. */
102
0
    mb_activity = vp8_encode_intra(x, use_dc_pred);
103
0
  } else {
104
    /* Original activity measure from Tim T's code. */
105
0
    mb_activity = tt_activity_measure(x);
106
0
  }
107
108
0
  if (mb_activity < VP8_ACTIVITY_AVG_MIN) mb_activity = VP8_ACTIVITY_AVG_MIN;
109
110
0
  return mb_activity;
111
0
}
112
113
/* Calculate an "average" mb activity value for the frame */
114
#define ACT_MEDIAN 0
115
0
static void calc_av_activity(VP8_COMP *cpi, int64_t activity_sum) {
116
#if ACT_MEDIAN
117
  /* Find median: Simple n^2 algorithm for experimentation */
118
  {
119
    unsigned int median;
120
    unsigned int i, j;
121
    unsigned int *sortlist;
122
    unsigned int tmp;
123
124
    /* Create a list to sort to */
125
    CHECK_MEM_ERROR(&cpi->common.error, sortlist,
126
                    vpx_calloc(sizeof(unsigned int), cpi->common.MBs));
127
128
    /* Copy map to sort list */
129
    memcpy(sortlist, cpi->mb_activity_map,
130
           sizeof(unsigned int) * cpi->common.MBs);
131
132
    /* Ripple each value down to its correct position */
133
    for (i = 1; i < cpi->common.MBs; ++i) {
134
      for (j = i; j > 0; j--) {
135
        if (sortlist[j] < sortlist[j - 1]) {
136
          /* Swap values */
137
          tmp = sortlist[j - 1];
138
          sortlist[j - 1] = sortlist[j];
139
          sortlist[j] = tmp;
140
        } else
141
          break;
142
      }
143
    }
144
145
    /* Even number MBs so estimate median as mean of two either side. */
146
    median = (1 + sortlist[cpi->common.MBs >> 1] +
147
              sortlist[(cpi->common.MBs >> 1) + 1]) >>
148
             1;
149
150
    cpi->activity_avg = median;
151
152
    vpx_free(sortlist);
153
  }
154
#else
155
  /* Simple mean for now */
156
0
  cpi->activity_avg = (unsigned int)(activity_sum / cpi->common.MBs);
157
0
#endif
158
159
0
  if (cpi->activity_avg < VP8_ACTIVITY_AVG_MIN) {
160
0
    cpi->activity_avg = VP8_ACTIVITY_AVG_MIN;
161
0
  }
162
163
  /* Experimental code: return fixed value normalized for several clips */
164
0
  if (ALT_ACT_MEASURE) cpi->activity_avg = 100000;
165
0
}
166
167
#define USE_ACT_INDEX 0
168
#define OUTPUT_NORM_ACT_STATS 0
169
170
#if USE_ACT_INDEX
171
/* Calculate and activity index for each mb */
172
static void calc_activity_index(VP8_COMP *cpi, MACROBLOCK *x) {
173
  VP8_COMMON *const cm = &cpi->common;
174
  int mb_row, mb_col;
175
176
  int64_t act;
177
  int64_t a;
178
  int64_t b;
179
180
#if OUTPUT_NORM_ACT_STATS
181
  FILE *f = fopen("norm_act.stt", "a");
182
  fprintf(f, "\n%12d\n", cpi->activity_avg);
183
#endif
184
185
  /* Reset pointers to start of activity map */
186
  x->mb_activity_ptr = cpi->mb_activity_map;
187
188
  /* Calculate normalized mb activity number. */
189
  for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
190
    /* for each macroblock col in image */
191
    for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
192
      /* Read activity from the map */
193
      act = *(x->mb_activity_ptr);
194
195
      /* Calculate a normalized activity number */
196
      a = act + 4 * cpi->activity_avg;
197
      b = 4 * act + cpi->activity_avg;
198
199
      if (b >= a)
200
        *(x->activity_ptr) = (int)((b + (a >> 1)) / a) - 1;
201
      else
202
        *(x->activity_ptr) = 1 - (int)((a + (b >> 1)) / b);
203
204
#if OUTPUT_NORM_ACT_STATS
205
      fprintf(f, " %6d", *(x->mb_activity_ptr));
206
#endif
207
      /* Increment activity map pointers */
208
      x->mb_activity_ptr++;
209
    }
210
211
#if OUTPUT_NORM_ACT_STATS
212
    fprintf(f, "\n");
213
#endif
214
  }
215
216
#if OUTPUT_NORM_ACT_STATS
217
  fclose(f);
218
#endif
219
}
220
#endif
221
222
/* Loop through all MBs. Note activity of each, average activity and
223
 * calculate a normalized activity for each
224
 */
225
0
static void build_activity_map(VP8_COMP *cpi) {
226
0
  MACROBLOCK *const x = &cpi->mb;
227
0
  MACROBLOCKD *xd = &x->e_mbd;
228
0
  VP8_COMMON *const cm = &cpi->common;
229
230
0
#if ALT_ACT_MEASURE
231
0
  YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
232
0
  int recon_yoffset;
233
0
  int recon_y_stride = new_yv12->y_stride;
234
0
#endif
235
236
0
  int mb_row, mb_col;
237
0
  unsigned int mb_activity;
238
0
  int64_t activity_sum = 0;
239
240
  /* for each macroblock row in image */
241
0
  for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
242
0
#if ALT_ACT_MEASURE
243
    /* reset above block coeffs */
244
0
    xd->up_available = (mb_row != 0);
245
0
    recon_yoffset = (mb_row * recon_y_stride * 16);
246
0
#endif
247
    /* for each macroblock col in image */
248
0
    for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
249
0
#if ALT_ACT_MEASURE
250
0
      xd->dst.y_buffer = new_yv12->y_buffer + recon_yoffset;
251
0
      xd->left_available = (mb_col != 0);
252
0
      recon_yoffset += 16;
253
0
#endif
254
      /* Copy current mb to a buffer */
255
0
      vp8_copy_mem16x16(x->src.y_buffer, x->src.y_stride, x->thismb, 16);
256
257
      /* measure activity */
258
0
      mb_activity = mb_activity_measure(x, mb_row, mb_col);
259
260
      /* Keep frame sum */
261
0
      activity_sum += mb_activity;
262
263
      /* Store MB level activity details. */
264
0
      *x->mb_activity_ptr = mb_activity;
265
266
      /* Increment activity map pointer */
267
0
      x->mb_activity_ptr++;
268
269
      /* adjust to the next column of source macroblocks */
270
0
      x->src.y_buffer += 16;
271
0
    }
272
273
    /* adjust to the next row of mbs */
274
0
    x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
275
276
0
#if ALT_ACT_MEASURE
277
    /* extend the recon for intra prediction */
278
0
    vp8_extend_mb_row(new_yv12, xd->dst.y_buffer + 16, xd->dst.u_buffer + 8,
279
0
                      xd->dst.v_buffer + 8);
280
0
#endif
281
0
  }
282
283
  /* Calculate an "average" MB activity */
284
0
  calc_av_activity(cpi, activity_sum);
285
286
#if USE_ACT_INDEX
287
  /* Calculate an activity index number of each mb */
288
  calc_activity_index(cpi, x);
289
#endif
290
0
}
291
292
/* Macroblock activity masking */
293
0
void vp8_activity_masking(VP8_COMP *cpi, MACROBLOCK *x) {
294
#if USE_ACT_INDEX
295
  x->rdmult += *(x->mb_activity_ptr) * (x->rdmult >> 2);
296
  x->errorperbit = x->rdmult * 100 / (110 * x->rddiv);
297
  x->errorperbit += (x->errorperbit == 0);
298
#else
299
0
  int64_t a;
300
0
  int64_t b;
301
0
  int64_t act = *(x->mb_activity_ptr);
302
303
  /* Apply the masking to the RD multiplier. */
304
0
  a = act + (2 * cpi->activity_avg);
305
0
  b = (2 * act) + cpi->activity_avg;
306
307
0
  x->rdmult = (unsigned int)(((int64_t)x->rdmult * b + (a >> 1)) / a);
308
0
  x->errorperbit = x->rdmult * 100 / (110 * x->rddiv);
309
0
  x->errorperbit += (x->errorperbit == 0);
310
0
#endif
311
312
  /* Activity based Zbin adjustment */
313
0
  adjust_act_zbin(cpi, x);
314
0
}
315
316
static void encode_mb_row(VP8_COMP *cpi, VP8_COMMON *cm, int mb_row,
317
                          MACROBLOCK *x, MACROBLOCKD *xd, TOKENEXTRA **tp,
318
549k
                          int *segment_counts, int *totalrate) {
319
549k
  int recon_yoffset, recon_uvoffset;
320
549k
  int mb_col;
321
549k
  int ref_fb_idx = cm->lst_fb_idx;
322
549k
  int dst_fb_idx = cm->new_fb_idx;
323
549k
  int recon_y_stride = cm->yv12_fb[ref_fb_idx].y_stride;
324
549k
  int recon_uv_stride = cm->yv12_fb[ref_fb_idx].uv_stride;
325
549k
  int map_index = (mb_row * cpi->common.mb_cols);
326
327
#if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
328
  const int num_part = (1 << cm->multi_token_partition);
329
  TOKENEXTRA *tp_start = cpi->tok;
330
  vp8_writer *w;
331
#endif
332
333
549k
#if CONFIG_MULTITHREAD
334
549k
  const int nsync = cpi->mt_sync_range;
335
549k
  vpx_atomic_int rightmost_col = VPX_ATOMIC_INIT(cm->mb_cols + nsync);
336
549k
  const vpx_atomic_int *last_row_current_mb_col;
337
549k
  vpx_atomic_int *current_mb_col = NULL;
338
339
549k
  if (vpx_atomic_load_acquire(&cpi->b_multi_threaded) != 0) {
340
0
    current_mb_col = &cpi->mt_current_mb_col[mb_row];
341
0
  }
342
549k
  if (vpx_atomic_load_acquire(&cpi->b_multi_threaded) != 0 && mb_row != 0) {
343
0
    last_row_current_mb_col = &cpi->mt_current_mb_col[mb_row - 1];
344
549k
  } else {
345
549k
    last_row_current_mb_col = &rightmost_col;
346
549k
  }
347
549k
#endif
348
349
#if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
350
  if (num_part > 1)
351
    w = &cpi->bc[1 + (mb_row % num_part)];
352
  else
353
    w = &cpi->bc[1];
354
#endif
355
356
  /* reset above block coeffs */
357
549k
  xd->above_context = cm->above_context;
358
359
549k
  xd->up_available = (mb_row != 0);
360
549k
  recon_yoffset = (mb_row * recon_y_stride * 16);
361
549k
  recon_uvoffset = (mb_row * recon_uv_stride * 8);
362
363
549k
  cpi->tplist[mb_row].start = *tp;
364
  /* printf("Main mb_row = %d\n", mb_row); */
365
366
  /* Distance of Mb to the top & bottom edges, specified in 1/8th pel
367
   * units as they are always compared to values that are in 1/8th pel
368
   */
369
549k
  xd->mb_to_top_edge = -((mb_row * 16) << 3);
370
549k
  xd->mb_to_bottom_edge = ((cm->mb_rows - 1 - mb_row) * 16) << 3;
371
372
  /* Set up limit values for vertical motion vector components
373
   * to prevent them extending beyond the UMV borders
374
   */
375
549k
  x->mv_row_min = -((mb_row * 16) + (VP8BORDERINPIXELS - 16));
376
549k
  x->mv_row_max = ((cm->mb_rows - 1 - mb_row) * 16) + (VP8BORDERINPIXELS - 16);
377
378
  /* Set the mb activity pointer to the start of the row. */
379
549k
  x->mb_activity_ptr = &cpi->mb_activity_map[map_index];
380
381
  /* for each macroblock col in image */
382
3.52M
  for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
383
#if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
384
    *tp = cpi->tok;
385
#endif
386
    /* Distance of Mb to the left & right edges, specified in
387
     * 1/8th pel units as they are always compared to values
388
     * that are in 1/8th pel units
389
     */
390
2.97M
    xd->mb_to_left_edge = -((mb_col * 16) << 3);
391
2.97M
    xd->mb_to_right_edge = ((cm->mb_cols - 1 - mb_col) * 16) << 3;
392
393
    /* Set up limit values for horizontal motion vector components
394
     * to prevent them extending beyond the UMV borders
395
     */
396
2.97M
    x->mv_col_min = -((mb_col * 16) + (VP8BORDERINPIXELS - 16));
397
2.97M
    x->mv_col_max =
398
2.97M
        ((cm->mb_cols - 1 - mb_col) * 16) + (VP8BORDERINPIXELS - 16);
399
400
2.97M
    xd->dst.y_buffer = cm->yv12_fb[dst_fb_idx].y_buffer + recon_yoffset;
401
2.97M
    xd->dst.u_buffer = cm->yv12_fb[dst_fb_idx].u_buffer + recon_uvoffset;
402
2.97M
    xd->dst.v_buffer = cm->yv12_fb[dst_fb_idx].v_buffer + recon_uvoffset;
403
2.97M
    xd->left_available = (mb_col != 0);
404
405
2.97M
    x->rddiv = cpi->RDDIV;
406
2.97M
    x->rdmult = cpi->RDMULT;
407
408
    /* Copy current mb to a buffer */
409
2.97M
    vp8_copy_mem16x16(x->src.y_buffer, x->src.y_stride, x->thismb, 16);
410
411
2.97M
#if CONFIG_MULTITHREAD
412
2.97M
    if (vpx_atomic_load_acquire(&cpi->b_multi_threaded) != 0) {
413
0
      if (((mb_col - 1) % nsync) == 0) {
414
0
        vpx_atomic_store_release(current_mb_col, mb_col - 1);
415
0
      }
416
417
0
      if (mb_row && !(mb_col & (nsync - 1))) {
418
0
        vp8_atomic_spin_wait(mb_col, last_row_current_mb_col, nsync);
419
0
      }
420
0
    }
421
2.97M
#endif
422
423
2.97M
    if (cpi->oxcf.tuning == VP8_TUNE_SSIM) vp8_activity_masking(cpi, x);
424
425
    /* Is segmentation enabled */
426
    /* MB level adjustment to quantizer */
427
2.97M
    if (xd->segmentation_enabled) {
428
      /* Code to set segment id in xd->mbmi.segment_id for current MB
429
       * (with range checking)
430
       */
431
0
      if (cpi->segmentation_map[map_index + mb_col] <= 3) {
432
0
        xd->mode_info_context->mbmi.segment_id =
433
0
            cpi->segmentation_map[map_index + mb_col];
434
0
      } else {
435
0
        xd->mode_info_context->mbmi.segment_id = 0;
436
0
      }
437
438
0
      vp8cx_mb_init_quantizer(cpi, x, 1);
439
2.97M
    } else {
440
      /* Set to Segment 0 by default */
441
2.97M
      xd->mode_info_context->mbmi.segment_id = 0;
442
2.97M
    }
443
444
2.97M
    x->active_ptr = cpi->active_map + map_index + mb_col;
445
446
2.97M
    if (cm->frame_type == KEY_FRAME) {
447
1.42M
      const int intra_rate_cost = vp8cx_encode_intra_macroblock(cpi, x, tp);
448
1.42M
      if (INT_MAX - *totalrate > intra_rate_cost)
449
1.42M
        *totalrate += intra_rate_cost;
450
0
      else
451
0
        *totalrate = INT_MAX;
452
#ifdef MODE_STATS
453
      y_modes[xd->mbmi.mode]++;
454
#endif
455
1.54M
    } else {
456
1.54M
      const int inter_rate_cost = vp8cx_encode_inter_macroblock(
457
1.54M
          cpi, x, tp, recon_yoffset, recon_uvoffset, mb_row, mb_col);
458
1.54M
      if (INT_MAX - *totalrate > inter_rate_cost)
459
1.54M
        *totalrate += inter_rate_cost;
460
0
      else
461
0
        *totalrate = INT_MAX;
462
463
#ifdef MODE_STATS
464
      inter_y_modes[xd->mbmi.mode]++;
465
466
      if (xd->mbmi.mode == SPLITMV) {
467
        int b;
468
469
        for (b = 0; b < xd->mbmi.partition_count; ++b) {
470
          inter_b_modes[x->partition->bmi[b].mode]++;
471
        }
472
      }
473
474
#endif
475
476
      // Keep track of how many (consecutive) times a  block is coded
477
      // as ZEROMV_LASTREF, for base layer frames.
478
      // Reset to 0 if its coded as anything else.
479
1.54M
      if (cpi->current_layer == 0) {
480
1.54M
        if (xd->mode_info_context->mbmi.mode == ZEROMV &&
481
1.54M
            xd->mode_info_context->mbmi.ref_frame == LAST_FRAME) {
482
          // Increment, check for wrap-around.
483
127k
          if (cpi->consec_zero_last[map_index + mb_col] < 255) {
484
127k
            cpi->consec_zero_last[map_index + mb_col] += 1;
485
127k
          }
486
127k
          if (cpi->consec_zero_last_mvbias[map_index + mb_col] < 255) {
487
127k
            cpi->consec_zero_last_mvbias[map_index + mb_col] += 1;
488
127k
          }
489
1.42M
        } else {
490
1.42M
          cpi->consec_zero_last[map_index + mb_col] = 0;
491
1.42M
          cpi->consec_zero_last_mvbias[map_index + mb_col] = 0;
492
1.42M
        }
493
1.54M
        if (x->zero_last_dot_suppress) {
494
782
          cpi->consec_zero_last_mvbias[map_index + mb_col] = 0;
495
782
        }
496
1.54M
      }
497
498
      /* Special case code for cyclic refresh
499
       * If cyclic update enabled then copy xd->mbmi.segment_id; (which
500
       * may have been updated based on mode during
501
       * vp8cx_encode_inter_macroblock()) back into the global
502
       * segmentation map
503
       */
504
1.54M
      if ((cpi->current_layer == 0) &&
505
1.54M
          (cpi->cyclic_refresh_mode_enabled && xd->segmentation_enabled)) {
506
0
        cpi->segmentation_map[map_index + mb_col] =
507
0
            xd->mode_info_context->mbmi.segment_id;
508
509
        /* If the block has been refreshed mark it as clean (the
510
         * magnitude of the -ve influences how long it will be before
511
         * we consider another refresh):
512
         * Else if it was coded (last frame 0,0) and has not already
513
         * been refreshed then mark it as a candidate for cleanup
514
         * next time (marked 0) else mark it as dirty (1).
515
         */
516
0
        if (xd->mode_info_context->mbmi.segment_id) {
517
0
          cpi->cyclic_refresh_map[map_index + mb_col] = -1;
518
0
        } else if ((xd->mode_info_context->mbmi.mode == ZEROMV) &&
519
0
                   (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME)) {
520
0
          if (cpi->cyclic_refresh_map[map_index + mb_col] == 1) {
521
0
            cpi->cyclic_refresh_map[map_index + mb_col] = 0;
522
0
          }
523
0
        } else {
524
0
          cpi->cyclic_refresh_map[map_index + mb_col] = 1;
525
0
        }
526
0
      }
527
1.54M
    }
528
529
2.97M
    cpi->tplist[mb_row].stop = *tp;
530
531
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
532
    /* pack tokens for this MB */
533
    {
534
      int tok_count = *tp - tp_start;
535
      vp8_pack_tokens(w, tp_start, tok_count);
536
    }
537
#endif
538
    /* Increment pointer into gf usage flags structure. */
539
2.97M
    x->gf_active_ptr++;
540
541
    /* Increment the activity mask pointers. */
542
2.97M
    x->mb_activity_ptr++;
543
544
    /* adjust to the next column of macroblocks */
545
2.97M
    x->src.y_buffer += 16;
546
2.97M
    x->src.u_buffer += 8;
547
2.97M
    x->src.v_buffer += 8;
548
549
2.97M
    recon_yoffset += 16;
550
2.97M
    recon_uvoffset += 8;
551
552
    /* Keep track of segment usage */
553
2.97M
    segment_counts[xd->mode_info_context->mbmi.segment_id]++;
554
555
    /* skip to next mb */
556
2.97M
    xd->mode_info_context++;
557
2.97M
    x->partition_info++;
558
2.97M
    xd->above_context++;
559
2.97M
  }
560
561
  /* extend the recon for intra prediction */
562
549k
  vp8_extend_mb_row(&cm->yv12_fb[dst_fb_idx], xd->dst.y_buffer + 16,
563
549k
                    xd->dst.u_buffer + 8, xd->dst.v_buffer + 8);
564
565
549k
#if CONFIG_MULTITHREAD
566
549k
  if (vpx_atomic_load_acquire(&cpi->b_multi_threaded) != 0) {
567
0
    vpx_atomic_store_release(current_mb_col,
568
0
                             vpx_atomic_load_acquire(&rightmost_col));
569
0
  }
570
549k
#endif
571
572
  /* this is to account for the border */
573
549k
  xd->mode_info_context++;
574
549k
  x->partition_info++;
575
549k
}
576
577
114k
static void init_encode_frame_mb_context(VP8_COMP *cpi) {
578
114k
  MACROBLOCK *const x = &cpi->mb;
579
114k
  VP8_COMMON *const cm = &cpi->common;
580
114k
  MACROBLOCKD *const xd = &x->e_mbd;
581
582
  /* GF active flags data structure */
583
114k
  x->gf_active_ptr = (signed char *)cpi->gf_active_flags;
584
585
  /* Activity map pointer */
586
114k
  x->mb_activity_ptr = cpi->mb_activity_map;
587
588
114k
  x->act_zbin_adj = 0;
589
590
114k
  x->partition_info = x->pi;
591
592
114k
  xd->mode_info_context = cm->mi;
593
114k
  xd->mode_info_stride = cm->mode_info_stride;
594
595
114k
  xd->frame_type = cm->frame_type;
596
597
  /* reset intra mode contexts */
598
114k
  if (cm->frame_type == KEY_FRAME) vp8_init_mbmode_probs(cm);
599
600
  /* Copy data over into macro block data structures. */
601
114k
  x->src = *cpi->Source;
602
114k
  xd->pre = cm->yv12_fb[cm->lst_fb_idx];
603
114k
  xd->dst = cm->yv12_fb[cm->new_fb_idx];
604
605
  /* set up frame for intra coded blocks */
606
114k
  vp8_setup_intra_recon(&cm->yv12_fb[cm->new_fb_idx]);
607
608
114k
  vp8_build_block_offsets(x);
609
610
114k
  xd->mode_info_context->mbmi.mode = DC_PRED;
611
114k
  xd->mode_info_context->mbmi.uv_mode = DC_PRED;
612
613
114k
  xd->left_context = &cm->left_context;
614
615
114k
  x->mvc = cm->fc.mvc;
616
617
114k
  memset(cm->above_context, 0, sizeof(ENTROPY_CONTEXT_PLANES) * cm->mb_cols);
618
619
  /* Special case treatment when GF and ARF are not sensible options
620
   * for reference
621
   */
622
114k
  if (cpi->ref_frame_flags == VP8_LAST_FRAME) {
623
28.1k
    vp8_calc_ref_frame_costs(x->ref_frame_cost, cpi->prob_intra_coded, 255,
624
28.1k
                             128);
625
85.9k
  } else if ((cpi->oxcf.number_of_layers > 1) &&
626
85.9k
             (cpi->ref_frame_flags == VP8_GOLD_FRAME)) {
627
0
    vp8_calc_ref_frame_costs(x->ref_frame_cost, cpi->prob_intra_coded, 1, 255);
628
85.9k
  } else if ((cpi->oxcf.number_of_layers > 1) &&
629
85.9k
             (cpi->ref_frame_flags == VP8_ALTR_FRAME)) {
630
0
    vp8_calc_ref_frame_costs(x->ref_frame_cost, cpi->prob_intra_coded, 1, 1);
631
85.9k
  } else {
632
85.9k
    vp8_calc_ref_frame_costs(x->ref_frame_cost, cpi->prob_intra_coded,
633
85.9k
                             cpi->prob_last_coded, cpi->prob_gf_coded);
634
85.9k
  }
635
636
114k
  xd->fullpixel_mask = ~0;
637
114k
  if (cm->full_pixel) xd->fullpixel_mask = ~7;
638
639
114k
  vp8_zero(x->coef_counts);
640
114k
  vp8_zero(x->ymode_count);
641
114k
  vp8_zero(x->uv_mode_count);
642
114k
  x->prediction_error = 0;
643
114k
  x->intra_error = 0;
644
114k
  vp8_zero(x->count_mb_ref_frame_usage);
645
114k
}
646
647
#if CONFIG_MULTITHREAD
648
0
static void sum_coef_counts(MACROBLOCK *x, MACROBLOCK *x_thread) {
649
0
  int i = 0;
650
0
  do {
651
0
    int j = 0;
652
0
    do {
653
0
      int k = 0;
654
0
      do {
655
        /* at every context */
656
657
        /* calc probs and branch cts for this frame only */
658
0
        int t = 0; /* token/prob index */
659
660
0
        do {
661
0
          x->coef_counts[i][j][k][t] += x_thread->coef_counts[i][j][k][t];
662
0
        } while (++t < ENTROPY_NODES);
663
0
      } while (++k < PREV_COEF_CONTEXTS);
664
0
    } while (++j < COEF_BANDS);
665
0
  } while (++i < BLOCK_TYPES);
666
0
}
667
#endif  // CONFIG_MULTITHREAD
668
669
114k
void vp8_encode_frame(VP8_COMP *cpi) {
670
114k
  int mb_row;
671
114k
  MACROBLOCK *const x = &cpi->mb;
672
114k
  VP8_COMMON *const cm = &cpi->common;
673
114k
  MACROBLOCKD *const xd = &x->e_mbd;
674
114k
  TOKENEXTRA *tp = cpi->tok;
675
114k
  int segment_counts[MAX_MB_SEGMENTS];
676
114k
  int totalrate;
677
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
678
  BOOL_CODER *bc = &cpi->bc[1]; /* bc[0] is for control partition */
679
  const int num_part = (1 << cm->multi_token_partition);
680
#endif
681
682
114k
  memset(segment_counts, 0, sizeof(segment_counts));
683
114k
  totalrate = 0;
684
685
114k
  if (cpi->compressor_speed == 2) {
686
43.7k
    if (cpi->oxcf.cpu_used < 0) {
687
0
      cpi->Speed = -(cpi->oxcf.cpu_used);
688
43.7k
    } else {
689
43.7k
      vp8_auto_select_speed(cpi);
690
43.7k
    }
691
43.7k
  }
692
693
  /* Functions setup for all frame types so we can use MC in AltRef */
694
114k
  if (!cm->use_bilinear_mc_filter) {
695
114k
    xd->subpixel_predict = vp8_sixtap_predict4x4;
696
114k
    xd->subpixel_predict8x4 = vp8_sixtap_predict8x4;
697
114k
    xd->subpixel_predict8x8 = vp8_sixtap_predict8x8;
698
114k
    xd->subpixel_predict16x16 = vp8_sixtap_predict16x16;
699
114k
  } else {
700
0
    xd->subpixel_predict = vp8_bilinear_predict4x4;
701
0
    xd->subpixel_predict8x4 = vp8_bilinear_predict8x4;
702
0
    xd->subpixel_predict8x8 = vp8_bilinear_predict8x8;
703
0
    xd->subpixel_predict16x16 = vp8_bilinear_predict16x16;
704
0
  }
705
706
114k
  cpi->mb.skip_true_count = 0;
707
114k
  cpi->tok_count = 0;
708
709
#if 0
710
    /* Experimental code */
711
    cpi->frame_distortion = 0;
712
    cpi->last_mb_distortion = 0;
713
#endif
714
715
114k
  xd->mode_info_context = cm->mi;
716
717
114k
  vp8_zero(cpi->mb.MVcount);
718
719
114k
  vp8cx_frame_init_quantizer(cpi);
720
721
114k
  vp8_initialize_rd_consts(cpi, x,
722
114k
                           vp8_dc_quant(cm->base_qindex, cm->y1dc_delta_q));
723
724
114k
  vp8cx_initialize_me_consts(cpi, cm->base_qindex);
725
726
114k
  if (cpi->oxcf.tuning == VP8_TUNE_SSIM) {
727
    /* Initialize encode frame context. */
728
0
    init_encode_frame_mb_context(cpi);
729
730
    /* Build a frame level activity map */
731
0
    build_activity_map(cpi);
732
0
  }
733
734
  /* re-init encode frame context. */
735
114k
  init_encode_frame_mb_context(cpi);
736
737
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
738
  {
739
    int i;
740
    for (i = 0; i < num_part; ++i) {
741
      vp8_start_encode(&bc[i], cpi->partition_d[i + 1],
742
                       cpi->partition_d_end[i + 1]);
743
      bc[i].error = &cm->error;
744
    }
745
  }
746
747
#endif
748
749
114k
  {
750
#if CONFIG_INTERNAL_STATS
751
    struct vpx_usec_timer emr_timer;
752
    vpx_usec_timer_start(&emr_timer);
753
#endif
754
755
114k
#if CONFIG_MULTITHREAD
756
114k
    if (vpx_atomic_load_acquire(&cpi->b_multi_threaded)) {
757
0
      int i;
758
759
0
      vp8cx_init_mbrthread_data(cpi, x, cpi->mb_row_ei,
760
0
                                cpi->encoding_thread_count);
761
762
0
      if (cpi->mt_current_mb_col_size != cm->mb_rows) {
763
0
        vpx_free(cpi->mt_current_mb_col);
764
0
        cpi->mt_current_mb_col = NULL;
765
0
        cpi->mt_current_mb_col_size = 0;
766
0
        CHECK_MEM_ERROR(
767
0
            &cpi->common.error, cpi->mt_current_mb_col,
768
0
            vpx_malloc(sizeof(*cpi->mt_current_mb_col) * cm->mb_rows));
769
0
        cpi->mt_current_mb_col_size = cm->mb_rows;
770
0
      }
771
0
      for (i = 0; i < cm->mb_rows; ++i)
772
0
        vpx_atomic_store_release(&cpi->mt_current_mb_col[i], -1);
773
774
0
      for (i = 0; i < cpi->encoding_thread_count; ++i) {
775
0
        vp8_sem_post(&cpi->h_event_start_encoding[i]);
776
0
      }
777
778
0
      for (mb_row = 0; mb_row < cm->mb_rows;
779
0
           mb_row += (cpi->encoding_thread_count + 1)) {
780
0
        vp8_zero(cm->left_context);
781
782
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
783
        tp = cpi->tok;
784
#else
785
0
        tp = cpi->tok + mb_row * (cm->mb_cols * 16 * 24);
786
0
#endif
787
788
0
        encode_mb_row(cpi, cm, mb_row, x, xd, &tp, segment_counts, &totalrate);
789
790
        /* adjust to the next row of mbs */
791
0
        x->src.y_buffer +=
792
0
            16 * x->src.y_stride * (cpi->encoding_thread_count + 1) -
793
0
            16 * cm->mb_cols;
794
0
        x->src.u_buffer +=
795
0
            8 * x->src.uv_stride * (cpi->encoding_thread_count + 1) -
796
0
            8 * cm->mb_cols;
797
0
        x->src.v_buffer +=
798
0
            8 * x->src.uv_stride * (cpi->encoding_thread_count + 1) -
799
0
            8 * cm->mb_cols;
800
801
0
        xd->mode_info_context +=
802
0
            xd->mode_info_stride * cpi->encoding_thread_count;
803
0
        x->partition_info += xd->mode_info_stride * cpi->encoding_thread_count;
804
0
        x->gf_active_ptr += cm->mb_cols * cpi->encoding_thread_count;
805
0
      }
806
      /* Wait for all the threads to finish. */
807
0
      for (i = 0; i < cpi->encoding_thread_count; ++i) {
808
0
        vp8_sem_wait(&cpi->h_event_end_encoding[i]);
809
0
      }
810
811
0
      for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
812
0
        cpi->tok_count += (unsigned int)(cpi->tplist[mb_row].stop -
813
0
                                         cpi->tplist[mb_row].start);
814
0
      }
815
816
0
      if (xd->segmentation_enabled) {
817
0
        int j;
818
819
0
        if (xd->segmentation_enabled) {
820
0
          for (i = 0; i < cpi->encoding_thread_count; ++i) {
821
0
            for (j = 0; j < 4; ++j) {
822
0
              segment_counts[j] += cpi->mb_row_ei[i].segment_counts[j];
823
0
            }
824
0
          }
825
0
        }
826
0
      }
827
828
0
      for (i = 0; i < cpi->encoding_thread_count; ++i) {
829
0
        int mode_count;
830
0
        int c_idx;
831
0
        totalrate += cpi->mb_row_ei[i].totalrate;
832
833
0
        cpi->mb.skip_true_count += cpi->mb_row_ei[i].mb.skip_true_count;
834
835
0
        for (mode_count = 0; mode_count < VP8_YMODES; ++mode_count) {
836
0
          cpi->mb.ymode_count[mode_count] +=
837
0
              cpi->mb_row_ei[i].mb.ymode_count[mode_count];
838
0
        }
839
840
0
        for (mode_count = 0; mode_count < VP8_UV_MODES; ++mode_count) {
841
0
          cpi->mb.uv_mode_count[mode_count] +=
842
0
              cpi->mb_row_ei[i].mb.uv_mode_count[mode_count];
843
0
        }
844
845
0
        for (c_idx = 0; c_idx < MVvals; ++c_idx) {
846
0
          cpi->mb.MVcount[0][c_idx] += cpi->mb_row_ei[i].mb.MVcount[0][c_idx];
847
0
          cpi->mb.MVcount[1][c_idx] += cpi->mb_row_ei[i].mb.MVcount[1][c_idx];
848
0
        }
849
850
0
        cpi->mb.prediction_error += cpi->mb_row_ei[i].mb.prediction_error;
851
0
        cpi->mb.intra_error += cpi->mb_row_ei[i].mb.intra_error;
852
853
0
        for (c_idx = 0; c_idx < MAX_REF_FRAMES; ++c_idx) {
854
0
          cpi->mb.count_mb_ref_frame_usage[c_idx] +=
855
0
              cpi->mb_row_ei[i].mb.count_mb_ref_frame_usage[c_idx];
856
0
        }
857
858
0
        for (c_idx = 0; c_idx < MAX_ERROR_BINS; ++c_idx) {
859
0
          cpi->mb.error_bins[c_idx] += cpi->mb_row_ei[i].mb.error_bins[c_idx];
860
0
        }
861
862
        /* add up counts for each thread */
863
0
        sum_coef_counts(x, &cpi->mb_row_ei[i].mb);
864
0
      }
865
866
0
    } else
867
114k
#endif  // CONFIG_MULTITHREAD
868
114k
    {
869
870
      /* for each macroblock row in image */
871
663k
      for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
872
549k
        vp8_zero(cm->left_context);
873
874
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
875
        tp = cpi->tok;
876
#endif
877
878
549k
        encode_mb_row(cpi, cm, mb_row, x, xd, &tp, segment_counts, &totalrate);
879
880
        /* adjust to the next row of mbs */
881
549k
        x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
882
549k
        x->src.u_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
883
549k
        x->src.v_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
884
549k
      }
885
886
114k
      cpi->tok_count = (unsigned int)(tp - cpi->tok);
887
114k
    }
888
889
#if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
890
    {
891
      int i;
892
      for (i = 0; i < num_part; ++i) {
893
        vp8_stop_encode(&bc[i]);
894
        cpi->partition_sz[i + 1] = bc[i].pos;
895
      }
896
    }
897
#endif
898
899
#if CONFIG_INTERNAL_STATS
900
    vpx_usec_timer_mark(&emr_timer);
901
    cpi->time_encode_mb_row += vpx_usec_timer_elapsed(&emr_timer);
902
#endif
903
114k
  }
904
905
  // Work out the segment probabilities if segmentation is enabled
906
  // and needs to be updated
907
114k
  if (xd->segmentation_enabled && xd->update_mb_segmentation_map) {
908
0
    int tot_count;
909
0
    int i;
910
911
    /* Set to defaults */
912
0
    memset(xd->mb_segment_tree_probs, 255, sizeof(xd->mb_segment_tree_probs));
913
914
0
    tot_count = segment_counts[0] + segment_counts[1] + segment_counts[2] +
915
0
                segment_counts[3];
916
917
0
    if (tot_count) {
918
0
      xd->mb_segment_tree_probs[0] =
919
0
          ((segment_counts[0] + segment_counts[1]) * 255) / tot_count;
920
921
0
      tot_count = segment_counts[0] + segment_counts[1];
922
923
0
      if (tot_count > 0) {
924
0
        xd->mb_segment_tree_probs[1] = (segment_counts[0] * 255) / tot_count;
925
0
      }
926
927
0
      tot_count = segment_counts[2] + segment_counts[3];
928
929
0
      if (tot_count > 0) {
930
0
        xd->mb_segment_tree_probs[2] = (segment_counts[2] * 255) / tot_count;
931
0
      }
932
933
      /* Zero probabilities not allowed */
934
0
      for (i = 0; i < MB_FEATURE_TREE_PROBS; ++i) {
935
0
        if (xd->mb_segment_tree_probs[i] == 0) xd->mb_segment_tree_probs[i] = 1;
936
0
      }
937
0
    }
938
0
  }
939
940
  /* projected_frame_size in units of BYTES */
941
114k
  cpi->projected_frame_size = totalrate >> 8;
942
943
  /* Make a note of the percentage MBs coded Intra. */
944
114k
  if (cm->frame_type == KEY_FRAME) {
945
27.7k
    cpi->this_frame_percent_intra = 100;
946
86.3k
  } else {
947
86.3k
    int tot_modes;
948
949
86.3k
    tot_modes = cpi->mb.count_mb_ref_frame_usage[INTRA_FRAME] +
950
86.3k
                cpi->mb.count_mb_ref_frame_usage[LAST_FRAME] +
951
86.3k
                cpi->mb.count_mb_ref_frame_usage[GOLDEN_FRAME] +
952
86.3k
                cpi->mb.count_mb_ref_frame_usage[ALTREF_FRAME];
953
954
86.3k
    if (tot_modes) {
955
86.3k
      cpi->this_frame_percent_intra =
956
86.3k
          cpi->mb.count_mb_ref_frame_usage[INTRA_FRAME] * 100 / tot_modes;
957
86.3k
    }
958
86.3k
  }
959
960
114k
#if !CONFIG_REALTIME_ONLY
961
  /* Adjust the projected reference frame usage probability numbers to
962
   * reflect what we have just seen. This may be useful when we make
963
   * multiple iterations of the recode loop rather than continuing to use
964
   * values from the previous frame.
965
   */
966
114k
  if ((cm->frame_type != KEY_FRAME) &&
967
114k
      ((cpi->oxcf.number_of_layers > 1) ||
968
86.3k
       (!cm->refresh_alt_ref_frame && !cm->refresh_golden_frame))) {
969
77.9k
    vp8_convert_rfct_to_prob(cpi);
970
77.9k
  }
971
114k
#endif
972
114k
}
973
7.05k
void vp8_setup_block_ptrs(MACROBLOCK *x) {
974
7.05k
  int r, c;
975
7.05k
  int i;
976
977
35.2k
  for (r = 0; r < 4; ++r) {
978
141k
    for (c = 0; c < 4; ++c) {
979
112k
      x->block[r * 4 + c].src_diff = x->src_diff + r * 4 * 16 + c * 4;
980
112k
    }
981
28.2k
  }
982
983
21.1k
  for (r = 0; r < 2; ++r) {
984
42.3k
    for (c = 0; c < 2; ++c) {
985
28.2k
      x->block[16 + r * 2 + c].src_diff = x->src_diff + 256 + r * 4 * 8 + c * 4;
986
28.2k
    }
987
14.1k
  }
988
989
21.1k
  for (r = 0; r < 2; ++r) {
990
42.3k
    for (c = 0; c < 2; ++c) {
991
28.2k
      x->block[20 + r * 2 + c].src_diff = x->src_diff + 320 + r * 4 * 8 + c * 4;
992
28.2k
    }
993
14.1k
  }
994
995
7.05k
  x->block[24].src_diff = x->src_diff + 384;
996
997
183k
  for (i = 0; i < 25; ++i) {
998
176k
    x->block[i].coeff = x->coeff + i * 16;
999
176k
  }
1000
7.05k
}
1001
1002
114k
void vp8_build_block_offsets(MACROBLOCK *x) {
1003
114k
  int block = 0;
1004
114k
  int br, bc;
1005
1006
114k
  vp8_build_block_doffsets(&x->e_mbd);
1007
1008
  /* y blocks */
1009
114k
  x->thismb_ptr = &x->thismb[0];
1010
570k
  for (br = 0; br < 4; ++br) {
1011
2.28M
    for (bc = 0; bc < 4; ++bc) {
1012
1.82M
      BLOCK *this_block = &x->block[block];
1013
1.82M
      this_block->base_src = &x->thismb_ptr;
1014
1.82M
      this_block->src_stride = 16;
1015
1.82M
      this_block->src = 4 * br * 16 + 4 * bc;
1016
1.82M
      ++block;
1017
1.82M
    }
1018
456k
  }
1019
1020
  /* u blocks */
1021
342k
  for (br = 0; br < 2; ++br) {
1022
684k
    for (bc = 0; bc < 2; ++bc) {
1023
456k
      BLOCK *this_block = &x->block[block];
1024
456k
      this_block->base_src = &x->src.u_buffer;
1025
456k
      this_block->src_stride = x->src.uv_stride;
1026
456k
      this_block->src = 4 * br * this_block->src_stride + 4 * bc;
1027
456k
      ++block;
1028
456k
    }
1029
228k
  }
1030
1031
  /* v blocks */
1032
342k
  for (br = 0; br < 2; ++br) {
1033
684k
    for (bc = 0; bc < 2; ++bc) {
1034
456k
      BLOCK *this_block = &x->block[block];
1035
456k
      this_block->base_src = &x->src.v_buffer;
1036
456k
      this_block->src_stride = x->src.uv_stride;
1037
456k
      this_block->src = 4 * br * this_block->src_stride + 4 * bc;
1038
456k
      ++block;
1039
456k
    }
1040
228k
  }
1041
114k
}
1042
1043
2.32M
static void sum_intra_stats(VP8_COMP *cpi, MACROBLOCK *x) {
1044
2.32M
  const MACROBLOCKD *xd = &x->e_mbd;
1045
2.32M
  const MB_PREDICTION_MODE m = xd->mode_info_context->mbmi.mode;
1046
2.32M
  const MB_PREDICTION_MODE uvm = xd->mode_info_context->mbmi.uv_mode;
1047
1048
#ifdef MODE_STATS
1049
  const int is_key = cpi->common.frame_type == KEY_FRAME;
1050
1051
  ++(is_key ? uv_modes : inter_uv_modes)[uvm];
1052
1053
  if (m == B_PRED) {
1054
    unsigned int *const bct = is_key ? b_modes : inter_b_modes;
1055
1056
    int b = 0;
1057
1058
    do {
1059
      ++bct[xd->block[b].bmi.mode];
1060
    } while (++b < 16);
1061
  }
1062
1063
#else
1064
2.32M
  (void)cpi;
1065
2.32M
#endif
1066
1067
2.32M
  ++x->ymode_count[m];
1068
2.32M
  ++x->uv_mode_count[uvm];
1069
2.32M
}
1070
1071
/* Experimental stub function to create a per MB zbin adjustment based on
1072
 * some previously calculated measure of MB activity.
1073
 */
1074
0
static void adjust_act_zbin(VP8_COMP *cpi, MACROBLOCK *x) {
1075
#if USE_ACT_INDEX
1076
  x->act_zbin_adj = *(x->mb_activity_ptr);
1077
#else
1078
0
  int64_t a;
1079
0
  int64_t b;
1080
0
  int64_t act = *(x->mb_activity_ptr);
1081
1082
  /* Apply the masking to the RD multiplier. */
1083
0
  a = act + 4 * cpi->activity_avg;
1084
0
  b = 4 * act + cpi->activity_avg;
1085
1086
0
  if (act > cpi->activity_avg) {
1087
0
    x->act_zbin_adj = (int)(((int64_t)b + (a >> 1)) / a) - 1;
1088
0
  } else {
1089
0
    x->act_zbin_adj = 1 - (int)(((int64_t)a + (b >> 1)) / b);
1090
0
  }
1091
0
#endif
1092
0
}
1093
1094
int vp8cx_encode_intra_macroblock(VP8_COMP *cpi, MACROBLOCK *x,
1095
1.42M
                                  TOKENEXTRA **t) {
1096
1.42M
  MACROBLOCKD *xd = &x->e_mbd;
1097
1.42M
  int rate;
1098
1099
1.42M
  if (cpi->sf.RD && cpi->compressor_speed != 2) {
1100
824k
    vp8_rd_pick_intra_mode(x, &rate);
1101
824k
  } else {
1102
602k
    vp8_pick_intra_mode(x, &rate);
1103
602k
  }
1104
1105
1.42M
  if (cpi->oxcf.tuning == VP8_TUNE_SSIM) {
1106
0
    adjust_act_zbin(cpi, x);
1107
0
    vp8_update_zbin_extra(cpi, x);
1108
0
  }
1109
1110
1.42M
  if (x->e_mbd.mode_info_context->mbmi.mode == B_PRED) {
1111
639k
    vp8_encode_intra4x4mby(x);
1112
787k
  } else {
1113
787k
    vp8_encode_intra16x16mby(x);
1114
787k
  }
1115
1116
1.42M
  vp8_encode_intra16x16mbuv(x);
1117
1118
1.42M
  sum_intra_stats(cpi, x);
1119
1120
1.42M
  vp8_tokenize_mb(cpi, x, t);
1121
1122
1.42M
  if (xd->mode_info_context->mbmi.mode != B_PRED) vp8_inverse_transform_mby(xd);
1123
1124
1.42M
  vp8_dequant_idct_add_uv_block(xd->qcoeff + 16 * 16, xd->dequant_uv,
1125
1.42M
                                xd->dst.u_buffer, xd->dst.v_buffer,
1126
1.42M
                                xd->dst.uv_stride, xd->eobs + 16);
1127
1.42M
  return rate;
1128
1.42M
}
1129
#ifdef SPEEDSTATS
1130
extern int cnt_pm;
1131
#endif
1132
1133
extern void vp8_fix_contexts(MACROBLOCKD *x);
1134
1135
int vp8cx_encode_inter_macroblock(VP8_COMP *cpi, MACROBLOCK *x, TOKENEXTRA **t,
1136
                                  int recon_yoffset, int recon_uvoffset,
1137
1.54M
                                  int mb_row, int mb_col) {
1138
1.54M
  MACROBLOCKD *const xd = &x->e_mbd;
1139
1.54M
  int intra_error = 0;
1140
1.54M
  int rate;
1141
1.54M
  int distortion;
1142
1143
1.54M
  x->skip = 0;
1144
1145
1.54M
  if (xd->segmentation_enabled) {
1146
0
    x->encode_breakout =
1147
0
        cpi->segment_encode_breakout[xd->mode_info_context->mbmi.segment_id];
1148
1.54M
  } else {
1149
1.54M
    x->encode_breakout = cpi->oxcf.encode_breakout;
1150
1.54M
  }
1151
1152
1.54M
#if CONFIG_TEMPORAL_DENOISING
1153
  /* Reset the best sse mode/mv for each macroblock. */
1154
1.54M
  x->best_reference_frame = INTRA_FRAME;
1155
1.54M
  x->best_zeromv_reference_frame = INTRA_FRAME;
1156
1.54M
  x->best_sse_inter_mode = 0;
1157
1.54M
  x->best_sse_mv.as_int = 0;
1158
1.54M
  x->need_to_clamp_best_mvs = 0;
1159
1.54M
#endif
1160
1161
1.54M
  if (cpi->sf.RD) {
1162
797k
    int zbin_mode_boost_enabled = x->zbin_mode_boost_enabled;
1163
1164
    /* Are we using the fast quantizer for the mode selection? */
1165
797k
    if (cpi->sf.use_fastquant_for_pick) {
1166
797k
      x->quantize_b = vp8_fast_quantize_b;
1167
1168
      /* the fast quantizer does not use zbin_extra, so
1169
       * do not recalculate */
1170
797k
      x->zbin_mode_boost_enabled = 0;
1171
797k
    }
1172
797k
    vp8_rd_pick_inter_mode(cpi, x, recon_yoffset, recon_uvoffset, &rate,
1173
797k
                           &distortion, &intra_error, mb_row, mb_col);
1174
1175
    /* switch back to the regular quantizer for the encode */
1176
797k
    if (cpi->sf.improved_quant) {
1177
797k
      x->quantize_b = vp8_regular_quantize_b;
1178
797k
    }
1179
1180
    /* restore cpi->zbin_mode_boost_enabled */
1181
797k
    x->zbin_mode_boost_enabled = zbin_mode_boost_enabled;
1182
1183
797k
  } else {
1184
750k
    vp8_pick_inter_mode(cpi, x, recon_yoffset, recon_uvoffset, &rate,
1185
750k
                        &distortion, &intra_error, mb_row, mb_col);
1186
750k
  }
1187
1188
1.54M
  x->prediction_error += distortion;
1189
1.54M
  x->intra_error += intra_error;
1190
1191
1.54M
  if (cpi->oxcf.tuning == VP8_TUNE_SSIM) {
1192
    /* Adjust the zbin based on this MB rate. */
1193
0
    adjust_act_zbin(cpi, x);
1194
0
  }
1195
1196
#if 0
1197
    /* Experimental RD code */
1198
    cpi->frame_distortion += distortion;
1199
    cpi->last_mb_distortion = distortion;
1200
#endif
1201
1202
  /* MB level adjutment to quantizer setup */
1203
1.54M
  if (xd->segmentation_enabled) {
1204
    /* If cyclic update enabled */
1205
0
    if (cpi->current_layer == 0 && cpi->cyclic_refresh_mode_enabled) {
1206
      /* Clear segment_id back to 0 if not coded (last frame 0,0) */
1207
0
      if ((xd->mode_info_context->mbmi.segment_id == 1) &&
1208
0
          ((xd->mode_info_context->mbmi.ref_frame != LAST_FRAME) ||
1209
0
           (xd->mode_info_context->mbmi.mode != ZEROMV))) {
1210
0
        xd->mode_info_context->mbmi.segment_id = 0;
1211
1212
        /* segment_id changed, so update */
1213
0
        vp8cx_mb_init_quantizer(cpi, x, 1);
1214
0
      }
1215
0
    }
1216
0
  }
1217
1218
1.54M
  {
1219
    /* Experimental code.
1220
     * Special case for gf and arf zeromv modes, for 1 temporal layer.
1221
     * Increase zbin size to supress noise.
1222
     */
1223
1.54M
    x->zbin_mode_boost = 0;
1224
1.54M
    if (x->zbin_mode_boost_enabled) {
1225
1.54M
      if (xd->mode_info_context->mbmi.ref_frame != INTRA_FRAME) {
1226
652k
        if (xd->mode_info_context->mbmi.mode == ZEROMV) {
1227
139k
          if (xd->mode_info_context->mbmi.ref_frame != LAST_FRAME &&
1228
139k
              cpi->oxcf.number_of_layers == 1) {
1229
11.6k
            x->zbin_mode_boost = GF_ZEROMV_ZBIN_BOOST;
1230
127k
          } else {
1231
127k
            x->zbin_mode_boost = LF_ZEROMV_ZBIN_BOOST;
1232
127k
          }
1233
513k
        } else if (xd->mode_info_context->mbmi.mode == SPLITMV) {
1234
181k
          x->zbin_mode_boost = 0;
1235
332k
        } else {
1236
332k
          x->zbin_mode_boost = MV_ZBIN_BOOST;
1237
332k
        }
1238
652k
      }
1239
1.54M
    }
1240
1241
    /* The fast quantizer doesn't use zbin_extra, only do so with
1242
     * the regular quantizer. */
1243
1.54M
    if (cpi->sf.improved_quant) vp8_update_zbin_extra(cpi, x);
1244
1.54M
  }
1245
1246
1.54M
  x->count_mb_ref_frame_usage[xd->mode_info_context->mbmi.ref_frame]++;
1247
1248
1.54M
  if (xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME) {
1249
895k
    vp8_encode_intra16x16mbuv(x);
1250
1251
895k
    if (xd->mode_info_context->mbmi.mode == B_PRED) {
1252
333k
      vp8_encode_intra4x4mby(x);
1253
562k
    } else {
1254
562k
      vp8_encode_intra16x16mby(x);
1255
562k
    }
1256
1257
895k
    sum_intra_stats(cpi, x);
1258
895k
  } else {
1259
652k
    int ref_fb_idx;
1260
1261
652k
    if (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME) {
1262
583k
      ref_fb_idx = cpi->common.lst_fb_idx;
1263
583k
    } else if (xd->mode_info_context->mbmi.ref_frame == GOLDEN_FRAME) {
1264
55.4k
      ref_fb_idx = cpi->common.gld_fb_idx;
1265
55.4k
    } else {
1266
13.4k
      ref_fb_idx = cpi->common.alt_fb_idx;
1267
13.4k
    }
1268
1269
652k
    xd->pre.y_buffer = cpi->common.yv12_fb[ref_fb_idx].y_buffer + recon_yoffset;
1270
652k
    xd->pre.u_buffer =
1271
652k
        cpi->common.yv12_fb[ref_fb_idx].u_buffer + recon_uvoffset;
1272
652k
    xd->pre.v_buffer =
1273
652k
        cpi->common.yv12_fb[ref_fb_idx].v_buffer + recon_uvoffset;
1274
1275
652k
    if (!x->skip) {
1276
652k
      vp8_encode_inter16x16(x);
1277
652k
    } else {
1278
0
      vp8_build_inter16x16_predictors_mb(xd, xd->dst.y_buffer, xd->dst.u_buffer,
1279
0
                                         xd->dst.v_buffer, xd->dst.y_stride,
1280
0
                                         xd->dst.uv_stride);
1281
0
    }
1282
652k
  }
1283
1284
1.54M
  if (!x->skip) {
1285
1.54M
    vp8_tokenize_mb(cpi, x, t);
1286
1287
1.54M
    if (xd->mode_info_context->mbmi.mode != B_PRED) {
1288
1.21M
      vp8_inverse_transform_mby(xd);
1289
1.21M
    }
1290
1291
1.54M
    vp8_dequant_idct_add_uv_block(xd->qcoeff + 16 * 16, xd->dequant_uv,
1292
1.54M
                                  xd->dst.u_buffer, xd->dst.v_buffer,
1293
1.54M
                                  xd->dst.uv_stride, xd->eobs + 16);
1294
1.54M
  } else {
1295
    /* always set mb_skip_coeff as it is needed by the loopfilter */
1296
0
    xd->mode_info_context->mbmi.mb_skip_coeff = 1;
1297
1298
0
    if (cpi->common.mb_no_coeff_skip) {
1299
0
      x->skip_true_count++;
1300
0
      vp8_fix_contexts(xd);
1301
0
    } else {
1302
0
      vp8_stuff_mb(cpi, x, t);
1303
0
    }
1304
0
  }
1305
1306
1.54M
  return rate;
1307
1.54M
}