blob: 200e1f39d9ccceb637624a680c87a4eb116b0ff2 [file] [log] [blame]
Jeff Brown5912f952013-07-01 19:10:31 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// Provides a shared memory transport for input events.
5//
6#define LOG_TAG "InputTransport"
7
8//#define LOG_NDEBUG 0
9
10// Log debug messages about channel messages (send message, receive message)
11#define DEBUG_CHANNEL_MESSAGES 0
12
13// Log debug messages whenever InputChannel objects are created/destroyed
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -070014static constexpr bool DEBUG_CHANNEL_LIFECYCLE = false;
Jeff Brown5912f952013-07-01 19:10:31 -070015
16// Log debug messages about transport actions
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080017static constexpr bool DEBUG_TRANSPORT_ACTIONS = false;
Jeff Brown5912f952013-07-01 19:10:31 -070018
19// Log debug messages about touch event resampling
20#define DEBUG_RESAMPLING 0
21
Jeff Brown5912f952013-07-01 19:10:31 -070022#include <errno.h>
23#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070024#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070025#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070026#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070027#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070028#include <unistd.h>
29
Michael Wright3dd60e22019-03-27 22:06:44 +000030#include <android-base/stringprintf.h>
31#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070032#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070033#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000034#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070035
Jeff Brown5912f952013-07-01 19:10:31 -070036#include <input/InputTransport.h>
37
Michael Wright3dd60e22019-03-27 22:06:44 +000038using android::base::StringPrintf;
39
Jeff Brown5912f952013-07-01 19:10:31 -070040namespace android {
41
42// Socket buffer size. The default is typically about 128KB, which is much larger than
43// we really need. So we make it smaller. It just needs to be big enough to hold
44// a few dozen large multi-finger motion events in the case where an application gets
45// behind processing touches.
46static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
47
48// Nanoseconds per milliseconds.
49static const nsecs_t NANOS_PER_MS = 1000000;
50
51// Latency added during resampling. A few milliseconds doesn't hurt much but
52// reduces the impact of mispredicted touch positions.
53static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
54
55// Minimum time difference between consecutive samples before attempting to resample.
56static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
57
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070058// Maximum time difference between consecutive samples before attempting to resample
59// by extrapolation.
60static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
61
Jeff Brown5912f952013-07-01 19:10:31 -070062// Maximum time to predict forward from the last known state, to avoid predicting too
63// far into the future. This time is further bounded by 50% of the last time delta.
64static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
65
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -060066/**
67 * System property for enabling / disabling touch resampling.
68 * Resampling extrapolates / interpolates the reported touch event coordinates to better
69 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
70 * Resampling is not needed (and should be disabled) on hardware that already
71 * has touch events triggered by VSYNC.
72 * Set to "1" to enable resampling (default).
73 * Set to "0" to disable resampling.
74 * Resampling is enabled by default.
75 */
76static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
77
Jeff Brown5912f952013-07-01 19:10:31 -070078template<typename T>
79inline static T min(const T& a, const T& b) {
80 return a < b ? a : b;
81}
82
83inline static float lerp(float a, float b, float alpha) {
84 return a + alpha * (b - a);
85}
86
Siarhei Vishniakou128eab12019-05-23 10:25:59 +080087inline static bool isPointerEvent(int32_t source) {
88 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
89}
90
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080091inline static const char* toString(bool value) {
92 return value ? "true" : "false";
93}
94
Jeff Brown5912f952013-07-01 19:10:31 -070095// --- InputMessage ---
96
97bool InputMessage::isValid(size_t actualSize) const {
98 if (size() == actualSize) {
99 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700100 case Type::KEY:
101 return true;
102 case Type::MOTION:
103 return body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
104 case Type::FINISHED:
105 return true;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800106 case Type::FOCUS:
107 return true;
Jeff Brown5912f952013-07-01 19:10:31 -0700108 }
109 }
110 return false;
111}
112
113size_t InputMessage::size() const {
114 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700115 case Type::KEY:
116 return sizeof(Header) + body.key.size();
117 case Type::MOTION:
118 return sizeof(Header) + body.motion.size();
119 case Type::FINISHED:
120 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800121 case Type::FOCUS:
122 return sizeof(Header) + body.focus.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700123 }
124 return sizeof(Header);
125}
126
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800127/**
128 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
129 * memory to zero, then only copy the valid bytes on a per-field basis.
130 */
131void InputMessage::getSanitizedCopy(InputMessage* msg) const {
132 memset(msg, 0, sizeof(*msg));
133
134 // Write the header
135 msg->header.type = header.type;
136
137 // Write the body
138 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700139 case InputMessage::Type::KEY: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800140 // uint32_t seq
141 msg->body.key.seq = body.key.seq;
142 // nsecs_t eventTime
143 msg->body.key.eventTime = body.key.eventTime;
144 // int32_t deviceId
145 msg->body.key.deviceId = body.key.deviceId;
146 // int32_t source
147 msg->body.key.source = body.key.source;
148 // int32_t displayId
149 msg->body.key.displayId = body.key.displayId;
150 // int32_t action
151 msg->body.key.action = body.key.action;
152 // int32_t flags
153 msg->body.key.flags = body.key.flags;
154 // int32_t keyCode
155 msg->body.key.keyCode = body.key.keyCode;
156 // int32_t scanCode
157 msg->body.key.scanCode = body.key.scanCode;
158 // int32_t metaState
159 msg->body.key.metaState = body.key.metaState;
160 // int32_t repeatCount
161 msg->body.key.repeatCount = body.key.repeatCount;
162 // nsecs_t downTime
163 msg->body.key.downTime = body.key.downTime;
164 break;
165 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700166 case InputMessage::Type::MOTION: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800167 // uint32_t seq
168 msg->body.motion.seq = body.motion.seq;
169 // nsecs_t eventTime
170 msg->body.motion.eventTime = body.motion.eventTime;
171 // int32_t deviceId
172 msg->body.motion.deviceId = body.motion.deviceId;
173 // int32_t source
174 msg->body.motion.source = body.motion.source;
175 // int32_t displayId
176 msg->body.motion.displayId = body.motion.displayId;
177 // int32_t action
178 msg->body.motion.action = body.motion.action;
179 // int32_t actionButton
180 msg->body.motion.actionButton = body.motion.actionButton;
181 // int32_t flags
182 msg->body.motion.flags = body.motion.flags;
183 // int32_t metaState
184 msg->body.motion.metaState = body.motion.metaState;
185 // int32_t buttonState
186 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800187 // MotionClassification classification
188 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800189 // int32_t edgeFlags
190 msg->body.motion.edgeFlags = body.motion.edgeFlags;
191 // nsecs_t downTime
192 msg->body.motion.downTime = body.motion.downTime;
193 // float xOffset
194 msg->body.motion.xOffset = body.motion.xOffset;
195 // float yOffset
196 msg->body.motion.yOffset = body.motion.yOffset;
197 // float xPrecision
198 msg->body.motion.xPrecision = body.motion.xPrecision;
199 // float yPrecision
200 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700201 // float xCursorPosition
202 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
203 // float yCursorPosition
204 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800205 // uint32_t pointerCount
206 msg->body.motion.pointerCount = body.motion.pointerCount;
207 //struct Pointer pointers[MAX_POINTERS]
208 for (size_t i = 0; i < body.motion.pointerCount; i++) {
209 // PointerProperties properties
210 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
211 msg->body.motion.pointers[i].properties.toolType =
212 body.motion.pointers[i].properties.toolType,
213 // PointerCoords coords
214 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
215 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
216 memcpy(&msg->body.motion.pointers[i].coords.values[0],
217 &body.motion.pointers[i].coords.values[0],
218 count * (sizeof(body.motion.pointers[i].coords.values[0])));
219 }
220 break;
221 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700222 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800223 msg->body.finished.seq = body.finished.seq;
224 msg->body.finished.handled = body.finished.handled;
225 break;
226 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800227 case InputMessage::Type::FOCUS: {
228 msg->body.focus.seq = body.focus.seq;
229 msg->body.focus.hasFocus = body.focus.hasFocus;
230 msg->body.focus.inTouchMode = body.focus.inTouchMode;
231 break;
232 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800233 }
234}
Jeff Brown5912f952013-07-01 19:10:31 -0700235
236// --- InputChannel ---
237
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700238sp<InputChannel> InputChannel::create(const std::string& name, android::base::unique_fd fd,
239 sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700240 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
241 if (result != 0) {
242 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
243 strerror(errno));
244 return nullptr;
245 }
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700246 return new InputChannel(name, std::move(fd), token);
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700247}
248
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700249InputChannel::InputChannel(const std::string& name, android::base::unique_fd fd, sp<IBinder> token)
250 : mName(name), mFd(std::move(fd)), mToken(token) {
251 if (DEBUG_CHANNEL_LIFECYCLE) {
252 ALOGD("Input channel constructed: name='%s', fd=%d", mName.c_str(), mFd.get());
253 }
Jeff Brown5912f952013-07-01 19:10:31 -0700254}
255
256InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700257 if (DEBUG_CHANNEL_LIFECYCLE) {
258 ALOGD("Input channel destroyed: name='%s', fd=%d", mName.c_str(), mFd.get());
259 }
Robert Carr3720ed02018-08-08 16:08:27 -0700260}
261
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800262status_t InputChannel::openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700263 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
264 int sockets[2];
265 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
266 status_t result = -errno;
267 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 name.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700269 outServerChannel.clear();
270 outClientChannel.clear();
271 return result;
272 }
273
274 int bufferSize = SOCKET_BUFFER_SIZE;
275 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
276 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
277 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
278 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
279
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700280 sp<IBinder> token = new BBinder();
281
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700282 std::string serverChannelName = name + " (server)";
283 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700284 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700285
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700286 std::string clientChannelName = name + " (client)";
287 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700288 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700289 return OK;
290}
291
292status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800293 const size_t msgLength = msg->size();
294 InputMessage cleanMsg;
295 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700296 ssize_t nWrite;
297 do {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700298 nWrite = ::send(mFd.get(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700299 } while (nWrite == -1 && errno == EINTR);
300
301 if (nWrite < 0) {
302 int error = errno;
303#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800304 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.c_str(),
Jeff Brown5912f952013-07-01 19:10:31 -0700305 msg->header.type, error);
306#endif
307 if (error == EAGAIN || error == EWOULDBLOCK) {
308 return WOULD_BLOCK;
309 }
310 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
311 return DEAD_OBJECT;
312 }
313 return -error;
314 }
315
316 if (size_t(nWrite) != msgLength) {
317#if DEBUG_CHANNEL_MESSAGES
318 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800319 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700320#endif
321 return DEAD_OBJECT;
322 }
323
324#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800325 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700326#endif
327 return OK;
328}
329
330status_t InputChannel::receiveMessage(InputMessage* msg) {
331 ssize_t nRead;
332 do {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700333 nRead = ::recv(mFd.get(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700334 } while (nRead == -1 && errno == EINTR);
335
336 if (nRead < 0) {
337 int error = errno;
338#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800339 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700340#endif
341 if (error == EAGAIN || error == EWOULDBLOCK) {
342 return WOULD_BLOCK;
343 }
344 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
345 return DEAD_OBJECT;
346 }
347 return -error;
348 }
349
350 if (nRead == 0) { // check for EOF
351#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800352 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700353#endif
354 return DEAD_OBJECT;
355 }
356
357 if (!msg->isValid(nRead)) {
358#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800359 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700360#endif
361 return BAD_VALUE;
362 }
363
364#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800365 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700366#endif
367 return OK;
368}
369
370sp<InputChannel> InputChannel::dup() const {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700371 android::base::unique_fd newFd(::dup(getFd()));
372 if (!newFd.ok()) {
373 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd(), mName.c_str(),
374 strerror(errno));
Siarhei Vishniakou3d8df0e2019-09-17 14:53:07 +0100375 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
376 // If this process is out of file descriptors, then throwing that might end up exploding
377 // on the other side of a binder call, which isn't really helpful.
378 // Better to just crash here and hope that the FD leak is slow.
379 // Other failures could be client errors, so we still propagate those back to the caller.
380 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
381 getName().c_str());
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700382 return nullptr;
383 }
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700384 return InputChannel::create(mName, std::move(newFd), mToken);
Jeff Brown5912f952013-07-01 19:10:31 -0700385}
386
Robert Carr3720ed02018-08-08 16:08:27 -0700387status_t InputChannel::write(Parcel& out) const {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700388 status_t s = out.writeCString(getName().c_str());
Robert Carr3720ed02018-08-08 16:08:27 -0700389 if (s != OK) {
390 return s;
391 }
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700392
Robert Carr803535b2018-08-02 16:38:15 -0700393 s = out.writeStrongBinder(mToken);
394 if (s != OK) {
395 return s;
396 }
Robert Carr3720ed02018-08-08 16:08:27 -0700397
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700398 s = out.writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700399 return s;
400}
401
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700402sp<InputChannel> InputChannel::read(const Parcel& from) {
403 std::string name = from.readCString();
404 sp<IBinder> token = from.readStrongBinder();
405 android::base::unique_fd rawFd;
406 status_t fdResult = from.readUniqueFileDescriptor(&rawFd);
407 if (fdResult != OK) {
408 return nullptr;
Robert Carr3720ed02018-08-08 16:08:27 -0700409 }
410
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700411 return InputChannel::create(name, std::move(rawFd), token);
Robert Carr3720ed02018-08-08 16:08:27 -0700412}
413
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700414sp<IBinder> InputChannel::getConnectionToken() const {
Robert Carr803535b2018-08-02 16:38:15 -0700415 return mToken;
416}
417
Jeff Brown5912f952013-07-01 19:10:31 -0700418// --- InputPublisher ---
419
420InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
421 mChannel(channel) {
422}
423
424InputPublisher::~InputPublisher() {
425}
426
427status_t InputPublisher::publishKeyEvent(
428 uint32_t seq,
429 int32_t deviceId,
430 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100431 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700432 int32_t action,
433 int32_t flags,
434 int32_t keyCode,
435 int32_t scanCode,
436 int32_t metaState,
437 int32_t repeatCount,
438 nsecs_t downTime,
439 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000440 if (ATRACE_ENABLED()) {
441 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
442 mChannel->getName().c_str(), keyCode);
443 ATRACE_NAME(message.c_str());
444 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800445 if (DEBUG_TRANSPORT_ACTIONS) {
446 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
447 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
448 "downTime=%" PRId64 ", eventTime=%" PRId64,
449 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
450 metaState, repeatCount, downTime, eventTime);
451 }
Jeff Brown5912f952013-07-01 19:10:31 -0700452
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 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800488 if (DEBUG_TRANSPORT_ACTIONS) {
489 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
490 "displayId=%" PRId32 ", "
491 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
492 "metaState=0x%x, buttonState=0x%x, classification=%s, xOffset=%f, yOffset=%f, "
493 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
494 "pointerCount=%" PRIu32,
495 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
496 flags, edgeFlags, metaState, buttonState,
497 motionClassificationToString(classification), xOffset, yOffset, xPrecision,
498 yPrecision, downTime, eventTime, pointerCount);
499 }
Jeff Brown5912f952013-07-01 19:10:31 -0700500
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
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800542status_t InputPublisher::publishFocusEvent(uint32_t seq, bool hasFocus, bool inTouchMode) {
543 if (ATRACE_ENABLED()) {
544 std::string message =
545 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
546 mChannel->getName().c_str(), toString(hasFocus),
547 toString(inTouchMode));
548 ATRACE_NAME(message.c_str());
549 }
550
551 InputMessage msg;
552 msg.header.type = InputMessage::Type::FOCUS;
553 msg.body.focus.seq = seq;
554 msg.body.focus.hasFocus = hasFocus ? 1 : 0;
555 msg.body.focus.inTouchMode = inTouchMode ? 1 : 0;
556 return mChannel->sendMessage(&msg);
557}
558
Jeff Brown5912f952013-07-01 19:10:31 -0700559status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800560 if (DEBUG_TRANSPORT_ACTIONS) {
561 ALOGD("channel '%s' publisher ~ receiveFinishedSignal", mChannel->getName().c_str());
562 }
Jeff Brown5912f952013-07-01 19:10:31 -0700563
564 InputMessage msg;
565 status_t result = mChannel->receiveMessage(&msg);
566 if (result) {
567 *outSeq = 0;
568 *outHandled = false;
569 return result;
570 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700571 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700572 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800573 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700574 return UNKNOWN_ERROR;
575 }
576 *outSeq = msg.body.finished.seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800577 *outHandled = msg.body.finished.handled == 1;
Jeff Brown5912f952013-07-01 19:10:31 -0700578 return OK;
579}
580
581// --- InputConsumer ---
582
583InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
584 mResampleTouch(isTouchResamplingEnabled()),
585 mChannel(channel), mMsgDeferred(false) {
586}
587
588InputConsumer::~InputConsumer() {
589}
590
591bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600592 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700593}
594
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800595status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
596 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800597 if (DEBUG_TRANSPORT_ACTIONS) {
598 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
599 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
600 }
Jeff Brown5912f952013-07-01 19:10:31 -0700601
602 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700603 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700604
605 // Fetch the next input message.
606 // Loop until an event can be returned or no additional events are received.
607 while (!*outEvent) {
608 if (mMsgDeferred) {
609 // mMsg contains a valid input message from the previous call to consume
610 // that has not yet been processed.
611 mMsgDeferred = false;
612 } else {
613 // Receive a fresh message.
614 status_t result = mChannel->receiveMessage(&mMsg);
615 if (result) {
616 // Consume the next batched event unless batches are being held for later.
617 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800618 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700619 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800620 if (DEBUG_TRANSPORT_ACTIONS) {
621 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
622 mChannel->getName().c_str(), *outSeq);
623 }
Jeff Brown5912f952013-07-01 19:10:31 -0700624 break;
625 }
626 }
627 return result;
628 }
629 }
630
631 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700632 case InputMessage::Type::KEY: {
633 KeyEvent* keyEvent = factory->createKeyEvent();
634 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700635
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700636 initializeKeyEvent(keyEvent, &mMsg);
637 *outSeq = mMsg.body.key.seq;
638 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800639 if (DEBUG_TRANSPORT_ACTIONS) {
640 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
641 mChannel->getName().c_str(), *outSeq);
642 }
Jeff Brown5912f952013-07-01 19:10:31 -0700643 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700644 }
Jeff Brown5912f952013-07-01 19:10:31 -0700645
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700646 case InputMessage::Type::MOTION: {
647 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
648 if (batchIndex >= 0) {
649 Batch& batch = mBatches.editItemAt(batchIndex);
650 if (canAddSample(batch, &mMsg)) {
651 batch.samples.push(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800652 if (DEBUG_TRANSPORT_ACTIONS) {
653 ALOGD("channel '%s' consumer ~ appended to batch event",
654 mChannel->getName().c_str());
655 }
Jeff Brown5912f952013-07-01 19:10:31 -0700656 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700657 } else if (isPointerEvent(mMsg.body.motion.source) &&
658 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
659 // No need to process events that we are going to cancel anyways
660 const size_t count = batch.samples.size();
661 for (size_t i = 0; i < count; i++) {
662 const InputMessage& msg = batch.samples.itemAt(i);
663 sendFinishedSignal(msg.body.motion.seq, false);
664 }
665 batch.samples.removeItemsAt(0, count);
666 mBatches.removeAt(batchIndex);
667 } else {
668 // We cannot append to the batch in progress, so we need to consume
669 // the previous batch right now and defer the new message until later.
670 mMsgDeferred = true;
671 status_t result = consumeSamples(factory, batch, batch.samples.size(),
672 outSeq, outEvent);
673 mBatches.removeAt(batchIndex);
674 if (result) {
675 return result;
676 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800677 if (DEBUG_TRANSPORT_ACTIONS) {
678 ALOGD("channel '%s' consumer ~ consumed batch event and "
679 "deferred current event, seq=%u",
680 mChannel->getName().c_str(), *outSeq);
681 }
Jeff Brown5912f952013-07-01 19:10:31 -0700682 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700683 }
Jeff Brown5912f952013-07-01 19:10:31 -0700684 }
Jeff Brown5912f952013-07-01 19:10:31 -0700685
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800686 // Start a new batch if needed.
687 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
688 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
689 mBatches.push();
690 Batch& batch = mBatches.editTop();
691 batch.samples.push(mMsg);
692 if (DEBUG_TRANSPORT_ACTIONS) {
693 ALOGD("channel '%s' consumer ~ started batch event",
694 mChannel->getName().c_str());
695 }
696 break;
697 }
Jeff Brown5912f952013-07-01 19:10:31 -0700698
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800699 MotionEvent* motionEvent = factory->createMotionEvent();
700 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700701
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800702 updateTouchState(mMsg);
703 initializeMotionEvent(motionEvent, &mMsg);
704 *outSeq = mMsg.body.motion.seq;
705 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800706
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800707 if (DEBUG_TRANSPORT_ACTIONS) {
708 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
709 mChannel->getName().c_str(), *outSeq);
710 }
711 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700712 }
Jeff Brown5912f952013-07-01 19:10:31 -0700713
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800714 case InputMessage::Type::FINISHED: {
715 LOG_ALWAYS_FATAL("Consumed a FINISHED message, which should never be seen by "
716 "InputConsumer!");
717 break;
718 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800719
720 case InputMessage::Type::FOCUS: {
721 FocusEvent* focusEvent = factory->createFocusEvent();
722 if (!focusEvent) return NO_MEMORY;
723
724 initializeFocusEvent(focusEvent, &mMsg);
725 *outSeq = mMsg.body.focus.seq;
726 *outEvent = focusEvent;
727 break;
728 }
Jeff Brown5912f952013-07-01 19:10:31 -0700729 }
730 }
731 return OK;
732}
733
734status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800735 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700736 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700737 for (size_t i = mBatches.size(); i > 0; ) {
738 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700739 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700740 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800741 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700742 mBatches.removeAt(i);
743 return result;
744 }
745
Michael Wright32232172013-10-21 12:05:22 -0700746 nsecs_t sampleTime = frameTime;
747 if (mResampleTouch) {
748 sampleTime -= RESAMPLE_LATENCY;
749 }
Jeff Brown5912f952013-07-01 19:10:31 -0700750 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
751 if (split < 0) {
752 continue;
753 }
754
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800755 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700756 const InputMessage* next;
757 if (batch.samples.isEmpty()) {
758 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700759 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700760 } else {
761 next = &batch.samples.itemAt(0);
762 }
Michael Wright32232172013-10-21 12:05:22 -0700763 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700764 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
765 }
766 return result;
767 }
768
769 return WOULD_BLOCK;
770}
771
772status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800773 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700774 MotionEvent* motionEvent = factory->createMotionEvent();
775 if (! motionEvent) return NO_MEMORY;
776
777 uint32_t chain = 0;
778 for (size_t i = 0; i < count; i++) {
779 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100780 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700781 if (i) {
782 SeqChain seqChain;
783 seqChain.seq = msg.body.motion.seq;
784 seqChain.chain = chain;
785 mSeqChains.push(seqChain);
786 addSample(motionEvent, &msg);
787 } else {
788 initializeMotionEvent(motionEvent, &msg);
789 }
790 chain = msg.body.motion.seq;
791 }
792 batch.samples.removeItemsAt(0, count);
793
794 *outSeq = chain;
795 *outEvent = motionEvent;
796 return OK;
797}
798
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100799void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800800 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700801 return;
802 }
803
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100804 int32_t deviceId = msg.body.motion.deviceId;
805 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700806
807 // Update the touch state history to incorporate the new input message.
808 // If the message is in the past relative to the most recently produced resampled
809 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100810 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700811 case AMOTION_EVENT_ACTION_DOWN: {
812 ssize_t index = findTouchState(deviceId, source);
813 if (index < 0) {
814 mTouchStates.push();
815 index = mTouchStates.size() - 1;
816 }
817 TouchState& touchState = mTouchStates.editItemAt(index);
818 touchState.initialize(deviceId, source);
819 touchState.addHistory(msg);
820 break;
821 }
822
823 case AMOTION_EVENT_ACTION_MOVE: {
824 ssize_t index = findTouchState(deviceId, source);
825 if (index >= 0) {
826 TouchState& touchState = mTouchStates.editItemAt(index);
827 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800828 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700829 }
830 break;
831 }
832
833 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
834 ssize_t index = findTouchState(deviceId, source);
835 if (index >= 0) {
836 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100837 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700838 rewriteMessage(touchState, msg);
839 }
840 break;
841 }
842
843 case AMOTION_EVENT_ACTION_POINTER_UP: {
844 ssize_t index = findTouchState(deviceId, source);
845 if (index >= 0) {
846 TouchState& touchState = mTouchStates.editItemAt(index);
847 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100848 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700849 }
850 break;
851 }
852
853 case AMOTION_EVENT_ACTION_SCROLL: {
854 ssize_t index = findTouchState(deviceId, source);
855 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800856 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700857 rewriteMessage(touchState, msg);
858 }
859 break;
860 }
861
862 case AMOTION_EVENT_ACTION_UP:
863 case AMOTION_EVENT_ACTION_CANCEL: {
864 ssize_t index = findTouchState(deviceId, source);
865 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800866 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700867 rewriteMessage(touchState, msg);
868 mTouchStates.removeAt(index);
869 }
870 break;
871 }
872 }
873}
874
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800875/**
876 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
877 *
878 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
879 * is in the past relative to msg and the past two events do not contain identical coordinates),
880 * then invalidate the lastResample data for that pointer.
881 * If the two past events have identical coordinates, then lastResample data for that pointer will
882 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
883 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
884 * not equal to x0 is received.
885 */
886void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100887 nsecs_t eventTime = msg.body.motion.eventTime;
888 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
889 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700890 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100891 if (eventTime < state.lastResample.eventTime ||
892 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800893 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
894 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700895#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100896 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
897 resampleCoords.getX(), resampleCoords.getY(),
898 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700899#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800900 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
901 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
902 } else {
903 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100904 }
Jeff Brown5912f952013-07-01 19:10:31 -0700905 }
906 }
907}
908
909void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
910 const InputMessage* next) {
911 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800912 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700913 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
914 return;
915 }
916
917 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
918 if (index < 0) {
919#if DEBUG_RESAMPLING
920 ALOGD("Not resampled, no touch state for device.");
921#endif
922 return;
923 }
924
925 TouchState& touchState = mTouchStates.editItemAt(index);
926 if (touchState.historySize < 1) {
927#if DEBUG_RESAMPLING
928 ALOGD("Not resampled, no history for device.");
929#endif
930 return;
931 }
932
933 // Ensure that the current sample has all of the pointers that need to be reported.
934 const History* current = touchState.getHistory(0);
935 size_t pointerCount = event->getPointerCount();
936 for (size_t i = 0; i < pointerCount; i++) {
937 uint32_t id = event->getPointerId(i);
938 if (!current->idBits.hasBit(id)) {
939#if DEBUG_RESAMPLING
940 ALOGD("Not resampled, missing id %d", id);
941#endif
942 return;
943 }
944 }
945
946 // Find the data to use for resampling.
947 const History* other;
948 History future;
949 float alpha;
950 if (next) {
951 // Interpolate between current sample and future sample.
952 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100953 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700954 other = &future;
955 nsecs_t delta = future.eventTime - current->eventTime;
956 if (delta < RESAMPLE_MIN_DELTA) {
957#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100958 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700959#endif
960 return;
961 }
962 alpha = float(sampleTime - current->eventTime) / delta;
963 } else if (touchState.historySize >= 2) {
964 // Extrapolate future sample using current sample and past sample.
965 // So other->eventTime <= current->eventTime <= sampleTime.
966 other = touchState.getHistory(1);
967 nsecs_t delta = current->eventTime - other->eventTime;
968 if (delta < RESAMPLE_MIN_DELTA) {
969#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100970 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700971#endif
972 return;
973 } else if (delta > RESAMPLE_MAX_DELTA) {
974#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100975 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700976#endif
977 return;
978 }
979 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
980 if (sampleTime > maxPredict) {
981#if DEBUG_RESAMPLING
982 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100983 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700984 sampleTime - current->eventTime, maxPredict - current->eventTime);
985#endif
986 sampleTime = maxPredict;
987 }
988 alpha = float(current->eventTime - sampleTime) / delta;
989 } else {
990#if DEBUG_RESAMPLING
991 ALOGD("Not resampled, insufficient data.");
992#endif
993 return;
994 }
995
996 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800997 History oldLastResample;
998 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700999 touchState.lastResample.eventTime = sampleTime;
1000 touchState.lastResample.idBits.clear();
1001 for (size_t i = 0; i < pointerCount; i++) {
1002 uint32_t id = event->getPointerId(i);
1003 touchState.lastResample.idToIndex[id] = i;
1004 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001005 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1006 // We maintain the previously resampled value for this pointer (stored in
1007 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1008 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1009
1010 // We know here that the coordinates for the pointer haven't changed because we
1011 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1012 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1013 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1014 continue;
1015 }
1016
Jeff Brown5912f952013-07-01 19:10:31 -07001017 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1018 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001019 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001020 if (other->idBits.hasBit(id)
1021 && shouldResampleTool(event->getToolType(i))) {
1022 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001023 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1024 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1025 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1026 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1027#if DEBUG_RESAMPLING
1028 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1029 "other (%0.3f, %0.3f), alpha %0.3f",
1030 id, resampledCoords.getX(), resampledCoords.getY(),
1031 currentCoords.getX(), currentCoords.getY(),
1032 otherCoords.getX(), otherCoords.getY(),
1033 alpha);
1034#endif
1035 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001036#if DEBUG_RESAMPLING
1037 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1038 id, resampledCoords.getX(), resampledCoords.getY(),
1039 currentCoords.getX(), currentCoords.getY());
1040#endif
1041 }
1042 }
1043
1044 event->addSample(sampleTime, touchState.lastResample.pointers);
1045}
1046
1047bool InputConsumer::shouldResampleTool(int32_t toolType) {
1048 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1049 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1050}
1051
1052status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001053 if (DEBUG_TRANSPORT_ACTIONS) {
1054 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1055 mChannel->getName().c_str(), seq, toString(handled));
1056 }
Jeff Brown5912f952013-07-01 19:10:31 -07001057
1058 if (!seq) {
1059 ALOGE("Attempted to send a finished signal with sequence number 0.");
1060 return BAD_VALUE;
1061 }
1062
1063 // Send finished signals for the batch sequence chain first.
1064 size_t seqChainCount = mSeqChains.size();
1065 if (seqChainCount) {
1066 uint32_t currentSeq = seq;
1067 uint32_t chainSeqs[seqChainCount];
1068 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001069 for (size_t i = seqChainCount; i > 0; ) {
1070 i--;
Jeff Brown5912f952013-07-01 19:10:31 -07001071 const SeqChain& seqChain = mSeqChains.itemAt(i);
1072 if (seqChain.seq == currentSeq) {
1073 currentSeq = seqChain.chain;
1074 chainSeqs[chainIndex++] = currentSeq;
1075 mSeqChains.removeAt(i);
1076 }
1077 }
1078 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001079 while (!status && chainIndex > 0) {
1080 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001081 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1082 }
1083 if (status) {
1084 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001085 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001086 SeqChain seqChain;
1087 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1088 seqChain.chain = chainSeqs[chainIndex];
1089 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001090 if (!chainIndex) break;
1091 chainIndex--;
1092 }
Jeff Brown5912f952013-07-01 19:10:31 -07001093 return status;
1094 }
1095 }
1096
1097 // Send finished signal for the last message in the batch.
1098 return sendUnchainedFinishedSignal(seq, handled);
1099}
1100
1101status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1102 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001103 msg.header.type = InputMessage::Type::FINISHED;
Jeff Brown5912f952013-07-01 19:10:31 -07001104 msg.body.finished.seq = seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -08001105 msg.body.finished.handled = handled ? 1 : 0;
Jeff Brown5912f952013-07-01 19:10:31 -07001106 return mChannel->sendMessage(&msg);
1107}
1108
1109bool InputConsumer::hasDeferredEvent() const {
1110 return mMsgDeferred;
1111}
1112
1113bool InputConsumer::hasPendingBatch() const {
1114 return !mBatches.isEmpty();
1115}
1116
1117ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1118 for (size_t i = 0; i < mBatches.size(); i++) {
1119 const Batch& batch = mBatches.itemAt(i);
1120 const InputMessage& head = batch.samples.itemAt(0);
1121 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1122 return i;
1123 }
1124 }
1125 return -1;
1126}
1127
1128ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1129 for (size_t i = 0; i < mTouchStates.size(); i++) {
1130 const TouchState& touchState = mTouchStates.itemAt(i);
1131 if (touchState.deviceId == deviceId && touchState.source == source) {
1132 return i;
1133 }
1134 }
1135 return -1;
1136}
1137
1138void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
1139 event->initialize(
1140 msg->body.key.deviceId,
1141 msg->body.key.source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001142 msg->body.key.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001143 msg->body.key.action,
1144 msg->body.key.flags,
1145 msg->body.key.keyCode,
1146 msg->body.key.scanCode,
1147 msg->body.key.metaState,
1148 msg->body.key.repeatCount,
1149 msg->body.key.downTime,
1150 msg->body.key.eventTime);
1151}
1152
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001153void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
1154 event->initialize(msg->body.focus.hasFocus == 1, msg->body.focus.inTouchMode == 1);
1155}
1156
Jeff Brown5912f952013-07-01 19:10:31 -07001157void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001158 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001159 PointerProperties pointerProperties[pointerCount];
1160 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001161 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001162 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1163 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1164 }
1165
Garfield Tan00f511d2019-06-12 16:55:40 -07001166 event->initialize(msg->body.motion.deviceId, msg->body.motion.source,
1167 msg->body.motion.displayId, msg->body.motion.action,
1168 msg->body.motion.actionButton, msg->body.motion.flags,
1169 msg->body.motion.edgeFlags, msg->body.motion.metaState,
1170 msg->body.motion.buttonState, msg->body.motion.classification,
1171 msg->body.motion.xOffset, msg->body.motion.yOffset,
1172 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1173 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1174 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1175 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001176}
1177
1178void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001179 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001180 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001181 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001182 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1183 }
1184
1185 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1186 event->addSample(msg->body.motion.eventTime, pointerCoords);
1187}
1188
1189bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1190 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001191 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001192 if (head.body.motion.pointerCount != pointerCount
1193 || head.body.motion.action != msg->body.motion.action) {
1194 return false;
1195 }
1196 for (size_t i = 0; i < pointerCount; i++) {
1197 if (head.body.motion.pointers[i].properties
1198 != msg->body.motion.pointers[i].properties) {
1199 return false;
1200 }
1201 }
1202 return true;
1203}
1204
1205ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1206 size_t numSamples = batch.samples.size();
1207 size_t index = 0;
1208 while (index < numSamples
1209 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1210 index += 1;
1211 }
1212 return ssize_t(index) - 1;
1213}
1214
1215} // namespace android