blob: e13b40ef24096a4cfa01707236d2f7ef3bdd467c [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
Jeff Brown5912f952013-07-01 19:10:31 -070030#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070031#include <log/log.h>
32
Robert Carr3720ed02018-08-08 16:08:27 -070033#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070034#include <input/InputTransport.h>
35
Jeff Brown5912f952013-07-01 19:10:31 -070036namespace android {
37
38// Socket buffer size. The default is typically about 128KB, which is much larger than
39// we really need. So we make it smaller. It just needs to be big enough to hold
40// a few dozen large multi-finger motion events in the case where an application gets
41// behind processing touches.
42static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
43
44// Nanoseconds per milliseconds.
45static const nsecs_t NANOS_PER_MS = 1000000;
46
47// Latency added during resampling. A few milliseconds doesn't hurt much but
48// reduces the impact of mispredicted touch positions.
49static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
50
51// Minimum time difference between consecutive samples before attempting to resample.
52static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
53
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070054// Maximum time difference between consecutive samples before attempting to resample
55// by extrapolation.
56static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
57
Jeff Brown5912f952013-07-01 19:10:31 -070058// Maximum time to predict forward from the last known state, to avoid predicting too
59// far into the future. This time is further bounded by 50% of the last time delta.
60static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
61
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -060062/**
63 * System property for enabling / disabling touch resampling.
64 * Resampling extrapolates / interpolates the reported touch event coordinates to better
65 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
66 * Resampling is not needed (and should be disabled) on hardware that already
67 * has touch events triggered by VSYNC.
68 * Set to "1" to enable resampling (default).
69 * Set to "0" to disable resampling.
70 * Resampling is enabled by default.
71 */
72static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
73
Jeff Brown5912f952013-07-01 19:10:31 -070074template<typename T>
75inline static T min(const T& a, const T& b) {
76 return a < b ? a : b;
77}
78
79inline static float lerp(float a, float b, float alpha) {
80 return a + alpha * (b - a);
81}
82
83// --- InputMessage ---
84
85bool InputMessage::isValid(size_t actualSize) const {
86 if (size() == actualSize) {
87 switch (header.type) {
88 case TYPE_KEY:
89 return true;
90 case TYPE_MOTION:
91 return body.motion.pointerCount > 0
92 && body.motion.pointerCount <= MAX_POINTERS;
93 case TYPE_FINISHED:
94 return true;
95 }
96 }
97 return false;
98}
99
100size_t InputMessage::size() const {
101 switch (header.type) {
102 case TYPE_KEY:
103 return sizeof(Header) + body.key.size();
104 case TYPE_MOTION:
105 return sizeof(Header) + body.motion.size();
106 case TYPE_FINISHED:
107 return sizeof(Header) + body.finished.size();
108 }
109 return sizeof(Header);
110}
111
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800112/**
113 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
114 * memory to zero, then only copy the valid bytes on a per-field basis.
115 */
116void InputMessage::getSanitizedCopy(InputMessage* msg) const {
117 memset(msg, 0, sizeof(*msg));
118
119 // Write the header
120 msg->header.type = header.type;
121
122 // Write the body
123 switch(header.type) {
124 case InputMessage::TYPE_KEY: {
125 // uint32_t seq
126 msg->body.key.seq = body.key.seq;
127 // nsecs_t eventTime
128 msg->body.key.eventTime = body.key.eventTime;
129 // int32_t deviceId
130 msg->body.key.deviceId = body.key.deviceId;
131 // int32_t source
132 msg->body.key.source = body.key.source;
133 // int32_t displayId
134 msg->body.key.displayId = body.key.displayId;
135 // int32_t action
136 msg->body.key.action = body.key.action;
137 // int32_t flags
138 msg->body.key.flags = body.key.flags;
139 // int32_t keyCode
140 msg->body.key.keyCode = body.key.keyCode;
141 // int32_t scanCode
142 msg->body.key.scanCode = body.key.scanCode;
143 // int32_t metaState
144 msg->body.key.metaState = body.key.metaState;
145 // int32_t repeatCount
146 msg->body.key.repeatCount = body.key.repeatCount;
147 // nsecs_t downTime
148 msg->body.key.downTime = body.key.downTime;
149 break;
150 }
151 case InputMessage::TYPE_MOTION: {
152 // uint32_t seq
153 msg->body.motion.seq = body.motion.seq;
154 // nsecs_t eventTime
155 msg->body.motion.eventTime = body.motion.eventTime;
156 // int32_t deviceId
157 msg->body.motion.deviceId = body.motion.deviceId;
158 // int32_t source
159 msg->body.motion.source = body.motion.source;
160 // int32_t displayId
161 msg->body.motion.displayId = body.motion.displayId;
162 // int32_t action
163 msg->body.motion.action = body.motion.action;
164 // int32_t actionButton
165 msg->body.motion.actionButton = body.motion.actionButton;
166 // int32_t flags
167 msg->body.motion.flags = body.motion.flags;
168 // int32_t metaState
169 msg->body.motion.metaState = body.motion.metaState;
170 // int32_t buttonState
171 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800172 // MotionClassification classification
173 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800174 // int32_t edgeFlags
175 msg->body.motion.edgeFlags = body.motion.edgeFlags;
176 // nsecs_t downTime
177 msg->body.motion.downTime = body.motion.downTime;
178 // float xOffset
179 msg->body.motion.xOffset = body.motion.xOffset;
180 // float yOffset
181 msg->body.motion.yOffset = body.motion.yOffset;
182 // float xPrecision
183 msg->body.motion.xPrecision = body.motion.xPrecision;
184 // float yPrecision
185 msg->body.motion.yPrecision = body.motion.yPrecision;
186 // uint32_t pointerCount
187 msg->body.motion.pointerCount = body.motion.pointerCount;
188 //struct Pointer pointers[MAX_POINTERS]
189 for (size_t i = 0; i < body.motion.pointerCount; i++) {
190 // PointerProperties properties
191 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
192 msg->body.motion.pointers[i].properties.toolType =
193 body.motion.pointers[i].properties.toolType,
194 // PointerCoords coords
195 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
196 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
197 memcpy(&msg->body.motion.pointers[i].coords.values[0],
198 &body.motion.pointers[i].coords.values[0],
199 count * (sizeof(body.motion.pointers[i].coords.values[0])));
200 }
201 break;
202 }
203 case InputMessage::TYPE_FINISHED: {
204 msg->body.finished.seq = body.finished.seq;
205 msg->body.finished.handled = body.finished.handled;
206 break;
207 }
208 default: {
209 LOG_FATAL("Unexpected message type %i", header.type);
210 break;
211 }
212 }
213}
Jeff Brown5912f952013-07-01 19:10:31 -0700214
215// --- InputChannel ---
216
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800217InputChannel::InputChannel(const std::string& name, int fd) :
Robert Carr3720ed02018-08-08 16:08:27 -0700218 mName(name) {
Jeff Brown5912f952013-07-01 19:10:31 -0700219#if DEBUG_CHANNEL_LIFECYCLE
220 ALOGD("Input channel constructed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800221 mName.c_str(), fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700222#endif
223
Robert Carr3720ed02018-08-08 16:08:27 -0700224 setFd(fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700225}
226
227InputChannel::~InputChannel() {
228#if DEBUG_CHANNEL_LIFECYCLE
229 ALOGD("Input channel destroyed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800230 mName.c_str(), mFd);
Jeff Brown5912f952013-07-01 19:10:31 -0700231#endif
232
233 ::close(mFd);
234}
235
Robert Carr3720ed02018-08-08 16:08:27 -0700236void InputChannel::setFd(int fd) {
237 if (mFd > 0) {
238 ::close(mFd);
239 }
240 mFd = fd;
241 if (mFd > 0) {
242 int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
243 LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
244 "non-blocking. errno=%d", mName.c_str(), errno);
245 }
246}
247
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800248status_t InputChannel::openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700249 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
250 int sockets[2];
251 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
252 status_t result = -errno;
253 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800254 name.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700255 outServerChannel.clear();
256 outClientChannel.clear();
257 return result;
258 }
259
260 int bufferSize = SOCKET_BUFFER_SIZE;
261 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
262 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
263 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
264 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
265
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800266 std::string serverChannelName = name;
267 serverChannelName += " (server)";
Jeff Brown5912f952013-07-01 19:10:31 -0700268 outServerChannel = new InputChannel(serverChannelName, sockets[0]);
269
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800270 std::string clientChannelName = name;
271 clientChannelName += " (client)";
Jeff Brown5912f952013-07-01 19:10:31 -0700272 outClientChannel = new InputChannel(clientChannelName, sockets[1]);
273 return OK;
274}
275
276status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800277 const size_t msgLength = msg->size();
278 InputMessage cleanMsg;
279 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700280 ssize_t nWrite;
281 do {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800282 nWrite = ::send(mFd, &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700283 } while (nWrite == -1 && errno == EINTR);
284
285 if (nWrite < 0) {
286 int error = errno;
287#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800288 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.c_str(),
Jeff Brown5912f952013-07-01 19:10:31 -0700289 msg->header.type, error);
290#endif
291 if (error == EAGAIN || error == EWOULDBLOCK) {
292 return WOULD_BLOCK;
293 }
294 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
295 return DEAD_OBJECT;
296 }
297 return -error;
298 }
299
300 if (size_t(nWrite) != msgLength) {
301#if DEBUG_CHANNEL_MESSAGES
302 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800303 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700304#endif
305 return DEAD_OBJECT;
306 }
307
308#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800309 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700310#endif
311 return OK;
312}
313
314status_t InputChannel::receiveMessage(InputMessage* msg) {
315 ssize_t nRead;
316 do {
317 nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
318 } while (nRead == -1 && errno == EINTR);
319
320 if (nRead < 0) {
321 int error = errno;
322#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800323 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700324#endif
325 if (error == EAGAIN || error == EWOULDBLOCK) {
326 return WOULD_BLOCK;
327 }
328 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
329 return DEAD_OBJECT;
330 }
331 return -error;
332 }
333
334 if (nRead == 0) { // check for EOF
335#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800336 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700337#endif
338 return DEAD_OBJECT;
339 }
340
341 if (!msg->isValid(nRead)) {
342#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800343 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700344#endif
345 return BAD_VALUE;
346 }
347
348#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800349 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700350#endif
351 return OK;
352}
353
354sp<InputChannel> InputChannel::dup() const {
355 int fd = ::dup(getFd());
Yi Kong5bed83b2018-07-17 12:53:47 -0700356 return fd >= 0 ? new InputChannel(getName(), fd) : nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700357}
358
359
Robert Carr3720ed02018-08-08 16:08:27 -0700360status_t InputChannel::write(Parcel& out) const {
361 status_t s = out.writeString8(String8(getName().c_str()));
362
363 if (s != OK) {
364 return s;
365 }
Robert Carr803535b2018-08-02 16:38:15 -0700366 s = out.writeStrongBinder(mToken);
367 if (s != OK) {
368 return s;
369 }
Robert Carr3720ed02018-08-08 16:08:27 -0700370
371 s = out.writeDupFileDescriptor(getFd());
372
373 return s;
374}
375
376status_t InputChannel::read(const Parcel& from) {
377 mName = from.readString8();
Robert Carr803535b2018-08-02 16:38:15 -0700378 mToken = from.readStrongBinder();
Robert Carr3720ed02018-08-08 16:08:27 -0700379
380 int rawFd = from.readFileDescriptor();
381 setFd(::dup(rawFd));
382
383 if (mFd < 0) {
384 return BAD_VALUE;
385 }
386
387 return OK;
388}
389
Robert Carr803535b2018-08-02 16:38:15 -0700390sp<IBinder> InputChannel::getToken() const {
391 return mToken;
392}
393
394void InputChannel::setToken(const sp<IBinder>& token) {
395 if (mToken != nullptr) {
396 ALOGE("Assigning InputChannel (%s) a second handle?", mName.c_str());
397 }
398 mToken = token;
399}
400
Jeff Brown5912f952013-07-01 19:10:31 -0700401// --- InputPublisher ---
402
403InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
404 mChannel(channel) {
405}
406
407InputPublisher::~InputPublisher() {
408}
409
410status_t InputPublisher::publishKeyEvent(
411 uint32_t seq,
412 int32_t deviceId,
413 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100414 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700415 int32_t action,
416 int32_t flags,
417 int32_t keyCode,
418 int32_t scanCode,
419 int32_t metaState,
420 int32_t repeatCount,
421 nsecs_t downTime,
422 nsecs_t eventTime) {
423#if DEBUG_TRANSPORT_ACTIONS
424 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
425 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700426 "downTime=%" PRId64 ", eventTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800427 mChannel->getName().c_str(), seq,
Jeff Brown5912f952013-07-01 19:10:31 -0700428 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
429 downTime, eventTime);
430#endif
431
432 if (!seq) {
433 ALOGE("Attempted to publish a key event with sequence number 0.");
434 return BAD_VALUE;
435 }
436
437 InputMessage msg;
438 msg.header.type = InputMessage::TYPE_KEY;
439 msg.body.key.seq = seq;
440 msg.body.key.deviceId = deviceId;
441 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100442 msg.body.key.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700443 msg.body.key.action = action;
444 msg.body.key.flags = flags;
445 msg.body.key.keyCode = keyCode;
446 msg.body.key.scanCode = scanCode;
447 msg.body.key.metaState = metaState;
448 msg.body.key.repeatCount = repeatCount;
449 msg.body.key.downTime = downTime;
450 msg.body.key.eventTime = eventTime;
451 return mChannel->sendMessage(&msg);
452}
453
454status_t InputPublisher::publishMotionEvent(
455 uint32_t seq,
456 int32_t deviceId,
457 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700458 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700459 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100460 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700461 int32_t flags,
462 int32_t edgeFlags,
463 int32_t metaState,
464 int32_t buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800465 MotionClassification classification,
Jeff Brown5912f952013-07-01 19:10:31 -0700466 float xOffset,
467 float yOffset,
468 float xPrecision,
469 float yPrecision,
470 nsecs_t downTime,
471 nsecs_t eventTime,
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100472 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700473 const PointerProperties* pointerProperties,
474 const PointerCoords* pointerCoords) {
475#if DEBUG_TRANSPORT_ACTIONS
476 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800477 "displayId=%" PRId32 ", "
Michael Wright7b159c92015-05-14 14:48:03 +0100478 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800479 "metaState=0x%x, buttonState=0x%x, classification=%s, xOffset=%f, yOffset=%f, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700480 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
Michael Wright63ff3a82014-06-10 13:03:17 -0700481 "pointerCount=%" PRIu32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800482 mChannel->getName().c_str(), seq,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800483 deviceId, source, displayId, action, actionButton, flags, edgeFlags, metaState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800484 buttonState, motionClassificationToString(classification),
485 xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700486#endif
487
488 if (!seq) {
489 ALOGE("Attempted to publish a motion event with sequence number 0.");
490 return BAD_VALUE;
491 }
492
493 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700494 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800495 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700496 return BAD_VALUE;
497 }
498
499 InputMessage msg;
500 msg.header.type = InputMessage::TYPE_MOTION;
501 msg.body.motion.seq = seq;
502 msg.body.motion.deviceId = deviceId;
503 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700504 msg.body.motion.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700505 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100506 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700507 msg.body.motion.flags = flags;
508 msg.body.motion.edgeFlags = edgeFlags;
509 msg.body.motion.metaState = metaState;
510 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800511 msg.body.motion.classification = classification;
Jeff Brown5912f952013-07-01 19:10:31 -0700512 msg.body.motion.xOffset = xOffset;
513 msg.body.motion.yOffset = yOffset;
514 msg.body.motion.xPrecision = xPrecision;
515 msg.body.motion.yPrecision = yPrecision;
516 msg.body.motion.downTime = downTime;
517 msg.body.motion.eventTime = eventTime;
518 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100519 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700520 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
521 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
522 }
523 return mChannel->sendMessage(&msg);
524}
525
526status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
527#if DEBUG_TRANSPORT_ACTIONS
528 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800529 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700530#endif
531
532 InputMessage msg;
533 status_t result = mChannel->receiveMessage(&msg);
534 if (result) {
535 *outSeq = 0;
536 *outHandled = false;
537 return result;
538 }
539 if (msg.header.type != InputMessage::TYPE_FINISHED) {
540 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800541 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700542 return UNKNOWN_ERROR;
543 }
544 *outSeq = msg.body.finished.seq;
545 *outHandled = msg.body.finished.handled;
546 return OK;
547}
548
549// --- InputConsumer ---
550
551InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
552 mResampleTouch(isTouchResamplingEnabled()),
553 mChannel(channel), mMsgDeferred(false) {
554}
555
556InputConsumer::~InputConsumer() {
557}
558
559bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600560 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700561}
562
563status_t InputConsumer::consume(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800564 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700565#if DEBUG_TRANSPORT_ACTIONS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700566 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800567 mChannel->getName().c_str(), consumeBatches ? "true" : "false", frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700568#endif
569
570 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700571 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700572
573 // Fetch the next input message.
574 // Loop until an event can be returned or no additional events are received.
575 while (!*outEvent) {
576 if (mMsgDeferred) {
577 // mMsg contains a valid input message from the previous call to consume
578 // that has not yet been processed.
579 mMsgDeferred = false;
580 } else {
581 // Receive a fresh message.
582 status_t result = mChannel->receiveMessage(&mMsg);
583 if (result) {
584 // Consume the next batched event unless batches are being held for later.
585 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800586 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700587 if (*outEvent) {
588#if DEBUG_TRANSPORT_ACTIONS
589 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800590 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700591#endif
592 break;
593 }
594 }
595 return result;
596 }
597 }
598
599 switch (mMsg.header.type) {
600 case InputMessage::TYPE_KEY: {
601 KeyEvent* keyEvent = factory->createKeyEvent();
602 if (!keyEvent) return NO_MEMORY;
603
604 initializeKeyEvent(keyEvent, &mMsg);
605 *outSeq = mMsg.body.key.seq;
606 *outEvent = keyEvent;
607#if DEBUG_TRANSPORT_ACTIONS
608 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800609 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700610#endif
611 break;
612 }
613
gaoshange3e11a72017-08-08 16:11:31 +0800614 case InputMessage::TYPE_MOTION: {
Jeff Brown5912f952013-07-01 19:10:31 -0700615 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
616 if (batchIndex >= 0) {
617 Batch& batch = mBatches.editItemAt(batchIndex);
618 if (canAddSample(batch, &mMsg)) {
619 batch.samples.push(mMsg);
620#if DEBUG_TRANSPORT_ACTIONS
621 ALOGD("channel '%s' consumer ~ appended to batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800622 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700623#endif
624 break;
625 } else {
626 // We cannot append to the batch in progress, so we need to consume
627 // the previous batch right now and defer the new message until later.
628 mMsgDeferred = true;
629 status_t result = consumeSamples(factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800630 batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700631 mBatches.removeAt(batchIndex);
632 if (result) {
633 return result;
634 }
635#if DEBUG_TRANSPORT_ACTIONS
636 ALOGD("channel '%s' consumer ~ consumed batch event and "
637 "deferred current event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800638 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700639#endif
640 break;
641 }
642 }
643
644 // Start a new batch if needed.
645 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
646 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
647 mBatches.push();
648 Batch& batch = mBatches.editTop();
649 batch.samples.push(mMsg);
650#if DEBUG_TRANSPORT_ACTIONS
651 ALOGD("channel '%s' consumer ~ started batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800652 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700653#endif
654 break;
655 }
656
657 MotionEvent* motionEvent = factory->createMotionEvent();
658 if (! motionEvent) return NO_MEMORY;
659
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100660 updateTouchState(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700661 initializeMotionEvent(motionEvent, &mMsg);
662 *outSeq = mMsg.body.motion.seq;
663 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800664
Jeff Brown5912f952013-07-01 19:10:31 -0700665#if DEBUG_TRANSPORT_ACTIONS
666 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800667 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700668#endif
669 break;
670 }
671
672 default:
673 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800674 mChannel->getName().c_str(), mMsg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700675 return UNKNOWN_ERROR;
676 }
677 }
678 return OK;
679}
680
681status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800682 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700683 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700684 for (size_t i = mBatches.size(); i > 0; ) {
685 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700686 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700687 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800688 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700689 mBatches.removeAt(i);
690 return result;
691 }
692
Michael Wright32232172013-10-21 12:05:22 -0700693 nsecs_t sampleTime = frameTime;
694 if (mResampleTouch) {
695 sampleTime -= RESAMPLE_LATENCY;
696 }
Jeff Brown5912f952013-07-01 19:10:31 -0700697 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
698 if (split < 0) {
699 continue;
700 }
701
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800702 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700703 const InputMessage* next;
704 if (batch.samples.isEmpty()) {
705 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700706 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700707 } else {
708 next = &batch.samples.itemAt(0);
709 }
Michael Wright32232172013-10-21 12:05:22 -0700710 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700711 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
712 }
713 return result;
714 }
715
716 return WOULD_BLOCK;
717}
718
719status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800720 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700721 MotionEvent* motionEvent = factory->createMotionEvent();
722 if (! motionEvent) return NO_MEMORY;
723
724 uint32_t chain = 0;
725 for (size_t i = 0; i < count; i++) {
726 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100727 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700728 if (i) {
729 SeqChain seqChain;
730 seqChain.seq = msg.body.motion.seq;
731 seqChain.chain = chain;
732 mSeqChains.push(seqChain);
733 addSample(motionEvent, &msg);
734 } else {
735 initializeMotionEvent(motionEvent, &msg);
736 }
737 chain = msg.body.motion.seq;
738 }
739 batch.samples.removeItemsAt(0, count);
740
741 *outSeq = chain;
742 *outEvent = motionEvent;
743 return OK;
744}
745
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100746void InputConsumer::updateTouchState(InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700747 if (!mResampleTouch ||
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100748 !(msg.body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700749 return;
750 }
751
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100752 int32_t deviceId = msg.body.motion.deviceId;
753 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700754
755 // Update the touch state history to incorporate the new input message.
756 // If the message is in the past relative to the most recently produced resampled
757 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100758 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700759 case AMOTION_EVENT_ACTION_DOWN: {
760 ssize_t index = findTouchState(deviceId, source);
761 if (index < 0) {
762 mTouchStates.push();
763 index = mTouchStates.size() - 1;
764 }
765 TouchState& touchState = mTouchStates.editItemAt(index);
766 touchState.initialize(deviceId, source);
767 touchState.addHistory(msg);
768 break;
769 }
770
771 case AMOTION_EVENT_ACTION_MOVE: {
772 ssize_t index = findTouchState(deviceId, source);
773 if (index >= 0) {
774 TouchState& touchState = mTouchStates.editItemAt(index);
775 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800776 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700777 }
778 break;
779 }
780
781 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
782 ssize_t index = findTouchState(deviceId, source);
783 if (index >= 0) {
784 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100785 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700786 rewriteMessage(touchState, msg);
787 }
788 break;
789 }
790
791 case AMOTION_EVENT_ACTION_POINTER_UP: {
792 ssize_t index = findTouchState(deviceId, source);
793 if (index >= 0) {
794 TouchState& touchState = mTouchStates.editItemAt(index);
795 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100796 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700797 }
798 break;
799 }
800
801 case AMOTION_EVENT_ACTION_SCROLL: {
802 ssize_t index = findTouchState(deviceId, source);
803 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800804 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700805 rewriteMessage(touchState, msg);
806 }
807 break;
808 }
809
810 case AMOTION_EVENT_ACTION_UP:
811 case AMOTION_EVENT_ACTION_CANCEL: {
812 ssize_t index = findTouchState(deviceId, source);
813 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800814 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700815 rewriteMessage(touchState, msg);
816 mTouchStates.removeAt(index);
817 }
818 break;
819 }
820 }
821}
822
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800823/**
824 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
825 *
826 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
827 * is in the past relative to msg and the past two events do not contain identical coordinates),
828 * then invalidate the lastResample data for that pointer.
829 * If the two past events have identical coordinates, then lastResample data for that pointer will
830 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
831 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
832 * not equal to x0 is received.
833 */
834void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100835 nsecs_t eventTime = msg.body.motion.eventTime;
836 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
837 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700838 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100839 if (eventTime < state.lastResample.eventTime ||
840 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800841 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
842 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700843#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100844 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
845 resampleCoords.getX(), resampleCoords.getY(),
846 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700847#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800848 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
849 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
850 } else {
851 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100852 }
Jeff Brown5912f952013-07-01 19:10:31 -0700853 }
854 }
855}
856
857void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
858 const InputMessage* next) {
859 if (!mResampleTouch
860 || !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
861 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
862 return;
863 }
864
865 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
866 if (index < 0) {
867#if DEBUG_RESAMPLING
868 ALOGD("Not resampled, no touch state for device.");
869#endif
870 return;
871 }
872
873 TouchState& touchState = mTouchStates.editItemAt(index);
874 if (touchState.historySize < 1) {
875#if DEBUG_RESAMPLING
876 ALOGD("Not resampled, no history for device.");
877#endif
878 return;
879 }
880
881 // Ensure that the current sample has all of the pointers that need to be reported.
882 const History* current = touchState.getHistory(0);
883 size_t pointerCount = event->getPointerCount();
884 for (size_t i = 0; i < pointerCount; i++) {
885 uint32_t id = event->getPointerId(i);
886 if (!current->idBits.hasBit(id)) {
887#if DEBUG_RESAMPLING
888 ALOGD("Not resampled, missing id %d", id);
889#endif
890 return;
891 }
892 }
893
894 // Find the data to use for resampling.
895 const History* other;
896 History future;
897 float alpha;
898 if (next) {
899 // Interpolate between current sample and future sample.
900 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100901 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700902 other = &future;
903 nsecs_t delta = future.eventTime - current->eventTime;
904 if (delta < RESAMPLE_MIN_DELTA) {
905#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100906 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700907#endif
908 return;
909 }
910 alpha = float(sampleTime - current->eventTime) / delta;
911 } else if (touchState.historySize >= 2) {
912 // Extrapolate future sample using current sample and past sample.
913 // So other->eventTime <= current->eventTime <= sampleTime.
914 other = touchState.getHistory(1);
915 nsecs_t delta = current->eventTime - other->eventTime;
916 if (delta < RESAMPLE_MIN_DELTA) {
917#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100918 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700919#endif
920 return;
921 } else if (delta > RESAMPLE_MAX_DELTA) {
922#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100923 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700924#endif
925 return;
926 }
927 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
928 if (sampleTime > maxPredict) {
929#if DEBUG_RESAMPLING
930 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100931 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700932 sampleTime - current->eventTime, maxPredict - current->eventTime);
933#endif
934 sampleTime = maxPredict;
935 }
936 alpha = float(current->eventTime - sampleTime) / delta;
937 } else {
938#if DEBUG_RESAMPLING
939 ALOGD("Not resampled, insufficient data.");
940#endif
941 return;
942 }
943
944 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800945 History oldLastResample;
946 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700947 touchState.lastResample.eventTime = sampleTime;
948 touchState.lastResample.idBits.clear();
949 for (size_t i = 0; i < pointerCount; i++) {
950 uint32_t id = event->getPointerId(i);
951 touchState.lastResample.idToIndex[id] = i;
952 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800953 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
954 // We maintain the previously resampled value for this pointer (stored in
955 // oldLastResample) when the coordinates for this pointer haven't changed since then.
956 // This way we don't introduce artificial jitter when pointers haven't actually moved.
957
958 // We know here that the coordinates for the pointer haven't changed because we
959 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
960 // lastResample in place becasue the mapping from pointer ID to index may have changed.
961 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
962 continue;
963 }
964
Jeff Brown5912f952013-07-01 19:10:31 -0700965 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
966 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800967 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700968 if (other->idBits.hasBit(id)
969 && shouldResampleTool(event->getToolType(i))) {
970 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700971 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
972 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
973 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
974 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
975#if DEBUG_RESAMPLING
976 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
977 "other (%0.3f, %0.3f), alpha %0.3f",
978 id, resampledCoords.getX(), resampledCoords.getY(),
979 currentCoords.getX(), currentCoords.getY(),
980 otherCoords.getX(), otherCoords.getY(),
981 alpha);
982#endif
983 } else {
Jeff Brown5912f952013-07-01 19:10:31 -0700984#if DEBUG_RESAMPLING
985 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
986 id, resampledCoords.getX(), resampledCoords.getY(),
987 currentCoords.getX(), currentCoords.getY());
988#endif
989 }
990 }
991
992 event->addSample(sampleTime, touchState.lastResample.pointers);
993}
994
995bool InputConsumer::shouldResampleTool(int32_t toolType) {
996 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
997 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
998}
999
1000status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
1001#if DEBUG_TRANSPORT_ACTIONS
1002 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001003 mChannel->getName().c_str(), seq, handled ? "true" : "false");
Jeff Brown5912f952013-07-01 19:10:31 -07001004#endif
1005
1006 if (!seq) {
1007 ALOGE("Attempted to send a finished signal with sequence number 0.");
1008 return BAD_VALUE;
1009 }
1010
1011 // Send finished signals for the batch sequence chain first.
1012 size_t seqChainCount = mSeqChains.size();
1013 if (seqChainCount) {
1014 uint32_t currentSeq = seq;
1015 uint32_t chainSeqs[seqChainCount];
1016 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001017 for (size_t i = seqChainCount; i > 0; ) {
1018 i--;
Jeff Brown5912f952013-07-01 19:10:31 -07001019 const SeqChain& seqChain = mSeqChains.itemAt(i);
1020 if (seqChain.seq == currentSeq) {
1021 currentSeq = seqChain.chain;
1022 chainSeqs[chainIndex++] = currentSeq;
1023 mSeqChains.removeAt(i);
1024 }
1025 }
1026 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001027 while (!status && chainIndex > 0) {
1028 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001029 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1030 }
1031 if (status) {
1032 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001033 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001034 SeqChain seqChain;
1035 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1036 seqChain.chain = chainSeqs[chainIndex];
1037 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001038 if (!chainIndex) break;
1039 chainIndex--;
1040 }
Jeff Brown5912f952013-07-01 19:10:31 -07001041 return status;
1042 }
1043 }
1044
1045 // Send finished signal for the last message in the batch.
1046 return sendUnchainedFinishedSignal(seq, handled);
1047}
1048
1049status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1050 InputMessage msg;
1051 msg.header.type = InputMessage::TYPE_FINISHED;
1052 msg.body.finished.seq = seq;
1053 msg.body.finished.handled = handled;
1054 return mChannel->sendMessage(&msg);
1055}
1056
1057bool InputConsumer::hasDeferredEvent() const {
1058 return mMsgDeferred;
1059}
1060
1061bool InputConsumer::hasPendingBatch() const {
1062 return !mBatches.isEmpty();
1063}
1064
1065ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1066 for (size_t i = 0; i < mBatches.size(); i++) {
1067 const Batch& batch = mBatches.itemAt(i);
1068 const InputMessage& head = batch.samples.itemAt(0);
1069 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1070 return i;
1071 }
1072 }
1073 return -1;
1074}
1075
1076ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1077 for (size_t i = 0; i < mTouchStates.size(); i++) {
1078 const TouchState& touchState = mTouchStates.itemAt(i);
1079 if (touchState.deviceId == deviceId && touchState.source == source) {
1080 return i;
1081 }
1082 }
1083 return -1;
1084}
1085
1086void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
1087 event->initialize(
1088 msg->body.key.deviceId,
1089 msg->body.key.source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001090 msg->body.key.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001091 msg->body.key.action,
1092 msg->body.key.flags,
1093 msg->body.key.keyCode,
1094 msg->body.key.scanCode,
1095 msg->body.key.metaState,
1096 msg->body.key.repeatCount,
1097 msg->body.key.downTime,
1098 msg->body.key.eventTime);
1099}
1100
1101void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001102 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001103 PointerProperties pointerProperties[pointerCount];
1104 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001105 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001106 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1107 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1108 }
1109
1110 event->initialize(
1111 msg->body.motion.deviceId,
1112 msg->body.motion.source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001113 msg->body.motion.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001114 msg->body.motion.action,
Michael Wright7b159c92015-05-14 14:48:03 +01001115 msg->body.motion.actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -07001116 msg->body.motion.flags,
1117 msg->body.motion.edgeFlags,
1118 msg->body.motion.metaState,
1119 msg->body.motion.buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08001120 msg->body.motion.classification,
Jeff Brown5912f952013-07-01 19:10:31 -07001121 msg->body.motion.xOffset,
1122 msg->body.motion.yOffset,
1123 msg->body.motion.xPrecision,
1124 msg->body.motion.yPrecision,
1125 msg->body.motion.downTime,
1126 msg->body.motion.eventTime,
1127 pointerCount,
1128 pointerProperties,
1129 pointerCoords);
1130}
1131
1132void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001133 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001134 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001135 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001136 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1137 }
1138
1139 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1140 event->addSample(msg->body.motion.eventTime, pointerCoords);
1141}
1142
1143bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1144 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001145 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001146 if (head.body.motion.pointerCount != pointerCount
1147 || head.body.motion.action != msg->body.motion.action) {
1148 return false;
1149 }
1150 for (size_t i = 0; i < pointerCount; i++) {
1151 if (head.body.motion.pointers[i].properties
1152 != msg->body.motion.pointers[i].properties) {
1153 return false;
1154 }
1155 }
1156 return true;
1157}
1158
1159ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1160 size_t numSamples = batch.samples.size();
1161 size_t index = 0;
1162 while (index < numSamples
1163 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1164 index += 1;
1165 }
1166 return ssize_t(index) - 1;
1167}
1168
1169} // namespace android