blob: acea473242538c869488b3700e728c3c401ad60a [file] [log] [blame]
Jeff Brown5912f952013-07-01 19:10:31 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// Provides a shared memory transport for input events.
5//
6#define LOG_TAG "InputTransport"
7
8//#define LOG_NDEBUG 0
9
10// Log debug messages about channel messages (send message, receive message)
11#define DEBUG_CHANNEL_MESSAGES 0
12
13// Log debug messages whenever InputChannel objects are created/destroyed
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -070014static constexpr bool DEBUG_CHANNEL_LIFECYCLE = false;
Jeff Brown5912f952013-07-01 19:10:31 -070015
16// Log debug messages about transport actions
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080017static constexpr bool DEBUG_TRANSPORT_ACTIONS = false;
Jeff Brown5912f952013-07-01 19:10:31 -070018
19// Log debug messages about touch event resampling
20#define DEBUG_RESAMPLING 0
21
Jeff Brown5912f952013-07-01 19:10:31 -070022#include <errno.h>
23#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070024#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070025#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070026#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070027#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070028#include <unistd.h>
29
Michael Wright3dd60e22019-03-27 22:06:44 +000030#include <android-base/stringprintf.h>
31#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070032#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070033#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000034#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070035
Jeff Brown5912f952013-07-01 19:10:31 -070036#include <input/InputTransport.h>
37
Michael Wright3dd60e22019-03-27 22:06:44 +000038using android::base::StringPrintf;
39
Jeff Brown5912f952013-07-01 19:10:31 -070040namespace android {
41
42// Socket buffer size. The default is typically about 128KB, which is much larger than
43// we really need. So we make it smaller. It just needs to be big enough to hold
44// a few dozen large multi-finger motion events in the case where an application gets
45// behind processing touches.
46static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
47
48// Nanoseconds per milliseconds.
49static const nsecs_t NANOS_PER_MS = 1000000;
50
51// Latency added during resampling. A few milliseconds doesn't hurt much but
52// reduces the impact of mispredicted touch positions.
53static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
54
55// Minimum time difference between consecutive samples before attempting to resample.
56static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
57
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070058// Maximum time difference between consecutive samples before attempting to resample
59// by extrapolation.
60static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
61
Jeff Brown5912f952013-07-01 19:10:31 -070062// Maximum time to predict forward from the last known state, to avoid predicting too
63// far into the future. This time is further bounded by 50% of the last time delta.
64static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
65
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -060066/**
67 * System property for enabling / disabling touch resampling.
68 * Resampling extrapolates / interpolates the reported touch event coordinates to better
69 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
70 * Resampling is not needed (and should be disabled) on hardware that already
71 * has touch events triggered by VSYNC.
72 * Set to "1" to enable resampling (default).
73 * Set to "0" to disable resampling.
74 * Resampling is enabled by default.
75 */
76static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
77
Jeff Brown5912f952013-07-01 19:10:31 -070078template<typename T>
79inline static T min(const T& a, const T& b) {
80 return a < b ? a : b;
81}
82
83inline static float lerp(float a, float b, float alpha) {
84 return a + alpha * (b - a);
85}
86
Siarhei Vishniakou128eab12019-05-23 10:25:59 +080087inline static bool isPointerEvent(int32_t source) {
88 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
89}
90
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080091inline static const char* toString(bool value) {
92 return value ? "true" : "false";
93}
94
Jeff Brown5912f952013-07-01 19:10:31 -070095// --- InputMessage ---
96
97bool InputMessage::isValid(size_t actualSize) const {
98 if (size() == actualSize) {
99 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700100 case Type::KEY:
101 return true;
102 case Type::MOTION:
103 return body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
104 case Type::FINISHED:
105 return true;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800106 case Type::FOCUS:
107 return true;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800108 case Type::CAPTURE:
109 return true;
Jeff Brown5912f952013-07-01 19:10:31 -0700110 }
111 }
112 return false;
113}
114
115size_t InputMessage::size() const {
116 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700117 case Type::KEY:
118 return sizeof(Header) + body.key.size();
119 case Type::MOTION:
120 return sizeof(Header) + body.motion.size();
121 case Type::FINISHED:
122 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800123 case Type::FOCUS:
124 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800125 case Type::CAPTURE:
126 return sizeof(Header) + body.capture.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700127 }
128 return sizeof(Header);
129}
130
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800131/**
132 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
133 * memory to zero, then only copy the valid bytes on a per-field basis.
134 */
135void InputMessage::getSanitizedCopy(InputMessage* msg) const {
136 memset(msg, 0, sizeof(*msg));
137
138 // Write the header
139 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500140 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800141
142 // Write the body
143 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700144 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800145 // int32_t eventId
146 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800147 // nsecs_t eventTime
148 msg->body.key.eventTime = body.key.eventTime;
149 // int32_t deviceId
150 msg->body.key.deviceId = body.key.deviceId;
151 // int32_t source
152 msg->body.key.source = body.key.source;
153 // int32_t displayId
154 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600155 // std::array<uint8_t, 32> hmac
156 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800157 // int32_t action
158 msg->body.key.action = body.key.action;
159 // int32_t flags
160 msg->body.key.flags = body.key.flags;
161 // int32_t keyCode
162 msg->body.key.keyCode = body.key.keyCode;
163 // int32_t scanCode
164 msg->body.key.scanCode = body.key.scanCode;
165 // int32_t metaState
166 msg->body.key.metaState = body.key.metaState;
167 // int32_t repeatCount
168 msg->body.key.repeatCount = body.key.repeatCount;
169 // nsecs_t downTime
170 msg->body.key.downTime = body.key.downTime;
171 break;
172 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700173 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800174 // int32_t eventId
175 msg->body.motion.eventId = body.motion.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800176 // nsecs_t eventTime
177 msg->body.motion.eventTime = body.motion.eventTime;
178 // int32_t deviceId
179 msg->body.motion.deviceId = body.motion.deviceId;
180 // int32_t source
181 msg->body.motion.source = body.motion.source;
182 // int32_t displayId
183 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600184 // std::array<uint8_t, 32> hmac
185 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800186 // int32_t action
187 msg->body.motion.action = body.motion.action;
188 // int32_t actionButton
189 msg->body.motion.actionButton = body.motion.actionButton;
190 // int32_t flags
191 msg->body.motion.flags = body.motion.flags;
192 // int32_t metaState
193 msg->body.motion.metaState = body.motion.metaState;
194 // int32_t buttonState
195 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800196 // MotionClassification classification
197 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800198 // int32_t edgeFlags
199 msg->body.motion.edgeFlags = body.motion.edgeFlags;
200 // nsecs_t downTime
201 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700202
203 msg->body.motion.dsdx = body.motion.dsdx;
204 msg->body.motion.dtdx = body.motion.dtdx;
205 msg->body.motion.dtdy = body.motion.dtdy;
206 msg->body.motion.dsdy = body.motion.dsdy;
207 msg->body.motion.tx = body.motion.tx;
208 msg->body.motion.ty = body.motion.ty;
209
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800210 // float xPrecision
211 msg->body.motion.xPrecision = body.motion.xPrecision;
212 // float yPrecision
213 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700214 // float xCursorPosition
215 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
216 // float yCursorPosition
217 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800218 // uint32_t pointerCount
219 msg->body.motion.pointerCount = body.motion.pointerCount;
220 //struct Pointer pointers[MAX_POINTERS]
221 for (size_t i = 0; i < body.motion.pointerCount; i++) {
222 // PointerProperties properties
223 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
224 msg->body.motion.pointers[i].properties.toolType =
225 body.motion.pointers[i].properties.toolType,
226 // PointerCoords coords
227 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
228 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
229 memcpy(&msg->body.motion.pointers[i].coords.values[0],
230 &body.motion.pointers[i].coords.values[0],
231 count * (sizeof(body.motion.pointers[i].coords.values[0])));
232 }
233 break;
234 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700235 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800236 msg->body.finished.handled = body.finished.handled;
237 break;
238 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800239 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800240 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800241 msg->body.focus.hasFocus = body.focus.hasFocus;
242 msg->body.focus.inTouchMode = body.focus.inTouchMode;
243 break;
244 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800245 case InputMessage::Type::CAPTURE: {
246 msg->body.capture.eventId = body.capture.eventId;
247 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
248 break;
249 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800250 }
251}
Jeff Brown5912f952013-07-01 19:10:31 -0700252
253// --- InputChannel ---
254
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500255std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500256 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700257 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
258 if (result != 0) {
259 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
260 strerror(errno));
261 return nullptr;
262 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500263 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500264 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700265}
266
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500267InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
268 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700269 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500270 ALOGD("Input channel constructed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700271 }
Jeff Brown5912f952013-07-01 19:10:31 -0700272}
273
274InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700275 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500276 ALOGD("Input channel destroyed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700277 }
Robert Carr3720ed02018-08-08 16:08:27 -0700278}
279
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800280status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500281 std::unique_ptr<InputChannel>& outServerChannel,
282 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700283 int sockets[2];
284 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
285 status_t result = -errno;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500286 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d", name.c_str(), errno);
287 outServerChannel.reset();
288 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700289 return result;
290 }
291
292 int bufferSize = SOCKET_BUFFER_SIZE;
293 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
294 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
295 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
296 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
297
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700298 sp<IBinder> token = new BBinder();
299
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700300 std::string serverChannelName = name + " (server)";
301 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700302 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700303
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700304 std::string clientChannelName = name + " (client)";
305 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700306 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700307 return OK;
308}
309
310status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800311 const size_t msgLength = msg->size();
312 InputMessage cleanMsg;
313 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700314 ssize_t nWrite;
315 do {
Chris Ye0783e992020-06-02 21:34:49 -0700316 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700317 } while (nWrite == -1 && errno == EINTR);
318
319 if (nWrite < 0) {
320 int error = errno;
321#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800322 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
323 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700324#endif
325 if (error == EAGAIN || error == EWOULDBLOCK) {
326 return WOULD_BLOCK;
327 }
328 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
329 return DEAD_OBJECT;
330 }
331 return -error;
332 }
333
334 if (size_t(nWrite) != msgLength) {
335#if DEBUG_CHANNEL_MESSAGES
336 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800337 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700338#endif
339 return DEAD_OBJECT;
340 }
341
342#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800343 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700344#endif
345 return OK;
346}
347
348status_t InputChannel::receiveMessage(InputMessage* msg) {
349 ssize_t nRead;
350 do {
Chris Ye0783e992020-06-02 21:34:49 -0700351 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700352 } while (nRead == -1 && errno == EINTR);
353
354 if (nRead < 0) {
355 int error = errno;
356#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800357 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700358#endif
359 if (error == EAGAIN || error == EWOULDBLOCK) {
360 return WOULD_BLOCK;
361 }
362 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
363 return DEAD_OBJECT;
364 }
365 return -error;
366 }
367
368 if (nRead == 0) { // check for EOF
369#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800370 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700371#endif
372 return DEAD_OBJECT;
373 }
374
375 if (!msg->isValid(nRead)) {
376#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800377 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700378#endif
379 return BAD_VALUE;
380 }
381
382#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800383 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700384#endif
385 return OK;
386}
387
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500388std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700389 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700390 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700391}
392
Garfield Tan15601662020-09-22 15:32:38 -0700393void InputChannel::copyTo(InputChannel& outChannel) const {
394 outChannel.mName = getName();
395 outChannel.mFd = dupFd();
396 outChannel.mToken = getConnectionToken();
397}
398
Chris Ye0783e992020-06-02 21:34:49 -0700399status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500400 if (parcel == nullptr) {
401 ALOGE("%s: Null parcel", __func__);
402 return BAD_VALUE;
403 }
404 return parcel->writeStrongBinder(mToken)
405 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700406}
407
Chris Ye0783e992020-06-02 21:34:49 -0700408status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500409 if (parcel == nullptr) {
410 ALOGE("%s: Null parcel", __func__);
411 return BAD_VALUE;
412 }
413 mToken = parcel->readStrongBinder();
414 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700415}
416
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700417sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500418 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700419}
420
Garfield Tan15601662020-09-22 15:32:38 -0700421base::unique_fd InputChannel::dupFd() const {
422 android::base::unique_fd newFd(::dup(getFd()));
423 if (!newFd.ok()) {
424 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
425 strerror(errno));
426 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
427 // If this process is out of file descriptors, then throwing that might end up exploding
428 // on the other side of a binder call, which isn't really helpful.
429 // Better to just crash here and hope that the FD leak is slow.
430 // Other failures could be client errors, so we still propagate those back to the caller.
431 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
432 getName().c_str());
433 return {};
434 }
435 return newFd;
436}
437
Jeff Brown5912f952013-07-01 19:10:31 -0700438// --- InputPublisher ---
439
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500440InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700441
442InputPublisher::~InputPublisher() {
443}
444
Garfield Tan1c7bc862020-01-28 13:24:04 -0800445status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
446 int32_t source, int32_t displayId,
447 std::array<uint8_t, 32> hmac, int32_t action,
448 int32_t flags, int32_t keyCode, int32_t scanCode,
449 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
450 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000451 if (ATRACE_ENABLED()) {
452 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
453 mChannel->getName().c_str(), keyCode);
454 ATRACE_NAME(message.c_str());
455 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800456 if (DEBUG_TRANSPORT_ACTIONS) {
457 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
458 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
459 "downTime=%" PRId64 ", eventTime=%" PRId64,
460 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
461 metaState, repeatCount, downTime, eventTime);
462 }
Jeff Brown5912f952013-07-01 19:10:31 -0700463
464 if (!seq) {
465 ALOGE("Attempted to publish a key event with sequence number 0.");
466 return BAD_VALUE;
467 }
468
469 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700470 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500471 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800472 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700473 msg.body.key.deviceId = deviceId;
474 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100475 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700476 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700477 msg.body.key.action = action;
478 msg.body.key.flags = flags;
479 msg.body.key.keyCode = keyCode;
480 msg.body.key.scanCode = scanCode;
481 msg.body.key.metaState = metaState;
482 msg.body.key.repeatCount = repeatCount;
483 msg.body.key.downTime = downTime;
484 msg.body.key.eventTime = eventTime;
485 return mChannel->sendMessage(&msg);
486}
487
488status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800489 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600490 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
491 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700492 MotionClassification classification, const ui::Transform& transform, float xPrecision,
493 float yPrecision, float xCursorPosition, float yCursorPosition, nsecs_t downTime,
494 nsecs_t eventTime, uint32_t pointerCount, const PointerProperties* pointerProperties,
495 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000496 if (ATRACE_ENABLED()) {
497 std::string message = StringPrintf(
498 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
499 mChannel->getName().c_str(), action);
500 ATRACE_NAME(message.c_str());
501 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800502 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700503 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700504 transform.dump(transformString, "transform", " ");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800505 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
506 "displayId=%" PRId32 ", "
507 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700508 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800509 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700510 "pointerCount=%" PRIu32 " \n%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800511 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
512 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700513 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
514 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800515 }
Jeff Brown5912f952013-07-01 19:10:31 -0700516
517 if (!seq) {
518 ALOGE("Attempted to publish a motion event with sequence number 0.");
519 return BAD_VALUE;
520 }
521
522 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700523 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800524 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700525 return BAD_VALUE;
526 }
527
528 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700529 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500530 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800531 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700532 msg.body.motion.deviceId = deviceId;
533 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700534 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700535 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700536 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100537 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700538 msg.body.motion.flags = flags;
539 msg.body.motion.edgeFlags = edgeFlags;
540 msg.body.motion.metaState = metaState;
541 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800542 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700543 msg.body.motion.dsdx = transform.dsdx();
544 msg.body.motion.dtdx = transform.dtdx();
545 msg.body.motion.dtdy = transform.dtdy();
546 msg.body.motion.dsdy = transform.dsdy();
547 msg.body.motion.tx = transform.tx();
548 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700549 msg.body.motion.xPrecision = xPrecision;
550 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700551 msg.body.motion.xCursorPosition = xCursorPosition;
552 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700553 msg.body.motion.downTime = downTime;
554 msg.body.motion.eventTime = eventTime;
555 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100556 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700557 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
558 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
559 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700560
Jeff Brown5912f952013-07-01 19:10:31 -0700561 return mChannel->sendMessage(&msg);
562}
563
Garfield Tan1c7bc862020-01-28 13:24:04 -0800564status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
565 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800566 if (ATRACE_ENABLED()) {
567 std::string message =
568 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
569 mChannel->getName().c_str(), toString(hasFocus),
570 toString(inTouchMode));
571 ATRACE_NAME(message.c_str());
572 }
573
574 InputMessage msg;
575 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500576 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800577 msg.body.focus.eventId = eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800578 msg.body.focus.hasFocus = hasFocus ? 1 : 0;
579 msg.body.focus.inTouchMode = inTouchMode ? 1 : 0;
580 return mChannel->sendMessage(&msg);
581}
582
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800583status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
584 bool pointerCaptureEnabled) {
585 if (ATRACE_ENABLED()) {
586 std::string message =
587 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
588 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
589 ATRACE_NAME(message.c_str());
590 }
591
592 InputMessage msg;
593 msg.header.type = InputMessage::Type::CAPTURE;
594 msg.header.seq = seq;
595 msg.body.capture.eventId = eventId;
596 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled ? 1 : 0;
597 return mChannel->sendMessage(&msg);
598}
599
Jeff Brown5912f952013-07-01 19:10:31 -0700600status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800601 if (DEBUG_TRANSPORT_ACTIONS) {
602 ALOGD("channel '%s' publisher ~ receiveFinishedSignal", mChannel->getName().c_str());
603 }
Jeff Brown5912f952013-07-01 19:10:31 -0700604
605 InputMessage msg;
606 status_t result = mChannel->receiveMessage(&msg);
607 if (result) {
608 *outSeq = 0;
609 *outHandled = false;
610 return result;
611 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700612 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700613 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800614 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700615 return UNKNOWN_ERROR;
616 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500617 *outSeq = msg.header.seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800618 *outHandled = msg.body.finished.handled == 1;
Jeff Brown5912f952013-07-01 19:10:31 -0700619 return OK;
620}
621
622// --- InputConsumer ---
623
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500624InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
625 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700626
627InputConsumer::~InputConsumer() {
628}
629
630bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600631 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700632}
633
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800634status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
635 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800636 if (DEBUG_TRANSPORT_ACTIONS) {
637 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
638 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
639 }
Jeff Brown5912f952013-07-01 19:10:31 -0700640
641 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700642 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700643
644 // Fetch the next input message.
645 // Loop until an event can be returned or no additional events are received.
646 while (!*outEvent) {
647 if (mMsgDeferred) {
648 // mMsg contains a valid input message from the previous call to consume
649 // that has not yet been processed.
650 mMsgDeferred = false;
651 } else {
652 // Receive a fresh message.
653 status_t result = mChannel->receiveMessage(&mMsg);
654 if (result) {
655 // Consume the next batched event unless batches are being held for later.
656 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800657 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700658 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800659 if (DEBUG_TRANSPORT_ACTIONS) {
660 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
661 mChannel->getName().c_str(), *outSeq);
662 }
Jeff Brown5912f952013-07-01 19:10:31 -0700663 break;
664 }
665 }
666 return result;
667 }
668 }
669
670 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700671 case InputMessage::Type::KEY: {
672 KeyEvent* keyEvent = factory->createKeyEvent();
673 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700674
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700675 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500676 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700677 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800678 if (DEBUG_TRANSPORT_ACTIONS) {
679 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
680 mChannel->getName().c_str(), *outSeq);
681 }
Jeff Brown5912f952013-07-01 19:10:31 -0700682 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700683 }
Jeff Brown5912f952013-07-01 19:10:31 -0700684
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700685 case InputMessage::Type::MOTION: {
686 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
687 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500688 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700689 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500690 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800691 if (DEBUG_TRANSPORT_ACTIONS) {
692 ALOGD("channel '%s' consumer ~ appended to batch event",
693 mChannel->getName().c_str());
694 }
Jeff Brown5912f952013-07-01 19:10:31 -0700695 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700696 } else if (isPointerEvent(mMsg.body.motion.source) &&
697 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
698 // No need to process events that we are going to cancel anyways
699 const size_t count = batch.samples.size();
700 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500701 const InputMessage& msg = batch.samples[i];
702 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700703 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500704 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
705 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700706 } else {
707 // We cannot append to the batch in progress, so we need to consume
708 // the previous batch right now and defer the new message until later.
709 mMsgDeferred = true;
710 status_t result = consumeSamples(factory, batch, batch.samples.size(),
711 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500712 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700713 if (result) {
714 return result;
715 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800716 if (DEBUG_TRANSPORT_ACTIONS) {
717 ALOGD("channel '%s' consumer ~ consumed batch event and "
718 "deferred current event, seq=%u",
719 mChannel->getName().c_str(), *outSeq);
720 }
Jeff Brown5912f952013-07-01 19:10:31 -0700721 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700722 }
Jeff Brown5912f952013-07-01 19:10:31 -0700723 }
Jeff Brown5912f952013-07-01 19:10:31 -0700724
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800725 // Start a new batch if needed.
726 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
727 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500728 Batch batch;
729 batch.samples.push_back(mMsg);
730 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800731 if (DEBUG_TRANSPORT_ACTIONS) {
732 ALOGD("channel '%s' consumer ~ started batch event",
733 mChannel->getName().c_str());
734 }
735 break;
736 }
Jeff Brown5912f952013-07-01 19:10:31 -0700737
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800738 MotionEvent* motionEvent = factory->createMotionEvent();
739 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700740
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800741 updateTouchState(mMsg);
742 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500743 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800744 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800745
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800746 if (DEBUG_TRANSPORT_ACTIONS) {
747 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
748 mChannel->getName().c_str(), *outSeq);
749 }
750 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700751 }
Jeff Brown5912f952013-07-01 19:10:31 -0700752
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800753 case InputMessage::Type::FINISHED: {
754 LOG_ALWAYS_FATAL("Consumed a FINISHED message, which should never be seen by "
755 "InputConsumer!");
756 break;
757 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800758
759 case InputMessage::Type::FOCUS: {
760 FocusEvent* focusEvent = factory->createFocusEvent();
761 if (!focusEvent) return NO_MEMORY;
762
763 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500764 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800765 *outEvent = focusEvent;
766 break;
767 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800768
769 case InputMessage::Type::CAPTURE: {
770 CaptureEvent* captureEvent = factory->createCaptureEvent();
771 if (!captureEvent) return NO_MEMORY;
772
773 initializeCaptureEvent(captureEvent, &mMsg);
774 *outSeq = mMsg.header.seq;
775 *outEvent = captureEvent;
776 break;
777 }
Jeff Brown5912f952013-07-01 19:10:31 -0700778 }
779 }
780 return OK;
781}
782
783status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800784 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700785 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700786 for (size_t i = mBatches.size(); i > 0; ) {
787 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500788 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700789 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800790 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500791 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700792 return result;
793 }
794
Michael Wright32232172013-10-21 12:05:22 -0700795 nsecs_t sampleTime = frameTime;
796 if (mResampleTouch) {
797 sampleTime -= RESAMPLE_LATENCY;
798 }
Jeff Brown5912f952013-07-01 19:10:31 -0700799 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
800 if (split < 0) {
801 continue;
802 }
803
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800804 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700805 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500806 if (batch.samples.empty()) {
807 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700808 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700809 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500810 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700811 }
Michael Wright32232172013-10-21 12:05:22 -0700812 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700813 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
814 }
815 return result;
816 }
817
818 return WOULD_BLOCK;
819}
820
821status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800822 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700823 MotionEvent* motionEvent = factory->createMotionEvent();
824 if (! motionEvent) return NO_MEMORY;
825
826 uint32_t chain = 0;
827 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500828 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100829 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700830 if (i) {
831 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500832 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700833 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500834 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700835 addSample(motionEvent, &msg);
836 } else {
837 initializeMotionEvent(motionEvent, &msg);
838 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500839 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700840 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500841 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700842
843 *outSeq = chain;
844 *outEvent = motionEvent;
845 return OK;
846}
847
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100848void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800849 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700850 return;
851 }
852
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100853 int32_t deviceId = msg.body.motion.deviceId;
854 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700855
856 // Update the touch state history to incorporate the new input message.
857 // If the message is in the past relative to the most recently produced resampled
858 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100859 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700860 case AMOTION_EVENT_ACTION_DOWN: {
861 ssize_t index = findTouchState(deviceId, source);
862 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500863 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700864 index = mTouchStates.size() - 1;
865 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500866 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700867 touchState.initialize(deviceId, source);
868 touchState.addHistory(msg);
869 break;
870 }
871
872 case AMOTION_EVENT_ACTION_MOVE: {
873 ssize_t index = findTouchState(deviceId, source);
874 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500875 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700876 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800877 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700878 }
879 break;
880 }
881
882 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
883 ssize_t index = findTouchState(deviceId, source);
884 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500885 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100886 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700887 rewriteMessage(touchState, msg);
888 }
889 break;
890 }
891
892 case AMOTION_EVENT_ACTION_POINTER_UP: {
893 ssize_t index = findTouchState(deviceId, source);
894 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500895 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700896 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100897 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700898 }
899 break;
900 }
901
902 case AMOTION_EVENT_ACTION_SCROLL: {
903 ssize_t index = findTouchState(deviceId, source);
904 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500905 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700906 rewriteMessage(touchState, msg);
907 }
908 break;
909 }
910
911 case AMOTION_EVENT_ACTION_UP:
912 case AMOTION_EVENT_ACTION_CANCEL: {
913 ssize_t index = findTouchState(deviceId, source);
914 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500915 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700916 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500917 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -0700918 }
919 break;
920 }
921 }
922}
923
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800924/**
925 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
926 *
927 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
928 * is in the past relative to msg and the past two events do not contain identical coordinates),
929 * then invalidate the lastResample data for that pointer.
930 * If the two past events have identical coordinates, then lastResample data for that pointer will
931 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
932 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
933 * not equal to x0 is received.
934 */
935void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100936 nsecs_t eventTime = msg.body.motion.eventTime;
937 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
938 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700939 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100940 if (eventTime < state.lastResample.eventTime ||
941 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800942 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
943 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700944#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100945 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
946 resampleCoords.getX(), resampleCoords.getY(),
947 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700948#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800949 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
950 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
951 } else {
952 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100953 }
Jeff Brown5912f952013-07-01 19:10:31 -0700954 }
955 }
956}
957
958void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
959 const InputMessage* next) {
960 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800961 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700962 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
963 return;
964 }
965
966 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
967 if (index < 0) {
968#if DEBUG_RESAMPLING
969 ALOGD("Not resampled, no touch state for device.");
970#endif
971 return;
972 }
973
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500974 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700975 if (touchState.historySize < 1) {
976#if DEBUG_RESAMPLING
977 ALOGD("Not resampled, no history for device.");
978#endif
979 return;
980 }
981
982 // Ensure that the current sample has all of the pointers that need to be reported.
983 const History* current = touchState.getHistory(0);
984 size_t pointerCount = event->getPointerCount();
985 for (size_t i = 0; i < pointerCount; i++) {
986 uint32_t id = event->getPointerId(i);
987 if (!current->idBits.hasBit(id)) {
988#if DEBUG_RESAMPLING
989 ALOGD("Not resampled, missing id %d", id);
990#endif
991 return;
992 }
993 }
994
995 // Find the data to use for resampling.
996 const History* other;
997 History future;
998 float alpha;
999 if (next) {
1000 // Interpolate between current sample and future sample.
1001 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001002 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001003 other = &future;
1004 nsecs_t delta = future.eventTime - current->eventTime;
1005 if (delta < RESAMPLE_MIN_DELTA) {
1006#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001007 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001008#endif
1009 return;
1010 }
1011 alpha = float(sampleTime - current->eventTime) / delta;
1012 } else if (touchState.historySize >= 2) {
1013 // Extrapolate future sample using current sample and past sample.
1014 // So other->eventTime <= current->eventTime <= sampleTime.
1015 other = touchState.getHistory(1);
1016 nsecs_t delta = current->eventTime - other->eventTime;
1017 if (delta < RESAMPLE_MIN_DELTA) {
1018#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001019 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001020#endif
1021 return;
1022 } else if (delta > RESAMPLE_MAX_DELTA) {
1023#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001024 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001025#endif
1026 return;
1027 }
1028 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1029 if (sampleTime > maxPredict) {
1030#if DEBUG_RESAMPLING
1031 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001032 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001033 sampleTime - current->eventTime, maxPredict - current->eventTime);
1034#endif
1035 sampleTime = maxPredict;
1036 }
1037 alpha = float(current->eventTime - sampleTime) / delta;
1038 } else {
1039#if DEBUG_RESAMPLING
1040 ALOGD("Not resampled, insufficient data.");
1041#endif
1042 return;
1043 }
1044
1045 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001046 History oldLastResample;
1047 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001048 touchState.lastResample.eventTime = sampleTime;
1049 touchState.lastResample.idBits.clear();
1050 for (size_t i = 0; i < pointerCount; i++) {
1051 uint32_t id = event->getPointerId(i);
1052 touchState.lastResample.idToIndex[id] = i;
1053 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001054 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1055 // We maintain the previously resampled value for this pointer (stored in
1056 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1057 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1058
1059 // We know here that the coordinates for the pointer haven't changed because we
1060 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1061 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1062 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1063 continue;
1064 }
1065
Jeff Brown5912f952013-07-01 19:10:31 -07001066 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1067 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001068 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001069 if (other->idBits.hasBit(id)
1070 && shouldResampleTool(event->getToolType(i))) {
1071 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001072 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1073 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1074 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1075 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1076#if DEBUG_RESAMPLING
1077 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1078 "other (%0.3f, %0.3f), alpha %0.3f",
1079 id, resampledCoords.getX(), resampledCoords.getY(),
1080 currentCoords.getX(), currentCoords.getY(),
1081 otherCoords.getX(), otherCoords.getY(),
1082 alpha);
1083#endif
1084 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001085#if DEBUG_RESAMPLING
1086 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1087 id, resampledCoords.getX(), resampledCoords.getY(),
1088 currentCoords.getX(), currentCoords.getY());
1089#endif
1090 }
1091 }
1092
1093 event->addSample(sampleTime, touchState.lastResample.pointers);
1094}
1095
1096bool InputConsumer::shouldResampleTool(int32_t toolType) {
1097 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1098 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1099}
1100
1101status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001102 if (DEBUG_TRANSPORT_ACTIONS) {
1103 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1104 mChannel->getName().c_str(), seq, toString(handled));
1105 }
Jeff Brown5912f952013-07-01 19:10:31 -07001106
1107 if (!seq) {
1108 ALOGE("Attempted to send a finished signal with sequence number 0.");
1109 return BAD_VALUE;
1110 }
1111
1112 // Send finished signals for the batch sequence chain first.
1113 size_t seqChainCount = mSeqChains.size();
1114 if (seqChainCount) {
1115 uint32_t currentSeq = seq;
1116 uint32_t chainSeqs[seqChainCount];
1117 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001118 for (size_t i = seqChainCount; i > 0; ) {
1119 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001120 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001121 if (seqChain.seq == currentSeq) {
1122 currentSeq = seqChain.chain;
1123 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001124 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001125 }
1126 }
1127 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001128 while (!status && chainIndex > 0) {
1129 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001130 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1131 }
1132 if (status) {
1133 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001134 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001135 SeqChain seqChain;
1136 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1137 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001138 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001139 if (!chainIndex) break;
1140 chainIndex--;
1141 }
Jeff Brown5912f952013-07-01 19:10:31 -07001142 return status;
1143 }
1144 }
1145
1146 // Send finished signal for the last message in the batch.
1147 return sendUnchainedFinishedSignal(seq, handled);
1148}
1149
1150status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1151 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001152 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001153 msg.header.seq = seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -08001154 msg.body.finished.handled = handled ? 1 : 0;
Jeff Brown5912f952013-07-01 19:10:31 -07001155 return mChannel->sendMessage(&msg);
1156}
1157
1158bool InputConsumer::hasDeferredEvent() const {
1159 return mMsgDeferred;
1160}
1161
1162bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001163 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001164}
1165
Arthur Hungc7812be2020-02-27 22:40:27 +08001166int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001167 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001168 return AINPUT_SOURCE_CLASS_NONE;
1169 }
1170
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001171 const Batch& batch = mBatches[0];
1172 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001173 return head.body.motion.source;
1174}
1175
Jeff Brown5912f952013-07-01 19:10:31 -07001176ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1177 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001178 const Batch& batch = mBatches[i];
1179 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001180 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1181 return i;
1182 }
1183 }
1184 return -1;
1185}
1186
1187ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1188 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001189 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001190 if (touchState.deviceId == deviceId && touchState.source == source) {
1191 return i;
1192 }
1193 }
1194 return -1;
1195}
1196
1197void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001198 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001199 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1200 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1201 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1202 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001203}
1204
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001205void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001206 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus == 1,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001207 msg->body.focus.inTouchMode == 1);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001208}
1209
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001210void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
1211 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled == 1);
1212}
1213
Jeff Brown5912f952013-07-01 19:10:31 -07001214void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001215 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001216 PointerProperties pointerProperties[pointerCount];
1217 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001218 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001219 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1220 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1221 }
1222
chaviw9eaa22c2020-07-01 16:21:27 -07001223 ui::Transform transform;
1224 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1225 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001226 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1227 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1228 msg->body.motion.actionButton, msg->body.motion.flags,
1229 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001230 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1231 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1232 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1233 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1234 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001235}
1236
1237void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001238 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001239 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001240 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001241 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1242 }
1243
1244 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1245 event->addSample(msg->body.motion.eventTime, pointerCoords);
1246}
1247
1248bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001249 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001250 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001251 if (head.body.motion.pointerCount != pointerCount
1252 || head.body.motion.action != msg->body.motion.action) {
1253 return false;
1254 }
1255 for (size_t i = 0; i < pointerCount; i++) {
1256 if (head.body.motion.pointers[i].properties
1257 != msg->body.motion.pointers[i].properties) {
1258 return false;
1259 }
1260 }
1261 return true;
1262}
1263
1264ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1265 size_t numSamples = batch.samples.size();
1266 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001267 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001268 index += 1;
1269 }
1270 return ssize_t(index) - 1;
1271}
1272
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001273std::string InputConsumer::dump() const {
1274 std::string out;
1275 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1276 out = out + "mChannel = " + mChannel->getName() + "\n";
1277 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1278 if (mMsgDeferred) {
1279 out = out + "mMsg : " + InputMessage::typeToString(mMsg.header.type) + "\n";
1280 }
1281 out += "Batches:\n";
1282 for (const Batch& batch : mBatches) {
1283 out += " Batch:\n";
1284 for (const InputMessage& msg : batch.samples) {
1285 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
1286 InputMessage::typeToString(msg.header.type));
1287 switch (msg.header.type) {
1288 case InputMessage::Type::KEY: {
1289 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1290 KeyEvent::actionToString(
1291 msg.body.key.action),
1292 msg.body.key.keyCode);
1293 break;
1294 }
1295 case InputMessage::Type::MOTION: {
1296 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1297 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1298 const float x = msg.body.motion.pointers[i].coords.getX();
1299 const float y = msg.body.motion.pointers[i].coords.getY();
1300 out += android::base::StringPrintf("\n Pointer %" PRIu32
1301 " : x=%.1f y=%.1f",
1302 i, x, y);
1303 }
1304 break;
1305 }
1306 case InputMessage::Type::FINISHED: {
1307 out += android::base::StringPrintf("handled=%s",
1308 toString(msg.body.finished.handled));
1309 break;
1310 }
1311 case InputMessage::Type::FOCUS: {
1312 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1313 toString(msg.body.focus.hasFocus),
1314 toString(msg.body.focus.inTouchMode));
1315 break;
1316 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001317 case InputMessage::Type::CAPTURE: {
1318 out += android::base::StringPrintf("hasCapture=%s",
1319 toString(msg.body.capture
1320 .pointerCaptureEnabled));
1321 break;
1322 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001323 }
1324 out += "\n";
1325 }
1326 }
1327 if (mBatches.empty()) {
1328 out += " <empty>\n";
1329 }
1330 out += "mSeqChains:\n";
1331 for (const SeqChain& chain : mSeqChains) {
1332 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1333 chain.chain);
1334 }
1335 if (mSeqChains.empty()) {
1336 out += " <empty>\n";
1337 }
1338 return out;
1339}
1340
Jeff Brown5912f952013-07-01 19:10:31 -07001341} // namespace android