blob: 560e804c686b6c6a74e6537c3594ccc9ed7d5288 [file] [log] [blame]
Siarhei Vishniakou0438ca82024-03-12 14:27:25 -07001/*
2 * Copyright 2024 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#pragma once
18
19/*
20 * Native input transport.
21 *
22 * The InputConsumer is used by the application to receive events from the input dispatcher.
23 */
24
25#include "InputTransport.h"
26
27namespace android {
28
29/*
30 * Consumes input events from an input channel.
31 */
32class InputConsumer {
33public:
34 /* Create a consumer associated with an input channel. */
35 explicit InputConsumer(const std::shared_ptr<InputChannel>& channel);
36 /* Create a consumer associated with an input channel, override resampling system property */
37 explicit InputConsumer(const std::shared_ptr<InputChannel>& channel,
38 bool enableTouchResampling);
39
40 /* Destroys the consumer and releases its input channel. */
41 ~InputConsumer();
42
43 /* Gets the underlying input channel. */
44 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
45
46 /* Consumes an input event from the input channel and copies its contents into
47 * an InputEvent object created using the specified factory.
48 *
49 * Tries to combine a series of move events into larger batches whenever possible.
50 *
51 * If consumeBatches is false, then defers consuming pending batched events if it
52 * is possible for additional samples to be added to them later. Call hasPendingBatch()
53 * to determine whether a pending batch is available to be consumed.
54 *
55 * If consumeBatches is true, then events are still batched but they are consumed
56 * immediately as soon as the input channel is exhausted.
57 *
58 * The frameTime parameter specifies the time when the current display frame started
59 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
60 *
61 * The returned sequence number is never 0 unless the operation failed.
62 *
63 * Returns OK on success.
64 * Returns WOULD_BLOCK if there is no event present.
65 * Returns DEAD_OBJECT if the channel's peer has been closed.
66 * Returns NO_MEMORY if the event could not be created.
67 * Other errors probably indicate that the channel is broken.
68 */
69 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches, nsecs_t frameTime,
70 uint32_t* outSeq, InputEvent** outEvent);
71
72 /* Sends a finished signal to the publisher to inform it that the message
73 * with the specified sequence number has finished being process and whether
74 * the message was handled by the consumer.
75 *
76 * Returns OK on success.
77 * Returns BAD_VALUE if seq is 0.
78 * Other errors probably indicate that the channel is broken.
79 */
80 status_t sendFinishedSignal(uint32_t seq, bool handled);
81
82 status_t sendTimeline(int32_t inputEventId,
83 std::array<nsecs_t, GraphicsTimeline::SIZE> timeline);
84
85 /* Returns true if there is a pending batch.
86 *
87 * Should be called after calling consume() with consumeBatches == false to determine
88 * whether consume() should be called again later on with consumeBatches == true.
89 */
90 bool hasPendingBatch() const;
91
92 /* Returns the source of first pending batch if exist.
93 *
94 * Should be called after calling consume() with consumeBatches == false to determine
95 * whether consume() should be called again later on with consumeBatches == true.
96 */
97 int32_t getPendingBatchSource() const;
98
99 /* Returns true when there is *likely* a pending batch or a pending event in the channel.
100 *
101 * This is only a performance hint and may return false negative results. Clients should not
102 * rely on availability of the message based on the return value.
103 */
104 bool probablyHasInput() const;
105
106 std::string dump() const;
107
108private:
109 // True if touch resampling is enabled.
110 const bool mResampleTouch;
111
112 std::shared_ptr<InputChannel> mChannel;
113
114 // The current input message.
115 InputMessage mMsg;
116
117 // True if mMsg contains a valid input message that was deferred from the previous
118 // call to consume and that still needs to be handled.
119 bool mMsgDeferred;
120
121 // Batched motion events per device and source.
122 struct Batch {
123 std::vector<InputMessage> samples;
124 };
125 std::vector<Batch> mBatches;
126
127 // Touch state per device and source, only for sources of class pointer.
128 struct History {
129 nsecs_t eventTime;
130 BitSet32 idBits;
131 int32_t idToIndex[MAX_POINTER_ID + 1];
132 PointerCoords pointers[MAX_POINTERS];
133
134 void initializeFrom(const InputMessage& msg) {
135 eventTime = msg.body.motion.eventTime;
136 idBits.clear();
137 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
138 uint32_t id = msg.body.motion.pointers[i].properties.id;
139 idBits.markBit(id);
140 idToIndex[id] = i;
141 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
142 }
143 }
144
145 void initializeFrom(const History& other) {
146 eventTime = other.eventTime;
147 idBits = other.idBits; // temporary copy
148 for (size_t i = 0; i < other.idBits.count(); i++) {
149 uint32_t id = idBits.clearFirstMarkedBit();
150 int32_t index = other.idToIndex[id];
151 idToIndex[id] = index;
152 pointers[index].copyFrom(other.pointers[index]);
153 }
154 idBits = other.idBits; // final copy
155 }
156
157 const PointerCoords& getPointerById(uint32_t id) const { return pointers[idToIndex[id]]; }
158
159 bool hasPointerId(uint32_t id) const { return idBits.hasBit(id); }
160 };
161 struct TouchState {
162 int32_t deviceId;
163 int32_t source;
164 size_t historyCurrent;
165 size_t historySize;
166 History history[2];
167 History lastResample;
168
169 void initialize(int32_t incomingDeviceId, int32_t incomingSource) {
170 deviceId = incomingDeviceId;
171 source = incomingSource;
172 historyCurrent = 0;
173 historySize = 0;
174 lastResample.eventTime = 0;
175 lastResample.idBits.clear();
176 }
177
178 void addHistory(const InputMessage& msg) {
179 historyCurrent ^= 1;
180 if (historySize < 2) {
181 historySize += 1;
182 }
183 history[historyCurrent].initializeFrom(msg);
184 }
185
186 const History* getHistory(size_t index) const {
187 return &history[(historyCurrent + index) & 1];
188 }
189
190 bool recentCoordinatesAreIdentical(uint32_t id) const {
191 // Return true if the two most recently received "raw" coordinates are identical
192 if (historySize < 2) {
193 return false;
194 }
195 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
196 return false;
197 }
198 float currentX = getHistory(0)->getPointerById(id).getX();
199 float currentY = getHistory(0)->getPointerById(id).getY();
200 float previousX = getHistory(1)->getPointerById(id).getX();
201 float previousY = getHistory(1)->getPointerById(id).getY();
202 if (currentX == previousX && currentY == previousY) {
203 return true;
204 }
205 return false;
206 }
207 };
208 std::vector<TouchState> mTouchStates;
209
210 // Chain of batched sequence numbers. When multiple input messages are combined into
211 // a batch, we append a record here that associates the last sequence number in the
212 // batch with the previous one. When the finished signal is sent, we traverse the
213 // chain to individually finish all input messages that were part of the batch.
214 struct SeqChain {
215 uint32_t seq; // sequence number of batched input message
216 uint32_t chain; // sequence number of previous batched input message
217 };
218 std::vector<SeqChain> mSeqChains;
219
220 // The time at which each event with the sequence number 'seq' was consumed.
221 // This data is provided in 'finishInputEvent' so that the receiving end can measure the latency
222 // This collection is populated when the event is received, and the entries are erased when the
223 // events are finished. It should not grow infinitely because if an event is not ack'd, ANR
224 // will be raised for that connection, and no further events will be posted to that channel.
225 std::unordered_map<uint32_t /*seq*/, nsecs_t /*consumeTime*/> mConsumeTimes;
226
227 status_t consumeBatch(InputEventFactoryInterface* factory, nsecs_t frameTime, uint32_t* outSeq,
228 InputEvent** outEvent);
229 status_t consumeSamples(InputEventFactoryInterface* factory, Batch& batch, size_t count,
230 uint32_t* outSeq, InputEvent** outEvent);
231
232 void updateTouchState(InputMessage& msg);
233 void resampleTouchState(nsecs_t frameTime, MotionEvent* event, const InputMessage* next);
234
235 ssize_t findBatch(int32_t deviceId, int32_t source) const;
236 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
237
238 nsecs_t getConsumeTime(uint32_t seq) const;
239 void popConsumeTime(uint32_t seq);
240 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
241
242 static void rewriteMessage(TouchState& state, InputMessage& msg);
243 static bool canAddSample(const Batch& batch, const InputMessage* msg);
244 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
245
246 static bool isTouchResamplingEnabled();
247};
248
249} // namespace android