blob: a5dd3c0544a20c05cd771eb371a4b2c442930b6e [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
17#define DEBUG_TRANSPORT_ACTIONS 0
18
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
Jeff Brown5912f952013-07-01 19:10:31 -070091// --- InputMessage ---
92
93bool InputMessage::isValid(size_t actualSize) const {
94 if (size() == actualSize) {
95 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -070096 case Type::KEY:
97 return true;
98 case Type::MOTION:
99 return body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
100 case Type::FINISHED:
101 return true;
Jeff Brown5912f952013-07-01 19:10:31 -0700102 }
103 }
104 return false;
105}
106
107size_t InputMessage::size() const {
108 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700109 case Type::KEY:
110 return sizeof(Header) + body.key.size();
111 case Type::MOTION:
112 return sizeof(Header) + body.motion.size();
113 case Type::FINISHED:
114 return sizeof(Header) + body.finished.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700115 }
116 return sizeof(Header);
117}
118
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800119/**
120 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
121 * memory to zero, then only copy the valid bytes on a per-field basis.
122 */
123void InputMessage::getSanitizedCopy(InputMessage* msg) const {
124 memset(msg, 0, sizeof(*msg));
125
126 // Write the header
127 msg->header.type = header.type;
128
129 // Write the body
130 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700131 case InputMessage::Type::KEY: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800132 // uint32_t seq
133 msg->body.key.seq = body.key.seq;
134 // nsecs_t eventTime
135 msg->body.key.eventTime = body.key.eventTime;
136 // int32_t deviceId
137 msg->body.key.deviceId = body.key.deviceId;
138 // int32_t source
139 msg->body.key.source = body.key.source;
140 // int32_t displayId
141 msg->body.key.displayId = body.key.displayId;
142 // int32_t action
143 msg->body.key.action = body.key.action;
144 // int32_t flags
145 msg->body.key.flags = body.key.flags;
146 // int32_t keyCode
147 msg->body.key.keyCode = body.key.keyCode;
148 // int32_t scanCode
149 msg->body.key.scanCode = body.key.scanCode;
150 // int32_t metaState
151 msg->body.key.metaState = body.key.metaState;
152 // int32_t repeatCount
153 msg->body.key.repeatCount = body.key.repeatCount;
154 // nsecs_t downTime
155 msg->body.key.downTime = body.key.downTime;
156 break;
157 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700158 case InputMessage::Type::MOTION: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800159 // uint32_t seq
160 msg->body.motion.seq = body.motion.seq;
161 // nsecs_t eventTime
162 msg->body.motion.eventTime = body.motion.eventTime;
163 // int32_t deviceId
164 msg->body.motion.deviceId = body.motion.deviceId;
165 // int32_t source
166 msg->body.motion.source = body.motion.source;
167 // int32_t displayId
168 msg->body.motion.displayId = body.motion.displayId;
169 // int32_t action
170 msg->body.motion.action = body.motion.action;
171 // int32_t actionButton
172 msg->body.motion.actionButton = body.motion.actionButton;
173 // int32_t flags
174 msg->body.motion.flags = body.motion.flags;
175 // int32_t metaState
176 msg->body.motion.metaState = body.motion.metaState;
177 // int32_t buttonState
178 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800179 // MotionClassification classification
180 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800181 // int32_t edgeFlags
182 msg->body.motion.edgeFlags = body.motion.edgeFlags;
183 // nsecs_t downTime
184 msg->body.motion.downTime = body.motion.downTime;
185 // float xOffset
186 msg->body.motion.xOffset = body.motion.xOffset;
187 // float yOffset
188 msg->body.motion.yOffset = body.motion.yOffset;
189 // float xPrecision
190 msg->body.motion.xPrecision = body.motion.xPrecision;
191 // float yPrecision
192 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700193 // float xCursorPosition
194 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
195 // float yCursorPosition
196 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800197 // uint32_t pointerCount
198 msg->body.motion.pointerCount = body.motion.pointerCount;
199 //struct Pointer pointers[MAX_POINTERS]
200 for (size_t i = 0; i < body.motion.pointerCount; i++) {
201 // PointerProperties properties
202 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
203 msg->body.motion.pointers[i].properties.toolType =
204 body.motion.pointers[i].properties.toolType,
205 // PointerCoords coords
206 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
207 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
208 memcpy(&msg->body.motion.pointers[i].coords.values[0],
209 &body.motion.pointers[i].coords.values[0],
210 count * (sizeof(body.motion.pointers[i].coords.values[0])));
211 }
212 break;
213 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700214 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800215 msg->body.finished.seq = body.finished.seq;
216 msg->body.finished.handled = body.finished.handled;
217 break;
218 }
219 default: {
220 LOG_FATAL("Unexpected message type %i", header.type);
221 break;
222 }
223 }
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 }
Jeff Brown5912f952013-07-01 19:10:31 -0700435#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,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700438 "downTime=%" PRId64 ", eventTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800439 mChannel->getName().c_str(), seq,
Jeff Brown5912f952013-07-01 19:10:31 -0700440 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
441 downTime, eventTime);
442#endif
443
444 if (!seq) {
445 ALOGE("Attempted to publish a key event with sequence number 0.");
446 return BAD_VALUE;
447 }
448
449 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700450 msg.header.type = InputMessage::Type::KEY;
Jeff Brown5912f952013-07-01 19:10:31 -0700451 msg.body.key.seq = seq;
452 msg.body.key.deviceId = deviceId;
453 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100454 msg.body.key.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700455 msg.body.key.action = action;
456 msg.body.key.flags = flags;
457 msg.body.key.keyCode = keyCode;
458 msg.body.key.scanCode = scanCode;
459 msg.body.key.metaState = metaState;
460 msg.body.key.repeatCount = repeatCount;
461 msg.body.key.downTime = downTime;
462 msg.body.key.eventTime = eventTime;
463 return mChannel->sendMessage(&msg);
464}
465
466status_t InputPublisher::publishMotionEvent(
Garfield Tan00f511d2019-06-12 16:55:40 -0700467 uint32_t seq, int32_t deviceId, int32_t source, int32_t displayId, int32_t action,
468 int32_t actionButton, int32_t flags, int32_t edgeFlags, int32_t metaState,
469 int32_t buttonState, MotionClassification classification, float xOffset, float yOffset,
470 float xPrecision, float yPrecision, float xCursorPosition, float yCursorPosition,
471 nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
472 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000473 if (ATRACE_ENABLED()) {
474 std::string message = StringPrintf(
475 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
476 mChannel->getName().c_str(), action);
477 ATRACE_NAME(message.c_str());
478 }
Jeff Brown5912f952013-07-01 19:10:31 -0700479#if DEBUG_TRANSPORT_ACTIONS
480 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800481 "displayId=%" PRId32 ", "
Michael Wright7b159c92015-05-14 14:48:03 +0100482 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800483 "metaState=0x%x, buttonState=0x%x, classification=%s, xOffset=%f, yOffset=%f, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700484 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
Michael Wright63ff3a82014-06-10 13:03:17 -0700485 "pointerCount=%" PRIu32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800486 mChannel->getName().c_str(), seq,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800487 deviceId, source, displayId, action, actionButton, flags, edgeFlags, metaState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800488 buttonState, motionClassificationToString(classification),
489 xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700490#endif
491
492 if (!seq) {
493 ALOGE("Attempted to publish a motion event with sequence number 0.");
494 return BAD_VALUE;
495 }
496
497 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700498 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800499 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700500 return BAD_VALUE;
501 }
502
503 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700504 msg.header.type = InputMessage::Type::MOTION;
Jeff Brown5912f952013-07-01 19:10:31 -0700505 msg.body.motion.seq = seq;
506 msg.body.motion.deviceId = deviceId;
507 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700508 msg.body.motion.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700509 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100510 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700511 msg.body.motion.flags = flags;
512 msg.body.motion.edgeFlags = edgeFlags;
513 msg.body.motion.metaState = metaState;
514 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800515 msg.body.motion.classification = classification;
Jeff Brown5912f952013-07-01 19:10:31 -0700516 msg.body.motion.xOffset = xOffset;
517 msg.body.motion.yOffset = yOffset;
518 msg.body.motion.xPrecision = xPrecision;
519 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700520 msg.body.motion.xCursorPosition = xCursorPosition;
521 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700522 msg.body.motion.downTime = downTime;
523 msg.body.motion.eventTime = eventTime;
524 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100525 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700526 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
527 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
528 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700529
Jeff Brown5912f952013-07-01 19:10:31 -0700530 return mChannel->sendMessage(&msg);
531}
532
533status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
534#if DEBUG_TRANSPORT_ACTIONS
535 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800536 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700537#endif
538
539 InputMessage msg;
540 status_t result = mChannel->receiveMessage(&msg);
541 if (result) {
542 *outSeq = 0;
543 *outHandled = false;
544 return result;
545 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700546 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700547 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800548 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700549 return UNKNOWN_ERROR;
550 }
551 *outSeq = msg.body.finished.seq;
552 *outHandled = msg.body.finished.handled;
553 return OK;
554}
555
556// --- InputConsumer ---
557
558InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
559 mResampleTouch(isTouchResamplingEnabled()),
560 mChannel(channel), mMsgDeferred(false) {
561}
562
563InputConsumer::~InputConsumer() {
564}
565
566bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600567 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700568}
569
570status_t InputConsumer::consume(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800571 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700572#if DEBUG_TRANSPORT_ACTIONS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700573 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800574 mChannel->getName().c_str(), consumeBatches ? "true" : "false", frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700575#endif
576
577 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700578 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700579
580 // Fetch the next input message.
581 // Loop until an event can be returned or no additional events are received.
582 while (!*outEvent) {
583 if (mMsgDeferred) {
584 // mMsg contains a valid input message from the previous call to consume
585 // that has not yet been processed.
586 mMsgDeferred = false;
587 } else {
588 // Receive a fresh message.
589 status_t result = mChannel->receiveMessage(&mMsg);
590 if (result) {
591 // Consume the next batched event unless batches are being held for later.
592 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800593 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700594 if (*outEvent) {
595#if DEBUG_TRANSPORT_ACTIONS
596 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800597 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700598#endif
599 break;
600 }
601 }
602 return result;
603 }
604 }
605
606 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700607 case InputMessage::Type::KEY: {
608 KeyEvent* keyEvent = factory->createKeyEvent();
609 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700610
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700611 initializeKeyEvent(keyEvent, &mMsg);
612 *outSeq = mMsg.body.key.seq;
613 *outEvent = keyEvent;
Jeff Brown5912f952013-07-01 19:10:31 -0700614#if DEBUG_TRANSPORT_ACTIONS
615 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800616 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700617#endif
618 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700619 }
Jeff Brown5912f952013-07-01 19:10:31 -0700620
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700621 case InputMessage::Type::MOTION: {
622 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
623 if (batchIndex >= 0) {
624 Batch& batch = mBatches.editItemAt(batchIndex);
625 if (canAddSample(batch, &mMsg)) {
626 batch.samples.push(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700627#if DEBUG_TRANSPORT_ACTIONS
628 ALOGD("channel '%s' consumer ~ appended to batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800629 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700630#endif
631 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700632 } else if (isPointerEvent(mMsg.body.motion.source) &&
633 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
634 // No need to process events that we are going to cancel anyways
635 const size_t count = batch.samples.size();
636 for (size_t i = 0; i < count; i++) {
637 const InputMessage& msg = batch.samples.itemAt(i);
638 sendFinishedSignal(msg.body.motion.seq, false);
639 }
640 batch.samples.removeItemsAt(0, count);
641 mBatches.removeAt(batchIndex);
642 } else {
643 // We cannot append to the batch in progress, so we need to consume
644 // the previous batch right now and defer the new message until later.
645 mMsgDeferred = true;
646 status_t result = consumeSamples(factory, batch, batch.samples.size(),
647 outSeq, outEvent);
648 mBatches.removeAt(batchIndex);
649 if (result) {
650 return result;
651 }
Jeff Brown5912f952013-07-01 19:10:31 -0700652#if DEBUG_TRANSPORT_ACTIONS
653 ALOGD("channel '%s' consumer ~ consumed batch event and "
654 "deferred current event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800655 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700656#endif
657 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700658 }
Jeff Brown5912f952013-07-01 19:10:31 -0700659 }
Jeff Brown5912f952013-07-01 19:10:31 -0700660
661 // Start a new batch if needed.
662 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
663 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
664 mBatches.push();
665 Batch& batch = mBatches.editTop();
666 batch.samples.push(mMsg);
667#if DEBUG_TRANSPORT_ACTIONS
668 ALOGD("channel '%s' consumer ~ started batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800669 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700670#endif
671 break;
672 }
673
674 MotionEvent* motionEvent = factory->createMotionEvent();
675 if (! motionEvent) return NO_MEMORY;
676
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100677 updateTouchState(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700678 initializeMotionEvent(motionEvent, &mMsg);
679 *outSeq = mMsg.body.motion.seq;
680 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800681
Jeff Brown5912f952013-07-01 19:10:31 -0700682#if DEBUG_TRANSPORT_ACTIONS
683 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800684 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700685#endif
686 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700687 }
Jeff Brown5912f952013-07-01 19:10:31 -0700688
689 default:
690 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800691 mChannel->getName().c_str(), mMsg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700692 return UNKNOWN_ERROR;
693 }
694 }
695 return OK;
696}
697
698status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800699 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700700 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700701 for (size_t i = mBatches.size(); i > 0; ) {
702 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700703 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700704 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800705 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700706 mBatches.removeAt(i);
707 return result;
708 }
709
Michael Wright32232172013-10-21 12:05:22 -0700710 nsecs_t sampleTime = frameTime;
711 if (mResampleTouch) {
712 sampleTime -= RESAMPLE_LATENCY;
713 }
Jeff Brown5912f952013-07-01 19:10:31 -0700714 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
715 if (split < 0) {
716 continue;
717 }
718
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800719 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700720 const InputMessage* next;
721 if (batch.samples.isEmpty()) {
722 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700723 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700724 } else {
725 next = &batch.samples.itemAt(0);
726 }
Michael Wright32232172013-10-21 12:05:22 -0700727 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700728 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
729 }
730 return result;
731 }
732
733 return WOULD_BLOCK;
734}
735
736status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800737 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700738 MotionEvent* motionEvent = factory->createMotionEvent();
739 if (! motionEvent) return NO_MEMORY;
740
741 uint32_t chain = 0;
742 for (size_t i = 0; i < count; i++) {
743 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100744 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700745 if (i) {
746 SeqChain seqChain;
747 seqChain.seq = msg.body.motion.seq;
748 seqChain.chain = chain;
749 mSeqChains.push(seqChain);
750 addSample(motionEvent, &msg);
751 } else {
752 initializeMotionEvent(motionEvent, &msg);
753 }
754 chain = msg.body.motion.seq;
755 }
756 batch.samples.removeItemsAt(0, count);
757
758 *outSeq = chain;
759 *outEvent = motionEvent;
760 return OK;
761}
762
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100763void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800764 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700765 return;
766 }
767
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100768 int32_t deviceId = msg.body.motion.deviceId;
769 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700770
771 // Update the touch state history to incorporate the new input message.
772 // If the message is in the past relative to the most recently produced resampled
773 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100774 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700775 case AMOTION_EVENT_ACTION_DOWN: {
776 ssize_t index = findTouchState(deviceId, source);
777 if (index < 0) {
778 mTouchStates.push();
779 index = mTouchStates.size() - 1;
780 }
781 TouchState& touchState = mTouchStates.editItemAt(index);
782 touchState.initialize(deviceId, source);
783 touchState.addHistory(msg);
784 break;
785 }
786
787 case AMOTION_EVENT_ACTION_MOVE: {
788 ssize_t index = findTouchState(deviceId, source);
789 if (index >= 0) {
790 TouchState& touchState = mTouchStates.editItemAt(index);
791 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800792 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700793 }
794 break;
795 }
796
797 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
798 ssize_t index = findTouchState(deviceId, source);
799 if (index >= 0) {
800 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100801 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700802 rewriteMessage(touchState, msg);
803 }
804 break;
805 }
806
807 case AMOTION_EVENT_ACTION_POINTER_UP: {
808 ssize_t index = findTouchState(deviceId, source);
809 if (index >= 0) {
810 TouchState& touchState = mTouchStates.editItemAt(index);
811 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100812 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700813 }
814 break;
815 }
816
817 case AMOTION_EVENT_ACTION_SCROLL: {
818 ssize_t index = findTouchState(deviceId, source);
819 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800820 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700821 rewriteMessage(touchState, msg);
822 }
823 break;
824 }
825
826 case AMOTION_EVENT_ACTION_UP:
827 case AMOTION_EVENT_ACTION_CANCEL: {
828 ssize_t index = findTouchState(deviceId, source);
829 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800830 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700831 rewriteMessage(touchState, msg);
832 mTouchStates.removeAt(index);
833 }
834 break;
835 }
836 }
837}
838
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800839/**
840 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
841 *
842 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
843 * is in the past relative to msg and the past two events do not contain identical coordinates),
844 * then invalidate the lastResample data for that pointer.
845 * If the two past events have identical coordinates, then lastResample data for that pointer will
846 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
847 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
848 * not equal to x0 is received.
849 */
850void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100851 nsecs_t eventTime = msg.body.motion.eventTime;
852 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
853 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700854 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100855 if (eventTime < state.lastResample.eventTime ||
856 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800857 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
858 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700859#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100860 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
861 resampleCoords.getX(), resampleCoords.getY(),
862 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700863#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800864 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
865 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
866 } else {
867 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100868 }
Jeff Brown5912f952013-07-01 19:10:31 -0700869 }
870 }
871}
872
873void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
874 const InputMessage* next) {
875 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800876 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700877 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
878 return;
879 }
880
881 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
882 if (index < 0) {
883#if DEBUG_RESAMPLING
884 ALOGD("Not resampled, no touch state for device.");
885#endif
886 return;
887 }
888
889 TouchState& touchState = mTouchStates.editItemAt(index);
890 if (touchState.historySize < 1) {
891#if DEBUG_RESAMPLING
892 ALOGD("Not resampled, no history for device.");
893#endif
894 return;
895 }
896
897 // Ensure that the current sample has all of the pointers that need to be reported.
898 const History* current = touchState.getHistory(0);
899 size_t pointerCount = event->getPointerCount();
900 for (size_t i = 0; i < pointerCount; i++) {
901 uint32_t id = event->getPointerId(i);
902 if (!current->idBits.hasBit(id)) {
903#if DEBUG_RESAMPLING
904 ALOGD("Not resampled, missing id %d", id);
905#endif
906 return;
907 }
908 }
909
910 // Find the data to use for resampling.
911 const History* other;
912 History future;
913 float alpha;
914 if (next) {
915 // Interpolate between current sample and future sample.
916 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100917 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700918 other = &future;
919 nsecs_t delta = future.eventTime - current->eventTime;
920 if (delta < RESAMPLE_MIN_DELTA) {
921#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100922 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700923#endif
924 return;
925 }
926 alpha = float(sampleTime - current->eventTime) / delta;
927 } else if (touchState.historySize >= 2) {
928 // Extrapolate future sample using current sample and past sample.
929 // So other->eventTime <= current->eventTime <= sampleTime.
930 other = touchState.getHistory(1);
931 nsecs_t delta = current->eventTime - other->eventTime;
932 if (delta < RESAMPLE_MIN_DELTA) {
933#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100934 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700935#endif
936 return;
937 } else if (delta > RESAMPLE_MAX_DELTA) {
938#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100939 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700940#endif
941 return;
942 }
943 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
944 if (sampleTime > maxPredict) {
945#if DEBUG_RESAMPLING
946 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100947 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700948 sampleTime - current->eventTime, maxPredict - current->eventTime);
949#endif
950 sampleTime = maxPredict;
951 }
952 alpha = float(current->eventTime - sampleTime) / delta;
953 } else {
954#if DEBUG_RESAMPLING
955 ALOGD("Not resampled, insufficient data.");
956#endif
957 return;
958 }
959
960 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800961 History oldLastResample;
962 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700963 touchState.lastResample.eventTime = sampleTime;
964 touchState.lastResample.idBits.clear();
965 for (size_t i = 0; i < pointerCount; i++) {
966 uint32_t id = event->getPointerId(i);
967 touchState.lastResample.idToIndex[id] = i;
968 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800969 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
970 // We maintain the previously resampled value for this pointer (stored in
971 // oldLastResample) when the coordinates for this pointer haven't changed since then.
972 // This way we don't introduce artificial jitter when pointers haven't actually moved.
973
974 // We know here that the coordinates for the pointer haven't changed because we
975 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
976 // lastResample in place becasue the mapping from pointer ID to index may have changed.
977 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
978 continue;
979 }
980
Jeff Brown5912f952013-07-01 19:10:31 -0700981 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
982 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800983 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700984 if (other->idBits.hasBit(id)
985 && shouldResampleTool(event->getToolType(i))) {
986 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700987 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
988 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
989 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
990 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
991#if DEBUG_RESAMPLING
992 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
993 "other (%0.3f, %0.3f), alpha %0.3f",
994 id, resampledCoords.getX(), resampledCoords.getY(),
995 currentCoords.getX(), currentCoords.getY(),
996 otherCoords.getX(), otherCoords.getY(),
997 alpha);
998#endif
999 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001000#if DEBUG_RESAMPLING
1001 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1002 id, resampledCoords.getX(), resampledCoords.getY(),
1003 currentCoords.getX(), currentCoords.getY());
1004#endif
1005 }
1006 }
1007
1008 event->addSample(sampleTime, touchState.lastResample.pointers);
1009}
1010
1011bool InputConsumer::shouldResampleTool(int32_t toolType) {
1012 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1013 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1014}
1015
1016status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
1017#if DEBUG_TRANSPORT_ACTIONS
1018 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001019 mChannel->getName().c_str(), seq, handled ? "true" : "false");
Jeff Brown5912f952013-07-01 19:10:31 -07001020#endif
1021
1022 if (!seq) {
1023 ALOGE("Attempted to send a finished signal with sequence number 0.");
1024 return BAD_VALUE;
1025 }
1026
1027 // Send finished signals for the batch sequence chain first.
1028 size_t seqChainCount = mSeqChains.size();
1029 if (seqChainCount) {
1030 uint32_t currentSeq = seq;
1031 uint32_t chainSeqs[seqChainCount];
1032 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001033 for (size_t i = seqChainCount; i > 0; ) {
1034 i--;
Jeff Brown5912f952013-07-01 19:10:31 -07001035 const SeqChain& seqChain = mSeqChains.itemAt(i);
1036 if (seqChain.seq == currentSeq) {
1037 currentSeq = seqChain.chain;
1038 chainSeqs[chainIndex++] = currentSeq;
1039 mSeqChains.removeAt(i);
1040 }
1041 }
1042 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001043 while (!status && chainIndex > 0) {
1044 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001045 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1046 }
1047 if (status) {
1048 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001049 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001050 SeqChain seqChain;
1051 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1052 seqChain.chain = chainSeqs[chainIndex];
1053 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001054 if (!chainIndex) break;
1055 chainIndex--;
1056 }
Jeff Brown5912f952013-07-01 19:10:31 -07001057 return status;
1058 }
1059 }
1060
1061 // Send finished signal for the last message in the batch.
1062 return sendUnchainedFinishedSignal(seq, handled);
1063}
1064
1065status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1066 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001067 msg.header.type = InputMessage::Type::FINISHED;
Jeff Brown5912f952013-07-01 19:10:31 -07001068 msg.body.finished.seq = seq;
1069 msg.body.finished.handled = handled;
1070 return mChannel->sendMessage(&msg);
1071}
1072
1073bool InputConsumer::hasDeferredEvent() const {
1074 return mMsgDeferred;
1075}
1076
1077bool InputConsumer::hasPendingBatch() const {
1078 return !mBatches.isEmpty();
1079}
1080
1081ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1082 for (size_t i = 0; i < mBatches.size(); i++) {
1083 const Batch& batch = mBatches.itemAt(i);
1084 const InputMessage& head = batch.samples.itemAt(0);
1085 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1086 return i;
1087 }
1088 }
1089 return -1;
1090}
1091
1092ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1093 for (size_t i = 0; i < mTouchStates.size(); i++) {
1094 const TouchState& touchState = mTouchStates.itemAt(i);
1095 if (touchState.deviceId == deviceId && touchState.source == source) {
1096 return i;
1097 }
1098 }
1099 return -1;
1100}
1101
1102void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
1103 event->initialize(
1104 msg->body.key.deviceId,
1105 msg->body.key.source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001106 msg->body.key.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001107 msg->body.key.action,
1108 msg->body.key.flags,
1109 msg->body.key.keyCode,
1110 msg->body.key.scanCode,
1111 msg->body.key.metaState,
1112 msg->body.key.repeatCount,
1113 msg->body.key.downTime,
1114 msg->body.key.eventTime);
1115}
1116
1117void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001118 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001119 PointerProperties pointerProperties[pointerCount];
1120 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001121 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001122 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1123 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1124 }
1125
Garfield Tan00f511d2019-06-12 16:55:40 -07001126 event->initialize(msg->body.motion.deviceId, msg->body.motion.source,
1127 msg->body.motion.displayId, msg->body.motion.action,
1128 msg->body.motion.actionButton, msg->body.motion.flags,
1129 msg->body.motion.edgeFlags, msg->body.motion.metaState,
1130 msg->body.motion.buttonState, msg->body.motion.classification,
1131 msg->body.motion.xOffset, msg->body.motion.yOffset,
1132 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1133 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1134 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1135 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001136}
1137
1138void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001139 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001140 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001141 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001142 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1143 }
1144
1145 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1146 event->addSample(msg->body.motion.eventTime, pointerCoords);
1147}
1148
1149bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1150 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001151 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001152 if (head.body.motion.pointerCount != pointerCount
1153 || head.body.motion.action != msg->body.motion.action) {
1154 return false;
1155 }
1156 for (size_t i = 0; i < pointerCount; i++) {
1157 if (head.body.motion.pointers[i].properties
1158 != msg->body.motion.pointers[i].properties) {
1159 return false;
1160 }
1161 }
1162 return true;
1163}
1164
1165ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1166 size_t numSamples = batch.samples.size();
1167 size_t index = 0;
1168 while (index < numSamples
1169 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1170 index += 1;
1171 }
1172 return ssize_t(index) - 1;
1173}
1174
1175} // namespace android