• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 #pragma once
17 
18 #include <aidl/android/hardware/vibrator/BnVibrator.h>
19 #include <android-base/stringprintf.h>
20 #include <android-base/unique_fd.h>
21 #include <linux/input.h>
22 #include <tinyalsa/asoundlib.h>
23 
24 #include <array>
25 #include <chrono>
26 #include <ctime>
27 #include <fstream>
28 #include <future>
29 
30 #include "CapoDetector.h"
31 
32 using CapoDetector = android::chre::CapoDetector;
33 
34 namespace aidl {
35 namespace android {
36 namespace hardware {
37 namespace vibrator {
38 
39 using ::android::base::StringPrintf;
40 
41 class Vibrator : public BnVibrator {
42   public:
43     // APIs for interfacing with the kernel driver.
44     class HwApi {
45       public:
46         virtual ~HwApi() = default;
47         // Stores the LRA resonant frequency to be used for PWLE playback
48         // and click compensation.
49         virtual bool setF0(std::string value) = 0;
50         // Stores the frequency offset for long vibrations.
51         virtual bool setF0Offset(uint32_t value) = 0;
52         // Stores the LRA series resistance to be used for click
53         // compensation.
54         virtual bool setRedc(std::string value) = 0;
55         // Stores the LRA Q factor to be used for Q-dependent waveform
56         // selection.
57         virtual bool setQ(std::string value) = 0;
58         // Reports the number of effect waveforms loaded in firmware.
59         virtual bool getEffectCount(uint32_t *value) = 0;
60         // Blocks until timeout or vibrator reaches desired state
61         // (2 = ASP enabled, 1 = haptic enabled, 0 = disabled).
62         virtual bool pollVibeState(uint32_t value, int32_t timeoutMs = -1) = 0;
63         // Reports whether getOwtFreeSpace() is supported.
64         virtual bool hasOwtFreeSpace() = 0;
65         // Reports the available OWT bytes.
66         virtual bool getOwtFreeSpace(uint32_t *value) = 0;
67         // Enables/Disables F0 compensation enable status
68         virtual bool setF0CompEnable(bool value) = 0;
69         // Enables/Disables Redc compensation enable status
70         virtual bool setRedcCompEnable(bool value) = 0;
71         // Stores the minumun delay time between playback and stop effects.
72         virtual bool setMinOnOffInterval(uint32_t value) = 0;
73         // Determine the /dev and /sys paths for input force-feedback control.
74         virtual bool initFF() = 0;
75         // Gets the scaling factor for contextual haptic events.
76         virtual uint32_t getContextScale() = 0;
77         // Gets the enable status for contextual haptic events.
78         virtual bool getContextEnable() = 0;
79         // Gets the settling time for contextual haptic events.
80         // This will allow the device to stay face up for the duration given,
81         // even if InMotion events were detected.
82         virtual uint32_t getContextSettlingTime() = 0;
83         // Gets the cooldown time for contextual haptic events.
84         // This is used to avoid changing the scale of close playback events.
85         virtual uint32_t getContextCooldownTime() = 0;
86         // Checks the enable status for contextual haptics fade feature.  When enabled
87         // this feature will cause the scaling factor to fade back up to max over
88         // the setting time set, instead of instantaneously changing it back to max.
89         virtual bool getContextFadeEnable() = 0;
90         // Indicates the number of 0.125-dB steps of attenuation to apply to
91         // waveforms triggered in response to vibration calls from the
92         // Android vibrator HAL.
93         virtual bool setFFGain(uint16_t value) = 0;
94         // Create/modify custom effects for all physical waveforms.
95         virtual bool setFFEffect(struct ff_effect *effect, uint16_t timeoutMs) = 0;
96         // Activates/deactivates the effect index after setFFGain() and setFFEffect().
97         virtual bool setFFPlay(int8_t index, bool value) = 0;
98         // Get the Alsa device for the audio coupled haptics effect
99         virtual bool getHapticAlsaDevice(int *card, int *device) = 0;
100         // Set haptics PCM amplifier before triggering audio haptics feature
101         virtual bool setHapticPcmAmp(struct pcm **haptic_pcm, bool enable, int card,
102                                      int device) = 0;
103         // Set OWT waveform for compose or compose PWLE request
104         virtual bool uploadOwtEffect(const uint8_t *owtData, const uint32_t numBytes,
105                                      struct ff_effect *effect, uint32_t *outEffectIndex,
106                                      int *status) = 0;
107         // Erase OWT waveform
108         virtual bool eraseOwtEffect(int8_t effectIndex, std::vector<ff_effect> *effect) = 0;
109         // Checks to see if DBC (Dynamic Boost Control) feature is supported
110         // by the target device.
111         virtual bool isDbcSupported() = 0;
112         // Configures and enables the DBC feature and all associated parameters
113         virtual bool enableDbc() = 0;
114         // Emit diagnostic information to the given file.
115         virtual void debug(int fd) = 0;
116     };
117 
118     // APIs for obtaining calibration/configuration data from persistent memory.
119     class HwCal {
120       public:
121         virtual ~HwCal() = default;
122         // Obtain the calibration version
123         virtual bool getVersion(uint32_t *value) = 0;
124         // Obtains the LRA resonant frequency to be used for PWLE playback
125         // and click compensation.
126         virtual bool getF0(std::string *value) = 0;
127         // Obtains the LRA series resistance to be used for click
128         // compensation.
129         virtual bool getRedc(std::string *value) = 0;
130         // Obtains the LRA Q factor to be used for Q-dependent waveform
131         // selection.
132         virtual bool getQ(std::string *value) = 0;
133         // Obtains frequency shift for long vibrations.
134         virtual bool getLongFrequencyShift(int32_t *value) = 0;
135         // Obtains device mass for calculating the bandwidth amplitude map
136         virtual bool getDeviceMass(float *value) = 0;
137         // Obtains loc coeff for calculating the bandwidth amplitude map
138         virtual bool getLocCoeff(float *value) = 0;
139         // Obtains the v0/v1(min/max) voltage levels to be applied for
140         // tick/click/long in units of 1%.
141         virtual bool getTickVolLevels(std::array<uint32_t, 2> *value) = 0;
142         virtual bool getClickVolLevels(std::array<uint32_t, 2> *value) = 0;
143         virtual bool getLongVolLevels(std::array<uint32_t, 2> *value) = 0;
144         // Checks if the chirp feature is enabled.
145         virtual bool isChirpEnabled() = 0;
146         // Obtains the supported primitive effects.
147         virtual bool getSupportedPrimitives(uint32_t *value) = 0;
148         // Checks if the f0 compensation feature needs to be enabled.
149         virtual bool isF0CompEnabled() = 0;
150         // Checks if the redc compensation feature needs to be enabled.
151         virtual bool isRedcCompEnabled() = 0;
152         // Emit diagnostic information to the given file.
153         virtual void debug(int fd) = 0;
154     };
155 
156     // APIs for logging data to statistics backend
157     class StatsApi {
158       public:
159         virtual ~StatsApi() = default;
160         // Increment count for effect
161         virtual bool logPrimitive(uint16_t effectIndex) = 0;
162         // Increment count for long/short waveform and duration bucket
163         virtual bool logWaveform(uint16_t effectIndex, int32_t duration) = 0;
164         // Increment count for error
165         virtual bool logError(uint16_t errorIndex) = 0;
166         // Start new latency measurement
167         virtual bool logLatencyStart(uint16_t latencyIndex) = 0;
168         // Finish latency measurement and update latency statistics with result
169         virtual bool logLatencyEnd() = 0;
170         // Emit diagnostic information to the given file.
171         virtual void debug(int fd) = 0;
172     };
173 
174   public:
175     Vibrator(std::unique_ptr<HwApi> hwapi, std::unique_ptr<HwCal> hwcal,
176              std::unique_ptr<StatsApi> statsapi);
177 
178     ndk::ScopedAStatus getCapabilities(int32_t *_aidl_return) override;
179     ndk::ScopedAStatus off() override;
180     ndk::ScopedAStatus on(int32_t timeoutMs,
181                           const std::shared_ptr<IVibratorCallback> &callback) override;
182     ndk::ScopedAStatus perform(Effect effect, EffectStrength strength,
183                                const std::shared_ptr<IVibratorCallback> &callback,
184                                int32_t *_aidl_return) override;
185     ndk::ScopedAStatus getSupportedEffects(std::vector<Effect> *_aidl_return) override;
186     ndk::ScopedAStatus setAmplitude(float amplitude) override;
187     ndk::ScopedAStatus setExternalControl(bool enabled) override;
188     ndk::ScopedAStatus getCompositionDelayMax(int32_t *maxDelayMs);
189     ndk::ScopedAStatus getCompositionSizeMax(int32_t *maxSize);
190     ndk::ScopedAStatus getSupportedPrimitives(std::vector<CompositePrimitive> *supported) override;
191     ndk::ScopedAStatus getPrimitiveDuration(CompositePrimitive primitive,
192                                             int32_t *durationMs) override;
193     ndk::ScopedAStatus compose(const std::vector<CompositeEffect> &composite,
194                                const std::shared_ptr<IVibratorCallback> &callback) override;
195     ndk::ScopedAStatus getSupportedAlwaysOnEffects(std::vector<Effect> *_aidl_return) override;
196     ndk::ScopedAStatus alwaysOnEnable(int32_t id, Effect effect, EffectStrength strength) override;
197     ndk::ScopedAStatus alwaysOnDisable(int32_t id) override;
198     ndk::ScopedAStatus getResonantFrequency(float *resonantFreqHz) override;
199     ndk::ScopedAStatus getQFactor(float *qFactor) override;
200     ndk::ScopedAStatus getFrequencyResolution(float *freqResolutionHz) override;
201     ndk::ScopedAStatus getFrequencyMinimum(float *freqMinimumHz) override;
202     ndk::ScopedAStatus getBandwidthAmplitudeMap(std::vector<float> *_aidl_return) override;
203     ndk::ScopedAStatus getPwlePrimitiveDurationMax(int32_t *durationMs) override;
204     ndk::ScopedAStatus getPwleCompositionSizeMax(int32_t *maxSize) override;
205     ndk::ScopedAStatus getSupportedBraking(std::vector<Braking> *supported) override;
206     ndk::ScopedAStatus composePwle(const std::vector<PrimitivePwle> &composite,
207                                    const std::shared_ptr<IVibratorCallback> &callback) override;
208 
209     binder_status_t dump(int fd, const char **args, uint32_t numArgs) override;
210 
211   private:
212     ndk::ScopedAStatus on(uint32_t timeoutMs, uint32_t effectIndex, const class DspMemChunk *ch,
213                           const std::shared_ptr<IVibratorCallback> &callback);
214     // set 'amplitude' based on an arbitrary scale determined by 'maximum'
215     ndk::ScopedAStatus setEffectAmplitude(float amplitude, float maximum, bool scalable);
216     ndk::ScopedAStatus setGlobalAmplitude(bool set);
217     // 'simple' effects are those precompiled and loaded into the controller
218     ndk::ScopedAStatus getSimpleDetails(Effect effect, EffectStrength strength,
219                                         uint32_t *outEffectIndex, uint32_t *outTimeMs,
220                                         uint32_t *outVolLevel);
221     // 'compound' effects are those composed by stringing multiple 'simple' effects
222     ndk::ScopedAStatus getCompoundDetails(Effect effect, EffectStrength strength,
223                                           uint32_t *outTimeMs, class DspMemChunk *outCh);
224     ndk::ScopedAStatus getPrimitiveDetails(CompositePrimitive primitive, uint32_t *outEffectIndex);
225     ndk::ScopedAStatus performEffect(Effect effect, EffectStrength strength,
226                                      const std::shared_ptr<IVibratorCallback> &callback,
227                                      int32_t *outTimeMs);
228     ndk::ScopedAStatus performEffect(uint32_t effectIndex, uint32_t volLevel,
229                                      const class DspMemChunk *ch,
230                                      const std::shared_ptr<IVibratorCallback> &callback);
231     ndk::ScopedAStatus setPwle(const std::string &pwleQueue);
232     bool isUnderExternalControl();
233     void waitForComplete(std::shared_ptr<IVibratorCallback> &&callback);
234     uint32_t intensityToVolLevel(float intensity, uint32_t effectIndex);
235     bool findHapticAlsaDevice(int *card, int *device);
236     bool hasHapticAlsaDevice();
237     bool enableHapticPcmAmp(struct pcm **haptic_pcm, bool enable, int card, int device);
238     void createPwleMaxLevelLimitMap();
239     void createBandwidthAmplitudeMap();
240     uint16_t amplitudeToScale(float amplitude, float maximum, bool scalable);
241     void updateContext();
242 
243     std::unique_ptr<HwApi> mHwApi;
244     std::unique_ptr<HwCal> mHwCal;
245     std::unique_ptr<StatsApi> mStatsApi;
246     uint32_t mF0Offset;
247     std::array<uint32_t, 2> mTickEffectVol;
248     std::array<uint32_t, 2> mClickEffectVol;
249     std::array<uint32_t, 2> mLongEffectVol;
250     std::vector<ff_effect> mFfEffects;
251     std::vector<uint32_t> mEffectDurations;
252     std::vector<std::vector<int16_t>> mEffectCustomData;
253     std::future<void> mAsyncHandle;
254     int8_t mActiveId{-1};
255     struct pcm *mHapticPcm;
256     int mCard;
257     int mDevice;
258     bool mHasHapticAlsaDevice{false};
259     bool mIsUnderExternalControl;
260     float mLongEffectScale = 1.0;
261     bool mIsChirpEnabled;
262     uint32_t mSupportedPrimitivesBits = 0x0;
263     float mRedc{0};
264     float mResonantFrequency{0};
265     std::vector<CompositePrimitive> mSupportedPrimitives;
266     bool mConfigHapticAlsaDeviceDone{false};
267     std::vector<float> mBandwidthAmplitudeMap{};
268     bool mCreateBandwidthAmplitudeMapDone{false};
269     uint32_t mScaleTime;
270     bool mFadeEnable;
271     uint32_t mScalingFactor;
272     uint32_t mScaleCooldown;
273     bool mContextEnable;
274     bool mContextEnabledPreviously{false};
275     uint32_t mLastEffectPlayedTime = 0;
276     float mLastPlayedScale = 0;
277     sp<CapoDetector> mContextListener;
278     enum hal_state {
279         IDLE,
280         PREPARING,
281         ISSUED,
282         PLAYING,
283         STOPPED,
284         RESTORED,
285     };
286     hal_state halState = IDLE;
287 };
288 
289 }  // namespace vibrator
290 }  // namespace hardware
291 }  // namespace android
292 }  // namespace aidl
293