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/unique_fd.h>
20 #include <linux/input.h>
21 #include <tinyalsa/asoundlib.h>
22 
23 #include <array>
24 #include <fstream>
25 #include <future>
26 
27 namespace aidl {
28 namespace android {
29 namespace hardware {
30 namespace vibrator {
31 
32 class Vibrator : public BnVibrator {
33   public:
34     // APIs for interfacing with the GPIO pin.
35     class HwGPIO {
36       public:
37         virtual ~HwGPIO() = default;
38         // Get the GPIO pin num and address shift information
39         virtual bool getGPIO() = 0;
40         // Init the GPIO function
41         virtual bool initGPIO() = 0;
42         // Trigger the GPIO pin to synchronize both vibrators's play
43         virtual bool setGPIOOutput(bool value) = 0;
44         // Emit diagnostic information to the given file.
45         virtual void debug(int fd) = 0;
46     };
47 
48     // APIs for interfacing with the kernel driver.
49     class HwApi {
50       public:
51         virtual ~HwApi() = default;
52         // Stores the LRA resonant frequency to be used for PWLE playback
53         // and click compensation.
54         virtual bool setF0(std::string value) = 0;
55         // Stores the frequency offset for long vibrations.
56         virtual bool setF0Offset(uint32_t value) = 0;
57         // Stores the LRA series resistance to be used for click
58         // compensation.
59         virtual bool setRedc(std::string value) = 0;
60         // Stores the LRA Q factor to be used for Q-dependent waveform
61         // selection.
62         virtual bool setQ(std::string value) = 0;
63         // Reports the number of effect waveforms loaded in firmware.
64         virtual bool getEffectCount(uint32_t *value) = 0;
65         // Blocks until timeout or vibrator reaches desired state
66         // (2 = ASP enabled, 1 = haptic enabled, 0 = disabled).
67         virtual bool pollVibeState(uint32_t value, int32_t timeoutMs = -1) = 0;
68         // Reports whether getOwtFreeSpace() is supported.
69         virtual bool hasOwtFreeSpace() = 0;
70         // Reports the available OWT bytes.
71         virtual bool getOwtFreeSpace(uint32_t *value) = 0;
72         // Enables/Disables F0 compensation enable status
73         virtual bool setF0CompEnable(bool value) = 0;
74         // Enables/Disables Redc compensation enable status
75         virtual bool setRedcCompEnable(bool value) = 0;
76         // Stores the minumun delay time between playback and stop effects.
77         virtual bool setMinOnOffInterval(uint32_t value) = 0;
78         // Indicates the number of 0.125-dB steps of attenuation to apply to
79         // waveforms triggered in response to vibration calls from the
80         // Android vibrator HAL.
81         virtual bool setFFGain(int fd, uint16_t value) = 0;
82         // Create/modify custom effects for all physical waveforms.
83         virtual bool setFFEffect(int fd, struct ff_effect *effect, uint16_t timeoutMs) = 0;
84         // Activates/deactivates the effect index after setFFGain() and setFFEffect().
85         virtual bool setFFPlay(int fd, int8_t index, bool value) = 0;
86         // Get the Alsa device for the audio coupled haptics effect
87         virtual bool getHapticAlsaDevice(int *card, int *device) = 0;
88         // Set haptics PCM amplifier before triggering audio haptics feature
89         virtual bool setHapticPcmAmp(struct pcm **haptic_pcm, bool enable, int card,
90                                      int device) = 0;
91         // Set OWT waveform for compose or compose PWLE request
92         virtual bool uploadOwtEffect(int fd, const uint8_t *owtData, const uint32_t numBytes,
93                                      struct ff_effect *effect, uint32_t *outEffectIndex,
94                                      int *status) = 0;
95         // Erase OWT waveform
96         virtual bool eraseOwtEffect(int fd, int8_t effectIndex, std::vector<ff_effect> *effect) = 0;
97         // Emit diagnostic information to the given file.
98         virtual void debug(int fd) = 0;
99     };
100 
101     // APIs for obtaining calibration/configuration data from persistent memory.
102     class HwCal {
103       public:
104         virtual ~HwCal() = default;
105         // Obtain the calibration version
106         virtual bool getVersion(uint32_t *value) = 0;
107         // Obtains the LRA resonant frequency to be used for PWLE playback
108         // and click compensation.
109         virtual bool getF0(std::string *value) = 0;
110         // Obtains the offset for actuator that will adjust configured F0 to target
111         // frequency for dual actuators
112         virtual bool getF0SyncOffset(uint32_t *value) = 0;
113         // Obtains the LRA series resistance to be used for click
114         // compensation.
115         virtual bool getRedc(std::string *value) = 0;
116         // Obtains the LRA Q factor to be used for Q-dependent waveform
117         // selection.
118         virtual bool getQ(std::string *value) = 0;
119         // Obtains frequency shift for long vibrations.
120         virtual bool getLongFrequencyShift(int32_t *value) = 0;
121         // Obtains the v0/v1(min/max) voltage levels to be applied for
122         // tick/click/long in units of 1%.
123         virtual bool getTickVolLevels(std::array<uint32_t, 2> *value) = 0;
124         virtual bool getClickVolLevels(std::array<uint32_t, 2> *value) = 0;
125         virtual bool getLongVolLevels(std::array<uint32_t, 2> *value) = 0;
126         // Checks if the chirp feature is enabled.
127         virtual bool isChirpEnabled() = 0;
128         // Obtains the supported primitive effects.
129         virtual bool getSupportedPrimitives(uint32_t *value) = 0;
130         // Checks if the f0 compensation feature needs to be enabled.
131         virtual bool isF0CompEnabled() = 0;
132         // Checks if the redc compensation feature needs to be enabled.
133         virtual bool isRedcCompEnabled() = 0;
134         // Emit diagnostic information to the given file.
135         virtual void debug(int fd) = 0;
136     };
137 
138   public:
139     Vibrator(std::unique_ptr<HwApi> hwApiDefault, std::unique_ptr<HwCal> hwCalDefault,
140              std::unique_ptr<HwApi> hwApiDual, std::unique_ptr<HwCal> hwCalDual,
141              std::unique_ptr<HwGPIO> hwgpio);
142 
143     // BnVibrator APIs
144     ndk::ScopedAStatus getCapabilities(int32_t *_aidl_return) override;
145     ndk::ScopedAStatus off() override;
146     ndk::ScopedAStatus on(int32_t timeoutMs,
147                           const std::shared_ptr<IVibratorCallback> &callback) override;
148     ndk::ScopedAStatus perform(Effect effect, EffectStrength strength,
149                                const std::shared_ptr<IVibratorCallback> &callback,
150                                int32_t *_aidl_return) override;
151     ndk::ScopedAStatus getSupportedEffects(std::vector<Effect> *_aidl_return) override;
152     ndk::ScopedAStatus setAmplitude(float amplitude) override;
153     ndk::ScopedAStatus setExternalControl(bool enabled) override;
154     ndk::ScopedAStatus getCompositionDelayMax(int32_t *maxDelayMs);
155     ndk::ScopedAStatus getCompositionSizeMax(int32_t *maxSize);
156     ndk::ScopedAStatus getSupportedPrimitives(std::vector<CompositePrimitive> *supported) override;
157     ndk::ScopedAStatus getPrimitiveDuration(CompositePrimitive primitive,
158                                             int32_t *durationMs) override;
159     ndk::ScopedAStatus compose(const std::vector<CompositeEffect> &composite,
160                                const std::shared_ptr<IVibratorCallback> &callback) override;
161     ndk::ScopedAStatus getSupportedAlwaysOnEffects(std::vector<Effect> *_aidl_return) override;
162     ndk::ScopedAStatus alwaysOnEnable(int32_t id, Effect effect, EffectStrength strength) override;
163     ndk::ScopedAStatus alwaysOnDisable(int32_t id) override;
164     ndk::ScopedAStatus getResonantFrequency(float *resonantFreqHz) override;
165     ndk::ScopedAStatus getQFactor(float *qFactor) override;
166     ndk::ScopedAStatus getFrequencyResolution(float *freqResolutionHz) override;
167     ndk::ScopedAStatus getFrequencyMinimum(float *freqMinimumHz) override;
168     ndk::ScopedAStatus getBandwidthAmplitudeMap(std::vector<float> *_aidl_return) override;
169     ndk::ScopedAStatus getPwlePrimitiveDurationMax(int32_t *durationMs) override;
170     ndk::ScopedAStatus getPwleCompositionSizeMax(int32_t *maxSize) override;
171     ndk::ScopedAStatus getSupportedBraking(std::vector<Braking> *supported) override;
172     ndk::ScopedAStatus composePwle(const std::vector<PrimitivePwle> &composite,
173                                    const std::shared_ptr<IVibratorCallback> &callback) override;
174 
175     // BnCInterface APIs
176     binder_status_t dump(int fd, const char **args, uint32_t numArgs) override;
177 
178     static constexpr uint32_t MIN_ON_OFF_INTERVAL_US = 8500;  // SVC initialization time
179 
180   private:
181     ndk::ScopedAStatus on(uint32_t timeoutMs, uint32_t effectIndex, const class DspMemChunk *ch,
182                           const std::shared_ptr<IVibratorCallback> &callback);
183     // set 'amplitude' based on an arbitrary scale determined by 'maximum'
184     ndk::ScopedAStatus setEffectAmplitude(float amplitude, float maximum);
185     ndk::ScopedAStatus setGlobalAmplitude(bool set);
186     // 'simple' effects are those precompiled and loaded into the controller
187     ndk::ScopedAStatus getSimpleDetails(Effect effect, EffectStrength strength,
188                                         uint32_t *outEffectIndex, uint32_t *outTimeMs,
189                                         uint32_t *outVolLevel);
190     // 'compound' effects are those composed by stringing multiple 'simple' effects
191     ndk::ScopedAStatus getCompoundDetails(Effect effect, EffectStrength strength,
192                                           uint32_t *outTimeMs, class DspMemChunk *outCh);
193     ndk::ScopedAStatus getPrimitiveDetails(CompositePrimitive primitive, uint32_t *outEffectIndex);
194     ndk::ScopedAStatus performEffect(Effect effect, EffectStrength strength,
195                                      const std::shared_ptr<IVibratorCallback> &callback,
196                                      int32_t *outTimeMs);
197     ndk::ScopedAStatus performEffect(uint32_t effectIndex, uint32_t volLevel,
198                                      const class DspMemChunk *ch,
199                                      const std::shared_ptr<IVibratorCallback> &callback);
200     ndk::ScopedAStatus setPwle(const std::string &pwleQueue);
201     bool isUnderExternalControl();
202     void waitForComplete(std::shared_ptr<IVibratorCallback> &&callback);
203     uint32_t intensityToVolLevel(float intensity, uint32_t effectIndex);
204     bool findHapticAlsaDevice(int *card, int *device);
205     bool hasHapticAlsaDevice();
206     bool enableHapticPcmAmp(struct pcm **haptic_pcm, bool enable, int card, int device);
207 
208     std::unique_ptr<HwApi> mHwApiDef;
209     std::unique_ptr<HwCal> mHwCalDef;
210     std::unique_ptr<HwApi> mHwApiDual;
211     std::unique_ptr<HwCal> mHwCalDual;
212     std::unique_ptr<HwGPIO> mHwGPIO;
213     uint32_t mF0Offset;
214     uint32_t mF0OffsetDual;
215     std::array<uint32_t, 2> mTickEffectVol;
216     std::array<uint32_t, 2> mClickEffectVol;
217     std::array<uint32_t, 2> mLongEffectVol;
218     std::vector<ff_effect> mFfEffects;
219     std::vector<ff_effect> mFfEffectsDual;
220     std::vector<uint32_t> mEffectDurations;
221     std::vector<std::vector<int16_t>> mEffectCustomData;
222     std::vector<std::vector<int16_t>> mEffectCustomDataDual;
223     std::future<void> mAsyncHandle;
224     ::android::base::unique_fd mInputFd;
225     ::android::base::unique_fd mInputFdDual;
226     int8_t mActiveId{-1};
227     struct pcm *mHapticPcm;
228     int mCard;
229     int mDevice;
230     bool mHasHapticAlsaDevice{false};
231     bool mIsUnderExternalControl;
232     float mLongEffectScale{1.0};
233     bool mIsChirpEnabled;
234     uint32_t mSupportedPrimitivesBits = 0x0;
235     std::vector<CompositePrimitive> mSupportedPrimitives;
236     std::vector<float> mPrimitiveMaxScale;
237     std::vector<float> mPrimitiveMinScale;
238     bool mConfigHapticAlsaDeviceDone{false};
239     bool mGPIOStatus;
240     bool mIsDual{false};
241     std::mutex mActiveId_mutex;  // protects mActiveId
242 };
243 
244 }  // namespace vibrator
245 }  // namespace hardware
246 }  // namespace android
247 }  // namespace aidl
248