blob: 904a6feb03c6d69027beec1caed9d907299daac6 [file] [log] [blame]
Jeff Brown5912f952013-07-01 19:10:31 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// Provides a shared memory transport for input events.
5//
6#define LOG_TAG "InputTransport"
7
8//#define LOG_NDEBUG 0
9
10// Log debug messages about channel messages (send message, receive message)
11#define DEBUG_CHANNEL_MESSAGES 0
12
13// Log debug messages whenever InputChannel objects are created/destroyed
14#define DEBUG_CHANNEL_LIFECYCLE 0
15
16// Log debug messages about transport actions
17#define DEBUG_TRANSPORT_ACTIONS 0
18
19// Log debug messages about touch event resampling
20#define DEBUG_RESAMPLING 0
21
Jeff Brown5912f952013-07-01 19:10:31 -070022#include <errno.h>
23#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070024#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070025#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070026#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070027#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070028#include <unistd.h>
29
Michael Wright3dd60e22019-03-27 22:06:44 +000030#include <android-base/stringprintf.h>
31#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070032#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070033#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000034#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070035
Jeff Brown5912f952013-07-01 19:10:31 -070036#include <input/InputTransport.h>
37
Michael Wright3dd60e22019-03-27 22:06:44 +000038using android::base::StringPrintf;
39
Jeff Brown5912f952013-07-01 19:10:31 -070040namespace android {
41
42// Socket buffer size. The default is typically about 128KB, which is much larger than
43// we really need. So we make it smaller. It just needs to be big enough to hold
44// a few dozen large multi-finger motion events in the case where an application gets
45// behind processing touches.
46static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
47
48// Nanoseconds per milliseconds.
49static const nsecs_t NANOS_PER_MS = 1000000;
50
51// Latency added during resampling. A few milliseconds doesn't hurt much but
52// reduces the impact of mispredicted touch positions.
53static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
54
55// Minimum time difference between consecutive samples before attempting to resample.
56static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
57
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070058// Maximum time difference between consecutive samples before attempting to resample
59// by extrapolation.
60static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
61
Jeff Brown5912f952013-07-01 19:10:31 -070062// Maximum time to predict forward from the last known state, to avoid predicting too
63// far into the future. This time is further bounded by 50% of the last time delta.
64static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
65
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -060066/**
67 * System property for enabling / disabling touch resampling.
68 * Resampling extrapolates / interpolates the reported touch event coordinates to better
69 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
70 * Resampling is not needed (and should be disabled) on hardware that already
71 * has touch events triggered by VSYNC.
72 * Set to "1" to enable resampling (default).
73 * Set to "0" to disable resampling.
74 * Resampling is enabled by default.
75 */
76static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
77
Jeff Brown5912f952013-07-01 19:10:31 -070078template<typename T>
79inline static T min(const T& a, const T& b) {
80 return a < b ? a : b;
81}
82
83inline static float lerp(float a, float b, float alpha) {
84 return a + alpha * (b - a);
85}
86
Siarhei Vishniakou128eab12019-05-23 10:25:59 +080087inline static bool isPointerEvent(int32_t source) {
88 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
89}
90
Jeff Brown5912f952013-07-01 19:10:31 -070091// --- InputMessage ---
92
93bool InputMessage::isValid(size_t actualSize) const {
94 if (size() == actualSize) {
95 switch (header.type) {
96 case TYPE_KEY:
97 return true;
98 case TYPE_MOTION:
99 return body.motion.pointerCount > 0
100 && body.motion.pointerCount <= MAX_POINTERS;
101 case TYPE_FINISHED:
102 return true;
103 }
104 }
105 return false;
106}
107
108size_t InputMessage::size() const {
109 switch (header.type) {
110 case TYPE_KEY:
111 return sizeof(Header) + body.key.size();
112 case TYPE_MOTION:
113 return sizeof(Header) + body.motion.size();
114 case TYPE_FINISHED:
115 return sizeof(Header) + body.finished.size();
116 }
117 return sizeof(Header);
118}
119
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800120/**
121 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
122 * memory to zero, then only copy the valid bytes on a per-field basis.
123 */
124void InputMessage::getSanitizedCopy(InputMessage* msg) const {
125 memset(msg, 0, sizeof(*msg));
126
127 // Write the header
128 msg->header.type = header.type;
129
130 // Write the body
131 switch(header.type) {
132 case InputMessage::TYPE_KEY: {
133 // uint32_t seq
134 msg->body.key.seq = body.key.seq;
135 // nsecs_t eventTime
136 msg->body.key.eventTime = body.key.eventTime;
137 // int32_t deviceId
138 msg->body.key.deviceId = body.key.deviceId;
139 // int32_t source
140 msg->body.key.source = body.key.source;
141 // int32_t displayId
142 msg->body.key.displayId = body.key.displayId;
143 // int32_t action
144 msg->body.key.action = body.key.action;
145 // int32_t flags
146 msg->body.key.flags = body.key.flags;
147 // int32_t keyCode
148 msg->body.key.keyCode = body.key.keyCode;
149 // int32_t scanCode
150 msg->body.key.scanCode = body.key.scanCode;
151 // int32_t metaState
152 msg->body.key.metaState = body.key.metaState;
153 // int32_t repeatCount
154 msg->body.key.repeatCount = body.key.repeatCount;
155 // nsecs_t downTime
156 msg->body.key.downTime = body.key.downTime;
157 break;
158 }
159 case InputMessage::TYPE_MOTION: {
160 // uint32_t seq
161 msg->body.motion.seq = body.motion.seq;
162 // nsecs_t eventTime
163 msg->body.motion.eventTime = body.motion.eventTime;
164 // int32_t deviceId
165 msg->body.motion.deviceId = body.motion.deviceId;
166 // int32_t source
167 msg->body.motion.source = body.motion.source;
168 // int32_t displayId
169 msg->body.motion.displayId = body.motion.displayId;
170 // int32_t action
171 msg->body.motion.action = body.motion.action;
172 // int32_t actionButton
173 msg->body.motion.actionButton = body.motion.actionButton;
174 // int32_t flags
175 msg->body.motion.flags = body.motion.flags;
176 // int32_t metaState
177 msg->body.motion.metaState = body.motion.metaState;
178 // int32_t buttonState
179 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800180 // MotionClassification classification
181 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800182 // int32_t edgeFlags
183 msg->body.motion.edgeFlags = body.motion.edgeFlags;
184 // nsecs_t downTime
185 msg->body.motion.downTime = body.motion.downTime;
186 // float xOffset
187 msg->body.motion.xOffset = body.motion.xOffset;
188 // float yOffset
189 msg->body.motion.yOffset = body.motion.yOffset;
190 // float xPrecision
191 msg->body.motion.xPrecision = body.motion.xPrecision;
192 // float yPrecision
193 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700194 // float xCursorPosition
195 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
196 // float yCursorPosition
197 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800198 // uint32_t pointerCount
199 msg->body.motion.pointerCount = body.motion.pointerCount;
200 //struct Pointer pointers[MAX_POINTERS]
201 for (size_t i = 0; i < body.motion.pointerCount; i++) {
202 // PointerProperties properties
203 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
204 msg->body.motion.pointers[i].properties.toolType =
205 body.motion.pointers[i].properties.toolType,
206 // PointerCoords coords
207 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
208 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
209 memcpy(&msg->body.motion.pointers[i].coords.values[0],
210 &body.motion.pointers[i].coords.values[0],
211 count * (sizeof(body.motion.pointers[i].coords.values[0])));
212 }
213 break;
214 }
215 case InputMessage::TYPE_FINISHED: {
216 msg->body.finished.seq = body.finished.seq;
217 msg->body.finished.handled = body.finished.handled;
218 break;
219 }
220 default: {
221 LOG_FATAL("Unexpected message type %i", header.type);
222 break;
223 }
224 }
225}
Jeff Brown5912f952013-07-01 19:10:31 -0700226
227// --- InputChannel ---
228
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800229InputChannel::InputChannel(const std::string& name, int fd) :
Robert Carr3720ed02018-08-08 16:08:27 -0700230 mName(name) {
Jeff Brown5912f952013-07-01 19:10:31 -0700231#if DEBUG_CHANNEL_LIFECYCLE
232 ALOGD("Input channel constructed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 mName.c_str(), fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700234#endif
235
Robert Carr3720ed02018-08-08 16:08:27 -0700236 setFd(fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700237}
238
239InputChannel::~InputChannel() {
240#if DEBUG_CHANNEL_LIFECYCLE
241 ALOGD("Input channel destroyed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800242 mName.c_str(), mFd);
Jeff Brown5912f952013-07-01 19:10:31 -0700243#endif
244
245 ::close(mFd);
246}
247
Robert Carr3720ed02018-08-08 16:08:27 -0700248void InputChannel::setFd(int fd) {
249 if (mFd > 0) {
250 ::close(mFd);
251 }
252 mFd = fd;
253 if (mFd > 0) {
254 int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
255 LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
256 "non-blocking. errno=%d", mName.c_str(), errno);
257 }
258}
259
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800260status_t InputChannel::openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700261 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
262 int sockets[2];
263 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
264 status_t result = -errno;
265 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800266 name.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700267 outServerChannel.clear();
268 outClientChannel.clear();
269 return result;
270 }
271
272 int bufferSize = SOCKET_BUFFER_SIZE;
273 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
274 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
275 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
276 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
277
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800278 std::string serverChannelName = name;
279 serverChannelName += " (server)";
Jeff Brown5912f952013-07-01 19:10:31 -0700280 outServerChannel = new InputChannel(serverChannelName, sockets[0]);
281
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800282 std::string clientChannelName = name;
283 clientChannelName += " (client)";
Jeff Brown5912f952013-07-01 19:10:31 -0700284 outClientChannel = new InputChannel(clientChannelName, sockets[1]);
285 return OK;
286}
287
288status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800289 const size_t msgLength = msg->size();
290 InputMessage cleanMsg;
291 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700292 ssize_t nWrite;
293 do {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800294 nWrite = ::send(mFd, &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700295 } while (nWrite == -1 && errno == EINTR);
296
297 if (nWrite < 0) {
298 int error = errno;
299#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800300 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.c_str(),
Jeff Brown5912f952013-07-01 19:10:31 -0700301 msg->header.type, error);
302#endif
303 if (error == EAGAIN || error == EWOULDBLOCK) {
304 return WOULD_BLOCK;
305 }
306 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
307 return DEAD_OBJECT;
308 }
309 return -error;
310 }
311
312 if (size_t(nWrite) != msgLength) {
313#if DEBUG_CHANNEL_MESSAGES
314 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800315 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700316#endif
317 return DEAD_OBJECT;
318 }
319
320#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800321 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700322#endif
323 return OK;
324}
325
326status_t InputChannel::receiveMessage(InputMessage* msg) {
327 ssize_t nRead;
328 do {
329 nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
330 } while (nRead == -1 && errno == EINTR);
331
332 if (nRead < 0) {
333 int error = errno;
334#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800335 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700336#endif
337 if (error == EAGAIN || error == EWOULDBLOCK) {
338 return WOULD_BLOCK;
339 }
340 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
341 return DEAD_OBJECT;
342 }
343 return -error;
344 }
345
346 if (nRead == 0) { // check for EOF
347#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800348 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700349#endif
350 return DEAD_OBJECT;
351 }
352
353 if (!msg->isValid(nRead)) {
354#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800355 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700356#endif
357 return BAD_VALUE;
358 }
359
360#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800361 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700362#endif
363 return OK;
364}
365
366sp<InputChannel> InputChannel::dup() const {
367 int fd = ::dup(getFd());
Yi Kong5bed83b2018-07-17 12:53:47 -0700368 return fd >= 0 ? new InputChannel(getName(), fd) : nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700369}
370
371
Robert Carr3720ed02018-08-08 16:08:27 -0700372status_t InputChannel::write(Parcel& out) const {
373 status_t s = out.writeString8(String8(getName().c_str()));
374
375 if (s != OK) {
376 return s;
377 }
Robert Carr803535b2018-08-02 16:38:15 -0700378 s = out.writeStrongBinder(mToken);
379 if (s != OK) {
380 return s;
381 }
Robert Carr3720ed02018-08-08 16:08:27 -0700382
383 s = out.writeDupFileDescriptor(getFd());
384
385 return s;
386}
387
388status_t InputChannel::read(const Parcel& from) {
389 mName = from.readString8();
Robert Carr803535b2018-08-02 16:38:15 -0700390 mToken = from.readStrongBinder();
Robert Carr3720ed02018-08-08 16:08:27 -0700391
392 int rawFd = from.readFileDescriptor();
393 setFd(::dup(rawFd));
394
395 if (mFd < 0) {
396 return BAD_VALUE;
397 }
398
399 return OK;
400}
401
Robert Carr803535b2018-08-02 16:38:15 -0700402sp<IBinder> InputChannel::getToken() const {
403 return mToken;
404}
405
406void InputChannel::setToken(const sp<IBinder>& token) {
407 if (mToken != nullptr) {
408 ALOGE("Assigning InputChannel (%s) a second handle?", mName.c_str());
409 }
410 mToken = token;
411}
412
Jeff Brown5912f952013-07-01 19:10:31 -0700413// --- InputPublisher ---
414
415InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
416 mChannel(channel) {
417}
418
419InputPublisher::~InputPublisher() {
420}
421
422status_t InputPublisher::publishKeyEvent(
423 uint32_t seq,
424 int32_t deviceId,
425 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100426 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700427 int32_t action,
428 int32_t flags,
429 int32_t keyCode,
430 int32_t scanCode,
431 int32_t metaState,
432 int32_t repeatCount,
433 nsecs_t downTime,
434 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000435 if (ATRACE_ENABLED()) {
436 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
437 mChannel->getName().c_str(), keyCode);
438 ATRACE_NAME(message.c_str());
439 }
Jeff Brown5912f952013-07-01 19:10:31 -0700440#if DEBUG_TRANSPORT_ACTIONS
441 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
442 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700443 "downTime=%" PRId64 ", eventTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800444 mChannel->getName().c_str(), seq,
Jeff Brown5912f952013-07-01 19:10:31 -0700445 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
446 downTime, eventTime);
447#endif
448
449 if (!seq) {
450 ALOGE("Attempted to publish a key event with sequence number 0.");
451 return BAD_VALUE;
452 }
453
454 InputMessage msg;
455 msg.header.type = InputMessage::TYPE_KEY;
456 msg.body.key.seq = seq;
457 msg.body.key.deviceId = deviceId;
458 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100459 msg.body.key.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700460 msg.body.key.action = action;
461 msg.body.key.flags = flags;
462 msg.body.key.keyCode = keyCode;
463 msg.body.key.scanCode = scanCode;
464 msg.body.key.metaState = metaState;
465 msg.body.key.repeatCount = repeatCount;
466 msg.body.key.downTime = downTime;
467 msg.body.key.eventTime = eventTime;
468 return mChannel->sendMessage(&msg);
469}
470
471status_t InputPublisher::publishMotionEvent(
Garfield Tan00f511d2019-06-12 16:55:40 -0700472 uint32_t seq, int32_t deviceId, int32_t source, int32_t displayId, int32_t action,
473 int32_t actionButton, int32_t flags, int32_t edgeFlags, int32_t metaState,
474 int32_t buttonState, MotionClassification classification, float xOffset, float yOffset,
475 float xPrecision, float yPrecision, float xCursorPosition, float yCursorPosition,
476 nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
477 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000478 if (ATRACE_ENABLED()) {
479 std::string message = StringPrintf(
480 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
481 mChannel->getName().c_str(), action);
482 ATRACE_NAME(message.c_str());
483 }
Jeff Brown5912f952013-07-01 19:10:31 -0700484#if DEBUG_TRANSPORT_ACTIONS
485 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800486 "displayId=%" PRId32 ", "
Michael Wright7b159c92015-05-14 14:48:03 +0100487 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800488 "metaState=0x%x, buttonState=0x%x, classification=%s, xOffset=%f, yOffset=%f, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700489 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
Michael Wright63ff3a82014-06-10 13:03:17 -0700490 "pointerCount=%" PRIu32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800491 mChannel->getName().c_str(), seq,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800492 deviceId, source, displayId, action, actionButton, flags, edgeFlags, metaState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800493 buttonState, motionClassificationToString(classification),
494 xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700495#endif
496
497 if (!seq) {
498 ALOGE("Attempted to publish a motion event with sequence number 0.");
499 return BAD_VALUE;
500 }
501
502 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700503 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800504 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700505 return BAD_VALUE;
506 }
507
508 InputMessage msg;
509 msg.header.type = InputMessage::TYPE_MOTION;
510 msg.body.motion.seq = seq;
511 msg.body.motion.deviceId = deviceId;
512 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700513 msg.body.motion.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700514 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100515 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700516 msg.body.motion.flags = flags;
517 msg.body.motion.edgeFlags = edgeFlags;
518 msg.body.motion.metaState = metaState;
519 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800520 msg.body.motion.classification = classification;
Jeff Brown5912f952013-07-01 19:10:31 -0700521 msg.body.motion.xOffset = xOffset;
522 msg.body.motion.yOffset = yOffset;
523 msg.body.motion.xPrecision = xPrecision;
524 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700525 msg.body.motion.xCursorPosition = xCursorPosition;
526 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700527 msg.body.motion.downTime = downTime;
528 msg.body.motion.eventTime = eventTime;
529 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100530 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700531 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
532 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
533 }
534 return mChannel->sendMessage(&msg);
535}
536
537status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
538#if DEBUG_TRANSPORT_ACTIONS
539 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800540 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700541#endif
542
543 InputMessage msg;
544 status_t result = mChannel->receiveMessage(&msg);
545 if (result) {
546 *outSeq = 0;
547 *outHandled = false;
548 return result;
549 }
550 if (msg.header.type != InputMessage::TYPE_FINISHED) {
551 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800552 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700553 return UNKNOWN_ERROR;
554 }
555 *outSeq = msg.body.finished.seq;
556 *outHandled = msg.body.finished.handled;
557 return OK;
558}
559
560// --- InputConsumer ---
561
562InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
563 mResampleTouch(isTouchResamplingEnabled()),
564 mChannel(channel), mMsgDeferred(false) {
565}
566
567InputConsumer::~InputConsumer() {
568}
569
570bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600571 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700572}
573
574status_t InputConsumer::consume(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800575 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700576#if DEBUG_TRANSPORT_ACTIONS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700577 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800578 mChannel->getName().c_str(), consumeBatches ? "true" : "false", frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700579#endif
580
581 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700582 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700583
584 // Fetch the next input message.
585 // Loop until an event can be returned or no additional events are received.
586 while (!*outEvent) {
587 if (mMsgDeferred) {
588 // mMsg contains a valid input message from the previous call to consume
589 // that has not yet been processed.
590 mMsgDeferred = false;
591 } else {
592 // Receive a fresh message.
593 status_t result = mChannel->receiveMessage(&mMsg);
594 if (result) {
595 // Consume the next batched event unless batches are being held for later.
596 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800597 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700598 if (*outEvent) {
599#if DEBUG_TRANSPORT_ACTIONS
600 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800601 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700602#endif
603 break;
604 }
605 }
606 return result;
607 }
608 }
609
610 switch (mMsg.header.type) {
611 case InputMessage::TYPE_KEY: {
612 KeyEvent* keyEvent = factory->createKeyEvent();
613 if (!keyEvent) return NO_MEMORY;
614
615 initializeKeyEvent(keyEvent, &mMsg);
616 *outSeq = mMsg.body.key.seq;
617 *outEvent = keyEvent;
618#if DEBUG_TRANSPORT_ACTIONS
619 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800620 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700621#endif
622 break;
623 }
624
gaoshange3e11a72017-08-08 16:11:31 +0800625 case InputMessage::TYPE_MOTION: {
Jeff Brown5912f952013-07-01 19:10:31 -0700626 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
627 if (batchIndex >= 0) {
628 Batch& batch = mBatches.editItemAt(batchIndex);
629 if (canAddSample(batch, &mMsg)) {
630 batch.samples.push(mMsg);
631#if DEBUG_TRANSPORT_ACTIONS
632 ALOGD("channel '%s' consumer ~ appended to batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800633 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700634#endif
635 break;
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800636 } else if (isPointerEvent(mMsg.body.motion.source) &&
637 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
638 // No need to process events that we are going to cancel anyways
639 const size_t count = batch.samples.size();
640 for (size_t i = 0; i < count; i++) {
641 const InputMessage& msg = batch.samples.itemAt(i);
642 sendFinishedSignal(msg.body.motion.seq, false);
643 }
644 batch.samples.removeItemsAt(0, count);
645 mBatches.removeAt(batchIndex);
Jeff Brown5912f952013-07-01 19:10:31 -0700646 } else {
647 // We cannot append to the batch in progress, so we need to consume
648 // the previous batch right now and defer the new message until later.
649 mMsgDeferred = true;
650 status_t result = consumeSamples(factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800651 batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700652 mBatches.removeAt(batchIndex);
653 if (result) {
654 return result;
655 }
656#if DEBUG_TRANSPORT_ACTIONS
657 ALOGD("channel '%s' consumer ~ consumed batch event and "
658 "deferred current event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800659 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700660#endif
661 break;
662 }
663 }
664
665 // Start a new batch if needed.
666 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
667 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
668 mBatches.push();
669 Batch& batch = mBatches.editTop();
670 batch.samples.push(mMsg);
671#if DEBUG_TRANSPORT_ACTIONS
672 ALOGD("channel '%s' consumer ~ started batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800673 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700674#endif
675 break;
676 }
677
678 MotionEvent* motionEvent = factory->createMotionEvent();
679 if (! motionEvent) return NO_MEMORY;
680
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100681 updateTouchState(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700682 initializeMotionEvent(motionEvent, &mMsg);
683 *outSeq = mMsg.body.motion.seq;
684 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800685
Jeff Brown5912f952013-07-01 19:10:31 -0700686#if DEBUG_TRANSPORT_ACTIONS
687 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800688 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700689#endif
690 break;
691 }
692
693 default:
694 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800695 mChannel->getName().c_str(), mMsg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700696 return UNKNOWN_ERROR;
697 }
698 }
699 return OK;
700}
701
702status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800703 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700704 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700705 for (size_t i = mBatches.size(); i > 0; ) {
706 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700707 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700708 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800709 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700710 mBatches.removeAt(i);
711 return result;
712 }
713
Michael Wright32232172013-10-21 12:05:22 -0700714 nsecs_t sampleTime = frameTime;
715 if (mResampleTouch) {
716 sampleTime -= RESAMPLE_LATENCY;
717 }
Jeff Brown5912f952013-07-01 19:10:31 -0700718 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
719 if (split < 0) {
720 continue;
721 }
722
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800723 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700724 const InputMessage* next;
725 if (batch.samples.isEmpty()) {
726 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700727 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700728 } else {
729 next = &batch.samples.itemAt(0);
730 }
Michael Wright32232172013-10-21 12:05:22 -0700731 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700732 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
733 }
734 return result;
735 }
736
737 return WOULD_BLOCK;
738}
739
740status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800741 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700742 MotionEvent* motionEvent = factory->createMotionEvent();
743 if (! motionEvent) return NO_MEMORY;
744
745 uint32_t chain = 0;
746 for (size_t i = 0; i < count; i++) {
747 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100748 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700749 if (i) {
750 SeqChain seqChain;
751 seqChain.seq = msg.body.motion.seq;
752 seqChain.chain = chain;
753 mSeqChains.push(seqChain);
754 addSample(motionEvent, &msg);
755 } else {
756 initializeMotionEvent(motionEvent, &msg);
757 }
758 chain = msg.body.motion.seq;
759 }
760 batch.samples.removeItemsAt(0, count);
761
762 *outSeq = chain;
763 *outEvent = motionEvent;
764 return OK;
765}
766
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100767void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800768 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700769 return;
770 }
771
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100772 int32_t deviceId = msg.body.motion.deviceId;
773 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700774
775 // Update the touch state history to incorporate the new input message.
776 // If the message is in the past relative to the most recently produced resampled
777 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100778 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700779 case AMOTION_EVENT_ACTION_DOWN: {
780 ssize_t index = findTouchState(deviceId, source);
781 if (index < 0) {
782 mTouchStates.push();
783 index = mTouchStates.size() - 1;
784 }
785 TouchState& touchState = mTouchStates.editItemAt(index);
786 touchState.initialize(deviceId, source);
787 touchState.addHistory(msg);
788 break;
789 }
790
791 case AMOTION_EVENT_ACTION_MOVE: {
792 ssize_t index = findTouchState(deviceId, source);
793 if (index >= 0) {
794 TouchState& touchState = mTouchStates.editItemAt(index);
795 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800796 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700797 }
798 break;
799 }
800
801 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
802 ssize_t index = findTouchState(deviceId, source);
803 if (index >= 0) {
804 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100805 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700806 rewriteMessage(touchState, msg);
807 }
808 break;
809 }
810
811 case AMOTION_EVENT_ACTION_POINTER_UP: {
812 ssize_t index = findTouchState(deviceId, source);
813 if (index >= 0) {
814 TouchState& touchState = mTouchStates.editItemAt(index);
815 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100816 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700817 }
818 break;
819 }
820
821 case AMOTION_EVENT_ACTION_SCROLL: {
822 ssize_t index = findTouchState(deviceId, source);
823 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800824 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700825 rewriteMessage(touchState, msg);
826 }
827 break;
828 }
829
830 case AMOTION_EVENT_ACTION_UP:
831 case AMOTION_EVENT_ACTION_CANCEL: {
832 ssize_t index = findTouchState(deviceId, source);
833 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800834 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700835 rewriteMessage(touchState, msg);
836 mTouchStates.removeAt(index);
837 }
838 break;
839 }
840 }
841}
842
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800843/**
844 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
845 *
846 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
847 * is in the past relative to msg and the past two events do not contain identical coordinates),
848 * then invalidate the lastResample data for that pointer.
849 * If the two past events have identical coordinates, then lastResample data for that pointer will
850 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
851 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
852 * not equal to x0 is received.
853 */
854void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100855 nsecs_t eventTime = msg.body.motion.eventTime;
856 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
857 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700858 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100859 if (eventTime < state.lastResample.eventTime ||
860 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800861 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
862 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700863#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100864 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
865 resampleCoords.getX(), resampleCoords.getY(),
866 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700867#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800868 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
869 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
870 } else {
871 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100872 }
Jeff Brown5912f952013-07-01 19:10:31 -0700873 }
874 }
875}
876
877void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
878 const InputMessage* next) {
879 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800880 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700881 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
882 return;
883 }
884
885 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
886 if (index < 0) {
887#if DEBUG_RESAMPLING
888 ALOGD("Not resampled, no touch state for device.");
889#endif
890 return;
891 }
892
893 TouchState& touchState = mTouchStates.editItemAt(index);
894 if (touchState.historySize < 1) {
895#if DEBUG_RESAMPLING
896 ALOGD("Not resampled, no history for device.");
897#endif
898 return;
899 }
900
901 // Ensure that the current sample has all of the pointers that need to be reported.
902 const History* current = touchState.getHistory(0);
903 size_t pointerCount = event->getPointerCount();
904 for (size_t i = 0; i < pointerCount; i++) {
905 uint32_t id = event->getPointerId(i);
906 if (!current->idBits.hasBit(id)) {
907#if DEBUG_RESAMPLING
908 ALOGD("Not resampled, missing id %d", id);
909#endif
910 return;
911 }
912 }
913
914 // Find the data to use for resampling.
915 const History* other;
916 History future;
917 float alpha;
918 if (next) {
919 // Interpolate between current sample and future sample.
920 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100921 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700922 other = &future;
923 nsecs_t delta = future.eventTime - current->eventTime;
924 if (delta < RESAMPLE_MIN_DELTA) {
925#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100926 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700927#endif
928 return;
929 }
930 alpha = float(sampleTime - current->eventTime) / delta;
931 } else if (touchState.historySize >= 2) {
932 // Extrapolate future sample using current sample and past sample.
933 // So other->eventTime <= current->eventTime <= sampleTime.
934 other = touchState.getHistory(1);
935 nsecs_t delta = current->eventTime - other->eventTime;
936 if (delta < RESAMPLE_MIN_DELTA) {
937#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100938 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700939#endif
940 return;
941 } else if (delta > RESAMPLE_MAX_DELTA) {
942#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100943 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700944#endif
945 return;
946 }
947 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
948 if (sampleTime > maxPredict) {
949#if DEBUG_RESAMPLING
950 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100951 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700952 sampleTime - current->eventTime, maxPredict - current->eventTime);
953#endif
954 sampleTime = maxPredict;
955 }
956 alpha = float(current->eventTime - sampleTime) / delta;
957 } else {
958#if DEBUG_RESAMPLING
959 ALOGD("Not resampled, insufficient data.");
960#endif
961 return;
962 }
963
964 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800965 History oldLastResample;
966 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700967 touchState.lastResample.eventTime = sampleTime;
968 touchState.lastResample.idBits.clear();
969 for (size_t i = 0; i < pointerCount; i++) {
970 uint32_t id = event->getPointerId(i);
971 touchState.lastResample.idToIndex[id] = i;
972 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800973 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
974 // We maintain the previously resampled value for this pointer (stored in
975 // oldLastResample) when the coordinates for this pointer haven't changed since then.
976 // This way we don't introduce artificial jitter when pointers haven't actually moved.
977
978 // We know here that the coordinates for the pointer haven't changed because we
979 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
980 // lastResample in place becasue the mapping from pointer ID to index may have changed.
981 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
982 continue;
983 }
984
Jeff Brown5912f952013-07-01 19:10:31 -0700985 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
986 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800987 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700988 if (other->idBits.hasBit(id)
989 && shouldResampleTool(event->getToolType(i))) {
990 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700991 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
992 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
993 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
994 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
995#if DEBUG_RESAMPLING
996 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
997 "other (%0.3f, %0.3f), alpha %0.3f",
998 id, resampledCoords.getX(), resampledCoords.getY(),
999 currentCoords.getX(), currentCoords.getY(),
1000 otherCoords.getX(), otherCoords.getY(),
1001 alpha);
1002#endif
1003 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001004#if DEBUG_RESAMPLING
1005 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1006 id, resampledCoords.getX(), resampledCoords.getY(),
1007 currentCoords.getX(), currentCoords.getY());
1008#endif
1009 }
1010 }
1011
1012 event->addSample(sampleTime, touchState.lastResample.pointers);
1013}
1014
1015bool InputConsumer::shouldResampleTool(int32_t toolType) {
1016 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1017 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1018}
1019
1020status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
1021#if DEBUG_TRANSPORT_ACTIONS
1022 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001023 mChannel->getName().c_str(), seq, handled ? "true" : "false");
Jeff Brown5912f952013-07-01 19:10:31 -07001024#endif
1025
1026 if (!seq) {
1027 ALOGE("Attempted to send a finished signal with sequence number 0.");
1028 return BAD_VALUE;
1029 }
1030
1031 // Send finished signals for the batch sequence chain first.
1032 size_t seqChainCount = mSeqChains.size();
1033 if (seqChainCount) {
1034 uint32_t currentSeq = seq;
1035 uint32_t chainSeqs[seqChainCount];
1036 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001037 for (size_t i = seqChainCount; i > 0; ) {
1038 i--;
Jeff Brown5912f952013-07-01 19:10:31 -07001039 const SeqChain& seqChain = mSeqChains.itemAt(i);
1040 if (seqChain.seq == currentSeq) {
1041 currentSeq = seqChain.chain;
1042 chainSeqs[chainIndex++] = currentSeq;
1043 mSeqChains.removeAt(i);
1044 }
1045 }
1046 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001047 while (!status && chainIndex > 0) {
1048 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001049 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1050 }
1051 if (status) {
1052 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001053 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001054 SeqChain seqChain;
1055 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1056 seqChain.chain = chainSeqs[chainIndex];
1057 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001058 if (!chainIndex) break;
1059 chainIndex--;
1060 }
Jeff Brown5912f952013-07-01 19:10:31 -07001061 return status;
1062 }
1063 }
1064
1065 // Send finished signal for the last message in the batch.
1066 return sendUnchainedFinishedSignal(seq, handled);
1067}
1068
1069status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1070 InputMessage msg;
1071 msg.header.type = InputMessage::TYPE_FINISHED;
1072 msg.body.finished.seq = seq;
1073 msg.body.finished.handled = handled;
1074 return mChannel->sendMessage(&msg);
1075}
1076
1077bool InputConsumer::hasDeferredEvent() const {
1078 return mMsgDeferred;
1079}
1080
1081bool InputConsumer::hasPendingBatch() const {
1082 return !mBatches.isEmpty();
1083}
1084
1085ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1086 for (size_t i = 0; i < mBatches.size(); i++) {
1087 const Batch& batch = mBatches.itemAt(i);
1088 const InputMessage& head = batch.samples.itemAt(0);
1089 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1090 return i;
1091 }
1092 }
1093 return -1;
1094}
1095
1096ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1097 for (size_t i = 0; i < mTouchStates.size(); i++) {
1098 const TouchState& touchState = mTouchStates.itemAt(i);
1099 if (touchState.deviceId == deviceId && touchState.source == source) {
1100 return i;
1101 }
1102 }
1103 return -1;
1104}
1105
1106void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
1107 event->initialize(
1108 msg->body.key.deviceId,
1109 msg->body.key.source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001110 msg->body.key.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001111 msg->body.key.action,
1112 msg->body.key.flags,
1113 msg->body.key.keyCode,
1114 msg->body.key.scanCode,
1115 msg->body.key.metaState,
1116 msg->body.key.repeatCount,
1117 msg->body.key.downTime,
1118 msg->body.key.eventTime);
1119}
1120
1121void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001122 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001123 PointerProperties pointerProperties[pointerCount];
1124 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001125 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001126 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1127 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1128 }
1129
Garfield Tan00f511d2019-06-12 16:55:40 -07001130 event->initialize(msg->body.motion.deviceId, msg->body.motion.source,
1131 msg->body.motion.displayId, msg->body.motion.action,
1132 msg->body.motion.actionButton, msg->body.motion.flags,
1133 msg->body.motion.edgeFlags, msg->body.motion.metaState,
1134 msg->body.motion.buttonState, msg->body.motion.classification,
1135 msg->body.motion.xOffset, msg->body.motion.yOffset,
1136 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1137 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1138 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1139 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001140}
1141
1142void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001143 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001144 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001145 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001146 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1147 }
1148
1149 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1150 event->addSample(msg->body.motion.eventTime, pointerCoords);
1151}
1152
1153bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1154 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001155 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001156 if (head.body.motion.pointerCount != pointerCount
1157 || head.body.motion.action != msg->body.motion.action) {
1158 return false;
1159 }
1160 for (size_t i = 0; i < pointerCount; i++) {
1161 if (head.body.motion.pointers[i].properties
1162 != msg->body.motion.pointers[i].properties) {
1163 return false;
1164 }
1165 }
1166 return true;
1167}
1168
1169ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1170 size_t numSamples = batch.samples.size();
1171 size_t index = 0;
1172 while (index < numSamples
1173 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1174 index += 1;
1175 }
1176 return ssize_t(index) - 1;
1177}
1178
1179} // namespace android