blob: 7b8dfb0c3caaece65daf2cc5eb68cda1231ca983 [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;
Jeff Brown5912f952013-07-01 19:10:31 -0700108 }
109 }
110 return false;
111}
112
113size_t InputMessage::size() const {
114 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700115 case Type::KEY:
116 return sizeof(Header) + body.key.size();
117 case Type::MOTION:
118 return sizeof(Header) + body.motion.size();
119 case Type::FINISHED:
120 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800121 case Type::FOCUS:
122 return sizeof(Header) + body.focus.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700123 }
124 return sizeof(Header);
125}
126
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800127/**
128 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
129 * memory to zero, then only copy the valid bytes on a per-field basis.
130 */
131void InputMessage::getSanitizedCopy(InputMessage* msg) const {
132 memset(msg, 0, sizeof(*msg));
133
134 // Write the header
135 msg->header.type = header.type;
136
137 // Write the body
138 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700139 case InputMessage::Type::KEY: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800140 // uint32_t seq
141 msg->body.key.seq = body.key.seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800142 // int32_t eventId
143 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800144 // nsecs_t eventTime
145 msg->body.key.eventTime = body.key.eventTime;
146 // int32_t deviceId
147 msg->body.key.deviceId = body.key.deviceId;
148 // int32_t source
149 msg->body.key.source = body.key.source;
150 // int32_t displayId
151 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600152 // std::array<uint8_t, 32> hmac
153 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800154 // int32_t action
155 msg->body.key.action = body.key.action;
156 // int32_t flags
157 msg->body.key.flags = body.key.flags;
158 // int32_t keyCode
159 msg->body.key.keyCode = body.key.keyCode;
160 // int32_t scanCode
161 msg->body.key.scanCode = body.key.scanCode;
162 // int32_t metaState
163 msg->body.key.metaState = body.key.metaState;
164 // int32_t repeatCount
165 msg->body.key.repeatCount = body.key.repeatCount;
166 // nsecs_t downTime
167 msg->body.key.downTime = body.key.downTime;
168 break;
169 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700170 case InputMessage::Type::MOTION: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800171 // uint32_t seq
172 msg->body.motion.seq = body.motion.seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800173 // int32_t eventId
174 msg->body.motion.eventId = body.motion.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800175 // nsecs_t eventTime
176 msg->body.motion.eventTime = body.motion.eventTime;
177 // int32_t deviceId
178 msg->body.motion.deviceId = body.motion.deviceId;
179 // int32_t source
180 msg->body.motion.source = body.motion.source;
181 // int32_t displayId
182 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600183 // std::array<uint8_t, 32> hmac
184 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800185 // int32_t action
186 msg->body.motion.action = body.motion.action;
187 // int32_t actionButton
188 msg->body.motion.actionButton = body.motion.actionButton;
189 // int32_t flags
190 msg->body.motion.flags = body.motion.flags;
191 // int32_t metaState
192 msg->body.motion.metaState = body.motion.metaState;
193 // int32_t buttonState
194 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800195 // MotionClassification classification
196 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800197 // int32_t edgeFlags
198 msg->body.motion.edgeFlags = body.motion.edgeFlags;
199 // nsecs_t downTime
200 msg->body.motion.downTime = body.motion.downTime;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600201 // float xScale
202 msg->body.motion.xScale = body.motion.xScale;
203 // float yScale
204 msg->body.motion.yScale = body.motion.yScale;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800205 // float xOffset
206 msg->body.motion.xOffset = body.motion.xOffset;
207 // float yOffset
208 msg->body.motion.yOffset = body.motion.yOffset;
209 // float xPrecision
210 msg->body.motion.xPrecision = body.motion.xPrecision;
211 // float yPrecision
212 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700213 // float xCursorPosition
214 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
215 // float yCursorPosition
216 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800217 // uint32_t pointerCount
218 msg->body.motion.pointerCount = body.motion.pointerCount;
219 //struct Pointer pointers[MAX_POINTERS]
220 for (size_t i = 0; i < body.motion.pointerCount; i++) {
221 // PointerProperties properties
222 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
223 msg->body.motion.pointers[i].properties.toolType =
224 body.motion.pointers[i].properties.toolType,
225 // PointerCoords coords
226 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
227 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
228 memcpy(&msg->body.motion.pointers[i].coords.values[0],
229 &body.motion.pointers[i].coords.values[0],
230 count * (sizeof(body.motion.pointers[i].coords.values[0])));
231 }
232 break;
233 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700234 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800235 msg->body.finished.seq = body.finished.seq;
236 msg->body.finished.handled = body.finished.handled;
237 break;
238 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800239 case InputMessage::Type::FOCUS: {
240 msg->body.focus.seq = body.focus.seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800241 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800242 msg->body.focus.hasFocus = body.focus.hasFocus;
243 msg->body.focus.inTouchMode = body.focus.inTouchMode;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800244 break;
245 }
246 }
247}
Jeff Brown5912f952013-07-01 19:10:31 -0700248
249// --- InputChannel ---
250
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700251sp<InputChannel> InputChannel::create(const std::string& name, android::base::unique_fd fd,
252 sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700253 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
254 if (result != 0) {
255 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
256 strerror(errno));
257 return nullptr;
258 }
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700259 return new InputChannel(name, std::move(fd), token);
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700260}
261
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700262InputChannel::InputChannel(const std::string& name, android::base::unique_fd fd, sp<IBinder> token)
263 : mName(name), mFd(std::move(fd)), mToken(token) {
264 if (DEBUG_CHANNEL_LIFECYCLE) {
265 ALOGD("Input channel constructed: name='%s', fd=%d", mName.c_str(), mFd.get());
266 }
Jeff Brown5912f952013-07-01 19:10:31 -0700267}
268
269InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700270 if (DEBUG_CHANNEL_LIFECYCLE) {
271 ALOGD("Input channel destroyed: name='%s', fd=%d", mName.c_str(), mFd.get());
272 }
Robert Carr3720ed02018-08-08 16:08:27 -0700273}
274
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800275status_t InputChannel::openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700276 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
277 int sockets[2];
278 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
279 status_t result = -errno;
280 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800281 name.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700282 outServerChannel.clear();
283 outClientChannel.clear();
284 return result;
285 }
286
287 int bufferSize = SOCKET_BUFFER_SIZE;
288 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
289 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
290 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
291 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
292
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700293 sp<IBinder> token = new BBinder();
294
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700295 std::string serverChannelName = name + " (server)";
296 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700297 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700298
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700299 std::string clientChannelName = name + " (client)";
300 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700301 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700302 return OK;
303}
304
305status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800306 const size_t msgLength = msg->size();
307 InputMessage cleanMsg;
308 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700309 ssize_t nWrite;
310 do {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700311 nWrite = ::send(mFd.get(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700312 } while (nWrite == -1 && errno == EINTR);
313
314 if (nWrite < 0) {
315 int error = errno;
316#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800317 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
318 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700319#endif
320 if (error == EAGAIN || error == EWOULDBLOCK) {
321 return WOULD_BLOCK;
322 }
323 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
324 return DEAD_OBJECT;
325 }
326 return -error;
327 }
328
329 if (size_t(nWrite) != msgLength) {
330#if DEBUG_CHANNEL_MESSAGES
331 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800332 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700333#endif
334 return DEAD_OBJECT;
335 }
336
337#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800338 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700339#endif
340 return OK;
341}
342
343status_t InputChannel::receiveMessage(InputMessage* msg) {
344 ssize_t nRead;
345 do {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700346 nRead = ::recv(mFd.get(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700347 } while (nRead == -1 && errno == EINTR);
348
349 if (nRead < 0) {
350 int error = errno;
351#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800352 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700353#endif
354 if (error == EAGAIN || error == EWOULDBLOCK) {
355 return WOULD_BLOCK;
356 }
357 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
358 return DEAD_OBJECT;
359 }
360 return -error;
361 }
362
363 if (nRead == 0) { // check for EOF
364#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800365 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700366#endif
367 return DEAD_OBJECT;
368 }
369
370 if (!msg->isValid(nRead)) {
371#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800372 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700373#endif
374 return BAD_VALUE;
375 }
376
377#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800378 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700379#endif
380 return OK;
381}
382
383sp<InputChannel> InputChannel::dup() const {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700384 android::base::unique_fd newFd(::dup(getFd()));
385 if (!newFd.ok()) {
386 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd(), mName.c_str(),
387 strerror(errno));
Siarhei Vishniakou3d8df0e2019-09-17 14:53:07 +0100388 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
389 // If this process is out of file descriptors, then throwing that might end up exploding
390 // on the other side of a binder call, which isn't really helpful.
391 // Better to just crash here and hope that the FD leak is slow.
392 // Other failures could be client errors, so we still propagate those back to the caller.
393 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
394 getName().c_str());
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700395 return nullptr;
396 }
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700397 return InputChannel::create(mName, std::move(newFd), mToken);
Jeff Brown5912f952013-07-01 19:10:31 -0700398}
399
Robert Carr3720ed02018-08-08 16:08:27 -0700400status_t InputChannel::write(Parcel& out) const {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700401 status_t s = out.writeCString(getName().c_str());
Robert Carr3720ed02018-08-08 16:08:27 -0700402 if (s != OK) {
403 return s;
404 }
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700405
Robert Carr803535b2018-08-02 16:38:15 -0700406 s = out.writeStrongBinder(mToken);
407 if (s != OK) {
408 return s;
409 }
Robert Carr3720ed02018-08-08 16:08:27 -0700410
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700411 s = out.writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700412 return s;
413}
414
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700415sp<InputChannel> InputChannel::read(const Parcel& from) {
416 std::string name = from.readCString();
417 sp<IBinder> token = from.readStrongBinder();
418 android::base::unique_fd rawFd;
419 status_t fdResult = from.readUniqueFileDescriptor(&rawFd);
420 if (fdResult != OK) {
421 return nullptr;
Robert Carr3720ed02018-08-08 16:08:27 -0700422 }
423
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700424 return InputChannel::create(name, std::move(rawFd), token);
Robert Carr3720ed02018-08-08 16:08:27 -0700425}
426
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700427sp<IBinder> InputChannel::getConnectionToken() const {
Robert Carr803535b2018-08-02 16:38:15 -0700428 return mToken;
429}
430
Jeff Brown5912f952013-07-01 19:10:31 -0700431// --- InputPublisher ---
432
433InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
434 mChannel(channel) {
435}
436
437InputPublisher::~InputPublisher() {
438}
439
Garfield Tan1c7bc862020-01-28 13:24:04 -0800440status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
441 int32_t source, int32_t displayId,
442 std::array<uint8_t, 32> hmac, int32_t action,
443 int32_t flags, int32_t keyCode, int32_t scanCode,
444 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
445 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000446 if (ATRACE_ENABLED()) {
447 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
448 mChannel->getName().c_str(), keyCode);
449 ATRACE_NAME(message.c_str());
450 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800451 if (DEBUG_TRANSPORT_ACTIONS) {
452 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
453 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
454 "downTime=%" PRId64 ", eventTime=%" PRId64,
455 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
456 metaState, repeatCount, downTime, eventTime);
457 }
Jeff Brown5912f952013-07-01 19:10:31 -0700458
459 if (!seq) {
460 ALOGE("Attempted to publish a key event with sequence number 0.");
461 return BAD_VALUE;
462 }
463
464 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700465 msg.header.type = InputMessage::Type::KEY;
Jeff Brown5912f952013-07-01 19:10:31 -0700466 msg.body.key.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800467 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700468 msg.body.key.deviceId = deviceId;
469 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100470 msg.body.key.displayId = displayId;
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700471 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700472 msg.body.key.action = action;
473 msg.body.key.flags = flags;
474 msg.body.key.keyCode = keyCode;
475 msg.body.key.scanCode = scanCode;
476 msg.body.key.metaState = metaState;
477 msg.body.key.repeatCount = repeatCount;
478 msg.body.key.downTime = downTime;
479 msg.body.key.eventTime = eventTime;
480 return mChannel->sendMessage(&msg);
481}
482
483status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800484 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600485 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
486 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
487 MotionClassification classification, float xScale, float yScale, float xOffset,
488 float yOffset, float xPrecision, float yPrecision, float xCursorPosition,
489 float yCursorPosition, nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
Garfield Tan00f511d2019-06-12 16:55:40 -0700490 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000491 if (ATRACE_ENABLED()) {
492 std::string message = StringPrintf(
493 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
494 mChannel->getName().c_str(), action);
495 ATRACE_NAME(message.c_str());
496 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800497 if (DEBUG_TRANSPORT_ACTIONS) {
498 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
499 "displayId=%" PRId32 ", "
500 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600501 "metaState=0x%x, buttonState=0x%x, classification=%s, xScale=%.1f, yScale=%.1f, "
502 "xOffset=%.1f, yOffset=%.1f, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800503 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
504 "pointerCount=%" PRIu32,
505 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
506 flags, edgeFlags, metaState, buttonState,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600507 motionClassificationToString(classification), xScale, yScale, xOffset, yOffset,
508 xPrecision, yPrecision, downTime, eventTime, pointerCount);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800509 }
Jeff Brown5912f952013-07-01 19:10:31 -0700510
511 if (!seq) {
512 ALOGE("Attempted to publish a motion event with sequence number 0.");
513 return BAD_VALUE;
514 }
515
516 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700517 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800518 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700519 return BAD_VALUE;
520 }
521
522 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700523 msg.header.type = InputMessage::Type::MOTION;
Jeff Brown5912f952013-07-01 19:10:31 -0700524 msg.body.motion.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800525 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700526 msg.body.motion.deviceId = deviceId;
527 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700528 msg.body.motion.displayId = displayId;
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700529 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700530 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100531 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700532 msg.body.motion.flags = flags;
533 msg.body.motion.edgeFlags = edgeFlags;
534 msg.body.motion.metaState = metaState;
535 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800536 msg.body.motion.classification = classification;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600537 msg.body.motion.xScale = xScale;
538 msg.body.motion.yScale = yScale;
Jeff Brown5912f952013-07-01 19:10:31 -0700539 msg.body.motion.xOffset = xOffset;
540 msg.body.motion.yOffset = yOffset;
541 msg.body.motion.xPrecision = xPrecision;
542 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700543 msg.body.motion.xCursorPosition = xCursorPosition;
544 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700545 msg.body.motion.downTime = downTime;
546 msg.body.motion.eventTime = eventTime;
547 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100548 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700549 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
550 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
551 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700552
Jeff Brown5912f952013-07-01 19:10:31 -0700553 return mChannel->sendMessage(&msg);
554}
555
Garfield Tan1c7bc862020-01-28 13:24:04 -0800556status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
557 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800558 if (ATRACE_ENABLED()) {
559 std::string message =
560 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
561 mChannel->getName().c_str(), toString(hasFocus),
562 toString(inTouchMode));
563 ATRACE_NAME(message.c_str());
564 }
565
566 InputMessage msg;
567 msg.header.type = InputMessage::Type::FOCUS;
568 msg.body.focus.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800569 msg.body.focus.eventId = eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800570 msg.body.focus.hasFocus = hasFocus ? 1 : 0;
571 msg.body.focus.inTouchMode = inTouchMode ? 1 : 0;
572 return mChannel->sendMessage(&msg);
573}
574
Jeff Brown5912f952013-07-01 19:10:31 -0700575status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800576 if (DEBUG_TRANSPORT_ACTIONS) {
577 ALOGD("channel '%s' publisher ~ receiveFinishedSignal", mChannel->getName().c_str());
578 }
Jeff Brown5912f952013-07-01 19:10:31 -0700579
580 InputMessage msg;
581 status_t result = mChannel->receiveMessage(&msg);
582 if (result) {
583 *outSeq = 0;
584 *outHandled = false;
585 return result;
586 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700587 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700588 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800589 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700590 return UNKNOWN_ERROR;
591 }
592 *outSeq = msg.body.finished.seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800593 *outHandled = msg.body.finished.handled == 1;
Jeff Brown5912f952013-07-01 19:10:31 -0700594 return OK;
595}
596
597// --- InputConsumer ---
598
599InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
600 mResampleTouch(isTouchResamplingEnabled()),
601 mChannel(channel), mMsgDeferred(false) {
602}
603
604InputConsumer::~InputConsumer() {
605}
606
607bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600608 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700609}
610
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800611status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
Steven Laver53e246f2019-12-03 15:52:26 -0800612 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent,
613 int* motionEventType, int* touchMoveNumber, bool* flag) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800614 if (DEBUG_TRANSPORT_ACTIONS) {
615 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
616 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
617 }
Jeff Brown5912f952013-07-01 19:10:31 -0700618
619 *outSeq = 0;
Logan Chien4c75e562018-08-09 17:29:07 +0800620 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700621
622 // Fetch the next input message.
623 // Loop until an event can be returned or no additional events are received.
624 while (!*outEvent) {
625 if (mMsgDeferred) {
626 // mMsg contains a valid input message from the previous call to consume
627 // that has not yet been processed.
628 mMsgDeferred = false;
629 } else {
630 // Receive a fresh message.
631 status_t result = mChannel->receiveMessage(&mMsg);
Logan Chien4c75e562018-08-09 17:29:07 +0800632 if (result == 0) {
633 if ((mMsg.body.motion.action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_MOVE){
634 mTouchMoveCounter++;
635 } else {
636 mTouchMoveCounter = 0;
637 }
638 *flag = true;
639 }
640 *motionEventType = mMsg.body.motion.action & AMOTION_EVENT_ACTION_MASK;
641 *touchMoveNumber = mTouchMoveCounter;
Jeff Brown5912f952013-07-01 19:10:31 -0700642 if (result) {
643 // Consume the next batched event unless batches are being held for later.
644 if (consumeBatches || result != WOULD_BLOCK) {
Logan Chien4c75e562018-08-09 17:29:07 +0800645 result = consumeBatch(factory, frameTime, outSeq, outEvent, touchMoveNumber);
Jeff Brown5912f952013-07-01 19:10:31 -0700646 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800647 if (DEBUG_TRANSPORT_ACTIONS) {
648 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
649 mChannel->getName().c_str(), *outSeq);
650 }
Jeff Brown5912f952013-07-01 19:10:31 -0700651 break;
652 }
653 }
654 return result;
655 }
656 }
657
658 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700659 case InputMessage::Type::KEY: {
660 KeyEvent* keyEvent = factory->createKeyEvent();
661 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700662
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700663 initializeKeyEvent(keyEvent, &mMsg);
664 *outSeq = mMsg.body.key.seq;
665 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800666 if (DEBUG_TRANSPORT_ACTIONS) {
667 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
668 mChannel->getName().c_str(), *outSeq);
669 }
Jeff Brown5912f952013-07-01 19:10:31 -0700670 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700671 }
Jeff Brown5912f952013-07-01 19:10:31 -0700672
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700673 case InputMessage::Type::MOTION: {
674 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
675 if (batchIndex >= 0) {
676 Batch& batch = mBatches.editItemAt(batchIndex);
677 if (canAddSample(batch, &mMsg)) {
678 batch.samples.push(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800679 if (DEBUG_TRANSPORT_ACTIONS) {
680 ALOGD("channel '%s' consumer ~ appended to batch event",
681 mChannel->getName().c_str());
682 }
Jeff Brown5912f952013-07-01 19:10:31 -0700683 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700684 } else if (isPointerEvent(mMsg.body.motion.source) &&
685 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
686 // No need to process events that we are going to cancel anyways
687 const size_t count = batch.samples.size();
688 for (size_t i = 0; i < count; i++) {
689 const InputMessage& msg = batch.samples.itemAt(i);
690 sendFinishedSignal(msg.body.motion.seq, false);
691 }
692 batch.samples.removeItemsAt(0, count);
693 mBatches.removeAt(batchIndex);
694 } else {
695 // We cannot append to the batch in progress, so we need to consume
696 // the previous batch right now and defer the new message until later.
697 mMsgDeferred = true;
698 status_t result = consumeSamples(factory, batch, batch.samples.size(),
699 outSeq, outEvent);
700 mBatches.removeAt(batchIndex);
701 if (result) {
702 return result;
703 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800704 if (DEBUG_TRANSPORT_ACTIONS) {
705 ALOGD("channel '%s' consumer ~ consumed batch event and "
706 "deferred current event, seq=%u",
707 mChannel->getName().c_str(), *outSeq);
708 }
Jeff Brown5912f952013-07-01 19:10:31 -0700709 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700710 }
Jeff Brown5912f952013-07-01 19:10:31 -0700711 }
Jeff Brown5912f952013-07-01 19:10:31 -0700712
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800713 // Start a new batch if needed.
714 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
715 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
716 mBatches.push();
717 Batch& batch = mBatches.editTop();
718 batch.samples.push(mMsg);
719 if (DEBUG_TRANSPORT_ACTIONS) {
720 ALOGD("channel '%s' consumer ~ started batch event",
721 mChannel->getName().c_str());
722 }
723 break;
724 }
Jeff Brown5912f952013-07-01 19:10:31 -0700725
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800726 MotionEvent* motionEvent = factory->createMotionEvent();
727 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700728
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800729 updateTouchState(mMsg);
730 initializeMotionEvent(motionEvent, &mMsg);
731 *outSeq = mMsg.body.motion.seq;
732 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800733
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800734 if (DEBUG_TRANSPORT_ACTIONS) {
735 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
736 mChannel->getName().c_str(), *outSeq);
737 }
Jeff Brown5912f952013-07-01 19:10:31 -0700738 break;
739 }
740
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800741 case InputMessage::Type::FINISHED: {
742 LOG_ALWAYS_FATAL("Consumed a FINISHED message, which should never be seen by "
743 "InputConsumer!");
744 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700745 }
Jeff Brown5912f952013-07-01 19:10:31 -0700746
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800747 case InputMessage::Type::FOCUS: {
748 FocusEvent* focusEvent = factory->createFocusEvent();
749 if (!focusEvent) return NO_MEMORY;
750
751 initializeFocusEvent(focusEvent, &mMsg);
752 *outSeq = mMsg.body.focus.seq;
753 *outEvent = focusEvent;
754 break;
755 }
Jeff Brown5912f952013-07-01 19:10:31 -0700756 }
757 }
758 return OK;
759}
760
761status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Logan Chien4c75e562018-08-09 17:29:07 +0800762 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int* touchMoveNumber) {
Jeff Brown5912f952013-07-01 19:10:31 -0700763 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700764 for (size_t i = mBatches.size(); i > 0; ) {
765 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700766 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700767 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800768 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700769 mBatches.removeAt(i);
770 return result;
771 }
772
Michael Wright32232172013-10-21 12:05:22 -0700773 nsecs_t sampleTime = frameTime;
zfuc876d4a2018-03-01 18:14:50 +0800774 if (mResampleTouch && (*touchMoveNumber != 1)) {
775 sampleTime -= RESAMPLE_LATENCY;
776 }
777 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
778 if (split < 0) {
779 continue;
780 }
781
Logan Chien4c75e562018-08-09 17:29:07 +0800782 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
zfuc876d4a2018-03-01 18:14:50 +0800783 const InputMessage* next;
784 if (batch.samples.isEmpty()) {
785 mBatches.removeAt(i);
Logan Chien4c75e562018-08-09 17:29:07 +0800786 next = nullptr;
zfuc876d4a2018-03-01 18:14:50 +0800787 } else {
788 next = &batch.samples.itemAt(0);
789 }
790 if (!result && mResampleTouch) {
791 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
792 }
793 return result;
794 }
795
796 return WOULD_BLOCK;
797}
798
Jeff Brown5912f952013-07-01 19:10:31 -0700799status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800800 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700801 MotionEvent* motionEvent = factory->createMotionEvent();
802 if (! motionEvent) return NO_MEMORY;
803
804 uint32_t chain = 0;
805 for (size_t i = 0; i < count; i++) {
806 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100807 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700808 if (i) {
809 SeqChain seqChain;
810 seqChain.seq = msg.body.motion.seq;
811 seqChain.chain = chain;
812 mSeqChains.push(seqChain);
813 addSample(motionEvent, &msg);
814 } else {
815 initializeMotionEvent(motionEvent, &msg);
816 }
817 chain = msg.body.motion.seq;
818 }
819 batch.samples.removeItemsAt(0, count);
820
821 *outSeq = chain;
822 *outEvent = motionEvent;
823 return OK;
824}
825
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100826void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800827 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700828 return;
829 }
830
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100831 int32_t deviceId = msg.body.motion.deviceId;
832 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700833
834 // Update the touch state history to incorporate the new input message.
835 // If the message is in the past relative to the most recently produced resampled
836 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100837 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700838 case AMOTION_EVENT_ACTION_DOWN: {
839 ssize_t index = findTouchState(deviceId, source);
840 if (index < 0) {
841 mTouchStates.push();
842 index = mTouchStates.size() - 1;
843 }
844 TouchState& touchState = mTouchStates.editItemAt(index);
845 touchState.initialize(deviceId, source);
846 touchState.addHistory(msg);
847 break;
848 }
849
850 case AMOTION_EVENT_ACTION_MOVE: {
851 ssize_t index = findTouchState(deviceId, source);
852 if (index >= 0) {
853 TouchState& touchState = mTouchStates.editItemAt(index);
854 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800855 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700856 }
857 break;
858 }
859
860 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
861 ssize_t index = findTouchState(deviceId, source);
862 if (index >= 0) {
863 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100864 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700865 rewriteMessage(touchState, msg);
866 }
867 break;
868 }
869
870 case AMOTION_EVENT_ACTION_POINTER_UP: {
871 ssize_t index = findTouchState(deviceId, source);
872 if (index >= 0) {
873 TouchState& touchState = mTouchStates.editItemAt(index);
874 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100875 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700876 }
877 break;
878 }
879
880 case AMOTION_EVENT_ACTION_SCROLL: {
881 ssize_t index = findTouchState(deviceId, source);
882 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800883 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700884 rewriteMessage(touchState, msg);
885 }
886 break;
887 }
888
889 case AMOTION_EVENT_ACTION_UP:
890 case AMOTION_EVENT_ACTION_CANCEL: {
891 ssize_t index = findTouchState(deviceId, source);
892 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800893 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700894 rewriteMessage(touchState, msg);
895 mTouchStates.removeAt(index);
896 }
897 break;
898 }
899 }
900}
901
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800902/**
903 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
904 *
905 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
906 * is in the past relative to msg and the past two events do not contain identical coordinates),
907 * then invalidate the lastResample data for that pointer.
908 * If the two past events have identical coordinates, then lastResample data for that pointer will
909 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
910 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
911 * not equal to x0 is received.
912 */
913void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100914 nsecs_t eventTime = msg.body.motion.eventTime;
915 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
916 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700917 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100918 if (eventTime < state.lastResample.eventTime ||
919 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800920 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
921 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700922#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100923 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
924 resampleCoords.getX(), resampleCoords.getY(),
925 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700926#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800927 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
928 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
929 } else {
930 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100931 }
Jeff Brown5912f952013-07-01 19:10:31 -0700932 }
933 }
934}
935
936void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
937 const InputMessage* next) {
938 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800939 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700940 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
941 return;
942 }
943
944 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
945 if (index < 0) {
946#if DEBUG_RESAMPLING
947 ALOGD("Not resampled, no touch state for device.");
948#endif
949 return;
950 }
951
952 TouchState& touchState = mTouchStates.editItemAt(index);
953 if (touchState.historySize < 1) {
954#if DEBUG_RESAMPLING
955 ALOGD("Not resampled, no history for device.");
956#endif
957 return;
958 }
959
960 // Ensure that the current sample has all of the pointers that need to be reported.
961 const History* current = touchState.getHistory(0);
962 size_t pointerCount = event->getPointerCount();
963 for (size_t i = 0; i < pointerCount; i++) {
964 uint32_t id = event->getPointerId(i);
965 if (!current->idBits.hasBit(id)) {
966#if DEBUG_RESAMPLING
967 ALOGD("Not resampled, missing id %d", id);
968#endif
969 return;
970 }
971 }
972
973 // Find the data to use for resampling.
974 const History* other;
975 History future;
976 float alpha;
977 if (next) {
978 // Interpolate between current sample and future sample.
979 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100980 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700981 other = &future;
982 nsecs_t delta = future.eventTime - current->eventTime;
983 if (delta < RESAMPLE_MIN_DELTA) {
984#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100985 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700986#endif
987 return;
988 }
989 alpha = float(sampleTime - current->eventTime) / delta;
990 } else if (touchState.historySize >= 2) {
991 // Extrapolate future sample using current sample and past sample.
992 // So other->eventTime <= current->eventTime <= sampleTime.
993 other = touchState.getHistory(1);
994 nsecs_t delta = current->eventTime - other->eventTime;
995 if (delta < RESAMPLE_MIN_DELTA) {
996#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100997 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700998#endif
999 return;
1000 } else if (delta > RESAMPLE_MAX_DELTA) {
1001#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001002 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001003#endif
1004 return;
1005 }
1006 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1007 if (sampleTime > maxPredict) {
1008#if DEBUG_RESAMPLING
1009 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001010 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001011 sampleTime - current->eventTime, maxPredict - current->eventTime);
1012#endif
1013 sampleTime = maxPredict;
1014 }
1015 alpha = float(current->eventTime - sampleTime) / delta;
1016 } else {
1017#if DEBUG_RESAMPLING
1018 ALOGD("Not resampled, insufficient data.");
1019#endif
1020 return;
1021 }
1022
1023 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001024 History oldLastResample;
1025 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001026 touchState.lastResample.eventTime = sampleTime;
1027 touchState.lastResample.idBits.clear();
1028 for (size_t i = 0; i < pointerCount; i++) {
1029 uint32_t id = event->getPointerId(i);
1030 touchState.lastResample.idToIndex[id] = i;
1031 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001032 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1033 // We maintain the previously resampled value for this pointer (stored in
1034 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1035 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1036
1037 // We know here that the coordinates for the pointer haven't changed because we
1038 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1039 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1040 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1041 continue;
1042 }
1043
Jeff Brown5912f952013-07-01 19:10:31 -07001044 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1045 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001046 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001047 if (other->idBits.hasBit(id)
1048 && shouldResampleTool(event->getToolType(i))) {
1049 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001050 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1051 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1052 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1053 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1054#if DEBUG_RESAMPLING
1055 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1056 "other (%0.3f, %0.3f), alpha %0.3f",
1057 id, resampledCoords.getX(), resampledCoords.getY(),
1058 currentCoords.getX(), currentCoords.getY(),
1059 otherCoords.getX(), otherCoords.getY(),
1060 alpha);
1061#endif
1062 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001063#if DEBUG_RESAMPLING
1064 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1065 id, resampledCoords.getX(), resampledCoords.getY(),
1066 currentCoords.getX(), currentCoords.getY());
1067#endif
1068 }
1069 }
1070
1071 event->addSample(sampleTime, touchState.lastResample.pointers);
1072}
1073
1074bool InputConsumer::shouldResampleTool(int32_t toolType) {
1075 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1076 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1077}
1078
1079status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001080 if (DEBUG_TRANSPORT_ACTIONS) {
1081 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1082 mChannel->getName().c_str(), seq, toString(handled));
1083 }
Jeff Brown5912f952013-07-01 19:10:31 -07001084
1085 if (!seq) {
1086 ALOGE("Attempted to send a finished signal with sequence number 0.");
1087 return BAD_VALUE;
1088 }
1089
1090 // Send finished signals for the batch sequence chain first.
1091 size_t seqChainCount = mSeqChains.size();
1092 if (seqChainCount) {
1093 uint32_t currentSeq = seq;
1094 uint32_t chainSeqs[seqChainCount];
1095 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001096 for (size_t i = seqChainCount; i > 0; ) {
1097 i--;
Jeff Brown5912f952013-07-01 19:10:31 -07001098 const SeqChain& seqChain = mSeqChains.itemAt(i);
1099 if (seqChain.seq == currentSeq) {
1100 currentSeq = seqChain.chain;
1101 chainSeqs[chainIndex++] = currentSeq;
1102 mSeqChains.removeAt(i);
1103 }
1104 }
1105 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001106 while (!status && chainIndex > 0) {
1107 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001108 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1109 }
1110 if (status) {
1111 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001112 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001113 SeqChain seqChain;
1114 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1115 seqChain.chain = chainSeqs[chainIndex];
1116 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001117 if (!chainIndex) break;
1118 chainIndex--;
1119 }
Jeff Brown5912f952013-07-01 19:10:31 -07001120 return status;
1121 }
1122 }
1123
1124 // Send finished signal for the last message in the batch.
1125 return sendUnchainedFinishedSignal(seq, handled);
1126}
1127
1128status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1129 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001130 msg.header.type = InputMessage::Type::FINISHED;
Jeff Brown5912f952013-07-01 19:10:31 -07001131 msg.body.finished.seq = seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -08001132 msg.body.finished.handled = handled ? 1 : 0;
Jeff Brown5912f952013-07-01 19:10:31 -07001133 return mChannel->sendMessage(&msg);
1134}
1135
1136bool InputConsumer::hasDeferredEvent() const {
1137 return mMsgDeferred;
1138}
1139
1140bool InputConsumer::hasPendingBatch() const {
1141 return !mBatches.isEmpty();
1142}
1143
Arthur Hungc7812be2020-02-27 22:40:27 +08001144int32_t InputConsumer::getPendingBatchSource() const {
1145 if (mBatches.isEmpty()) {
1146 return AINPUT_SOURCE_CLASS_NONE;
1147 }
1148
1149 const Batch& batch = mBatches.itemAt(0);
1150 const InputMessage& head = batch.samples.itemAt(0);
1151 return head.body.motion.source;
1152}
1153
Jeff Brown5912f952013-07-01 19:10:31 -07001154ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1155 for (size_t i = 0; i < mBatches.size(); i++) {
1156 const Batch& batch = mBatches.itemAt(i);
1157 const InputMessage& head = batch.samples.itemAt(0);
1158 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1159 return i;
1160 }
1161 }
1162 return -1;
1163}
1164
1165ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1166 for (size_t i = 0; i < mTouchStates.size(); i++) {
1167 const TouchState& touchState = mTouchStates.itemAt(i);
1168 if (touchState.deviceId == deviceId && touchState.source == source) {
1169 return i;
1170 }
1171 }
1172 return -1;
1173}
1174
1175void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001176 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001177 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1178 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1179 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1180 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001181}
1182
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001183void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001184 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus == 1,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001185 msg->body.focus.inTouchMode == 1);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001186}
1187
Jeff Brown5912f952013-07-01 19:10:31 -07001188void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001189 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001190 PointerProperties pointerProperties[pointerCount];
1191 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001192 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001193 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1194 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1195 }
1196
Garfield Tan1c7bc862020-01-28 13:24:04 -08001197 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -06001198 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
Garfield Tan00f511d2019-06-12 16:55:40 -07001199 msg->body.motion.actionButton, msg->body.motion.flags,
1200 msg->body.motion.edgeFlags, msg->body.motion.metaState,
1201 msg->body.motion.buttonState, msg->body.motion.classification,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -06001202 msg->body.motion.xScale, msg->body.motion.yScale, msg->body.motion.xOffset,
1203 msg->body.motion.yOffset, msg->body.motion.xPrecision,
1204 msg->body.motion.yPrecision, msg->body.motion.xCursorPosition,
1205 msg->body.motion.yCursorPosition, msg->body.motion.downTime,
1206 msg->body.motion.eventTime, pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001207}
1208
1209void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001210 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001211 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001212 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001213 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1214 }
1215
1216 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1217 event->addSample(msg->body.motion.eventTime, pointerCoords);
1218}
1219
1220bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1221 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001222 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001223 if (head.body.motion.pointerCount != pointerCount
1224 || head.body.motion.action != msg->body.motion.action) {
1225 return false;
1226 }
1227 for (size_t i = 0; i < pointerCount; i++) {
1228 if (head.body.motion.pointers[i].properties
1229 != msg->body.motion.pointers[i].properties) {
1230 return false;
1231 }
1232 }
1233 return true;
1234}
1235
1236ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1237 size_t numSamples = batch.samples.size();
1238 size_t index = 0;
1239 while (index < numSamples
1240 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1241 index += 1;
1242 }
1243 return ssize_t(index) - 1;
1244}
1245
1246} // namespace android