1/*
2 *  Copyright (c) 2015 The WebRTC 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 <emmintrin.h>
12
13#include "webrtc/modules/video_processing/util/denoiser_filter_sse2.h"
14
15namespace webrtc {
16
17static void Get8x8varSse2(const uint8_t* src,
18                          int src_stride,
19                          const uint8_t* ref,
20                          int ref_stride,
21                          unsigned int* sse,
22                          int* sum) {
23  const __m128i zero = _mm_setzero_si128();
24  __m128i vsum = _mm_setzero_si128();
25  __m128i vsse = _mm_setzero_si128();
26
27  for (int i = 0; i < 8; i += 2) {
28    const __m128i src0 = _mm_unpacklo_epi8(
29        _mm_loadl_epi64((const __m128i*)(src + i * src_stride)), zero);
30    const __m128i ref0 = _mm_unpacklo_epi8(
31        _mm_loadl_epi64((const __m128i*)(ref + i * ref_stride)), zero);
32    const __m128i diff0 = _mm_sub_epi16(src0, ref0);
33
34    const __m128i src1 = _mm_unpacklo_epi8(
35        _mm_loadl_epi64((const __m128i*)(src + (i + 1) * src_stride)), zero);
36    const __m128i ref1 = _mm_unpacklo_epi8(
37        _mm_loadl_epi64((const __m128i*)(ref + (i + 1) * ref_stride)), zero);
38    const __m128i diff1 = _mm_sub_epi16(src1, ref1);
39
40    vsum = _mm_add_epi16(vsum, diff0);
41    vsum = _mm_add_epi16(vsum, diff1);
42    vsse = _mm_add_epi32(vsse, _mm_madd_epi16(diff0, diff0));
43    vsse = _mm_add_epi32(vsse, _mm_madd_epi16(diff1, diff1));
44  }
45
46  // sum
47  vsum = _mm_add_epi16(vsum, _mm_srli_si128(vsum, 8));
48  vsum = _mm_add_epi16(vsum, _mm_srli_si128(vsum, 4));
49  vsum = _mm_add_epi16(vsum, _mm_srli_si128(vsum, 2));
50  *sum = static_cast<int16_t>(_mm_extract_epi16(vsum, 0));
51
52  // sse
53  vsse = _mm_add_epi32(vsse, _mm_srli_si128(vsse, 8));
54  vsse = _mm_add_epi32(vsse, _mm_srli_si128(vsse, 4));
55  *sse = _mm_cvtsi128_si32(vsse);
56}
57
58static void VarianceSSE2(const unsigned char* src,
59                         int src_stride,
60                         const unsigned char* ref,
61                         int ref_stride,
62                         int w,
63                         int h,
64                         uint32_t* sse,
65                         int64_t* sum,
66                         int block_size) {
67  *sse = 0;
68  *sum = 0;
69
70  for (int i = 0; i < h; i += block_size) {
71    for (int j = 0; j < w; j += block_size) {
72      uint32_t sse0 = 0;
73      int32_t sum0 = 0;
74
75      Get8x8varSse2(src + src_stride * i + j, src_stride,
76                    ref + ref_stride * i + j, ref_stride, &sse0, &sum0);
77      *sse += sse0;
78      *sum += sum0;
79    }
80  }
81}
82
83// Compute the sum of all pixel differences of this MB.
84static uint32_t AbsSumDiff16x1(__m128i acc_diff) {
85  const __m128i k_1 = _mm_set1_epi16(1);
86  const __m128i acc_diff_lo =
87      _mm_srai_epi16(_mm_unpacklo_epi8(acc_diff, acc_diff), 8);
88  const __m128i acc_diff_hi =
89      _mm_srai_epi16(_mm_unpackhi_epi8(acc_diff, acc_diff), 8);
90  const __m128i acc_diff_16 = _mm_add_epi16(acc_diff_lo, acc_diff_hi);
91  const __m128i hg_fe_dc_ba = _mm_madd_epi16(acc_diff_16, k_1);
92  const __m128i hgfe_dcba =
93      _mm_add_epi32(hg_fe_dc_ba, _mm_srli_si128(hg_fe_dc_ba, 8));
94  const __m128i hgfedcba =
95      _mm_add_epi32(hgfe_dcba, _mm_srli_si128(hgfe_dcba, 4));
96  unsigned int sum_diff = abs(_mm_cvtsi128_si32(hgfedcba));
97
98  return sum_diff;
99}
100
101// TODO(jackychen): Optimize this function using SSE2.
102void DenoiserFilterSSE2::CopyMem16x16(const uint8_t* src,
103                                      int src_stride,
104                                      uint8_t* dst,
105                                      int dst_stride) {
106  for (int i = 0; i < 16; i++) {
107    memcpy(dst, src, 16);
108    src += src_stride;
109    dst += dst_stride;
110  }
111}
112
113// TODO(jackychen): Optimize this function using SSE2.
114void DenoiserFilterSSE2::CopyMem8x8(const uint8_t* src,
115                                    int src_stride,
116                                    uint8_t* dst,
117                                    int dst_stride) {
118  for (int i = 0; i < 8; i++) {
119    memcpy(dst, src, 8);
120    src += src_stride;
121    dst += dst_stride;
122  }
123}
124
125uint32_t DenoiserFilterSSE2::Variance16x8(const uint8_t* src,
126                                          int src_stride,
127                                          const uint8_t* ref,
128                                          int ref_stride,
129                                          uint32_t* sse) {
130  int64_t sum = 0;
131  VarianceSSE2(src, src_stride << 1, ref, ref_stride << 1, 16, 8, sse, &sum, 8);
132  return *sse - ((sum * sum) >> 7);
133}
134
135DenoiserDecision DenoiserFilterSSE2::MbDenoise(uint8_t* mc_running_avg_y,
136                                               int mc_avg_y_stride,
137                                               uint8_t* running_avg_y,
138                                               int avg_y_stride,
139                                               const uint8_t* sig,
140                                               int sig_stride,
141                                               uint8_t motion_magnitude,
142                                               int increase_denoising) {
143  int shift_inc =
144      (increase_denoising && motion_magnitude <= kMotionMagnitudeThreshold) ? 1
145                                                                            : 0;
146  __m128i acc_diff = _mm_setzero_si128();
147  const __m128i k_0 = _mm_setzero_si128();
148  const __m128i k_4 = _mm_set1_epi8(4 + shift_inc);
149  const __m128i k_8 = _mm_set1_epi8(8);
150  const __m128i k_16 = _mm_set1_epi8(16);
151  // Modify each level's adjustment according to motion_magnitude.
152  const __m128i l3 = _mm_set1_epi8(
153      (motion_magnitude <= kMotionMagnitudeThreshold) ? 7 + shift_inc : 6);
154  // Difference between level 3 and level 2 is 2.
155  const __m128i l32 = _mm_set1_epi8(2);
156  // Difference between level 2 and level 1 is 1.
157  const __m128i l21 = _mm_set1_epi8(1);
158
159  for (int r = 0; r < 16; ++r) {
160    // Calculate differences.
161    const __m128i v_sig =
162        _mm_loadu_si128(reinterpret_cast<const __m128i*>(&sig[0]));
163    const __m128i v_mc_running_avg_y =
164        _mm_loadu_si128(reinterpret_cast<__m128i*>(&mc_running_avg_y[0]));
165    __m128i v_running_avg_y;
166    const __m128i pdiff = _mm_subs_epu8(v_mc_running_avg_y, v_sig);
167    const __m128i ndiff = _mm_subs_epu8(v_sig, v_mc_running_avg_y);
168    // Obtain the sign. FF if diff is negative.
169    const __m128i diff_sign = _mm_cmpeq_epi8(pdiff, k_0);
170    // Clamp absolute difference to 16 to be used to get mask. Doing this
171    // allows us to use _mm_cmpgt_epi8, which operates on signed byte.
172    const __m128i clamped_absdiff =
173        _mm_min_epu8(_mm_or_si128(pdiff, ndiff), k_16);
174    // Get masks for l2 l1 and l0 adjustments.
175    const __m128i mask2 = _mm_cmpgt_epi8(k_16, clamped_absdiff);
176    const __m128i mask1 = _mm_cmpgt_epi8(k_8, clamped_absdiff);
177    const __m128i mask0 = _mm_cmpgt_epi8(k_4, clamped_absdiff);
178    // Get adjustments for l2, l1, and l0.
179    __m128i adj2 = _mm_and_si128(mask2, l32);
180    const __m128i adj1 = _mm_and_si128(mask1, l21);
181    const __m128i adj0 = _mm_and_si128(mask0, clamped_absdiff);
182    __m128i adj, padj, nadj;
183
184    // Combine the adjustments and get absolute adjustments.
185    adj2 = _mm_add_epi8(adj2, adj1);
186    adj = _mm_sub_epi8(l3, adj2);
187    adj = _mm_andnot_si128(mask0, adj);
188    adj = _mm_or_si128(adj, adj0);
189
190    // Restore the sign and get positive and negative adjustments.
191    padj = _mm_andnot_si128(diff_sign, adj);
192    nadj = _mm_and_si128(diff_sign, adj);
193
194    // Calculate filtered value.
195    v_running_avg_y = _mm_adds_epu8(v_sig, padj);
196    v_running_avg_y = _mm_subs_epu8(v_running_avg_y, nadj);
197    _mm_storeu_si128(reinterpret_cast<__m128i*>(running_avg_y),
198                     v_running_avg_y);
199
200    // Adjustments <=7, and each element in acc_diff can fit in signed
201    // char.
202    acc_diff = _mm_adds_epi8(acc_diff, padj);
203    acc_diff = _mm_subs_epi8(acc_diff, nadj);
204
205    // Update pointers for next iteration.
206    sig += sig_stride;
207    mc_running_avg_y += mc_avg_y_stride;
208    running_avg_y += avg_y_stride;
209  }
210
211  {
212    // Compute the sum of all pixel differences of this MB.
213    unsigned int abs_sum_diff = AbsSumDiff16x1(acc_diff);
214    unsigned int sum_diff_thresh = kSumDiffThreshold;
215    if (increase_denoising)
216      sum_diff_thresh = kSumDiffThresholdHigh;
217    if (abs_sum_diff > sum_diff_thresh) {
218      // Before returning to copy the block (i.e., apply no denoising),
219      // check if we can still apply some (weaker) temporal filtering to
220      // this block, that would otherwise not be denoised at all. Simplest
221      // is to apply an additional adjustment to running_avg_y to bring it
222      // closer to sig. The adjustment is capped by a maximum delta, and
223      // chosen such that in most cases the resulting sum_diff will be
224      // within the acceptable range given by sum_diff_thresh.
225
226      // The delta is set by the excess of absolute pixel diff over the
227      // threshold.
228      int delta = ((abs_sum_diff - sum_diff_thresh) >> 8) + 1;
229      // Only apply the adjustment for max delta up to 3.
230      if (delta < 4) {
231        const __m128i k_delta = _mm_set1_epi8(delta);
232        sig -= sig_stride * 16;
233        mc_running_avg_y -= mc_avg_y_stride * 16;
234        running_avg_y -= avg_y_stride * 16;
235        for (int r = 0; r < 16; ++r) {
236          __m128i v_running_avg_y =
237              _mm_loadu_si128(reinterpret_cast<__m128i*>(&running_avg_y[0]));
238          // Calculate differences.
239          const __m128i v_sig =
240              _mm_loadu_si128(reinterpret_cast<const __m128i*>(&sig[0]));
241          const __m128i v_mc_running_avg_y =
242              _mm_loadu_si128(reinterpret_cast<__m128i*>(&mc_running_avg_y[0]));
243          const __m128i pdiff = _mm_subs_epu8(v_mc_running_avg_y, v_sig);
244          const __m128i ndiff = _mm_subs_epu8(v_sig, v_mc_running_avg_y);
245          // Obtain the sign. FF if diff is negative.
246          const __m128i diff_sign = _mm_cmpeq_epi8(pdiff, k_0);
247          // Clamp absolute difference to delta to get the adjustment.
248          const __m128i adj = _mm_min_epu8(_mm_or_si128(pdiff, ndiff), k_delta);
249          // Restore the sign and get positive and negative adjustments.
250          __m128i padj, nadj;
251          padj = _mm_andnot_si128(diff_sign, adj);
252          nadj = _mm_and_si128(diff_sign, adj);
253          // Calculate filtered value.
254          v_running_avg_y = _mm_subs_epu8(v_running_avg_y, padj);
255          v_running_avg_y = _mm_adds_epu8(v_running_avg_y, nadj);
256          _mm_storeu_si128(reinterpret_cast<__m128i*>(running_avg_y),
257                           v_running_avg_y);
258
259          // Accumulate the adjustments.
260          acc_diff = _mm_subs_epi8(acc_diff, padj);
261          acc_diff = _mm_adds_epi8(acc_diff, nadj);
262
263          // Update pointers for next iteration.
264          sig += sig_stride;
265          mc_running_avg_y += mc_avg_y_stride;
266          running_avg_y += avg_y_stride;
267        }
268        abs_sum_diff = AbsSumDiff16x1(acc_diff);
269        if (abs_sum_diff > sum_diff_thresh) {
270          return COPY_BLOCK;
271        }
272      } else {
273        return COPY_BLOCK;
274      }
275    }
276  }
277  return FILTER_BLOCK;
278}
279
280}  // namespace webrtc
281