blob: 9ec02a6f8640b3dc83d23b15d28cdc0b7a3bea73 [file] [log] [blame]
Yeabkal Wubshit6b662762023-05-22 23:07:31 -07001/*
2 * Copyright 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// clang-format off
18#include "../Macros.h"
19// clang-format on
20
21#include "SlopController.h"
22
23namespace {
24int signOf(float value) {
25 if (value == 0) return 0;
26 if (value > 0) return 1;
27 return -1;
28}
29} // namespace
30
31namespace android {
32
33SlopController::SlopController(float slopThreshold, nsecs_t slopDurationNanos)
34 : mSlopThreshold(slopThreshold), mSlopDurationNanos(slopDurationNanos) {}
35
Yeabkal Wubshit6b662762023-05-22 23:07:31 -070036float SlopController::consumeEvent(nsecs_t eventTimeNanos, float value) {
37 if (mSlopDurationNanos == 0) {
38 return value;
39 }
40
41 if (shouldResetSlopTracking(eventTimeNanos, value)) {
42 mCumulativeValue = 0;
43 mHasSlopBeenMet = false;
44 }
45
46 mLastEventTimeNanos = eventTimeNanos;
47
48 if (mHasSlopBeenMet) {
49 // Since slop has already been met, we know that all of the current value would pass the
50 // slop threshold. So return that, without any further processing.
51 return value;
52 }
53
54 mCumulativeValue += value;
55
56 if (abs(mCumulativeValue) >= mSlopThreshold) {
Yeabkal Wubshit734f92f2023-07-24 18:56:51 -070057 ALOGD("SlopController: did not drop event with value .%3f", value);
Yeabkal Wubshit6b662762023-05-22 23:07:31 -070058 mHasSlopBeenMet = true;
59 // Return the amount of value that exceeds the slop.
60 return signOf(value) * (abs(mCumulativeValue) - mSlopThreshold);
61 }
62
Yeabkal Wubshit734f92f2023-07-24 18:56:51 -070063 ALOGD("SlopController: dropping event with value .%3f", value);
Yeabkal Wubshit6b662762023-05-22 23:07:31 -070064 return 0;
65}
66
Yeabkal Wubshitf1ed7052023-06-16 10:01:53 -070067bool SlopController::shouldResetSlopTracking(nsecs_t eventTimeNanos, float value) const {
Yeabkal Wubshit6b662762023-05-22 23:07:31 -070068 const nsecs_t ageNanos = eventTimeNanos - mLastEventTimeNanos;
69 if (ageNanos >= mSlopDurationNanos) {
70 return true;
71 }
72 if (value == 0) {
73 return false;
74 }
75 if (signOf(mCumulativeValue) != signOf(value)) {
76 return true;
77 }
78 return false;
79}
80
81} // namespace android