1 /*
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 
23 namespace {
signOf(float value)24 int signOf(float value) {
25     if (value == 0) return 0;
26     if (value > 0) return 1;
27     return -1;
28 }
29 } // namespace
30 
31 namespace android {
32 
SlopController(float slopThreshold,nsecs_t slopDurationNanos)33 SlopController::SlopController(float slopThreshold, nsecs_t slopDurationNanos)
34       : mSlopThreshold(slopThreshold), mSlopDurationNanos(slopDurationNanos) {}
35 
consumeEvent(nsecs_t eventTimeNanos,float value)36 float 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) {
57         ALOGD("SlopController: did not drop event with value .%3f", value);
58         mHasSlopBeenMet = true;
59         // Return the amount of value that exceeds the slop.
60         return signOf(value) * (abs(mCumulativeValue) - mSlopThreshold);
61     }
62 
63     ALOGD("SlopController: dropping event with value .%3f", value);
64     return 0;
65 }
66 
shouldResetSlopTracking(nsecs_t eventTimeNanos,float value) const67 bool SlopController::shouldResetSlopTracking(nsecs_t eventTimeNanos, float value) const {
68     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
82