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
11#include <limits.h>
12
13#include "vpx_mem/vpx_mem.h"
14#include "vp9/encoder/vp9_segmentation.h"
15#include "vp9/encoder/vp9_mcomp.h"
16#include "vp9/common/vp9_blockd.h"
17#include "vp9/common/vp9_reconinter.h"
18#include "vp9/common/vp9_reconintra.h"
19#include "vp9/common/vp9_systemdependent.h"
20
21
22static unsigned int do_16x16_motion_iteration(VP9_COMP *cpi,
23                                              const MV *ref_mv,
24                                              MV *dst_mv,
25                                              int mb_row,
26                                              int mb_col) {
27  MACROBLOCK *const x = &cpi->mb;
28  MACROBLOCKD *const xd = &x->e_mbd;
29  const MV_SPEED_FEATURES *const mv_sf = &cpi->sf.mv;
30  const vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[BLOCK_16X16];
31
32  const int tmp_col_min = x->mv_col_min;
33  const int tmp_col_max = x->mv_col_max;
34  const int tmp_row_min = x->mv_row_min;
35  const int tmp_row_max = x->mv_row_max;
36  MV ref_full;
37  int sad_list[5];
38
39  // Further step/diamond searches as necessary
40  int step_param = mv_sf->reduce_first_step_size;
41  step_param = MIN(step_param, MAX_MVSEARCH_STEPS - 2);
42
43  vp9_set_mv_search_range(x, ref_mv);
44
45  ref_full.col = ref_mv->col >> 3;
46  ref_full.row = ref_mv->row >> 3;
47
48  /*cpi->sf.search_method == HEX*/
49  vp9_hex_search(x, &ref_full, step_param, x->errorperbit, 0,
50                 cond_sad_list(cpi, sad_list),
51                 &v_fn_ptr, 0, ref_mv, dst_mv);
52
53  // Try sub-pixel MC
54  // if (bestsme > error_thresh && bestsme < INT_MAX)
55  {
56    int distortion;
57    unsigned int sse;
58    cpi->find_fractional_mv_step(
59        x, dst_mv, ref_mv, cpi->common.allow_high_precision_mv, x->errorperbit,
60        &v_fn_ptr, 0, mv_sf->subpel_iters_per_step,
61        cond_sad_list(cpi, sad_list),
62        NULL, NULL,
63        &distortion, &sse, NULL, 0, 0);
64  }
65
66  xd->mi[0].src_mi->mbmi.mode = NEWMV;
67  xd->mi[0].src_mi->mbmi.mv[0].as_mv = *dst_mv;
68
69  vp9_build_inter_predictors_sby(xd, mb_row, mb_col, BLOCK_16X16);
70
71  /* restore UMV window */
72  x->mv_col_min = tmp_col_min;
73  x->mv_col_max = tmp_col_max;
74  x->mv_row_min = tmp_row_min;
75  x->mv_row_max = tmp_row_max;
76
77  return vp9_sad16x16(x->plane[0].src.buf, x->plane[0].src.stride,
78          xd->plane[0].dst.buf, xd->plane[0].dst.stride);
79}
80
81static int do_16x16_motion_search(VP9_COMP *cpi, const MV *ref_mv,
82                                  int_mv *dst_mv, int mb_row, int mb_col) {
83  MACROBLOCK *const x = &cpi->mb;
84  MACROBLOCKD *const xd = &x->e_mbd;
85  unsigned int err, tmp_err;
86  MV tmp_mv;
87
88  // Try zero MV first
89  // FIXME should really use something like near/nearest MV and/or MV prediction
90  err = vp9_sad16x16(x->plane[0].src.buf, x->plane[0].src.stride,
91                     xd->plane[0].pre[0].buf, xd->plane[0].pre[0].stride);
92  dst_mv->as_int = 0;
93
94  // Test last reference frame using the previous best mv as the
95  // starting point (best reference) for the search
96  tmp_err = do_16x16_motion_iteration(cpi, ref_mv, &tmp_mv, mb_row, mb_col);
97  if (tmp_err < err) {
98    err = tmp_err;
99    dst_mv->as_mv = tmp_mv;
100  }
101
102  // If the current best reference mv is not centered on 0,0 then do a 0,0
103  // based search as well.
104  if (ref_mv->row != 0 || ref_mv->col != 0) {
105    unsigned int tmp_err;
106    MV zero_ref_mv = {0, 0}, tmp_mv;
107
108    tmp_err = do_16x16_motion_iteration(cpi, &zero_ref_mv, &tmp_mv,
109                                        mb_row, mb_col);
110    if (tmp_err < err) {
111      dst_mv->as_mv = tmp_mv;
112      err = tmp_err;
113    }
114  }
115
116  return err;
117}
118
119static int do_16x16_zerozero_search(VP9_COMP *cpi, int_mv *dst_mv) {
120  MACROBLOCK *const x = &cpi->mb;
121  MACROBLOCKD *const xd = &x->e_mbd;
122  unsigned int err;
123
124  // Try zero MV first
125  // FIXME should really use something like near/nearest MV and/or MV prediction
126  err = vp9_sad16x16(x->plane[0].src.buf, x->plane[0].src.stride,
127                     xd->plane[0].pre[0].buf, xd->plane[0].pre[0].stride);
128
129  dst_mv->as_int = 0;
130
131  return err;
132}
133static int find_best_16x16_intra(VP9_COMP *cpi, PREDICTION_MODE *pbest_mode) {
134  MACROBLOCK   *const x  = &cpi->mb;
135  MACROBLOCKD *const xd = &x->e_mbd;
136  PREDICTION_MODE best_mode = -1, mode;
137  unsigned int best_err = INT_MAX;
138
139  // calculate SATD for each intra prediction mode;
140  // we're intentionally not doing 4x4, we just want a rough estimate
141  for (mode = DC_PRED; mode <= TM_PRED; mode++) {
142    unsigned int err;
143
144    xd->mi[0].src_mi->mbmi.mode = mode;
145    vp9_predict_intra_block(xd, 0, 2, TX_16X16, mode,
146                            x->plane[0].src.buf, x->plane[0].src.stride,
147                            xd->plane[0].dst.buf, xd->plane[0].dst.stride,
148                            0, 0, 0);
149    err = vp9_sad16x16(x->plane[0].src.buf, x->plane[0].src.stride,
150                       xd->plane[0].dst.buf, xd->plane[0].dst.stride);
151
152    // find best
153    if (err < best_err) {
154      best_err  = err;
155      best_mode = mode;
156    }
157  }
158
159  if (pbest_mode)
160    *pbest_mode = best_mode;
161
162  return best_err;
163}
164
165static void update_mbgraph_mb_stats
166(
167  VP9_COMP *cpi,
168  MBGRAPH_MB_STATS *stats,
169  YV12_BUFFER_CONFIG *buf,
170  int mb_y_offset,
171  YV12_BUFFER_CONFIG *golden_ref,
172  const MV *prev_golden_ref_mv,
173  YV12_BUFFER_CONFIG *alt_ref,
174  int mb_row,
175  int mb_col
176) {
177  MACROBLOCK *const x = &cpi->mb;
178  MACROBLOCKD *const xd = &x->e_mbd;
179  int intra_error;
180  VP9_COMMON *cm = &cpi->common;
181
182  // FIXME in practice we're completely ignoring chroma here
183  x->plane[0].src.buf = buf->y_buffer + mb_y_offset;
184  x->plane[0].src.stride = buf->y_stride;
185
186  xd->plane[0].dst.buf = get_frame_new_buffer(cm)->y_buffer + mb_y_offset;
187  xd->plane[0].dst.stride = get_frame_new_buffer(cm)->y_stride;
188
189  // do intra 16x16 prediction
190  intra_error = find_best_16x16_intra(cpi,
191                                      &stats->ref[INTRA_FRAME].m.mode);
192  if (intra_error <= 0)
193    intra_error = 1;
194  stats->ref[INTRA_FRAME].err = intra_error;
195
196  // Golden frame MV search, if it exists and is different than last frame
197  if (golden_ref) {
198    int g_motion_error;
199    xd->plane[0].pre[0].buf = golden_ref->y_buffer + mb_y_offset;
200    xd->plane[0].pre[0].stride = golden_ref->y_stride;
201    g_motion_error = do_16x16_motion_search(cpi,
202                                            prev_golden_ref_mv,
203                                            &stats->ref[GOLDEN_FRAME].m.mv,
204                                            mb_row, mb_col);
205    stats->ref[GOLDEN_FRAME].err = g_motion_error;
206  } else {
207    stats->ref[GOLDEN_FRAME].err = INT_MAX;
208    stats->ref[GOLDEN_FRAME].m.mv.as_int = 0;
209  }
210
211  // Do an Alt-ref frame MV search, if it exists and is different than
212  // last/golden frame.
213  if (alt_ref) {
214    int a_motion_error;
215    xd->plane[0].pre[0].buf = alt_ref->y_buffer + mb_y_offset;
216    xd->plane[0].pre[0].stride = alt_ref->y_stride;
217    a_motion_error = do_16x16_zerozero_search(cpi,
218                                              &stats->ref[ALTREF_FRAME].m.mv);
219
220    stats->ref[ALTREF_FRAME].err = a_motion_error;
221  } else {
222    stats->ref[ALTREF_FRAME].err = INT_MAX;
223    stats->ref[ALTREF_FRAME].m.mv.as_int = 0;
224  }
225}
226
227static void update_mbgraph_frame_stats(VP9_COMP *cpi,
228                                       MBGRAPH_FRAME_STATS *stats,
229                                       YV12_BUFFER_CONFIG *buf,
230                                       YV12_BUFFER_CONFIG *golden_ref,
231                                       YV12_BUFFER_CONFIG *alt_ref) {
232  MACROBLOCK *const x = &cpi->mb;
233  MACROBLOCKD *const xd = &x->e_mbd;
234  VP9_COMMON *const cm = &cpi->common;
235
236  int mb_col, mb_row, offset = 0;
237  int mb_y_offset = 0, arf_y_offset = 0, gld_y_offset = 0;
238  MV gld_top_mv = {0, 0};
239  MODE_INFO mi_local;
240
241  vp9_zero(mi_local);
242  // Set up limit values for motion vectors to prevent them extending outside
243  // the UMV borders.
244  x->mv_row_min     = -BORDER_MV_PIXELS_B16;
245  x->mv_row_max     = (cm->mb_rows - 1) * 8 + BORDER_MV_PIXELS_B16;
246  xd->up_available  = 0;
247  xd->plane[0].dst.stride  = buf->y_stride;
248  xd->plane[0].pre[0].stride  = buf->y_stride;
249  xd->plane[1].dst.stride = buf->uv_stride;
250  xd->mi[0].src_mi = &mi_local;
251  mi_local.mbmi.sb_type = BLOCK_16X16;
252  mi_local.mbmi.ref_frame[0] = LAST_FRAME;
253  mi_local.mbmi.ref_frame[1] = NONE;
254
255  for (mb_row = 0; mb_row < cm->mb_rows; mb_row++) {
256    MV gld_left_mv = gld_top_mv;
257    int mb_y_in_offset  = mb_y_offset;
258    int arf_y_in_offset = arf_y_offset;
259    int gld_y_in_offset = gld_y_offset;
260
261    // Set up limit values for motion vectors to prevent them extending outside
262    // the UMV borders.
263    x->mv_col_min      = -BORDER_MV_PIXELS_B16;
264    x->mv_col_max      = (cm->mb_cols - 1) * 8 + BORDER_MV_PIXELS_B16;
265    xd->left_available = 0;
266
267    for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) {
268      MBGRAPH_MB_STATS *mb_stats = &stats->mb_stats[offset + mb_col];
269
270      update_mbgraph_mb_stats(cpi, mb_stats, buf, mb_y_in_offset,
271                              golden_ref, &gld_left_mv, alt_ref,
272                              mb_row, mb_col);
273      gld_left_mv = mb_stats->ref[GOLDEN_FRAME].m.mv.as_mv;
274      if (mb_col == 0) {
275        gld_top_mv = gld_left_mv;
276      }
277      xd->left_available = 1;
278      mb_y_in_offset    += 16;
279      gld_y_in_offset   += 16;
280      arf_y_in_offset   += 16;
281      x->mv_col_min     -= 16;
282      x->mv_col_max     -= 16;
283    }
284    xd->up_available = 1;
285    mb_y_offset     += buf->y_stride * 16;
286    gld_y_offset    += golden_ref->y_stride * 16;
287    if (alt_ref)
288      arf_y_offset    += alt_ref->y_stride * 16;
289    x->mv_row_min   -= 16;
290    x->mv_row_max   -= 16;
291    offset          += cm->mb_cols;
292  }
293}
294
295// void separate_arf_mbs_byzz
296static void separate_arf_mbs(VP9_COMP *cpi) {
297  VP9_COMMON *const cm = &cpi->common;
298  int mb_col, mb_row, offset, i;
299  int mi_row, mi_col;
300  int ncnt[4] = { 0 };
301  int n_frames = cpi->mbgraph_n_frames;
302
303  int *arf_not_zz;
304
305  CHECK_MEM_ERROR(cm, arf_not_zz,
306                  vpx_calloc(cm->mb_rows * cm->mb_cols * sizeof(*arf_not_zz),
307                             1));
308
309  // We are not interested in results beyond the alt ref itself.
310  if (n_frames > cpi->rc.frames_till_gf_update_due)
311    n_frames = cpi->rc.frames_till_gf_update_due;
312
313  // defer cost to reference frames
314  for (i = n_frames - 1; i >= 0; i--) {
315    MBGRAPH_FRAME_STATS *frame_stats = &cpi->mbgraph_stats[i];
316
317    for (offset = 0, mb_row = 0; mb_row < cm->mb_rows;
318         offset += cm->mb_cols, mb_row++) {
319      for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) {
320        MBGRAPH_MB_STATS *mb_stats = &frame_stats->mb_stats[offset + mb_col];
321
322        int altref_err = mb_stats->ref[ALTREF_FRAME].err;
323        int intra_err  = mb_stats->ref[INTRA_FRAME ].err;
324        int golden_err = mb_stats->ref[GOLDEN_FRAME].err;
325
326        // Test for altref vs intra and gf and that its mv was 0,0.
327        if (altref_err > 1000 ||
328            altref_err > intra_err ||
329            altref_err > golden_err) {
330          arf_not_zz[offset + mb_col]++;
331        }
332      }
333    }
334  }
335
336  // arf_not_zz is indexed by MB, but this loop is indexed by MI to avoid out
337  // of bound access in segmentation_map
338  for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) {
339    for (mi_col = 0; mi_col < cm->mi_cols; mi_col++) {
340      // If any of the blocks in the sequence failed then the MB
341      // goes in segment 0
342      if (arf_not_zz[mi_row / 2 * cm->mb_cols + mi_col / 2]) {
343        ncnt[0]++;
344        cpi->segmentation_map[mi_row * cm->mi_cols + mi_col] = 0;
345      } else {
346        cpi->segmentation_map[mi_row * cm->mi_cols + mi_col] = 1;
347        ncnt[1]++;
348      }
349    }
350  }
351
352  // Only bother with segmentation if over 10% of the MBs in static segment
353  // if ( ncnt[1] && (ncnt[0] / ncnt[1] < 10) )
354  if (1) {
355    // Note % of blocks that are marked as static
356    if (cm->MBs)
357      cpi->static_mb_pct = (ncnt[1] * 100) / (cm->mi_rows * cm->mi_cols);
358
359    // This error case should not be reachable as this function should
360    // never be called with the common data structure uninitialized.
361    else
362      cpi->static_mb_pct = 0;
363
364    vp9_enable_segmentation(&cm->seg);
365  } else {
366    cpi->static_mb_pct = 0;
367    vp9_disable_segmentation(&cm->seg);
368  }
369
370  // Free localy allocated storage
371  vpx_free(arf_not_zz);
372}
373
374void vp9_update_mbgraph_stats(VP9_COMP *cpi) {
375  VP9_COMMON *const cm = &cpi->common;
376  int i, n_frames = vp9_lookahead_depth(cpi->lookahead);
377  YV12_BUFFER_CONFIG *golden_ref = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
378
379  // we need to look ahead beyond where the ARF transitions into
380  // being a GF - so exit if we don't look ahead beyond that
381  if (n_frames <= cpi->rc.frames_till_gf_update_due)
382    return;
383
384  if (n_frames > MAX_LAG_BUFFERS)
385    n_frames = MAX_LAG_BUFFERS;
386
387  cpi->mbgraph_n_frames = n_frames;
388  for (i = 0; i < n_frames; i++) {
389    MBGRAPH_FRAME_STATS *frame_stats = &cpi->mbgraph_stats[i];
390    vpx_memset(frame_stats->mb_stats, 0,
391               cm->mb_rows * cm->mb_cols *
392               sizeof(*cpi->mbgraph_stats[i].mb_stats));
393  }
394
395  // do motion search to find contribution of each reference to data
396  // later on in this GF group
397  // FIXME really, the GF/last MC search should be done forward, and
398  // the ARF MC search backwards, to get optimal results for MV caching
399  for (i = 0; i < n_frames; i++) {
400    MBGRAPH_FRAME_STATS *frame_stats = &cpi->mbgraph_stats[i];
401    struct lookahead_entry *q_cur = vp9_lookahead_peek(cpi->lookahead, i);
402
403    assert(q_cur != NULL);
404
405    update_mbgraph_frame_stats(cpi, frame_stats, &q_cur->img,
406                               golden_ref, cpi->Source);
407  }
408
409  vp9_clear_system_state();
410
411  separate_arf_mbs(cpi);
412}
413