blob: c6043ac203a1accbf0089c24c38eba03ac5cd2dc [file] [log] [blame]
Jeff Brown5912f952013-07-01 19:10:31 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// Provides a shared memory transport for input events.
5//
6#define LOG_TAG "InputTransport"
7
8//#define LOG_NDEBUG 0
9
10// Log debug messages about channel messages (send message, receive message)
11#define DEBUG_CHANNEL_MESSAGES 0
12
13// Log debug messages whenever InputChannel objects are created/destroyed
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -070014static constexpr bool DEBUG_CHANNEL_LIFECYCLE = false;
Jeff Brown5912f952013-07-01 19:10:31 -070015
16// Log debug messages about transport actions
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080017static constexpr bool DEBUG_TRANSPORT_ACTIONS = false;
Jeff Brown5912f952013-07-01 19:10:31 -070018
19// Log debug messages about touch event resampling
20#define DEBUG_RESAMPLING 0
21
Jeff Brown5912f952013-07-01 19:10:31 -070022#include <errno.h>
23#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070024#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070025#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070026#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070027#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070028#include <unistd.h>
29
Michael Wright3dd60e22019-03-27 22:06:44 +000030#include <android-base/stringprintf.h>
31#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070032#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070033#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000034#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070035
Jeff Brown5912f952013-07-01 19:10:31 -070036#include <input/InputTransport.h>
37
Michael Wright3dd60e22019-03-27 22:06:44 +000038using android::base::StringPrintf;
39
Jeff Brown5912f952013-07-01 19:10:31 -070040namespace android {
41
42// Socket buffer size. The default is typically about 128KB, which is much larger than
43// we really need. So we make it smaller. It just needs to be big enough to hold
44// a few dozen large multi-finger motion events in the case where an application gets
45// behind processing touches.
46static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
47
48// Nanoseconds per milliseconds.
49static const nsecs_t NANOS_PER_MS = 1000000;
50
51// Latency added during resampling. A few milliseconds doesn't hurt much but
52// reduces the impact of mispredicted touch positions.
53static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
54
55// Minimum time difference between consecutive samples before attempting to resample.
56static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
57
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070058// Maximum time difference between consecutive samples before attempting to resample
59// by extrapolation.
60static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
61
Jeff Brown5912f952013-07-01 19:10:31 -070062// Maximum time to predict forward from the last known state, to avoid predicting too
63// far into the future. This time is further bounded by 50% of the last time delta.
64static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
65
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -060066/**
67 * System property for enabling / disabling touch resampling.
68 * Resampling extrapolates / interpolates the reported touch event coordinates to better
69 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
70 * Resampling is not needed (and should be disabled) on hardware that already
71 * has touch events triggered by VSYNC.
72 * Set to "1" to enable resampling (default).
73 * Set to "0" to disable resampling.
74 * Resampling is enabled by default.
75 */
76static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
77
Jeff Brown5912f952013-07-01 19:10:31 -070078template<typename T>
79inline static T min(const T& a, const T& b) {
80 return a < b ? a : b;
81}
82
83inline static float lerp(float a, float b, float alpha) {
84 return a + alpha * (b - a);
85}
86
Siarhei Vishniakou128eab12019-05-23 10:25:59 +080087inline static bool isPointerEvent(int32_t source) {
88 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
89}
90
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080091inline static const char* toString(bool value) {
92 return value ? "true" : "false";
93}
94
Jeff Brown5912f952013-07-01 19:10:31 -070095// --- InputMessage ---
96
97bool InputMessage::isValid(size_t actualSize) const {
98 if (size() == actualSize) {
99 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700100 case Type::KEY:
101 return true;
102 case Type::MOTION:
103 return body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
104 case Type::FINISHED:
105 return true;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800106 case Type::FOCUS:
107 return true;
Jeff Brown5912f952013-07-01 19:10:31 -0700108 }
109 }
110 return false;
111}
112
113size_t InputMessage::size() const {
114 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700115 case Type::KEY:
116 return sizeof(Header) + body.key.size();
117 case Type::MOTION:
118 return sizeof(Header) + body.motion.size();
119 case Type::FINISHED:
120 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800121 case Type::FOCUS:
122 return sizeof(Header) + body.focus.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700123 }
124 return sizeof(Header);
125}
126
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800127/**
128 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
129 * memory to zero, then only copy the valid bytes on a per-field basis.
130 */
131void InputMessage::getSanitizedCopy(InputMessage* msg) const {
132 memset(msg, 0, sizeof(*msg));
133
134 // Write the header
135 msg->header.type = header.type;
136
137 // Write the body
138 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700139 case InputMessage::Type::KEY: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800140 // uint32_t seq
141 msg->body.key.seq = body.key.seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800142 // int32_t eventId
143 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800144 // nsecs_t eventTime
145 msg->body.key.eventTime = body.key.eventTime;
146 // int32_t deviceId
147 msg->body.key.deviceId = body.key.deviceId;
148 // int32_t source
149 msg->body.key.source = body.key.source;
150 // int32_t displayId
151 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600152 // std::array<uint8_t, 32> hmac
153 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800154 // int32_t action
155 msg->body.key.action = body.key.action;
156 // int32_t flags
157 msg->body.key.flags = body.key.flags;
158 // int32_t keyCode
159 msg->body.key.keyCode = body.key.keyCode;
160 // int32_t scanCode
161 msg->body.key.scanCode = body.key.scanCode;
162 // int32_t metaState
163 msg->body.key.metaState = body.key.metaState;
164 // int32_t repeatCount
165 msg->body.key.repeatCount = body.key.repeatCount;
166 // nsecs_t downTime
167 msg->body.key.downTime = body.key.downTime;
168 break;
169 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700170 case InputMessage::Type::MOTION: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800171 // uint32_t seq
172 msg->body.motion.seq = body.motion.seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800173 // int32_t eventId
174 msg->body.motion.eventId = body.motion.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800175 // nsecs_t eventTime
176 msg->body.motion.eventTime = body.motion.eventTime;
177 // int32_t deviceId
178 msg->body.motion.deviceId = body.motion.deviceId;
179 // int32_t source
180 msg->body.motion.source = body.motion.source;
181 // int32_t displayId
182 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600183 // std::array<uint8_t, 32> hmac
184 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800185 // int32_t action
186 msg->body.motion.action = body.motion.action;
187 // int32_t actionButton
188 msg->body.motion.actionButton = body.motion.actionButton;
189 // int32_t flags
190 msg->body.motion.flags = body.motion.flags;
191 // int32_t metaState
192 msg->body.motion.metaState = body.motion.metaState;
193 // int32_t buttonState
194 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800195 // MotionClassification classification
196 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800197 // int32_t edgeFlags
198 msg->body.motion.edgeFlags = body.motion.edgeFlags;
199 // nsecs_t downTime
200 msg->body.motion.downTime = body.motion.downTime;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600201 // float xScale
202 msg->body.motion.xScale = body.motion.xScale;
203 // float yScale
204 msg->body.motion.yScale = body.motion.yScale;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800205 // float xOffset
206 msg->body.motion.xOffset = body.motion.xOffset;
207 // float yOffset
208 msg->body.motion.yOffset = body.motion.yOffset;
209 // float xPrecision
210 msg->body.motion.xPrecision = body.motion.xPrecision;
211 // float yPrecision
212 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700213 // float xCursorPosition
214 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
215 // float yCursorPosition
216 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800217 // uint32_t pointerCount
218 msg->body.motion.pointerCount = body.motion.pointerCount;
219 //struct Pointer pointers[MAX_POINTERS]
220 for (size_t i = 0; i < body.motion.pointerCount; i++) {
221 // PointerProperties properties
222 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
223 msg->body.motion.pointers[i].properties.toolType =
224 body.motion.pointers[i].properties.toolType,
225 // PointerCoords coords
226 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
227 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
228 memcpy(&msg->body.motion.pointers[i].coords.values[0],
229 &body.motion.pointers[i].coords.values[0],
230 count * (sizeof(body.motion.pointers[i].coords.values[0])));
231 }
232 break;
233 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700234 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800235 msg->body.finished.seq = body.finished.seq;
236 msg->body.finished.handled = body.finished.handled;
237 break;
238 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800239 case InputMessage::Type::FOCUS: {
240 msg->body.focus.seq = body.focus.seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800241 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800242 msg->body.focus.hasFocus = body.focus.hasFocus;
243 msg->body.focus.inTouchMode = body.focus.inTouchMode;
244 break;
245 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800246 }
247}
Jeff Brown5912f952013-07-01 19:10:31 -0700248
Chris Ye0783e992020-06-02 21:34:49 -0700249// --- InputChannelInfo ---
250
251status_t InputChannelInfo::writeToParcel(android::Parcel* parcel) const {
252 if (parcel == nullptr) {
253 ALOGE("%s: Null parcel", __func__);
254 return BAD_VALUE;
255 }
256 status_t status = parcel->writeStrongBinder(mToken)
257 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
258 return status;
259}
260
261status_t InputChannelInfo::readFromParcel(const android::Parcel* parcel) {
262 if (parcel == nullptr) {
263 ALOGE("%s: Null parcel", __func__);
264 return BAD_VALUE;
265 }
266 mToken = parcel->readStrongBinder();
267 status_t status = parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
268 return status;
269}
270
Jeff Brown5912f952013-07-01 19:10:31 -0700271// --- InputChannel ---
272
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700273sp<InputChannel> InputChannel::create(const std::string& name, android::base::unique_fd fd,
274 sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700275 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
276 if (result != 0) {
277 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
278 strerror(errno));
279 return nullptr;
280 }
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700281 return new InputChannel(name, std::move(fd), token);
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700282}
283
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700284InputChannel::InputChannel(const std::string& name, android::base::unique_fd fd, sp<IBinder> token)
Chris Ye0783e992020-06-02 21:34:49 -0700285 : mInfo(name, std::move(fd), token) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700286 if (DEBUG_CHANNEL_LIFECYCLE) {
Chris Ye0783e992020-06-02 21:34:49 -0700287 ALOGD("Input channel constructed: name='%s', fd=%d", mInfo.mName.c_str(), mInfo.mFd.get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700288 }
Jeff Brown5912f952013-07-01 19:10:31 -0700289}
290
Chris Ye0783e992020-06-02 21:34:49 -0700291InputChannel::InputChannel() {}
292
Jeff Brown5912f952013-07-01 19:10:31 -0700293InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700294 if (DEBUG_CHANNEL_LIFECYCLE) {
Chris Ye0783e992020-06-02 21:34:49 -0700295 ALOGD("Input channel destroyed: name='%s', fd=%d", getName().c_str(), getFd());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700296 }
Robert Carr3720ed02018-08-08 16:08:27 -0700297}
298
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800299status_t InputChannel::openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700300 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
301 int sockets[2];
302 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
303 status_t result = -errno;
304 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800305 name.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700306 outServerChannel.clear();
307 outClientChannel.clear();
308 return result;
309 }
310
311 int bufferSize = SOCKET_BUFFER_SIZE;
312 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
313 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
314 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
315 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
316
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700317 sp<IBinder> token = new BBinder();
318
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700319 std::string serverChannelName = name + " (server)";
320 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700321 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700322
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700323 std::string clientChannelName = name + " (client)";
324 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700325 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700326 return OK;
327}
328
329status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800330 const size_t msgLength = msg->size();
331 InputMessage cleanMsg;
332 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700333 ssize_t nWrite;
334 do {
Chris Ye0783e992020-06-02 21:34:49 -0700335 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700336 } while (nWrite == -1 && errno == EINTR);
337
338 if (nWrite < 0) {
339 int error = errno;
340#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800341 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
342 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700343#endif
344 if (error == EAGAIN || error == EWOULDBLOCK) {
345 return WOULD_BLOCK;
346 }
347 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
348 return DEAD_OBJECT;
349 }
350 return -error;
351 }
352
353 if (size_t(nWrite) != msgLength) {
354#if DEBUG_CHANNEL_MESSAGES
355 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800356 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700357#endif
358 return DEAD_OBJECT;
359 }
360
361#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800362 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700363#endif
364 return OK;
365}
366
367status_t InputChannel::receiveMessage(InputMessage* msg) {
368 ssize_t nRead;
369 do {
Chris Ye0783e992020-06-02 21:34:49 -0700370 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700371 } while (nRead == -1 && errno == EINTR);
372
373 if (nRead < 0) {
374 int error = errno;
375#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800376 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700377#endif
378 if (error == EAGAIN || error == EWOULDBLOCK) {
379 return WOULD_BLOCK;
380 }
381 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
382 return DEAD_OBJECT;
383 }
384 return -error;
385 }
386
387 if (nRead == 0) { // check for EOF
388#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800389 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700390#endif
391 return DEAD_OBJECT;
392 }
393
394 if (!msg->isValid(nRead)) {
395#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800396 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700397#endif
398 return BAD_VALUE;
399 }
400
401#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800402 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700403#endif
404 return OK;
405}
406
407sp<InputChannel> InputChannel::dup() const {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700408 android::base::unique_fd newFd(::dup(getFd()));
409 if (!newFd.ok()) {
Chris Ye0783e992020-06-02 21:34:49 -0700410 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd(), getName().c_str(),
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700411 strerror(errno));
Siarhei Vishniakou3d8df0e2019-09-17 14:53:07 +0100412 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
413 // If this process is out of file descriptors, then throwing that might end up exploding
414 // on the other side of a binder call, which isn't really helpful.
415 // Better to just crash here and hope that the FD leak is slow.
416 // Other failures could be client errors, so we still propagate those back to the caller.
417 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
418 getName().c_str());
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700419 return nullptr;
420 }
Chris Ye0783e992020-06-02 21:34:49 -0700421 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700422}
423
Chris Ye0783e992020-06-02 21:34:49 -0700424status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
425 return mInfo.writeToParcel(parcel);
Robert Carr3720ed02018-08-08 16:08:27 -0700426}
427
Chris Ye0783e992020-06-02 21:34:49 -0700428status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
429 return mInfo.readFromParcel(parcel);
Robert Carr3720ed02018-08-08 16:08:27 -0700430}
431
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700432sp<IBinder> InputChannel::getConnectionToken() const {
Chris Ye0783e992020-06-02 21:34:49 -0700433 return mInfo.mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700434}
435
Jeff Brown5912f952013-07-01 19:10:31 -0700436// --- InputPublisher ---
437
438InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
439 mChannel(channel) {
440}
441
442InputPublisher::~InputPublisher() {
443}
444
Garfield Tan1c7bc862020-01-28 13:24:04 -0800445status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
446 int32_t source, int32_t displayId,
447 std::array<uint8_t, 32> hmac, int32_t action,
448 int32_t flags, int32_t keyCode, int32_t scanCode,
449 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
450 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000451 if (ATRACE_ENABLED()) {
452 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
453 mChannel->getName().c_str(), keyCode);
454 ATRACE_NAME(message.c_str());
455 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800456 if (DEBUG_TRANSPORT_ACTIONS) {
457 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
458 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
459 "downTime=%" PRId64 ", eventTime=%" PRId64,
460 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
461 metaState, repeatCount, downTime, eventTime);
462 }
Jeff Brown5912f952013-07-01 19:10:31 -0700463
464 if (!seq) {
465 ALOGE("Attempted to publish a key event with sequence number 0.");
466 return BAD_VALUE;
467 }
468
469 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700470 msg.header.type = InputMessage::Type::KEY;
Jeff Brown5912f952013-07-01 19:10:31 -0700471 msg.body.key.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800472 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700473 msg.body.key.deviceId = deviceId;
474 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100475 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700476 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700477 msg.body.key.action = action;
478 msg.body.key.flags = flags;
479 msg.body.key.keyCode = keyCode;
480 msg.body.key.scanCode = scanCode;
481 msg.body.key.metaState = metaState;
482 msg.body.key.repeatCount = repeatCount;
483 msg.body.key.downTime = downTime;
484 msg.body.key.eventTime = eventTime;
485 return mChannel->sendMessage(&msg);
486}
487
488status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800489 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600490 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
491 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
492 MotionClassification classification, float xScale, float yScale, float xOffset,
493 float yOffset, float xPrecision, float yPrecision, float xCursorPosition,
494 float yCursorPosition, nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
Garfield Tan00f511d2019-06-12 16:55:40 -0700495 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000496 if (ATRACE_ENABLED()) {
497 std::string message = StringPrintf(
498 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
499 mChannel->getName().c_str(), action);
500 ATRACE_NAME(message.c_str());
501 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800502 if (DEBUG_TRANSPORT_ACTIONS) {
503 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
504 "displayId=%" PRId32 ", "
505 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600506 "metaState=0x%x, buttonState=0x%x, classification=%s, xScale=%.1f, yScale=%.1f, "
507 "xOffset=%.1f, yOffset=%.1f, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800508 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
509 "pointerCount=%" PRIu32,
510 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
511 flags, edgeFlags, metaState, buttonState,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600512 motionClassificationToString(classification), xScale, yScale, xOffset, yOffset,
513 xPrecision, yPrecision, downTime, eventTime, pointerCount);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800514 }
Jeff Brown5912f952013-07-01 19:10:31 -0700515
516 if (!seq) {
517 ALOGE("Attempted to publish a motion event with sequence number 0.");
518 return BAD_VALUE;
519 }
520
521 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700522 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800523 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700524 return BAD_VALUE;
525 }
526
527 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700528 msg.header.type = InputMessage::Type::MOTION;
Jeff Brown5912f952013-07-01 19:10:31 -0700529 msg.body.motion.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800530 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700531 msg.body.motion.deviceId = deviceId;
532 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700533 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700534 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700535 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100536 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700537 msg.body.motion.flags = flags;
538 msg.body.motion.edgeFlags = edgeFlags;
539 msg.body.motion.metaState = metaState;
540 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800541 msg.body.motion.classification = classification;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600542 msg.body.motion.xScale = xScale;
543 msg.body.motion.yScale = yScale;
Jeff Brown5912f952013-07-01 19:10:31 -0700544 msg.body.motion.xOffset = xOffset;
545 msg.body.motion.yOffset = yOffset;
546 msg.body.motion.xPrecision = xPrecision;
547 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700548 msg.body.motion.xCursorPosition = xCursorPosition;
549 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700550 msg.body.motion.downTime = downTime;
551 msg.body.motion.eventTime = eventTime;
552 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100553 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700554 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
555 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
556 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700557
Jeff Brown5912f952013-07-01 19:10:31 -0700558 return mChannel->sendMessage(&msg);
559}
560
Garfield Tan1c7bc862020-01-28 13:24:04 -0800561status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
562 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800563 if (ATRACE_ENABLED()) {
564 std::string message =
565 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
566 mChannel->getName().c_str(), toString(hasFocus),
567 toString(inTouchMode));
568 ATRACE_NAME(message.c_str());
569 }
570
571 InputMessage msg;
572 msg.header.type = InputMessage::Type::FOCUS;
573 msg.body.focus.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800574 msg.body.focus.eventId = eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800575 msg.body.focus.hasFocus = hasFocus ? 1 : 0;
576 msg.body.focus.inTouchMode = inTouchMode ? 1 : 0;
577 return mChannel->sendMessage(&msg);
578}
579
Jeff Brown5912f952013-07-01 19:10:31 -0700580status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800581 if (DEBUG_TRANSPORT_ACTIONS) {
582 ALOGD("channel '%s' publisher ~ receiveFinishedSignal", mChannel->getName().c_str());
583 }
Jeff Brown5912f952013-07-01 19:10:31 -0700584
585 InputMessage msg;
586 status_t result = mChannel->receiveMessage(&msg);
587 if (result) {
588 *outSeq = 0;
589 *outHandled = false;
590 return result;
591 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700592 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700593 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800594 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700595 return UNKNOWN_ERROR;
596 }
597 *outSeq = msg.body.finished.seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800598 *outHandled = msg.body.finished.handled == 1;
Jeff Brown5912f952013-07-01 19:10:31 -0700599 return OK;
600}
601
602// --- InputConsumer ---
603
604InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
605 mResampleTouch(isTouchResamplingEnabled()),
606 mChannel(channel), mMsgDeferred(false) {
607}
608
609InputConsumer::~InputConsumer() {
610}
611
612bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600613 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700614}
615
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800616status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
617 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800618 if (DEBUG_TRANSPORT_ACTIONS) {
619 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
620 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
621 }
Jeff Brown5912f952013-07-01 19:10:31 -0700622
623 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700624 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700625
626 // Fetch the next input message.
627 // Loop until an event can be returned or no additional events are received.
628 while (!*outEvent) {
629 if (mMsgDeferred) {
630 // mMsg contains a valid input message from the previous call to consume
631 // that has not yet been processed.
632 mMsgDeferred = false;
633 } else {
634 // Receive a fresh message.
635 status_t result = mChannel->receiveMessage(&mMsg);
636 if (result) {
637 // Consume the next batched event unless batches are being held for later.
638 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800639 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700640 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800641 if (DEBUG_TRANSPORT_ACTIONS) {
642 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
643 mChannel->getName().c_str(), *outSeq);
644 }
Jeff Brown5912f952013-07-01 19:10:31 -0700645 break;
646 }
647 }
648 return result;
649 }
650 }
651
652 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700653 case InputMessage::Type::KEY: {
654 KeyEvent* keyEvent = factory->createKeyEvent();
655 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700656
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700657 initializeKeyEvent(keyEvent, &mMsg);
658 *outSeq = mMsg.body.key.seq;
659 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800660 if (DEBUG_TRANSPORT_ACTIONS) {
661 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
662 mChannel->getName().c_str(), *outSeq);
663 }
Jeff Brown5912f952013-07-01 19:10:31 -0700664 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700665 }
Jeff Brown5912f952013-07-01 19:10:31 -0700666
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700667 case InputMessage::Type::MOTION: {
668 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
669 if (batchIndex >= 0) {
670 Batch& batch = mBatches.editItemAt(batchIndex);
671 if (canAddSample(batch, &mMsg)) {
672 batch.samples.push(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800673 if (DEBUG_TRANSPORT_ACTIONS) {
674 ALOGD("channel '%s' consumer ~ appended to batch event",
675 mChannel->getName().c_str());
676 }
Jeff Brown5912f952013-07-01 19:10:31 -0700677 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700678 } else if (isPointerEvent(mMsg.body.motion.source) &&
679 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
680 // No need to process events that we are going to cancel anyways
681 const size_t count = batch.samples.size();
682 for (size_t i = 0; i < count; i++) {
683 const InputMessage& msg = batch.samples.itemAt(i);
684 sendFinishedSignal(msg.body.motion.seq, false);
685 }
686 batch.samples.removeItemsAt(0, count);
687 mBatches.removeAt(batchIndex);
688 } else {
689 // We cannot append to the batch in progress, so we need to consume
690 // the previous batch right now and defer the new message until later.
691 mMsgDeferred = true;
692 status_t result = consumeSamples(factory, batch, batch.samples.size(),
693 outSeq, outEvent);
694 mBatches.removeAt(batchIndex);
695 if (result) {
696 return result;
697 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800698 if (DEBUG_TRANSPORT_ACTIONS) {
699 ALOGD("channel '%s' consumer ~ consumed batch event and "
700 "deferred current event, seq=%u",
701 mChannel->getName().c_str(), *outSeq);
702 }
Jeff Brown5912f952013-07-01 19:10:31 -0700703 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700704 }
Jeff Brown5912f952013-07-01 19:10:31 -0700705 }
Jeff Brown5912f952013-07-01 19:10:31 -0700706
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800707 // Start a new batch if needed.
708 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
709 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
710 mBatches.push();
711 Batch& batch = mBatches.editTop();
712 batch.samples.push(mMsg);
713 if (DEBUG_TRANSPORT_ACTIONS) {
714 ALOGD("channel '%s' consumer ~ started batch event",
715 mChannel->getName().c_str());
716 }
717 break;
718 }
Jeff Brown5912f952013-07-01 19:10:31 -0700719
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800720 MotionEvent* motionEvent = factory->createMotionEvent();
721 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700722
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800723 updateTouchState(mMsg);
724 initializeMotionEvent(motionEvent, &mMsg);
725 *outSeq = mMsg.body.motion.seq;
726 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800727
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800728 if (DEBUG_TRANSPORT_ACTIONS) {
729 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
730 mChannel->getName().c_str(), *outSeq);
731 }
732 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700733 }
Jeff Brown5912f952013-07-01 19:10:31 -0700734
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800735 case InputMessage::Type::FINISHED: {
736 LOG_ALWAYS_FATAL("Consumed a FINISHED message, which should never be seen by "
737 "InputConsumer!");
738 break;
739 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800740
741 case InputMessage::Type::FOCUS: {
742 FocusEvent* focusEvent = factory->createFocusEvent();
743 if (!focusEvent) return NO_MEMORY;
744
745 initializeFocusEvent(focusEvent, &mMsg);
746 *outSeq = mMsg.body.focus.seq;
747 *outEvent = focusEvent;
748 break;
749 }
Jeff Brown5912f952013-07-01 19:10:31 -0700750 }
751 }
752 return OK;
753}
754
755status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800756 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700757 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700758 for (size_t i = mBatches.size(); i > 0; ) {
759 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700760 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700761 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800762 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700763 mBatches.removeAt(i);
764 return result;
765 }
766
Michael Wright32232172013-10-21 12:05:22 -0700767 nsecs_t sampleTime = frameTime;
768 if (mResampleTouch) {
769 sampleTime -= RESAMPLE_LATENCY;
770 }
Jeff Brown5912f952013-07-01 19:10:31 -0700771 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
772 if (split < 0) {
773 continue;
774 }
775
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800776 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700777 const InputMessage* next;
778 if (batch.samples.isEmpty()) {
779 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700780 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700781 } else {
782 next = &batch.samples.itemAt(0);
783 }
Michael Wright32232172013-10-21 12:05:22 -0700784 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700785 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
786 }
787 return result;
788 }
789
790 return WOULD_BLOCK;
791}
792
793status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800794 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700795 MotionEvent* motionEvent = factory->createMotionEvent();
796 if (! motionEvent) return NO_MEMORY;
797
798 uint32_t chain = 0;
799 for (size_t i = 0; i < count; i++) {
800 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100801 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700802 if (i) {
803 SeqChain seqChain;
804 seqChain.seq = msg.body.motion.seq;
805 seqChain.chain = chain;
806 mSeqChains.push(seqChain);
807 addSample(motionEvent, &msg);
808 } else {
809 initializeMotionEvent(motionEvent, &msg);
810 }
811 chain = msg.body.motion.seq;
812 }
813 batch.samples.removeItemsAt(0, count);
814
815 *outSeq = chain;
816 *outEvent = motionEvent;
817 return OK;
818}
819
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100820void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800821 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700822 return;
823 }
824
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100825 int32_t deviceId = msg.body.motion.deviceId;
826 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700827
828 // Update the touch state history to incorporate the new input message.
829 // If the message is in the past relative to the most recently produced resampled
830 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100831 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700832 case AMOTION_EVENT_ACTION_DOWN: {
833 ssize_t index = findTouchState(deviceId, source);
834 if (index < 0) {
835 mTouchStates.push();
836 index = mTouchStates.size() - 1;
837 }
838 TouchState& touchState = mTouchStates.editItemAt(index);
839 touchState.initialize(deviceId, source);
840 touchState.addHistory(msg);
841 break;
842 }
843
844 case AMOTION_EVENT_ACTION_MOVE: {
845 ssize_t index = findTouchState(deviceId, source);
846 if (index >= 0) {
847 TouchState& touchState = mTouchStates.editItemAt(index);
848 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800849 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700850 }
851 break;
852 }
853
854 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
855 ssize_t index = findTouchState(deviceId, source);
856 if (index >= 0) {
857 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100858 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700859 rewriteMessage(touchState, msg);
860 }
861 break;
862 }
863
864 case AMOTION_EVENT_ACTION_POINTER_UP: {
865 ssize_t index = findTouchState(deviceId, source);
866 if (index >= 0) {
867 TouchState& touchState = mTouchStates.editItemAt(index);
868 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100869 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700870 }
871 break;
872 }
873
874 case AMOTION_EVENT_ACTION_SCROLL: {
875 ssize_t index = findTouchState(deviceId, source);
876 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800877 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700878 rewriteMessage(touchState, msg);
879 }
880 break;
881 }
882
883 case AMOTION_EVENT_ACTION_UP:
884 case AMOTION_EVENT_ACTION_CANCEL: {
885 ssize_t index = findTouchState(deviceId, source);
886 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800887 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700888 rewriteMessage(touchState, msg);
889 mTouchStates.removeAt(index);
890 }
891 break;
892 }
893 }
894}
895
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800896/**
897 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
898 *
899 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
900 * is in the past relative to msg and the past two events do not contain identical coordinates),
901 * then invalidate the lastResample data for that pointer.
902 * If the two past events have identical coordinates, then lastResample data for that pointer will
903 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
904 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
905 * not equal to x0 is received.
906 */
907void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100908 nsecs_t eventTime = msg.body.motion.eventTime;
909 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
910 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700911 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100912 if (eventTime < state.lastResample.eventTime ||
913 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800914 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
915 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700916#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100917 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
918 resampleCoords.getX(), resampleCoords.getY(),
919 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700920#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800921 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
922 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
923 } else {
924 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100925 }
Jeff Brown5912f952013-07-01 19:10:31 -0700926 }
927 }
928}
929
930void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
931 const InputMessage* next) {
932 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800933 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700934 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
935 return;
936 }
937
938 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
939 if (index < 0) {
940#if DEBUG_RESAMPLING
941 ALOGD("Not resampled, no touch state for device.");
942#endif
943 return;
944 }
945
946 TouchState& touchState = mTouchStates.editItemAt(index);
947 if (touchState.historySize < 1) {
948#if DEBUG_RESAMPLING
949 ALOGD("Not resampled, no history for device.");
950#endif
951 return;
952 }
953
954 // Ensure that the current sample has all of the pointers that need to be reported.
955 const History* current = touchState.getHistory(0);
956 size_t pointerCount = event->getPointerCount();
957 for (size_t i = 0; i < pointerCount; i++) {
958 uint32_t id = event->getPointerId(i);
959 if (!current->idBits.hasBit(id)) {
960#if DEBUG_RESAMPLING
961 ALOGD("Not resampled, missing id %d", id);
962#endif
963 return;
964 }
965 }
966
967 // Find the data to use for resampling.
968 const History* other;
969 History future;
970 float alpha;
971 if (next) {
972 // Interpolate between current sample and future sample.
973 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100974 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700975 other = &future;
976 nsecs_t delta = future.eventTime - current->eventTime;
977 if (delta < RESAMPLE_MIN_DELTA) {
978#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100979 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700980#endif
981 return;
982 }
983 alpha = float(sampleTime - current->eventTime) / delta;
984 } else if (touchState.historySize >= 2) {
985 // Extrapolate future sample using current sample and past sample.
986 // So other->eventTime <= current->eventTime <= sampleTime.
987 other = touchState.getHistory(1);
988 nsecs_t delta = current->eventTime - other->eventTime;
989 if (delta < RESAMPLE_MIN_DELTA) {
990#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100991 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700992#endif
993 return;
994 } else if (delta > RESAMPLE_MAX_DELTA) {
995#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100996 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700997#endif
998 return;
999 }
1000 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1001 if (sampleTime > maxPredict) {
1002#if DEBUG_RESAMPLING
1003 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001004 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001005 sampleTime - current->eventTime, maxPredict - current->eventTime);
1006#endif
1007 sampleTime = maxPredict;
1008 }
1009 alpha = float(current->eventTime - sampleTime) / delta;
1010 } else {
1011#if DEBUG_RESAMPLING
1012 ALOGD("Not resampled, insufficient data.");
1013#endif
1014 return;
1015 }
1016
1017 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001018 History oldLastResample;
1019 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001020 touchState.lastResample.eventTime = sampleTime;
1021 touchState.lastResample.idBits.clear();
1022 for (size_t i = 0; i < pointerCount; i++) {
1023 uint32_t id = event->getPointerId(i);
1024 touchState.lastResample.idToIndex[id] = i;
1025 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001026 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1027 // We maintain the previously resampled value for this pointer (stored in
1028 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1029 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1030
1031 // We know here that the coordinates for the pointer haven't changed because we
1032 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1033 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1034 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1035 continue;
1036 }
1037
Jeff Brown5912f952013-07-01 19:10:31 -07001038 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1039 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001040 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001041 if (other->idBits.hasBit(id)
1042 && shouldResampleTool(event->getToolType(i))) {
1043 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001044 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1045 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1046 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1047 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1048#if DEBUG_RESAMPLING
1049 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1050 "other (%0.3f, %0.3f), alpha %0.3f",
1051 id, resampledCoords.getX(), resampledCoords.getY(),
1052 currentCoords.getX(), currentCoords.getY(),
1053 otherCoords.getX(), otherCoords.getY(),
1054 alpha);
1055#endif
1056 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001057#if DEBUG_RESAMPLING
1058 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1059 id, resampledCoords.getX(), resampledCoords.getY(),
1060 currentCoords.getX(), currentCoords.getY());
1061#endif
1062 }
1063 }
1064
1065 event->addSample(sampleTime, touchState.lastResample.pointers);
1066}
1067
1068bool InputConsumer::shouldResampleTool(int32_t toolType) {
1069 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1070 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1071}
1072
1073status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001074 if (DEBUG_TRANSPORT_ACTIONS) {
1075 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1076 mChannel->getName().c_str(), seq, toString(handled));
1077 }
Jeff Brown5912f952013-07-01 19:10:31 -07001078
1079 if (!seq) {
1080 ALOGE("Attempted to send a finished signal with sequence number 0.");
1081 return BAD_VALUE;
1082 }
1083
1084 // Send finished signals for the batch sequence chain first.
1085 size_t seqChainCount = mSeqChains.size();
1086 if (seqChainCount) {
1087 uint32_t currentSeq = seq;
1088 uint32_t chainSeqs[seqChainCount];
1089 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001090 for (size_t i = seqChainCount; i > 0; ) {
1091 i--;
Jeff Brown5912f952013-07-01 19:10:31 -07001092 const SeqChain& seqChain = mSeqChains.itemAt(i);
1093 if (seqChain.seq == currentSeq) {
1094 currentSeq = seqChain.chain;
1095 chainSeqs[chainIndex++] = currentSeq;
1096 mSeqChains.removeAt(i);
1097 }
1098 }
1099 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001100 while (!status && chainIndex > 0) {
1101 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001102 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1103 }
1104 if (status) {
1105 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001106 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001107 SeqChain seqChain;
1108 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1109 seqChain.chain = chainSeqs[chainIndex];
1110 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001111 if (!chainIndex) break;
1112 chainIndex--;
1113 }
Jeff Brown5912f952013-07-01 19:10:31 -07001114 return status;
1115 }
1116 }
1117
1118 // Send finished signal for the last message in the batch.
1119 return sendUnchainedFinishedSignal(seq, handled);
1120}
1121
1122status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1123 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001124 msg.header.type = InputMessage::Type::FINISHED;
Jeff Brown5912f952013-07-01 19:10:31 -07001125 msg.body.finished.seq = seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -08001126 msg.body.finished.handled = handled ? 1 : 0;
Jeff Brown5912f952013-07-01 19:10:31 -07001127 return mChannel->sendMessage(&msg);
1128}
1129
1130bool InputConsumer::hasDeferredEvent() const {
1131 return mMsgDeferred;
1132}
1133
1134bool InputConsumer::hasPendingBatch() const {
1135 return !mBatches.isEmpty();
1136}
1137
Arthur Hungc7812be2020-02-27 22:40:27 +08001138int32_t InputConsumer::getPendingBatchSource() const {
1139 if (mBatches.isEmpty()) {
1140 return AINPUT_SOURCE_CLASS_NONE;
1141 }
1142
1143 const Batch& batch = mBatches.itemAt(0);
1144 const InputMessage& head = batch.samples.itemAt(0);
1145 return head.body.motion.source;
1146}
1147
Jeff Brown5912f952013-07-01 19:10:31 -07001148ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1149 for (size_t i = 0; i < mBatches.size(); i++) {
1150 const Batch& batch = mBatches.itemAt(i);
1151 const InputMessage& head = batch.samples.itemAt(0);
1152 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1153 return i;
1154 }
1155 }
1156 return -1;
1157}
1158
1159ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1160 for (size_t i = 0; i < mTouchStates.size(); i++) {
1161 const TouchState& touchState = mTouchStates.itemAt(i);
1162 if (touchState.deviceId == deviceId && touchState.source == source) {
1163 return i;
1164 }
1165 }
1166 return -1;
1167}
1168
1169void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001170 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001171 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1172 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1173 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1174 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001175}
1176
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001177void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001178 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus == 1,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001179 msg->body.focus.inTouchMode == 1);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001180}
1181
Jeff Brown5912f952013-07-01 19:10:31 -07001182void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001183 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001184 PointerProperties pointerProperties[pointerCount];
1185 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001186 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001187 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1188 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1189 }
1190
Garfield Tan1c7bc862020-01-28 13:24:04 -08001191 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1192 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1193 msg->body.motion.actionButton, msg->body.motion.flags,
1194 msg->body.motion.edgeFlags, msg->body.motion.metaState,
1195 msg->body.motion.buttonState, msg->body.motion.classification,
1196 msg->body.motion.xScale, msg->body.motion.yScale, msg->body.motion.xOffset,
1197 msg->body.motion.yOffset, msg->body.motion.xPrecision,
1198 msg->body.motion.yPrecision, msg->body.motion.xCursorPosition,
1199 msg->body.motion.yCursorPosition, msg->body.motion.downTime,
1200 msg->body.motion.eventTime, pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001201}
1202
1203void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001204 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001205 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001206 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001207 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1208 }
1209
1210 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1211 event->addSample(msg->body.motion.eventTime, pointerCoords);
1212}
1213
1214bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1215 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001216 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001217 if (head.body.motion.pointerCount != pointerCount
1218 || head.body.motion.action != msg->body.motion.action) {
1219 return false;
1220 }
1221 for (size_t i = 0; i < pointerCount; i++) {
1222 if (head.body.motion.pointers[i].properties
1223 != msg->body.motion.pointers[i].properties) {
1224 return false;
1225 }
1226 }
1227 return true;
1228}
1229
1230ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1231 size_t numSamples = batch.samples.size();
1232 size_t index = 0;
1233 while (index < numSamples
1234 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1235 index += 1;
1236 }
1237 return ssize_t(index) - 1;
1238}
1239
1240} // namespace android