blob: 0f7a1f04e5ef6762710c26b90e5327f13e040613 [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
62template<typename T>
63inline static T min(const T& a, const T& b) {
64 return a < b ? a : b;
65}
66
67inline static float lerp(float a, float b, float alpha) {
68 return a + alpha * (b - a);
69}
70
71// --- InputMessage ---
72
73bool InputMessage::isValid(size_t actualSize) const {
74 if (size() == actualSize) {
75 switch (header.type) {
76 case TYPE_KEY:
77 return true;
78 case TYPE_MOTION:
79 return body.motion.pointerCount > 0
80 && body.motion.pointerCount <= MAX_POINTERS;
81 case TYPE_FINISHED:
82 return true;
83 }
84 }
85 return false;
86}
87
88size_t InputMessage::size() const {
89 switch (header.type) {
90 case TYPE_KEY:
91 return sizeof(Header) + body.key.size();
92 case TYPE_MOTION:
93 return sizeof(Header) + body.motion.size();
94 case TYPE_FINISHED:
95 return sizeof(Header) + body.finished.size();
96 }
97 return sizeof(Header);
98}
99
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800100/**
101 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
102 * memory to zero, then only copy the valid bytes on a per-field basis.
103 */
104void InputMessage::getSanitizedCopy(InputMessage* msg) const {
105 memset(msg, 0, sizeof(*msg));
106
107 // Write the header
108 msg->header.type = header.type;
109
110 // Write the body
111 switch(header.type) {
112 case InputMessage::TYPE_KEY: {
113 // uint32_t seq
114 msg->body.key.seq = body.key.seq;
115 // nsecs_t eventTime
116 msg->body.key.eventTime = body.key.eventTime;
117 // int32_t deviceId
118 msg->body.key.deviceId = body.key.deviceId;
119 // int32_t source
120 msg->body.key.source = body.key.source;
121 // int32_t displayId
122 msg->body.key.displayId = body.key.displayId;
123 // int32_t action
124 msg->body.key.action = body.key.action;
125 // int32_t flags
126 msg->body.key.flags = body.key.flags;
127 // int32_t keyCode
128 msg->body.key.keyCode = body.key.keyCode;
129 // int32_t scanCode
130 msg->body.key.scanCode = body.key.scanCode;
131 // int32_t metaState
132 msg->body.key.metaState = body.key.metaState;
133 // int32_t repeatCount
134 msg->body.key.repeatCount = body.key.repeatCount;
135 // nsecs_t downTime
136 msg->body.key.downTime = body.key.downTime;
137 break;
138 }
139 case InputMessage::TYPE_MOTION: {
140 // uint32_t seq
141 msg->body.motion.seq = body.motion.seq;
142 // nsecs_t eventTime
143 msg->body.motion.eventTime = body.motion.eventTime;
144 // int32_t deviceId
145 msg->body.motion.deviceId = body.motion.deviceId;
146 // int32_t source
147 msg->body.motion.source = body.motion.source;
148 // int32_t displayId
149 msg->body.motion.displayId = body.motion.displayId;
150 // int32_t action
151 msg->body.motion.action = body.motion.action;
152 // int32_t actionButton
153 msg->body.motion.actionButton = body.motion.actionButton;
154 // int32_t flags
155 msg->body.motion.flags = body.motion.flags;
156 // int32_t metaState
157 msg->body.motion.metaState = body.motion.metaState;
158 // int32_t buttonState
159 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800160 // MotionClassification classification
161 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800162 // int32_t edgeFlags
163 msg->body.motion.edgeFlags = body.motion.edgeFlags;
164 // nsecs_t downTime
165 msg->body.motion.downTime = body.motion.downTime;
166 // float xOffset
167 msg->body.motion.xOffset = body.motion.xOffset;
168 // float yOffset
169 msg->body.motion.yOffset = body.motion.yOffset;
170 // float xPrecision
171 msg->body.motion.xPrecision = body.motion.xPrecision;
172 // float yPrecision
173 msg->body.motion.yPrecision = body.motion.yPrecision;
174 // uint32_t pointerCount
175 msg->body.motion.pointerCount = body.motion.pointerCount;
176 //struct Pointer pointers[MAX_POINTERS]
177 for (size_t i = 0; i < body.motion.pointerCount; i++) {
178 // PointerProperties properties
179 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
180 msg->body.motion.pointers[i].properties.toolType =
181 body.motion.pointers[i].properties.toolType,
182 // PointerCoords coords
183 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
184 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
185 memcpy(&msg->body.motion.pointers[i].coords.values[0],
186 &body.motion.pointers[i].coords.values[0],
187 count * (sizeof(body.motion.pointers[i].coords.values[0])));
188 }
189 break;
190 }
191 case InputMessage::TYPE_FINISHED: {
192 msg->body.finished.seq = body.finished.seq;
193 msg->body.finished.handled = body.finished.handled;
194 break;
195 }
196 default: {
197 LOG_FATAL("Unexpected message type %i", header.type);
198 break;
199 }
200 }
201}
Jeff Brown5912f952013-07-01 19:10:31 -0700202
203// --- InputChannel ---
204
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800205InputChannel::InputChannel(const std::string& name, int fd) :
Robert Carr3720ed02018-08-08 16:08:27 -0700206 mName(name) {
Jeff Brown5912f952013-07-01 19:10:31 -0700207#if DEBUG_CHANNEL_LIFECYCLE
208 ALOGD("Input channel constructed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800209 mName.c_str(), fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700210#endif
211
Robert Carr3720ed02018-08-08 16:08:27 -0700212 setFd(fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700213}
214
215InputChannel::~InputChannel() {
216#if DEBUG_CHANNEL_LIFECYCLE
217 ALOGD("Input channel destroyed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218 mName.c_str(), mFd);
Jeff Brown5912f952013-07-01 19:10:31 -0700219#endif
220
221 ::close(mFd);
222}
223
Robert Carr3720ed02018-08-08 16:08:27 -0700224void InputChannel::setFd(int fd) {
225 if (mFd > 0) {
226 ::close(mFd);
227 }
228 mFd = fd;
229 if (mFd > 0) {
230 int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
231 LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
232 "non-blocking. errno=%d", mName.c_str(), errno);
233 }
234}
235
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800236status_t InputChannel::openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700237 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
238 int sockets[2];
239 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
240 status_t result = -errno;
241 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800242 name.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700243 outServerChannel.clear();
244 outClientChannel.clear();
245 return result;
246 }
247
248 int bufferSize = SOCKET_BUFFER_SIZE;
249 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
250 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
251 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
252 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
253
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800254 std::string serverChannelName = name;
255 serverChannelName += " (server)";
Jeff Brown5912f952013-07-01 19:10:31 -0700256 outServerChannel = new InputChannel(serverChannelName, sockets[0]);
257
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800258 std::string clientChannelName = name;
259 clientChannelName += " (client)";
Jeff Brown5912f952013-07-01 19:10:31 -0700260 outClientChannel = new InputChannel(clientChannelName, sockets[1]);
261 return OK;
262}
263
264status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800265 const size_t msgLength = msg->size();
266 InputMessage cleanMsg;
267 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700268 ssize_t nWrite;
269 do {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800270 nWrite = ::send(mFd, &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700271 } while (nWrite == -1 && errno == EINTR);
272
273 if (nWrite < 0) {
274 int error = errno;
275#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800276 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.c_str(),
Jeff Brown5912f952013-07-01 19:10:31 -0700277 msg->header.type, error);
278#endif
279 if (error == EAGAIN || error == EWOULDBLOCK) {
280 return WOULD_BLOCK;
281 }
282 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
283 return DEAD_OBJECT;
284 }
285 return -error;
286 }
287
288 if (size_t(nWrite) != msgLength) {
289#if DEBUG_CHANNEL_MESSAGES
290 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800291 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700292#endif
293 return DEAD_OBJECT;
294 }
295
296#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800297 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700298#endif
299 return OK;
300}
301
302status_t InputChannel::receiveMessage(InputMessage* msg) {
303 ssize_t nRead;
304 do {
305 nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
306 } while (nRead == -1 && errno == EINTR);
307
308 if (nRead < 0) {
309 int error = errno;
310#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800311 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700312#endif
313 if (error == EAGAIN || error == EWOULDBLOCK) {
314 return WOULD_BLOCK;
315 }
316 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
317 return DEAD_OBJECT;
318 }
319 return -error;
320 }
321
322 if (nRead == 0) { // check for EOF
323#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800324 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700325#endif
326 return DEAD_OBJECT;
327 }
328
329 if (!msg->isValid(nRead)) {
330#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800331 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700332#endif
333 return BAD_VALUE;
334 }
335
336#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800337 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700338#endif
339 return OK;
340}
341
342sp<InputChannel> InputChannel::dup() const {
343 int fd = ::dup(getFd());
Yi Kong5bed83b2018-07-17 12:53:47 -0700344 return fd >= 0 ? new InputChannel(getName(), fd) : nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700345}
346
347
Robert Carr3720ed02018-08-08 16:08:27 -0700348status_t InputChannel::write(Parcel& out) const {
349 status_t s = out.writeString8(String8(getName().c_str()));
350
351 if (s != OK) {
352 return s;
353 }
Robert Carr803535b2018-08-02 16:38:15 -0700354 s = out.writeStrongBinder(mToken);
355 if (s != OK) {
356 return s;
357 }
Robert Carr3720ed02018-08-08 16:08:27 -0700358
359 s = out.writeDupFileDescriptor(getFd());
360
361 return s;
362}
363
364status_t InputChannel::read(const Parcel& from) {
365 mName = from.readString8();
Robert Carr803535b2018-08-02 16:38:15 -0700366 mToken = from.readStrongBinder();
Robert Carr3720ed02018-08-08 16:08:27 -0700367
368 int rawFd = from.readFileDescriptor();
369 setFd(::dup(rawFd));
370
371 if (mFd < 0) {
372 return BAD_VALUE;
373 }
374
375 return OK;
376}
377
Robert Carr803535b2018-08-02 16:38:15 -0700378sp<IBinder> InputChannel::getToken() const {
379 return mToken;
380}
381
382void InputChannel::setToken(const sp<IBinder>& token) {
383 if (mToken != nullptr) {
384 ALOGE("Assigning InputChannel (%s) a second handle?", mName.c_str());
385 }
386 mToken = token;
387}
388
Jeff Brown5912f952013-07-01 19:10:31 -0700389// --- InputPublisher ---
390
391InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
392 mChannel(channel) {
393}
394
395InputPublisher::~InputPublisher() {
396}
397
398status_t InputPublisher::publishKeyEvent(
399 uint32_t seq,
400 int32_t deviceId,
401 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100402 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700403 int32_t action,
404 int32_t flags,
405 int32_t keyCode,
406 int32_t scanCode,
407 int32_t metaState,
408 int32_t repeatCount,
409 nsecs_t downTime,
410 nsecs_t eventTime) {
411#if DEBUG_TRANSPORT_ACTIONS
412 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
413 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700414 "downTime=%" PRId64 ", eventTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800415 mChannel->getName().c_str(), seq,
Jeff Brown5912f952013-07-01 19:10:31 -0700416 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
417 downTime, eventTime);
418#endif
419
420 if (!seq) {
421 ALOGE("Attempted to publish a key event with sequence number 0.");
422 return BAD_VALUE;
423 }
424
425 InputMessage msg;
426 msg.header.type = InputMessage::TYPE_KEY;
427 msg.body.key.seq = seq;
428 msg.body.key.deviceId = deviceId;
429 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100430 msg.body.key.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700431 msg.body.key.action = action;
432 msg.body.key.flags = flags;
433 msg.body.key.keyCode = keyCode;
434 msg.body.key.scanCode = scanCode;
435 msg.body.key.metaState = metaState;
436 msg.body.key.repeatCount = repeatCount;
437 msg.body.key.downTime = downTime;
438 msg.body.key.eventTime = eventTime;
439 return mChannel->sendMessage(&msg);
440}
441
442status_t InputPublisher::publishMotionEvent(
443 uint32_t seq,
444 int32_t deviceId,
445 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700446 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700447 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100448 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700449 int32_t flags,
450 int32_t edgeFlags,
451 int32_t metaState,
452 int32_t buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800453 MotionClassification classification,
Jeff Brown5912f952013-07-01 19:10:31 -0700454 float xOffset,
455 float yOffset,
456 float xPrecision,
457 float yPrecision,
458 nsecs_t downTime,
459 nsecs_t eventTime,
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100460 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700461 const PointerProperties* pointerProperties,
462 const PointerCoords* pointerCoords) {
463#if DEBUG_TRANSPORT_ACTIONS
464 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800465 "displayId=%" PRId32 ", "
Michael Wright7b159c92015-05-14 14:48:03 +0100466 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800467 "metaState=0x%x, buttonState=0x%x, classification=%s, xOffset=%f, yOffset=%f, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700468 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
Michael Wright63ff3a82014-06-10 13:03:17 -0700469 "pointerCount=%" PRIu32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800470 mChannel->getName().c_str(), seq,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800471 deviceId, source, displayId, action, actionButton, flags, edgeFlags, metaState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800472 buttonState, motionClassificationToString(classification),
473 xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700474#endif
475
476 if (!seq) {
477 ALOGE("Attempted to publish a motion event with sequence number 0.");
478 return BAD_VALUE;
479 }
480
481 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700482 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800483 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700484 return BAD_VALUE;
485 }
486
487 InputMessage msg;
488 msg.header.type = InputMessage::TYPE_MOTION;
489 msg.body.motion.seq = seq;
490 msg.body.motion.deviceId = deviceId;
491 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700492 msg.body.motion.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700493 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100494 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700495 msg.body.motion.flags = flags;
496 msg.body.motion.edgeFlags = edgeFlags;
497 msg.body.motion.metaState = metaState;
498 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800499 msg.body.motion.classification = classification;
Jeff Brown5912f952013-07-01 19:10:31 -0700500 msg.body.motion.xOffset = xOffset;
501 msg.body.motion.yOffset = yOffset;
502 msg.body.motion.xPrecision = xPrecision;
503 msg.body.motion.yPrecision = yPrecision;
504 msg.body.motion.downTime = downTime;
505 msg.body.motion.eventTime = eventTime;
506 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100507 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700508 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
509 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
510 }
511 return mChannel->sendMessage(&msg);
512}
513
514status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
515#if DEBUG_TRANSPORT_ACTIONS
516 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800517 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700518#endif
519
520 InputMessage msg;
521 status_t result = mChannel->receiveMessage(&msg);
522 if (result) {
523 *outSeq = 0;
524 *outHandled = false;
525 return result;
526 }
527 if (msg.header.type != InputMessage::TYPE_FINISHED) {
528 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800529 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700530 return UNKNOWN_ERROR;
531 }
532 *outSeq = msg.body.finished.seq;
533 *outHandled = msg.body.finished.handled;
534 return OK;
535}
536
537// --- InputConsumer ---
538
539InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
540 mResampleTouch(isTouchResamplingEnabled()),
541 mChannel(channel), mMsgDeferred(false) {
542}
543
544InputConsumer::~InputConsumer() {
545}
546
547bool InputConsumer::isTouchResamplingEnabled() {
548 char value[PROPERTY_VALUE_MAX];
Yi Kong5bed83b2018-07-17 12:53:47 -0700549 int length = property_get("ro.input.noresample", value, nullptr);
Jeff Brown5912f952013-07-01 19:10:31 -0700550 if (length > 0) {
Michael Wrightad526f82013-10-10 18:54:12 -0700551 if (!strcmp("1", value)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700552 return false;
553 }
Michael Wrightad526f82013-10-10 18:54:12 -0700554 if (strcmp("0", value)) {
555 ALOGD("Unrecognized property value for 'ro.input.noresample'. "
Jeff Brown5912f952013-07-01 19:10:31 -0700556 "Use '1' or '0'.");
557 }
558 }
559 return true;
560}
561
562status_t InputConsumer::consume(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800563 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700564#if DEBUG_TRANSPORT_ACTIONS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700565 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800566 mChannel->getName().c_str(), consumeBatches ? "true" : "false", frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700567#endif
568
569 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700570 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700571
572 // Fetch the next input message.
573 // Loop until an event can be returned or no additional events are received.
574 while (!*outEvent) {
575 if (mMsgDeferred) {
576 // mMsg contains a valid input message from the previous call to consume
577 // that has not yet been processed.
578 mMsgDeferred = false;
579 } else {
580 // Receive a fresh message.
581 status_t result = mChannel->receiveMessage(&mMsg);
582 if (result) {
583 // Consume the next batched event unless batches are being held for later.
584 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800585 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700586 if (*outEvent) {
587#if DEBUG_TRANSPORT_ACTIONS
588 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800589 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700590#endif
591 break;
592 }
593 }
594 return result;
595 }
596 }
597
598 switch (mMsg.header.type) {
599 case InputMessage::TYPE_KEY: {
600 KeyEvent* keyEvent = factory->createKeyEvent();
601 if (!keyEvent) return NO_MEMORY;
602
603 initializeKeyEvent(keyEvent, &mMsg);
604 *outSeq = mMsg.body.key.seq;
605 *outEvent = keyEvent;
606#if DEBUG_TRANSPORT_ACTIONS
607 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800608 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700609#endif
610 break;
611 }
612
gaoshange3e11a72017-08-08 16:11:31 +0800613 case InputMessage::TYPE_MOTION: {
Jeff Brown5912f952013-07-01 19:10:31 -0700614 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
615 if (batchIndex >= 0) {
616 Batch& batch = mBatches.editItemAt(batchIndex);
617 if (canAddSample(batch, &mMsg)) {
618 batch.samples.push(mMsg);
619#if DEBUG_TRANSPORT_ACTIONS
620 ALOGD("channel '%s' consumer ~ appended to batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800621 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700622#endif
623 break;
624 } else {
625 // We cannot append to the batch in progress, so we need to consume
626 // the previous batch right now and defer the new message until later.
627 mMsgDeferred = true;
628 status_t result = consumeSamples(factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800629 batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700630 mBatches.removeAt(batchIndex);
631 if (result) {
632 return result;
633 }
634#if DEBUG_TRANSPORT_ACTIONS
635 ALOGD("channel '%s' consumer ~ consumed batch event and "
636 "deferred current event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800637 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700638#endif
639 break;
640 }
641 }
642
643 // Start a new batch if needed.
644 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
645 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
646 mBatches.push();
647 Batch& batch = mBatches.editTop();
648 batch.samples.push(mMsg);
649#if DEBUG_TRANSPORT_ACTIONS
650 ALOGD("channel '%s' consumer ~ started batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800651 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700652#endif
653 break;
654 }
655
656 MotionEvent* motionEvent = factory->createMotionEvent();
657 if (! motionEvent) return NO_MEMORY;
658
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100659 updateTouchState(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700660 initializeMotionEvent(motionEvent, &mMsg);
661 *outSeq = mMsg.body.motion.seq;
662 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800663
Jeff Brown5912f952013-07-01 19:10:31 -0700664#if DEBUG_TRANSPORT_ACTIONS
665 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800666 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700667#endif
668 break;
669 }
670
671 default:
672 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800673 mChannel->getName().c_str(), mMsg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700674 return UNKNOWN_ERROR;
675 }
676 }
677 return OK;
678}
679
680status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800681 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700682 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700683 for (size_t i = mBatches.size(); i > 0; ) {
684 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700685 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700686 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800687 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700688 mBatches.removeAt(i);
689 return result;
690 }
691
Michael Wright32232172013-10-21 12:05:22 -0700692 nsecs_t sampleTime = frameTime;
693 if (mResampleTouch) {
694 sampleTime -= RESAMPLE_LATENCY;
695 }
Jeff Brown5912f952013-07-01 19:10:31 -0700696 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
697 if (split < 0) {
698 continue;
699 }
700
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800701 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700702 const InputMessage* next;
703 if (batch.samples.isEmpty()) {
704 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700705 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700706 } else {
707 next = &batch.samples.itemAt(0);
708 }
Michael Wright32232172013-10-21 12:05:22 -0700709 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700710 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
711 }
712 return result;
713 }
714
715 return WOULD_BLOCK;
716}
717
718status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800719 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700720 MotionEvent* motionEvent = factory->createMotionEvent();
721 if (! motionEvent) return NO_MEMORY;
722
723 uint32_t chain = 0;
724 for (size_t i = 0; i < count; i++) {
725 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100726 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700727 if (i) {
728 SeqChain seqChain;
729 seqChain.seq = msg.body.motion.seq;
730 seqChain.chain = chain;
731 mSeqChains.push(seqChain);
732 addSample(motionEvent, &msg);
733 } else {
734 initializeMotionEvent(motionEvent, &msg);
735 }
736 chain = msg.body.motion.seq;
737 }
738 batch.samples.removeItemsAt(0, count);
739
740 *outSeq = chain;
741 *outEvent = motionEvent;
742 return OK;
743}
744
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100745void InputConsumer::updateTouchState(InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700746 if (!mResampleTouch ||
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100747 !(msg.body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700748 return;
749 }
750
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100751 int32_t deviceId = msg.body.motion.deviceId;
752 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700753
754 // Update the touch state history to incorporate the new input message.
755 // If the message is in the past relative to the most recently produced resampled
756 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100757 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700758 case AMOTION_EVENT_ACTION_DOWN: {
759 ssize_t index = findTouchState(deviceId, source);
760 if (index < 0) {
761 mTouchStates.push();
762 index = mTouchStates.size() - 1;
763 }
764 TouchState& touchState = mTouchStates.editItemAt(index);
765 touchState.initialize(deviceId, source);
766 touchState.addHistory(msg);
767 break;
768 }
769
770 case AMOTION_EVENT_ACTION_MOVE: {
771 ssize_t index = findTouchState(deviceId, source);
772 if (index >= 0) {
773 TouchState& touchState = mTouchStates.editItemAt(index);
774 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800775 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700776 }
777 break;
778 }
779
780 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
781 ssize_t index = findTouchState(deviceId, source);
782 if (index >= 0) {
783 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100784 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700785 rewriteMessage(touchState, msg);
786 }
787 break;
788 }
789
790 case AMOTION_EVENT_ACTION_POINTER_UP: {
791 ssize_t index = findTouchState(deviceId, source);
792 if (index >= 0) {
793 TouchState& touchState = mTouchStates.editItemAt(index);
794 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100795 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700796 }
797 break;
798 }
799
800 case AMOTION_EVENT_ACTION_SCROLL: {
801 ssize_t index = findTouchState(deviceId, source);
802 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800803 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700804 rewriteMessage(touchState, msg);
805 }
806 break;
807 }
808
809 case AMOTION_EVENT_ACTION_UP:
810 case AMOTION_EVENT_ACTION_CANCEL: {
811 ssize_t index = findTouchState(deviceId, source);
812 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800813 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700814 rewriteMessage(touchState, msg);
815 mTouchStates.removeAt(index);
816 }
817 break;
818 }
819 }
820}
821
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800822/**
823 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
824 *
825 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
826 * is in the past relative to msg and the past two events do not contain identical coordinates),
827 * then invalidate the lastResample data for that pointer.
828 * If the two past events have identical coordinates, then lastResample data for that pointer will
829 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
830 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
831 * not equal to x0 is received.
832 */
833void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100834 nsecs_t eventTime = msg.body.motion.eventTime;
835 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
836 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700837 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100838 if (eventTime < state.lastResample.eventTime ||
839 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800840 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
841 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700842#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100843 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
844 resampleCoords.getX(), resampleCoords.getY(),
845 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700846#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800847 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
848 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
849 } else {
850 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100851 }
Jeff Brown5912f952013-07-01 19:10:31 -0700852 }
853 }
854}
855
856void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
857 const InputMessage* next) {
858 if (!mResampleTouch
859 || !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
860 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
861 return;
862 }
863
864 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
865 if (index < 0) {
866#if DEBUG_RESAMPLING
867 ALOGD("Not resampled, no touch state for device.");
868#endif
869 return;
870 }
871
872 TouchState& touchState = mTouchStates.editItemAt(index);
873 if (touchState.historySize < 1) {
874#if DEBUG_RESAMPLING
875 ALOGD("Not resampled, no history for device.");
876#endif
877 return;
878 }
879
880 // Ensure that the current sample has all of the pointers that need to be reported.
881 const History* current = touchState.getHistory(0);
882 size_t pointerCount = event->getPointerCount();
883 for (size_t i = 0; i < pointerCount; i++) {
884 uint32_t id = event->getPointerId(i);
885 if (!current->idBits.hasBit(id)) {
886#if DEBUG_RESAMPLING
887 ALOGD("Not resampled, missing id %d", id);
888#endif
889 return;
890 }
891 }
892
893 // Find the data to use for resampling.
894 const History* other;
895 History future;
896 float alpha;
897 if (next) {
898 // Interpolate between current sample and future sample.
899 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100900 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700901 other = &future;
902 nsecs_t delta = future.eventTime - current->eventTime;
903 if (delta < RESAMPLE_MIN_DELTA) {
904#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100905 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700906#endif
907 return;
908 }
909 alpha = float(sampleTime - current->eventTime) / delta;
910 } else if (touchState.historySize >= 2) {
911 // Extrapolate future sample using current sample and past sample.
912 // So other->eventTime <= current->eventTime <= sampleTime.
913 other = touchState.getHistory(1);
914 nsecs_t delta = current->eventTime - other->eventTime;
915 if (delta < RESAMPLE_MIN_DELTA) {
916#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100917 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700918#endif
919 return;
920 } else if (delta > RESAMPLE_MAX_DELTA) {
921#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100922 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700923#endif
924 return;
925 }
926 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
927 if (sampleTime > maxPredict) {
928#if DEBUG_RESAMPLING
929 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100930 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700931 sampleTime - current->eventTime, maxPredict - current->eventTime);
932#endif
933 sampleTime = maxPredict;
934 }
935 alpha = float(current->eventTime - sampleTime) / delta;
936 } else {
937#if DEBUG_RESAMPLING
938 ALOGD("Not resampled, insufficient data.");
939#endif
940 return;
941 }
942
943 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800944 History oldLastResample;
945 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700946 touchState.lastResample.eventTime = sampleTime;
947 touchState.lastResample.idBits.clear();
948 for (size_t i = 0; i < pointerCount; i++) {
949 uint32_t id = event->getPointerId(i);
950 touchState.lastResample.idToIndex[id] = i;
951 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800952 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
953 // We maintain the previously resampled value for this pointer (stored in
954 // oldLastResample) when the coordinates for this pointer haven't changed since then.
955 // This way we don't introduce artificial jitter when pointers haven't actually moved.
956
957 // We know here that the coordinates for the pointer haven't changed because we
958 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
959 // lastResample in place becasue the mapping from pointer ID to index may have changed.
960 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
961 continue;
962 }
963
Jeff Brown5912f952013-07-01 19:10:31 -0700964 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
965 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800966 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700967 if (other->idBits.hasBit(id)
968 && shouldResampleTool(event->getToolType(i))) {
969 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700970 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
971 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
972 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
973 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
974#if DEBUG_RESAMPLING
975 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
976 "other (%0.3f, %0.3f), alpha %0.3f",
977 id, resampledCoords.getX(), resampledCoords.getY(),
978 currentCoords.getX(), currentCoords.getY(),
979 otherCoords.getX(), otherCoords.getY(),
980 alpha);
981#endif
982 } else {
Jeff Brown5912f952013-07-01 19:10:31 -0700983#if DEBUG_RESAMPLING
984 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
985 id, resampledCoords.getX(), resampledCoords.getY(),
986 currentCoords.getX(), currentCoords.getY());
987#endif
988 }
989 }
990
991 event->addSample(sampleTime, touchState.lastResample.pointers);
992}
993
994bool InputConsumer::shouldResampleTool(int32_t toolType) {
995 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
996 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
997}
998
999status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
1000#if DEBUG_TRANSPORT_ACTIONS
1001 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001002 mChannel->getName().c_str(), seq, handled ? "true" : "false");
Jeff Brown5912f952013-07-01 19:10:31 -07001003#endif
1004
1005 if (!seq) {
1006 ALOGE("Attempted to send a finished signal with sequence number 0.");
1007 return BAD_VALUE;
1008 }
1009
1010 // Send finished signals for the batch sequence chain first.
1011 size_t seqChainCount = mSeqChains.size();
1012 if (seqChainCount) {
1013 uint32_t currentSeq = seq;
1014 uint32_t chainSeqs[seqChainCount];
1015 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001016 for (size_t i = seqChainCount; i > 0; ) {
1017 i--;
Jeff Brown5912f952013-07-01 19:10:31 -07001018 const SeqChain& seqChain = mSeqChains.itemAt(i);
1019 if (seqChain.seq == currentSeq) {
1020 currentSeq = seqChain.chain;
1021 chainSeqs[chainIndex++] = currentSeq;
1022 mSeqChains.removeAt(i);
1023 }
1024 }
1025 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001026 while (!status && chainIndex > 0) {
1027 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001028 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1029 }
1030 if (status) {
1031 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001032 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001033 SeqChain seqChain;
1034 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1035 seqChain.chain = chainSeqs[chainIndex];
1036 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001037 if (!chainIndex) break;
1038 chainIndex--;
1039 }
Jeff Brown5912f952013-07-01 19:10:31 -07001040 return status;
1041 }
1042 }
1043
1044 // Send finished signal for the last message in the batch.
1045 return sendUnchainedFinishedSignal(seq, handled);
1046}
1047
1048status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1049 InputMessage msg;
1050 msg.header.type = InputMessage::TYPE_FINISHED;
1051 msg.body.finished.seq = seq;
1052 msg.body.finished.handled = handled;
1053 return mChannel->sendMessage(&msg);
1054}
1055
1056bool InputConsumer::hasDeferredEvent() const {
1057 return mMsgDeferred;
1058}
1059
1060bool InputConsumer::hasPendingBatch() const {
1061 return !mBatches.isEmpty();
1062}
1063
1064ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1065 for (size_t i = 0; i < mBatches.size(); i++) {
1066 const Batch& batch = mBatches.itemAt(i);
1067 const InputMessage& head = batch.samples.itemAt(0);
1068 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1069 return i;
1070 }
1071 }
1072 return -1;
1073}
1074
1075ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1076 for (size_t i = 0; i < mTouchStates.size(); i++) {
1077 const TouchState& touchState = mTouchStates.itemAt(i);
1078 if (touchState.deviceId == deviceId && touchState.source == source) {
1079 return i;
1080 }
1081 }
1082 return -1;
1083}
1084
1085void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
1086 event->initialize(
1087 msg->body.key.deviceId,
1088 msg->body.key.source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001089 msg->body.key.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001090 msg->body.key.action,
1091 msg->body.key.flags,
1092 msg->body.key.keyCode,
1093 msg->body.key.scanCode,
1094 msg->body.key.metaState,
1095 msg->body.key.repeatCount,
1096 msg->body.key.downTime,
1097 msg->body.key.eventTime);
1098}
1099
1100void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001101 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001102 PointerProperties pointerProperties[pointerCount];
1103 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001104 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001105 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1106 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1107 }
1108
1109 event->initialize(
1110 msg->body.motion.deviceId,
1111 msg->body.motion.source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001112 msg->body.motion.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001113 msg->body.motion.action,
Michael Wright7b159c92015-05-14 14:48:03 +01001114 msg->body.motion.actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -07001115 msg->body.motion.flags,
1116 msg->body.motion.edgeFlags,
1117 msg->body.motion.metaState,
1118 msg->body.motion.buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08001119 msg->body.motion.classification,
Jeff Brown5912f952013-07-01 19:10:31 -07001120 msg->body.motion.xOffset,
1121 msg->body.motion.yOffset,
1122 msg->body.motion.xPrecision,
1123 msg->body.motion.yPrecision,
1124 msg->body.motion.downTime,
1125 msg->body.motion.eventTime,
1126 pointerCount,
1127 pointerProperties,
1128 pointerCoords);
1129}
1130
1131void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001132 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001133 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001134 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001135 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1136 }
1137
1138 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1139 event->addSample(msg->body.motion.eventTime, pointerCoords);
1140}
1141
1142bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1143 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001144 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001145 if (head.body.motion.pointerCount != pointerCount
1146 || head.body.motion.action != msg->body.motion.action) {
1147 return false;
1148 }
1149 for (size_t i = 0; i < pointerCount; i++) {
1150 if (head.body.motion.pointers[i].properties
1151 != msg->body.motion.pointers[i].properties) {
1152 return false;
1153 }
1154 }
1155 return true;
1156}
1157
1158ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1159 size_t numSamples = batch.samples.size();
1160 size_t index = 0;
1161 while (index < numSamples
1162 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1163 index += 1;
1164 }
1165 return ssize_t(index) - 1;
1166}
1167
1168} // namespace android