blob: c4f7fe0bf2a1791f2ca77df6e13a2fbdbbe13efd [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
14#define DEBUG_CHANNEL_LIFECYCLE 0
15
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
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700228sp<InputChannel> InputChannel::create(const std::string& name, android::base::unique_fd fd) {
229 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
230 if (result != 0) {
231 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
232 strerror(errno));
233 return nullptr;
234 }
235 return new InputChannel(name, std::move(fd));
236}
237
238InputChannel::InputChannel(const std::string& name, android::base::unique_fd fd)
239 : mName(name), mFd(std::move(fd)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700240#if DEBUG_CHANNEL_LIFECYCLE
241 ALOGD("Input channel constructed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800242 mName.c_str(), fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700243#endif
Jeff Brown5912f952013-07-01 19:10:31 -0700244}
245
246InputChannel::~InputChannel() {
247#if DEBUG_CHANNEL_LIFECYCLE
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700248 ALOGD("Input channel destroyed: name='%s', fd=%d", mName.c_str(), mFd.get());
Jeff Brown5912f952013-07-01 19:10:31 -0700249#endif
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
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700270 std::string serverChannelName = name + " (server)";
271 android::base::unique_fd serverFd(sockets[0]);
272 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd));
Jeff Brown5912f952013-07-01 19:10:31 -0700273
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700274 std::string clientChannelName = name + " (client)";
275 android::base::unique_fd clientFd(sockets[1]);
276 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd));
Jeff Brown5912f952013-07-01 19:10:31 -0700277 return OK;
278}
279
280status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800281 const size_t msgLength = msg->size();
282 InputMessage cleanMsg;
283 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700284 ssize_t nWrite;
285 do {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700286 nWrite = ::send(mFd.get(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700287 } while (nWrite == -1 && errno == EINTR);
288
289 if (nWrite < 0) {
290 int error = errno;
291#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800292 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.c_str(),
Jeff Brown5912f952013-07-01 19:10:31 -0700293 msg->header.type, error);
294#endif
295 if (error == EAGAIN || error == EWOULDBLOCK) {
296 return WOULD_BLOCK;
297 }
298 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
299 return DEAD_OBJECT;
300 }
301 return -error;
302 }
303
304 if (size_t(nWrite) != msgLength) {
305#if DEBUG_CHANNEL_MESSAGES
306 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800307 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700308#endif
309 return DEAD_OBJECT;
310 }
311
312#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800313 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700314#endif
315 return OK;
316}
317
318status_t InputChannel::receiveMessage(InputMessage* msg) {
319 ssize_t nRead;
320 do {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700321 nRead = ::recv(mFd.get(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700322 } while (nRead == -1 && errno == EINTR);
323
324 if (nRead < 0) {
325 int error = errno;
326#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800327 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700328#endif
329 if (error == EAGAIN || error == EWOULDBLOCK) {
330 return WOULD_BLOCK;
331 }
332 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
333 return DEAD_OBJECT;
334 }
335 return -error;
336 }
337
338 if (nRead == 0) { // check for EOF
339#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800340 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700341#endif
342 return DEAD_OBJECT;
343 }
344
345 if (!msg->isValid(nRead)) {
346#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800347 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700348#endif
349 return BAD_VALUE;
350 }
351
352#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800353 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700354#endif
355 return OK;
356}
357
358sp<InputChannel> InputChannel::dup() const {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700359 android::base::unique_fd newFd(::dup(getFd()));
360 if (!newFd.ok()) {
361 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd(), mName.c_str(),
362 strerror(errno));
Siarhei Vishniakou3d8df0e2019-09-17 14:53:07 +0100363 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
364 // If this process is out of file descriptors, then throwing that might end up exploding
365 // on the other side of a binder call, which isn't really helpful.
366 // Better to just crash here and hope that the FD leak is slow.
367 // Other failures could be client errors, so we still propagate those back to the caller.
368 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
369 getName().c_str());
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700370 return nullptr;
371 }
372 return InputChannel::create(mName, std::move(newFd));
Jeff Brown5912f952013-07-01 19:10:31 -0700373}
374
Robert Carr3720ed02018-08-08 16:08:27 -0700375status_t InputChannel::write(Parcel& out) const {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700376 status_t s = out.writeCString(getName().c_str());
Robert Carr3720ed02018-08-08 16:08:27 -0700377 if (s != OK) {
378 return s;
379 }
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700380
Robert Carr803535b2018-08-02 16:38:15 -0700381 s = out.writeStrongBinder(mToken);
382 if (s != OK) {
383 return s;
384 }
Robert Carr3720ed02018-08-08 16:08:27 -0700385
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700386 s = out.writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700387 return s;
388}
389
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700390sp<InputChannel> InputChannel::read(const Parcel& from) {
391 std::string name = from.readCString();
392 sp<IBinder> token = from.readStrongBinder();
393 android::base::unique_fd rawFd;
394 status_t fdResult = from.readUniqueFileDescriptor(&rawFd);
395 if (fdResult != OK) {
396 return nullptr;
Robert Carr3720ed02018-08-08 16:08:27 -0700397 }
398
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700399 sp<InputChannel> channel = InputChannel::create(name, std::move(rawFd));
400 if (channel != nullptr) {
401 channel->setToken(token);
402 }
403 return channel;
Robert Carr3720ed02018-08-08 16:08:27 -0700404}
405
Robert Carr803535b2018-08-02 16:38:15 -0700406sp<IBinder> InputChannel::getToken() const {
407 return mToken;
408}
409
410void InputChannel::setToken(const sp<IBinder>& token) {
411 if (mToken != nullptr) {
412 ALOGE("Assigning InputChannel (%s) a second handle?", mName.c_str());
413 }
414 mToken = token;
415}
416
Jeff Brown5912f952013-07-01 19:10:31 -0700417// --- InputPublisher ---
418
419InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
420 mChannel(channel) {
421}
422
423InputPublisher::~InputPublisher() {
424}
425
426status_t InputPublisher::publishKeyEvent(
427 uint32_t seq,
428 int32_t deviceId,
429 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100430 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700431 int32_t action,
432 int32_t flags,
433 int32_t keyCode,
434 int32_t scanCode,
435 int32_t metaState,
436 int32_t repeatCount,
437 nsecs_t downTime,
438 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000439 if (ATRACE_ENABLED()) {
440 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
441 mChannel->getName().c_str(), keyCode);
442 ATRACE_NAME(message.c_str());
443 }
Jeff Brown5912f952013-07-01 19:10:31 -0700444#if DEBUG_TRANSPORT_ACTIONS
445 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
446 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700447 "downTime=%" PRId64 ", eventTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800448 mChannel->getName().c_str(), seq,
Jeff Brown5912f952013-07-01 19:10:31 -0700449 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
450 downTime, eventTime);
451#endif
452
453 if (!seq) {
454 ALOGE("Attempted to publish a key event with sequence number 0.");
455 return BAD_VALUE;
456 }
457
458 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700459 msg.header.type = InputMessage::Type::KEY;
Jeff Brown5912f952013-07-01 19:10:31 -0700460 msg.body.key.seq = seq;
461 msg.body.key.deviceId = deviceId;
462 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100463 msg.body.key.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700464 msg.body.key.action = action;
465 msg.body.key.flags = flags;
466 msg.body.key.keyCode = keyCode;
467 msg.body.key.scanCode = scanCode;
468 msg.body.key.metaState = metaState;
469 msg.body.key.repeatCount = repeatCount;
470 msg.body.key.downTime = downTime;
471 msg.body.key.eventTime = eventTime;
472 return mChannel->sendMessage(&msg);
473}
474
475status_t InputPublisher::publishMotionEvent(
Garfield Tan00f511d2019-06-12 16:55:40 -0700476 uint32_t seq, int32_t deviceId, int32_t source, int32_t displayId, int32_t action,
477 int32_t actionButton, int32_t flags, int32_t edgeFlags, int32_t metaState,
478 int32_t buttonState, MotionClassification classification, float xOffset, float yOffset,
479 float xPrecision, float yPrecision, float xCursorPosition, float yCursorPosition,
480 nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
481 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000482 if (ATRACE_ENABLED()) {
483 std::string message = StringPrintf(
484 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
485 mChannel->getName().c_str(), action);
486 ATRACE_NAME(message.c_str());
487 }
Jeff Brown5912f952013-07-01 19:10:31 -0700488#if DEBUG_TRANSPORT_ACTIONS
489 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800490 "displayId=%" PRId32 ", "
Michael Wright7b159c92015-05-14 14:48:03 +0100491 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800492 "metaState=0x%x, buttonState=0x%x, classification=%s, xOffset=%f, yOffset=%f, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700493 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
Michael Wright63ff3a82014-06-10 13:03:17 -0700494 "pointerCount=%" PRIu32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800495 mChannel->getName().c_str(), seq,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800496 deviceId, source, displayId, action, actionButton, flags, edgeFlags, metaState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800497 buttonState, motionClassificationToString(classification),
498 xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700499#endif
500
501 if (!seq) {
502 ALOGE("Attempted to publish a motion event with sequence number 0.");
503 return BAD_VALUE;
504 }
505
506 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700507 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800508 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700509 return BAD_VALUE;
510 }
511
512 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700513 msg.header.type = InputMessage::Type::MOTION;
Jeff Brown5912f952013-07-01 19:10:31 -0700514 msg.body.motion.seq = seq;
515 msg.body.motion.deviceId = deviceId;
516 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700517 msg.body.motion.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700518 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100519 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700520 msg.body.motion.flags = flags;
521 msg.body.motion.edgeFlags = edgeFlags;
522 msg.body.motion.metaState = metaState;
523 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800524 msg.body.motion.classification = classification;
Jeff Brown5912f952013-07-01 19:10:31 -0700525 msg.body.motion.xOffset = xOffset;
526 msg.body.motion.yOffset = yOffset;
527 msg.body.motion.xPrecision = xPrecision;
528 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700529 msg.body.motion.xCursorPosition = xCursorPosition;
530 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700531 msg.body.motion.downTime = downTime;
532 msg.body.motion.eventTime = eventTime;
533 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100534 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700535 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
536 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
537 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700538
Jeff Brown5912f952013-07-01 19:10:31 -0700539 return mChannel->sendMessage(&msg);
540}
541
542status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
543#if DEBUG_TRANSPORT_ACTIONS
544 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800545 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700546#endif
547
548 InputMessage msg;
549 status_t result = mChannel->receiveMessage(&msg);
550 if (result) {
551 *outSeq = 0;
552 *outHandled = false;
553 return result;
554 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700555 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700556 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800557 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700558 return UNKNOWN_ERROR;
559 }
560 *outSeq = msg.body.finished.seq;
561 *outHandled = msg.body.finished.handled;
562 return OK;
563}
564
565// --- InputConsumer ---
566
567InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
568 mResampleTouch(isTouchResamplingEnabled()),
569 mChannel(channel), mMsgDeferred(false) {
570}
571
572InputConsumer::~InputConsumer() {
573}
574
575bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600576 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700577}
578
579status_t InputConsumer::consume(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800580 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700581#if DEBUG_TRANSPORT_ACTIONS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700582 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800583 mChannel->getName().c_str(), consumeBatches ? "true" : "false", frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700584#endif
585
586 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700587 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700588
589 // Fetch the next input message.
590 // Loop until an event can be returned or no additional events are received.
591 while (!*outEvent) {
592 if (mMsgDeferred) {
593 // mMsg contains a valid input message from the previous call to consume
594 // that has not yet been processed.
595 mMsgDeferred = false;
596 } else {
597 // Receive a fresh message.
598 status_t result = mChannel->receiveMessage(&mMsg);
599 if (result) {
600 // Consume the next batched event unless batches are being held for later.
601 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800602 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700603 if (*outEvent) {
604#if DEBUG_TRANSPORT_ACTIONS
605 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800606 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700607#endif
608 break;
609 }
610 }
611 return result;
612 }
613 }
614
615 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700616 case InputMessage::Type::KEY: {
617 KeyEvent* keyEvent = factory->createKeyEvent();
618 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700619
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700620 initializeKeyEvent(keyEvent, &mMsg);
621 *outSeq = mMsg.body.key.seq;
622 *outEvent = keyEvent;
Jeff Brown5912f952013-07-01 19:10:31 -0700623#if DEBUG_TRANSPORT_ACTIONS
624 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800625 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700626#endif
627 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700628 }
Jeff Brown5912f952013-07-01 19:10:31 -0700629
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700630 case InputMessage::Type::MOTION: {
631 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
632 if (batchIndex >= 0) {
633 Batch& batch = mBatches.editItemAt(batchIndex);
634 if (canAddSample(batch, &mMsg)) {
635 batch.samples.push(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700636#if DEBUG_TRANSPORT_ACTIONS
637 ALOGD("channel '%s' consumer ~ appended to batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800638 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700639#endif
640 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700641 } else if (isPointerEvent(mMsg.body.motion.source) &&
642 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
643 // No need to process events that we are going to cancel anyways
644 const size_t count = batch.samples.size();
645 for (size_t i = 0; i < count; i++) {
646 const InputMessage& msg = batch.samples.itemAt(i);
647 sendFinishedSignal(msg.body.motion.seq, false);
648 }
649 batch.samples.removeItemsAt(0, count);
650 mBatches.removeAt(batchIndex);
651 } else {
652 // We cannot append to the batch in progress, so we need to consume
653 // the previous batch right now and defer the new message until later.
654 mMsgDeferred = true;
655 status_t result = consumeSamples(factory, batch, batch.samples.size(),
656 outSeq, outEvent);
657 mBatches.removeAt(batchIndex);
658 if (result) {
659 return result;
660 }
Jeff Brown5912f952013-07-01 19:10:31 -0700661#if DEBUG_TRANSPORT_ACTIONS
662 ALOGD("channel '%s' consumer ~ consumed batch event and "
663 "deferred current event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800664 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700665#endif
666 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700667 }
Jeff Brown5912f952013-07-01 19:10:31 -0700668 }
Jeff Brown5912f952013-07-01 19:10:31 -0700669
670 // Start a new batch if needed.
671 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
672 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
673 mBatches.push();
674 Batch& batch = mBatches.editTop();
675 batch.samples.push(mMsg);
676#if DEBUG_TRANSPORT_ACTIONS
677 ALOGD("channel '%s' consumer ~ started batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800678 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700679#endif
680 break;
681 }
682
683 MotionEvent* motionEvent = factory->createMotionEvent();
684 if (! motionEvent) return NO_MEMORY;
685
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100686 updateTouchState(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700687 initializeMotionEvent(motionEvent, &mMsg);
688 *outSeq = mMsg.body.motion.seq;
689 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800690
Jeff Brown5912f952013-07-01 19:10:31 -0700691#if DEBUG_TRANSPORT_ACTIONS
692 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800693 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700694#endif
695 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700696 }
Jeff Brown5912f952013-07-01 19:10:31 -0700697
698 default:
699 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800700 mChannel->getName().c_str(), mMsg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700701 return UNKNOWN_ERROR;
702 }
703 }
704 return OK;
705}
706
707status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800708 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700709 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700710 for (size_t i = mBatches.size(); i > 0; ) {
711 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700712 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700713 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800714 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700715 mBatches.removeAt(i);
716 return result;
717 }
718
Michael Wright32232172013-10-21 12:05:22 -0700719 nsecs_t sampleTime = frameTime;
720 if (mResampleTouch) {
721 sampleTime -= RESAMPLE_LATENCY;
722 }
Jeff Brown5912f952013-07-01 19:10:31 -0700723 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
724 if (split < 0) {
725 continue;
726 }
727
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800728 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700729 const InputMessage* next;
730 if (batch.samples.isEmpty()) {
731 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700732 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700733 } else {
734 next = &batch.samples.itemAt(0);
735 }
Michael Wright32232172013-10-21 12:05:22 -0700736 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700737 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
738 }
739 return result;
740 }
741
742 return WOULD_BLOCK;
743}
744
745status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800746 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700747 MotionEvent* motionEvent = factory->createMotionEvent();
748 if (! motionEvent) return NO_MEMORY;
749
750 uint32_t chain = 0;
751 for (size_t i = 0; i < count; i++) {
752 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100753 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700754 if (i) {
755 SeqChain seqChain;
756 seqChain.seq = msg.body.motion.seq;
757 seqChain.chain = chain;
758 mSeqChains.push(seqChain);
759 addSample(motionEvent, &msg);
760 } else {
761 initializeMotionEvent(motionEvent, &msg);
762 }
763 chain = msg.body.motion.seq;
764 }
765 batch.samples.removeItemsAt(0, count);
766
767 *outSeq = chain;
768 *outEvent = motionEvent;
769 return OK;
770}
771
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100772void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800773 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700774 return;
775 }
776
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100777 int32_t deviceId = msg.body.motion.deviceId;
778 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700779
780 // Update the touch state history to incorporate the new input message.
781 // If the message is in the past relative to the most recently produced resampled
782 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100783 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700784 case AMOTION_EVENT_ACTION_DOWN: {
785 ssize_t index = findTouchState(deviceId, source);
786 if (index < 0) {
787 mTouchStates.push();
788 index = mTouchStates.size() - 1;
789 }
790 TouchState& touchState = mTouchStates.editItemAt(index);
791 touchState.initialize(deviceId, source);
792 touchState.addHistory(msg);
793 break;
794 }
795
796 case AMOTION_EVENT_ACTION_MOVE: {
797 ssize_t index = findTouchState(deviceId, source);
798 if (index >= 0) {
799 TouchState& touchState = mTouchStates.editItemAt(index);
800 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800801 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700802 }
803 break;
804 }
805
806 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
807 ssize_t index = findTouchState(deviceId, source);
808 if (index >= 0) {
809 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100810 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700811 rewriteMessage(touchState, msg);
812 }
813 break;
814 }
815
816 case AMOTION_EVENT_ACTION_POINTER_UP: {
817 ssize_t index = findTouchState(deviceId, source);
818 if (index >= 0) {
819 TouchState& touchState = mTouchStates.editItemAt(index);
820 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100821 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700822 }
823 break;
824 }
825
826 case AMOTION_EVENT_ACTION_SCROLL: {
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 }
832 break;
833 }
834
835 case AMOTION_EVENT_ACTION_UP:
836 case AMOTION_EVENT_ACTION_CANCEL: {
837 ssize_t index = findTouchState(deviceId, source);
838 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800839 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700840 rewriteMessage(touchState, msg);
841 mTouchStates.removeAt(index);
842 }
843 break;
844 }
845 }
846}
847
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800848/**
849 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
850 *
851 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
852 * is in the past relative to msg and the past two events do not contain identical coordinates),
853 * then invalidate the lastResample data for that pointer.
854 * If the two past events have identical coordinates, then lastResample data for that pointer will
855 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
856 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
857 * not equal to x0 is received.
858 */
859void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100860 nsecs_t eventTime = msg.body.motion.eventTime;
861 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
862 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700863 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100864 if (eventTime < state.lastResample.eventTime ||
865 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800866 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
867 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700868#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100869 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
870 resampleCoords.getX(), resampleCoords.getY(),
871 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700872#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800873 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
874 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
875 } else {
876 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100877 }
Jeff Brown5912f952013-07-01 19:10:31 -0700878 }
879 }
880}
881
882void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
883 const InputMessage* next) {
884 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800885 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700886 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
887 return;
888 }
889
890 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
891 if (index < 0) {
892#if DEBUG_RESAMPLING
893 ALOGD("Not resampled, no touch state for device.");
894#endif
895 return;
896 }
897
898 TouchState& touchState = mTouchStates.editItemAt(index);
899 if (touchState.historySize < 1) {
900#if DEBUG_RESAMPLING
901 ALOGD("Not resampled, no history for device.");
902#endif
903 return;
904 }
905
906 // Ensure that the current sample has all of the pointers that need to be reported.
907 const History* current = touchState.getHistory(0);
908 size_t pointerCount = event->getPointerCount();
909 for (size_t i = 0; i < pointerCount; i++) {
910 uint32_t id = event->getPointerId(i);
911 if (!current->idBits.hasBit(id)) {
912#if DEBUG_RESAMPLING
913 ALOGD("Not resampled, missing id %d", id);
914#endif
915 return;
916 }
917 }
918
919 // Find the data to use for resampling.
920 const History* other;
921 History future;
922 float alpha;
923 if (next) {
924 // Interpolate between current sample and future sample.
925 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100926 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700927 other = &future;
928 nsecs_t delta = future.eventTime - current->eventTime;
929 if (delta < RESAMPLE_MIN_DELTA) {
930#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100931 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700932#endif
933 return;
934 }
935 alpha = float(sampleTime - current->eventTime) / delta;
936 } else if (touchState.historySize >= 2) {
937 // Extrapolate future sample using current sample and past sample.
938 // So other->eventTime <= current->eventTime <= sampleTime.
939 other = touchState.getHistory(1);
940 nsecs_t delta = current->eventTime - other->eventTime;
941 if (delta < RESAMPLE_MIN_DELTA) {
942#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100943 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700944#endif
945 return;
946 } else if (delta > RESAMPLE_MAX_DELTA) {
947#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100948 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700949#endif
950 return;
951 }
952 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
953 if (sampleTime > maxPredict) {
954#if DEBUG_RESAMPLING
955 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100956 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700957 sampleTime - current->eventTime, maxPredict - current->eventTime);
958#endif
959 sampleTime = maxPredict;
960 }
961 alpha = float(current->eventTime - sampleTime) / delta;
962 } else {
963#if DEBUG_RESAMPLING
964 ALOGD("Not resampled, insufficient data.");
965#endif
966 return;
967 }
968
969 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800970 History oldLastResample;
971 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700972 touchState.lastResample.eventTime = sampleTime;
973 touchState.lastResample.idBits.clear();
974 for (size_t i = 0; i < pointerCount; i++) {
975 uint32_t id = event->getPointerId(i);
976 touchState.lastResample.idToIndex[id] = i;
977 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800978 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
979 // We maintain the previously resampled value for this pointer (stored in
980 // oldLastResample) when the coordinates for this pointer haven't changed since then.
981 // This way we don't introduce artificial jitter when pointers haven't actually moved.
982
983 // We know here that the coordinates for the pointer haven't changed because we
984 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
985 // lastResample in place becasue the mapping from pointer ID to index may have changed.
986 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
987 continue;
988 }
989
Jeff Brown5912f952013-07-01 19:10:31 -0700990 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
991 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800992 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700993 if (other->idBits.hasBit(id)
994 && shouldResampleTool(event->getToolType(i))) {
995 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700996 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
997 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
998 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
999 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1000#if DEBUG_RESAMPLING
1001 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1002 "other (%0.3f, %0.3f), alpha %0.3f",
1003 id, resampledCoords.getX(), resampledCoords.getY(),
1004 currentCoords.getX(), currentCoords.getY(),
1005 otherCoords.getX(), otherCoords.getY(),
1006 alpha);
1007#endif
1008 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001009#if DEBUG_RESAMPLING
1010 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1011 id, resampledCoords.getX(), resampledCoords.getY(),
1012 currentCoords.getX(), currentCoords.getY());
1013#endif
1014 }
1015 }
1016
1017 event->addSample(sampleTime, touchState.lastResample.pointers);
1018}
1019
1020bool InputConsumer::shouldResampleTool(int32_t toolType) {
1021 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1022 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1023}
1024
1025status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
1026#if DEBUG_TRANSPORT_ACTIONS
1027 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001028 mChannel->getName().c_str(), seq, handled ? "true" : "false");
Jeff Brown5912f952013-07-01 19:10:31 -07001029#endif
1030
1031 if (!seq) {
1032 ALOGE("Attempted to send a finished signal with sequence number 0.");
1033 return BAD_VALUE;
1034 }
1035
1036 // Send finished signals for the batch sequence chain first.
1037 size_t seqChainCount = mSeqChains.size();
1038 if (seqChainCount) {
1039 uint32_t currentSeq = seq;
1040 uint32_t chainSeqs[seqChainCount];
1041 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001042 for (size_t i = seqChainCount; i > 0; ) {
1043 i--;
Jeff Brown5912f952013-07-01 19:10:31 -07001044 const SeqChain& seqChain = mSeqChains.itemAt(i);
1045 if (seqChain.seq == currentSeq) {
1046 currentSeq = seqChain.chain;
1047 chainSeqs[chainIndex++] = currentSeq;
1048 mSeqChains.removeAt(i);
1049 }
1050 }
1051 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001052 while (!status && chainIndex > 0) {
1053 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001054 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1055 }
1056 if (status) {
1057 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001058 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001059 SeqChain seqChain;
1060 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1061 seqChain.chain = chainSeqs[chainIndex];
1062 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001063 if (!chainIndex) break;
1064 chainIndex--;
1065 }
Jeff Brown5912f952013-07-01 19:10:31 -07001066 return status;
1067 }
1068 }
1069
1070 // Send finished signal for the last message in the batch.
1071 return sendUnchainedFinishedSignal(seq, handled);
1072}
1073
1074status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1075 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001076 msg.header.type = InputMessage::Type::FINISHED;
Jeff Brown5912f952013-07-01 19:10:31 -07001077 msg.body.finished.seq = seq;
1078 msg.body.finished.handled = handled;
1079 return mChannel->sendMessage(&msg);
1080}
1081
1082bool InputConsumer::hasDeferredEvent() const {
1083 return mMsgDeferred;
1084}
1085
1086bool InputConsumer::hasPendingBatch() const {
1087 return !mBatches.isEmpty();
1088}
1089
1090ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1091 for (size_t i = 0; i < mBatches.size(); i++) {
1092 const Batch& batch = mBatches.itemAt(i);
1093 const InputMessage& head = batch.samples.itemAt(0);
1094 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1095 return i;
1096 }
1097 }
1098 return -1;
1099}
1100
1101ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1102 for (size_t i = 0; i < mTouchStates.size(); i++) {
1103 const TouchState& touchState = mTouchStates.itemAt(i);
1104 if (touchState.deviceId == deviceId && touchState.source == source) {
1105 return i;
1106 }
1107 }
1108 return -1;
1109}
1110
1111void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
1112 event->initialize(
1113 msg->body.key.deviceId,
1114 msg->body.key.source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001115 msg->body.key.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001116 msg->body.key.action,
1117 msg->body.key.flags,
1118 msg->body.key.keyCode,
1119 msg->body.key.scanCode,
1120 msg->body.key.metaState,
1121 msg->body.key.repeatCount,
1122 msg->body.key.downTime,
1123 msg->body.key.eventTime);
1124}
1125
1126void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001127 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001128 PointerProperties pointerProperties[pointerCount];
1129 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001130 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001131 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1132 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1133 }
1134
Garfield Tan00f511d2019-06-12 16:55:40 -07001135 event->initialize(msg->body.motion.deviceId, msg->body.motion.source,
1136 msg->body.motion.displayId, msg->body.motion.action,
1137 msg->body.motion.actionButton, msg->body.motion.flags,
1138 msg->body.motion.edgeFlags, msg->body.motion.metaState,
1139 msg->body.motion.buttonState, msg->body.motion.classification,
1140 msg->body.motion.xOffset, msg->body.motion.yOffset,
1141 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1142 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1143 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1144 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001145}
1146
1147void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001148 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001149 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001150 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001151 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1152 }
1153
1154 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1155 event->addSample(msg->body.motion.eventTime, pointerCoords);
1156}
1157
1158bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1159 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001160 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001161 if (head.body.motion.pointerCount != pointerCount
1162 || head.body.motion.action != msg->body.motion.action) {
1163 return false;
1164 }
1165 for (size_t i = 0; i < pointerCount; i++) {
1166 if (head.body.motion.pointers[i].properties
1167 != msg->body.motion.pointers[i].properties) {
1168 return false;
1169 }
1170 }
1171 return true;
1172}
1173
1174ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1175 size_t numSamples = batch.samples.size();
1176 size_t index = 0;
1177 while (index < numSamples
1178 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1179 index += 1;
1180 }
1181 return ssize_t(index) - 1;
1182}
1183
1184} // namespace android