blob: 8d1dd639bb10abccaa16f22f35bc1608f55c33c8 [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;
Jeff Brown5912f952013-07-01 19:10:31 -0700106 }
107 }
108 return false;
109}
110
111size_t InputMessage::size() const {
112 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700113 case Type::KEY:
114 return sizeof(Header) + body.key.size();
115 case Type::MOTION:
116 return sizeof(Header) + body.motion.size();
117 case Type::FINISHED:
118 return sizeof(Header) + body.finished.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700119 }
120 return sizeof(Header);
121}
122
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800123/**
124 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
125 * memory to zero, then only copy the valid bytes on a per-field basis.
126 */
127void InputMessage::getSanitizedCopy(InputMessage* msg) const {
128 memset(msg, 0, sizeof(*msg));
129
130 // Write the header
131 msg->header.type = header.type;
132
133 // Write the body
134 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700135 case InputMessage::Type::KEY: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800136 // uint32_t seq
137 msg->body.key.seq = body.key.seq;
138 // nsecs_t eventTime
139 msg->body.key.eventTime = body.key.eventTime;
140 // int32_t deviceId
141 msg->body.key.deviceId = body.key.deviceId;
142 // int32_t source
143 msg->body.key.source = body.key.source;
144 // int32_t displayId
145 msg->body.key.displayId = body.key.displayId;
146 // int32_t action
147 msg->body.key.action = body.key.action;
148 // int32_t flags
149 msg->body.key.flags = body.key.flags;
150 // int32_t keyCode
151 msg->body.key.keyCode = body.key.keyCode;
152 // int32_t scanCode
153 msg->body.key.scanCode = body.key.scanCode;
154 // int32_t metaState
155 msg->body.key.metaState = body.key.metaState;
156 // int32_t repeatCount
157 msg->body.key.repeatCount = body.key.repeatCount;
158 // nsecs_t downTime
159 msg->body.key.downTime = body.key.downTime;
160 break;
161 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700162 case InputMessage::Type::MOTION: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800163 // uint32_t seq
164 msg->body.motion.seq = body.motion.seq;
165 // nsecs_t eventTime
166 msg->body.motion.eventTime = body.motion.eventTime;
167 // int32_t deviceId
168 msg->body.motion.deviceId = body.motion.deviceId;
169 // int32_t source
170 msg->body.motion.source = body.motion.source;
171 // int32_t displayId
172 msg->body.motion.displayId = body.motion.displayId;
173 // int32_t action
174 msg->body.motion.action = body.motion.action;
175 // int32_t actionButton
176 msg->body.motion.actionButton = body.motion.actionButton;
177 // int32_t flags
178 msg->body.motion.flags = body.motion.flags;
179 // int32_t metaState
180 msg->body.motion.metaState = body.motion.metaState;
181 // int32_t buttonState
182 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800183 // MotionClassification classification
184 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800185 // int32_t edgeFlags
186 msg->body.motion.edgeFlags = body.motion.edgeFlags;
187 // nsecs_t downTime
188 msg->body.motion.downTime = body.motion.downTime;
189 // float xOffset
190 msg->body.motion.xOffset = body.motion.xOffset;
191 // float yOffset
192 msg->body.motion.yOffset = body.motion.yOffset;
193 // float xPrecision
194 msg->body.motion.xPrecision = body.motion.xPrecision;
195 // float yPrecision
196 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700197 // float xCursorPosition
198 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
199 // float yCursorPosition
200 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800201 // uint32_t pointerCount
202 msg->body.motion.pointerCount = body.motion.pointerCount;
203 //struct Pointer pointers[MAX_POINTERS]
204 for (size_t i = 0; i < body.motion.pointerCount; i++) {
205 // PointerProperties properties
206 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
207 msg->body.motion.pointers[i].properties.toolType =
208 body.motion.pointers[i].properties.toolType,
209 // PointerCoords coords
210 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
211 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
212 memcpy(&msg->body.motion.pointers[i].coords.values[0],
213 &body.motion.pointers[i].coords.values[0],
214 count * (sizeof(body.motion.pointers[i].coords.values[0])));
215 }
216 break;
217 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700218 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800219 msg->body.finished.seq = body.finished.seq;
220 msg->body.finished.handled = body.finished.handled;
221 break;
222 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800223 }
224}
Jeff Brown5912f952013-07-01 19:10:31 -0700225
226// --- InputChannel ---
227
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700228sp<InputChannel> InputChannel::create(const std::string& name, android::base::unique_fd fd,
229 sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700230 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
231 if (result != 0) {
232 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
233 strerror(errno));
234 return nullptr;
235 }
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700236 return new InputChannel(name, std::move(fd), token);
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700237}
238
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700239InputChannel::InputChannel(const std::string& name, android::base::unique_fd fd, sp<IBinder> token)
240 : mName(name), mFd(std::move(fd)), mToken(token) {
241 if (DEBUG_CHANNEL_LIFECYCLE) {
242 ALOGD("Input channel constructed: name='%s', fd=%d", mName.c_str(), mFd.get());
243 }
Jeff Brown5912f952013-07-01 19:10:31 -0700244}
245
246InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700247 if (DEBUG_CHANNEL_LIFECYCLE) {
248 ALOGD("Input channel destroyed: name='%s', fd=%d", mName.c_str(), mFd.get());
249 }
Robert Carr3720ed02018-08-08 16:08:27 -0700250}
251
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800252status_t InputChannel::openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700253 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
254 int sockets[2];
255 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
256 status_t result = -errno;
257 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800258 name.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700259 outServerChannel.clear();
260 outClientChannel.clear();
261 return result;
262 }
263
264 int bufferSize = SOCKET_BUFFER_SIZE;
265 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
266 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
267 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
268 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
269
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700270 sp<IBinder> token = new BBinder();
271
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700272 std::string serverChannelName = name + " (server)";
273 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700274 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700275
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700276 std::string clientChannelName = name + " (client)";
277 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700278 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700279 return OK;
280}
281
282status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800283 const size_t msgLength = msg->size();
284 InputMessage cleanMsg;
285 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700286 ssize_t nWrite;
287 do {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700288 nWrite = ::send(mFd.get(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700289 } while (nWrite == -1 && errno == EINTR);
290
291 if (nWrite < 0) {
292 int error = errno;
293#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800294 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.c_str(),
Jeff Brown5912f952013-07-01 19:10:31 -0700295 msg->header.type, error);
296#endif
297 if (error == EAGAIN || error == EWOULDBLOCK) {
298 return WOULD_BLOCK;
299 }
300 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
301 return DEAD_OBJECT;
302 }
303 return -error;
304 }
305
306 if (size_t(nWrite) != msgLength) {
307#if DEBUG_CHANNEL_MESSAGES
308 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800309 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700310#endif
311 return DEAD_OBJECT;
312 }
313
314#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800315 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700316#endif
317 return OK;
318}
319
320status_t InputChannel::receiveMessage(InputMessage* msg) {
321 ssize_t nRead;
322 do {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700323 nRead = ::recv(mFd.get(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700324 } while (nRead == -1 && errno == EINTR);
325
326 if (nRead < 0) {
327 int error = errno;
328#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800329 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700330#endif
331 if (error == EAGAIN || error == EWOULDBLOCK) {
332 return WOULD_BLOCK;
333 }
334 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
335 return DEAD_OBJECT;
336 }
337 return -error;
338 }
339
340 if (nRead == 0) { // check for EOF
341#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800342 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700343#endif
344 return DEAD_OBJECT;
345 }
346
347 if (!msg->isValid(nRead)) {
348#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800349 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700350#endif
351 return BAD_VALUE;
352 }
353
354#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800355 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700356#endif
357 return OK;
358}
359
360sp<InputChannel> InputChannel::dup() const {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700361 android::base::unique_fd newFd(::dup(getFd()));
362 if (!newFd.ok()) {
363 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd(), mName.c_str(),
364 strerror(errno));
Siarhei Vishniakou3d8df0e2019-09-17 14:53:07 +0100365 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
366 // If this process is out of file descriptors, then throwing that might end up exploding
367 // on the other side of a binder call, which isn't really helpful.
368 // Better to just crash here and hope that the FD leak is slow.
369 // Other failures could be client errors, so we still propagate those back to the caller.
370 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
371 getName().c_str());
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700372 return nullptr;
373 }
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700374 return InputChannel::create(mName, std::move(newFd), mToken);
Jeff Brown5912f952013-07-01 19:10:31 -0700375}
376
Robert Carr3720ed02018-08-08 16:08:27 -0700377status_t InputChannel::write(Parcel& out) const {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700378 status_t s = out.writeCString(getName().c_str());
Robert Carr3720ed02018-08-08 16:08:27 -0700379 if (s != OK) {
380 return s;
381 }
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700382
Robert Carr803535b2018-08-02 16:38:15 -0700383 s = out.writeStrongBinder(mToken);
384 if (s != OK) {
385 return s;
386 }
Robert Carr3720ed02018-08-08 16:08:27 -0700387
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700388 s = out.writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700389 return s;
390}
391
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700392sp<InputChannel> InputChannel::read(const Parcel& from) {
393 std::string name = from.readCString();
394 sp<IBinder> token = from.readStrongBinder();
395 android::base::unique_fd rawFd;
396 status_t fdResult = from.readUniqueFileDescriptor(&rawFd);
397 if (fdResult != OK) {
398 return nullptr;
Robert Carr3720ed02018-08-08 16:08:27 -0700399 }
400
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700401 return InputChannel::create(name, std::move(rawFd), token);
Robert Carr3720ed02018-08-08 16:08:27 -0700402}
403
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700404sp<IBinder> InputChannel::getConnectionToken() const {
Robert Carr803535b2018-08-02 16:38:15 -0700405 return mToken;
406}
407
Jeff Brown5912f952013-07-01 19:10:31 -0700408// --- InputPublisher ---
409
410InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
411 mChannel(channel) {
412}
413
414InputPublisher::~InputPublisher() {
415}
416
417status_t InputPublisher::publishKeyEvent(
418 uint32_t seq,
419 int32_t deviceId,
420 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100421 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700422 int32_t action,
423 int32_t flags,
424 int32_t keyCode,
425 int32_t scanCode,
426 int32_t metaState,
427 int32_t repeatCount,
428 nsecs_t downTime,
429 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000430 if (ATRACE_ENABLED()) {
431 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
432 mChannel->getName().c_str(), keyCode);
433 ATRACE_NAME(message.c_str());
434 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800435 if (DEBUG_TRANSPORT_ACTIONS) {
436 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
437 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
438 "downTime=%" PRId64 ", eventTime=%" PRId64,
439 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
440 metaState, repeatCount, downTime, eventTime);
441 }
Jeff Brown5912f952013-07-01 19:10:31 -0700442
443 if (!seq) {
444 ALOGE("Attempted to publish a key event with sequence number 0.");
445 return BAD_VALUE;
446 }
447
448 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700449 msg.header.type = InputMessage::Type::KEY;
Jeff Brown5912f952013-07-01 19:10:31 -0700450 msg.body.key.seq = seq;
451 msg.body.key.deviceId = deviceId;
452 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100453 msg.body.key.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700454 msg.body.key.action = action;
455 msg.body.key.flags = flags;
456 msg.body.key.keyCode = keyCode;
457 msg.body.key.scanCode = scanCode;
458 msg.body.key.metaState = metaState;
459 msg.body.key.repeatCount = repeatCount;
460 msg.body.key.downTime = downTime;
461 msg.body.key.eventTime = eventTime;
462 return mChannel->sendMessage(&msg);
463}
464
465status_t InputPublisher::publishMotionEvent(
Garfield Tan00f511d2019-06-12 16:55:40 -0700466 uint32_t seq, int32_t deviceId, int32_t source, int32_t displayId, int32_t action,
467 int32_t actionButton, int32_t flags, int32_t edgeFlags, int32_t metaState,
468 int32_t buttonState, MotionClassification classification, float xOffset, float yOffset,
469 float xPrecision, float yPrecision, float xCursorPosition, float yCursorPosition,
470 nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
471 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000472 if (ATRACE_ENABLED()) {
473 std::string message = StringPrintf(
474 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
475 mChannel->getName().c_str(), action);
476 ATRACE_NAME(message.c_str());
477 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800478 if (DEBUG_TRANSPORT_ACTIONS) {
479 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
480 "displayId=%" PRId32 ", "
481 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
482 "metaState=0x%x, buttonState=0x%x, classification=%s, xOffset=%f, yOffset=%f, "
483 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
484 "pointerCount=%" PRIu32,
485 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
486 flags, edgeFlags, metaState, buttonState,
487 motionClassificationToString(classification), xOffset, yOffset, xPrecision,
488 yPrecision, downTime, eventTime, pointerCount);
489 }
Jeff Brown5912f952013-07-01 19:10:31 -0700490
491 if (!seq) {
492 ALOGE("Attempted to publish a motion event with sequence number 0.");
493 return BAD_VALUE;
494 }
495
496 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700497 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800498 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700499 return BAD_VALUE;
500 }
501
502 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700503 msg.header.type = InputMessage::Type::MOTION;
Jeff Brown5912f952013-07-01 19:10:31 -0700504 msg.body.motion.seq = seq;
505 msg.body.motion.deviceId = deviceId;
506 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700507 msg.body.motion.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700508 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100509 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700510 msg.body.motion.flags = flags;
511 msg.body.motion.edgeFlags = edgeFlags;
512 msg.body.motion.metaState = metaState;
513 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800514 msg.body.motion.classification = classification;
Jeff Brown5912f952013-07-01 19:10:31 -0700515 msg.body.motion.xOffset = xOffset;
516 msg.body.motion.yOffset = yOffset;
517 msg.body.motion.xPrecision = xPrecision;
518 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700519 msg.body.motion.xCursorPosition = xCursorPosition;
520 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700521 msg.body.motion.downTime = downTime;
522 msg.body.motion.eventTime = eventTime;
523 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100524 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700525 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
526 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
527 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700528
Jeff Brown5912f952013-07-01 19:10:31 -0700529 return mChannel->sendMessage(&msg);
530}
531
532status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800533 if (DEBUG_TRANSPORT_ACTIONS) {
534 ALOGD("channel '%s' publisher ~ receiveFinishedSignal", mChannel->getName().c_str());
535 }
Jeff Brown5912f952013-07-01 19:10:31 -0700536
537 InputMessage msg;
538 status_t result = mChannel->receiveMessage(&msg);
539 if (result) {
540 *outSeq = 0;
541 *outHandled = false;
542 return result;
543 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700544 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700545 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800546 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700547 return UNKNOWN_ERROR;
548 }
549 *outSeq = msg.body.finished.seq;
550 *outHandled = msg.body.finished.handled;
551 return OK;
552}
553
554// --- InputConsumer ---
555
556InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
557 mResampleTouch(isTouchResamplingEnabled()),
558 mChannel(channel), mMsgDeferred(false) {
559}
560
561InputConsumer::~InputConsumer() {
562}
563
564bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600565 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700566}
567
568status_t InputConsumer::consume(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800569 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800570 if (DEBUG_TRANSPORT_ACTIONS) {
571 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
572 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
573 }
Jeff Brown5912f952013-07-01 19:10:31 -0700574
575 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700576 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700577
578 // Fetch the next input message.
579 // Loop until an event can be returned or no additional events are received.
580 while (!*outEvent) {
581 if (mMsgDeferred) {
582 // mMsg contains a valid input message from the previous call to consume
583 // that has not yet been processed.
584 mMsgDeferred = false;
585 } else {
586 // Receive a fresh message.
587 status_t result = mChannel->receiveMessage(&mMsg);
588 if (result) {
589 // Consume the next batched event unless batches are being held for later.
590 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800591 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700592 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800593 if (DEBUG_TRANSPORT_ACTIONS) {
594 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
595 mChannel->getName().c_str(), *outSeq);
596 }
Jeff Brown5912f952013-07-01 19:10:31 -0700597 break;
598 }
599 }
600 return result;
601 }
602 }
603
604 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700605 case InputMessage::Type::KEY: {
606 KeyEvent* keyEvent = factory->createKeyEvent();
607 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700608
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700609 initializeKeyEvent(keyEvent, &mMsg);
610 *outSeq = mMsg.body.key.seq;
611 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800612 if (DEBUG_TRANSPORT_ACTIONS) {
613 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
614 mChannel->getName().c_str(), *outSeq);
615 }
Jeff Brown5912f952013-07-01 19:10:31 -0700616 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700617 }
Jeff Brown5912f952013-07-01 19:10:31 -0700618
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700619 case InputMessage::Type::MOTION: {
620 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
621 if (batchIndex >= 0) {
622 Batch& batch = mBatches.editItemAt(batchIndex);
623 if (canAddSample(batch, &mMsg)) {
624 batch.samples.push(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800625 if (DEBUG_TRANSPORT_ACTIONS) {
626 ALOGD("channel '%s' consumer ~ appended to batch event",
627 mChannel->getName().c_str());
628 }
Jeff Brown5912f952013-07-01 19:10:31 -0700629 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700630 } else if (isPointerEvent(mMsg.body.motion.source) &&
631 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
632 // No need to process events that we are going to cancel anyways
633 const size_t count = batch.samples.size();
634 for (size_t i = 0; i < count; i++) {
635 const InputMessage& msg = batch.samples.itemAt(i);
636 sendFinishedSignal(msg.body.motion.seq, false);
637 }
638 batch.samples.removeItemsAt(0, count);
639 mBatches.removeAt(batchIndex);
640 } else {
641 // We cannot append to the batch in progress, so we need to consume
642 // the previous batch right now and defer the new message until later.
643 mMsgDeferred = true;
644 status_t result = consumeSamples(factory, batch, batch.samples.size(),
645 outSeq, outEvent);
646 mBatches.removeAt(batchIndex);
647 if (result) {
648 return result;
649 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800650 if (DEBUG_TRANSPORT_ACTIONS) {
651 ALOGD("channel '%s' consumer ~ consumed batch event and "
652 "deferred current event, seq=%u",
653 mChannel->getName().c_str(), *outSeq);
654 }
Jeff Brown5912f952013-07-01 19:10:31 -0700655 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700656 }
Jeff Brown5912f952013-07-01 19:10:31 -0700657 }
Jeff Brown5912f952013-07-01 19:10:31 -0700658
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800659 // Start a new batch if needed.
660 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
661 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
662 mBatches.push();
663 Batch& batch = mBatches.editTop();
664 batch.samples.push(mMsg);
665 if (DEBUG_TRANSPORT_ACTIONS) {
666 ALOGD("channel '%s' consumer ~ started batch event",
667 mChannel->getName().c_str());
668 }
669 break;
670 }
Jeff Brown5912f952013-07-01 19:10:31 -0700671
672 MotionEvent* motionEvent = factory->createMotionEvent();
673 if (! motionEvent) return NO_MEMORY;
674
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100675 updateTouchState(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700676 initializeMotionEvent(motionEvent, &mMsg);
677 *outSeq = mMsg.body.motion.seq;
678 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800679
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800680 if (DEBUG_TRANSPORT_ACTIONS) {
681 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
682 mChannel->getName().c_str(), *outSeq);
683 }
Jeff Brown5912f952013-07-01 19:10:31 -0700684 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700685 }
Jeff Brown5912f952013-07-01 19:10:31 -0700686
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800687 case InputMessage::Type::FINISHED: {
688 LOG_ALWAYS_FATAL("Consumed a FINISHED message, which should never be seen by "
689 "InputConsumer!");
690 break;
691 }
Jeff Brown5912f952013-07-01 19:10:31 -0700692 }
693 }
694 return OK;
695}
696
697status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800698 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700699 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700700 for (size_t i = mBatches.size(); i > 0; ) {
701 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700702 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700703 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800704 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700705 mBatches.removeAt(i);
706 return result;
707 }
708
Michael Wright32232172013-10-21 12:05:22 -0700709 nsecs_t sampleTime = frameTime;
710 if (mResampleTouch) {
711 sampleTime -= RESAMPLE_LATENCY;
712 }
Jeff Brown5912f952013-07-01 19:10:31 -0700713 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
714 if (split < 0) {
715 continue;
716 }
717
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800718 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700719 const InputMessage* next;
720 if (batch.samples.isEmpty()) {
721 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700722 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700723 } else {
724 next = &batch.samples.itemAt(0);
725 }
Michael Wright32232172013-10-21 12:05:22 -0700726 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700727 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
728 }
729 return result;
730 }
731
732 return WOULD_BLOCK;
733}
734
735status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800736 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700737 MotionEvent* motionEvent = factory->createMotionEvent();
738 if (! motionEvent) return NO_MEMORY;
739
740 uint32_t chain = 0;
741 for (size_t i = 0; i < count; i++) {
742 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100743 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700744 if (i) {
745 SeqChain seqChain;
746 seqChain.seq = msg.body.motion.seq;
747 seqChain.chain = chain;
748 mSeqChains.push(seqChain);
749 addSample(motionEvent, &msg);
750 } else {
751 initializeMotionEvent(motionEvent, &msg);
752 }
753 chain = msg.body.motion.seq;
754 }
755 batch.samples.removeItemsAt(0, count);
756
757 *outSeq = chain;
758 *outEvent = motionEvent;
759 return OK;
760}
761
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100762void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800763 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700764 return;
765 }
766
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100767 int32_t deviceId = msg.body.motion.deviceId;
768 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700769
770 // Update the touch state history to incorporate the new input message.
771 // If the message is in the past relative to the most recently produced resampled
772 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100773 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700774 case AMOTION_EVENT_ACTION_DOWN: {
775 ssize_t index = findTouchState(deviceId, source);
776 if (index < 0) {
777 mTouchStates.push();
778 index = mTouchStates.size() - 1;
779 }
780 TouchState& touchState = mTouchStates.editItemAt(index);
781 touchState.initialize(deviceId, source);
782 touchState.addHistory(msg);
783 break;
784 }
785
786 case AMOTION_EVENT_ACTION_MOVE: {
787 ssize_t index = findTouchState(deviceId, source);
788 if (index >= 0) {
789 TouchState& touchState = mTouchStates.editItemAt(index);
790 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800791 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700792 }
793 break;
794 }
795
796 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
797 ssize_t index = findTouchState(deviceId, source);
798 if (index >= 0) {
799 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100800 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700801 rewriteMessage(touchState, msg);
802 }
803 break;
804 }
805
806 case AMOTION_EVENT_ACTION_POINTER_UP: {
807 ssize_t index = findTouchState(deviceId, source);
808 if (index >= 0) {
809 TouchState& touchState = mTouchStates.editItemAt(index);
810 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100811 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700812 }
813 break;
814 }
815
816 case AMOTION_EVENT_ACTION_SCROLL: {
817 ssize_t index = findTouchState(deviceId, source);
818 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800819 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700820 rewriteMessage(touchState, msg);
821 }
822 break;
823 }
824
825 case AMOTION_EVENT_ACTION_UP:
826 case AMOTION_EVENT_ACTION_CANCEL: {
827 ssize_t index = findTouchState(deviceId, source);
828 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800829 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700830 rewriteMessage(touchState, msg);
831 mTouchStates.removeAt(index);
832 }
833 break;
834 }
835 }
836}
837
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800838/**
839 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
840 *
841 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
842 * is in the past relative to msg and the past two events do not contain identical coordinates),
843 * then invalidate the lastResample data for that pointer.
844 * If the two past events have identical coordinates, then lastResample data for that pointer will
845 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
846 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
847 * not equal to x0 is received.
848 */
849void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100850 nsecs_t eventTime = msg.body.motion.eventTime;
851 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
852 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700853 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100854 if (eventTime < state.lastResample.eventTime ||
855 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800856 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
857 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700858#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100859 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
860 resampleCoords.getX(), resampleCoords.getY(),
861 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700862#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800863 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
864 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
865 } else {
866 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100867 }
Jeff Brown5912f952013-07-01 19:10:31 -0700868 }
869 }
870}
871
872void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
873 const InputMessage* next) {
874 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800875 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700876 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
877 return;
878 }
879
880 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
881 if (index < 0) {
882#if DEBUG_RESAMPLING
883 ALOGD("Not resampled, no touch state for device.");
884#endif
885 return;
886 }
887
888 TouchState& touchState = mTouchStates.editItemAt(index);
889 if (touchState.historySize < 1) {
890#if DEBUG_RESAMPLING
891 ALOGD("Not resampled, no history for device.");
892#endif
893 return;
894 }
895
896 // Ensure that the current sample has all of the pointers that need to be reported.
897 const History* current = touchState.getHistory(0);
898 size_t pointerCount = event->getPointerCount();
899 for (size_t i = 0; i < pointerCount; i++) {
900 uint32_t id = event->getPointerId(i);
901 if (!current->idBits.hasBit(id)) {
902#if DEBUG_RESAMPLING
903 ALOGD("Not resampled, missing id %d", id);
904#endif
905 return;
906 }
907 }
908
909 // Find the data to use for resampling.
910 const History* other;
911 History future;
912 float alpha;
913 if (next) {
914 // Interpolate between current sample and future sample.
915 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100916 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700917 other = &future;
918 nsecs_t delta = future.eventTime - current->eventTime;
919 if (delta < RESAMPLE_MIN_DELTA) {
920#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100921 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700922#endif
923 return;
924 }
925 alpha = float(sampleTime - current->eventTime) / delta;
926 } else if (touchState.historySize >= 2) {
927 // Extrapolate future sample using current sample and past sample.
928 // So other->eventTime <= current->eventTime <= sampleTime.
929 other = touchState.getHistory(1);
930 nsecs_t delta = current->eventTime - other->eventTime;
931 if (delta < RESAMPLE_MIN_DELTA) {
932#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100933 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700934#endif
935 return;
936 } else if (delta > RESAMPLE_MAX_DELTA) {
937#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100938 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700939#endif
940 return;
941 }
942 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
943 if (sampleTime > maxPredict) {
944#if DEBUG_RESAMPLING
945 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100946 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700947 sampleTime - current->eventTime, maxPredict - current->eventTime);
948#endif
949 sampleTime = maxPredict;
950 }
951 alpha = float(current->eventTime - sampleTime) / delta;
952 } else {
953#if DEBUG_RESAMPLING
954 ALOGD("Not resampled, insufficient data.");
955#endif
956 return;
957 }
958
959 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800960 History oldLastResample;
961 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700962 touchState.lastResample.eventTime = sampleTime;
963 touchState.lastResample.idBits.clear();
964 for (size_t i = 0; i < pointerCount; i++) {
965 uint32_t id = event->getPointerId(i);
966 touchState.lastResample.idToIndex[id] = i;
967 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800968 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
969 // We maintain the previously resampled value for this pointer (stored in
970 // oldLastResample) when the coordinates for this pointer haven't changed since then.
971 // This way we don't introduce artificial jitter when pointers haven't actually moved.
972
973 // We know here that the coordinates for the pointer haven't changed because we
974 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
975 // lastResample in place becasue the mapping from pointer ID to index may have changed.
976 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
977 continue;
978 }
979
Jeff Brown5912f952013-07-01 19:10:31 -0700980 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
981 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800982 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700983 if (other->idBits.hasBit(id)
984 && shouldResampleTool(event->getToolType(i))) {
985 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700986 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
987 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
988 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
989 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
990#if DEBUG_RESAMPLING
991 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
992 "other (%0.3f, %0.3f), alpha %0.3f",
993 id, resampledCoords.getX(), resampledCoords.getY(),
994 currentCoords.getX(), currentCoords.getY(),
995 otherCoords.getX(), otherCoords.getY(),
996 alpha);
997#endif
998 } else {
Jeff Brown5912f952013-07-01 19:10:31 -0700999#if DEBUG_RESAMPLING
1000 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1001 id, resampledCoords.getX(), resampledCoords.getY(),
1002 currentCoords.getX(), currentCoords.getY());
1003#endif
1004 }
1005 }
1006
1007 event->addSample(sampleTime, touchState.lastResample.pointers);
1008}
1009
1010bool InputConsumer::shouldResampleTool(int32_t toolType) {
1011 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1012 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1013}
1014
1015status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001016 if (DEBUG_TRANSPORT_ACTIONS) {
1017 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1018 mChannel->getName().c_str(), seq, toString(handled));
1019 }
Jeff Brown5912f952013-07-01 19:10:31 -07001020
1021 if (!seq) {
1022 ALOGE("Attempted to send a finished signal with sequence number 0.");
1023 return BAD_VALUE;
1024 }
1025
1026 // Send finished signals for the batch sequence chain first.
1027 size_t seqChainCount = mSeqChains.size();
1028 if (seqChainCount) {
1029 uint32_t currentSeq = seq;
1030 uint32_t chainSeqs[seqChainCount];
1031 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001032 for (size_t i = seqChainCount; i > 0; ) {
1033 i--;
Jeff Brown5912f952013-07-01 19:10:31 -07001034 const SeqChain& seqChain = mSeqChains.itemAt(i);
1035 if (seqChain.seq == currentSeq) {
1036 currentSeq = seqChain.chain;
1037 chainSeqs[chainIndex++] = currentSeq;
1038 mSeqChains.removeAt(i);
1039 }
1040 }
1041 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001042 while (!status && chainIndex > 0) {
1043 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001044 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1045 }
1046 if (status) {
1047 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001048 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001049 SeqChain seqChain;
1050 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1051 seqChain.chain = chainSeqs[chainIndex];
1052 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001053 if (!chainIndex) break;
1054 chainIndex--;
1055 }
Jeff Brown5912f952013-07-01 19:10:31 -07001056 return status;
1057 }
1058 }
1059
1060 // Send finished signal for the last message in the batch.
1061 return sendUnchainedFinishedSignal(seq, handled);
1062}
1063
1064status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1065 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001066 msg.header.type = InputMessage::Type::FINISHED;
Jeff Brown5912f952013-07-01 19:10:31 -07001067 msg.body.finished.seq = seq;
1068 msg.body.finished.handled = handled;
1069 return mChannel->sendMessage(&msg);
1070}
1071
1072bool InputConsumer::hasDeferredEvent() const {
1073 return mMsgDeferred;
1074}
1075
1076bool InputConsumer::hasPendingBatch() const {
1077 return !mBatches.isEmpty();
1078}
1079
1080ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1081 for (size_t i = 0; i < mBatches.size(); i++) {
1082 const Batch& batch = mBatches.itemAt(i);
1083 const InputMessage& head = batch.samples.itemAt(0);
1084 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1085 return i;
1086 }
1087 }
1088 return -1;
1089}
1090
1091ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1092 for (size_t i = 0; i < mTouchStates.size(); i++) {
1093 const TouchState& touchState = mTouchStates.itemAt(i);
1094 if (touchState.deviceId == deviceId && touchState.source == source) {
1095 return i;
1096 }
1097 }
1098 return -1;
1099}
1100
1101void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
1102 event->initialize(
1103 msg->body.key.deviceId,
1104 msg->body.key.source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001105 msg->body.key.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001106 msg->body.key.action,
1107 msg->body.key.flags,
1108 msg->body.key.keyCode,
1109 msg->body.key.scanCode,
1110 msg->body.key.metaState,
1111 msg->body.key.repeatCount,
1112 msg->body.key.downTime,
1113 msg->body.key.eventTime);
1114}
1115
1116void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001117 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001118 PointerProperties pointerProperties[pointerCount];
1119 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001120 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001121 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1122 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1123 }
1124
Garfield Tan00f511d2019-06-12 16:55:40 -07001125 event->initialize(msg->body.motion.deviceId, msg->body.motion.source,
1126 msg->body.motion.displayId, msg->body.motion.action,
1127 msg->body.motion.actionButton, msg->body.motion.flags,
1128 msg->body.motion.edgeFlags, msg->body.motion.metaState,
1129 msg->body.motion.buttonState, msg->body.motion.classification,
1130 msg->body.motion.xOffset, msg->body.motion.yOffset,
1131 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1132 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1133 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1134 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001135}
1136
1137void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001138 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001139 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001140 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001141 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1142 }
1143
1144 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1145 event->addSample(msg->body.motion.eventTime, pointerCoords);
1146}
1147
1148bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1149 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001150 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001151 if (head.body.motion.pointerCount != pointerCount
1152 || head.body.motion.action != msg->body.motion.action) {
1153 return false;
1154 }
1155 for (size_t i = 0; i < pointerCount; i++) {
1156 if (head.body.motion.pointers[i].properties
1157 != msg->body.motion.pointers[i].properties) {
1158 return false;
1159 }
1160 }
1161 return true;
1162}
1163
1164ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1165 size_t numSamples = batch.samples.size();
1166 size_t index = 0;
1167 while (index < numSamples
1168 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1169 index += 1;
1170 }
1171 return ssize_t(index) - 1;
1172}
1173
1174} // namespace android