blob: f33b210c4c1c4fd0b387f04ccf5e32590beec9ae [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;
160 // int32_t edgeFlags
161 msg->body.motion.edgeFlags = body.motion.edgeFlags;
162 // nsecs_t downTime
163 msg->body.motion.downTime = body.motion.downTime;
164 // float xOffset
165 msg->body.motion.xOffset = body.motion.xOffset;
166 // float yOffset
167 msg->body.motion.yOffset = body.motion.yOffset;
168 // float xPrecision
169 msg->body.motion.xPrecision = body.motion.xPrecision;
170 // float yPrecision
171 msg->body.motion.yPrecision = body.motion.yPrecision;
172 // uint32_t pointerCount
173 msg->body.motion.pointerCount = body.motion.pointerCount;
174 //struct Pointer pointers[MAX_POINTERS]
175 for (size_t i = 0; i < body.motion.pointerCount; i++) {
176 // PointerProperties properties
177 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
178 msg->body.motion.pointers[i].properties.toolType =
179 body.motion.pointers[i].properties.toolType,
180 // PointerCoords coords
181 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
182 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
183 memcpy(&msg->body.motion.pointers[i].coords.values[0],
184 &body.motion.pointers[i].coords.values[0],
185 count * (sizeof(body.motion.pointers[i].coords.values[0])));
186 }
187 break;
188 }
189 case InputMessage::TYPE_FINISHED: {
190 msg->body.finished.seq = body.finished.seq;
191 msg->body.finished.handled = body.finished.handled;
192 break;
193 }
194 default: {
195 LOG_FATAL("Unexpected message type %i", header.type);
196 break;
197 }
198 }
199}
Jeff Brown5912f952013-07-01 19:10:31 -0700200
201// --- InputChannel ---
202
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800203InputChannel::InputChannel(const std::string& name, int fd) :
Robert Carr3720ed02018-08-08 16:08:27 -0700204 mName(name) {
Jeff Brown5912f952013-07-01 19:10:31 -0700205#if DEBUG_CHANNEL_LIFECYCLE
206 ALOGD("Input channel constructed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800207 mName.c_str(), fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700208#endif
209
Robert Carr3720ed02018-08-08 16:08:27 -0700210 setFd(fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700211}
212
213InputChannel::~InputChannel() {
214#if DEBUG_CHANNEL_LIFECYCLE
215 ALOGD("Input channel destroyed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800216 mName.c_str(), mFd);
Jeff Brown5912f952013-07-01 19:10:31 -0700217#endif
218
219 ::close(mFd);
220}
221
Robert Carr3720ed02018-08-08 16:08:27 -0700222void InputChannel::setFd(int fd) {
223 if (mFd > 0) {
224 ::close(mFd);
225 }
226 mFd = fd;
227 if (mFd > 0) {
228 int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
229 LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
230 "non-blocking. errno=%d", mName.c_str(), errno);
231 }
232}
233
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800234status_t InputChannel::openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700235 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
236 int sockets[2];
237 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
238 status_t result = -errno;
239 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800240 name.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700241 outServerChannel.clear();
242 outClientChannel.clear();
243 return result;
244 }
245
246 int bufferSize = SOCKET_BUFFER_SIZE;
247 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
248 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
249 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
250 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
251
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800252 std::string serverChannelName = name;
253 serverChannelName += " (server)";
Jeff Brown5912f952013-07-01 19:10:31 -0700254 outServerChannel = new InputChannel(serverChannelName, sockets[0]);
255
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800256 std::string clientChannelName = name;
257 clientChannelName += " (client)";
Jeff Brown5912f952013-07-01 19:10:31 -0700258 outClientChannel = new InputChannel(clientChannelName, sockets[1]);
259 return OK;
260}
261
262status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800263 const size_t msgLength = msg->size();
264 InputMessage cleanMsg;
265 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700266 ssize_t nWrite;
267 do {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800268 nWrite = ::send(mFd, &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700269 } while (nWrite == -1 && errno == EINTR);
270
271 if (nWrite < 0) {
272 int error = errno;
273#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800274 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.c_str(),
Jeff Brown5912f952013-07-01 19:10:31 -0700275 msg->header.type, error);
276#endif
277 if (error == EAGAIN || error == EWOULDBLOCK) {
278 return WOULD_BLOCK;
279 }
280 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
281 return DEAD_OBJECT;
282 }
283 return -error;
284 }
285
286 if (size_t(nWrite) != msgLength) {
287#if DEBUG_CHANNEL_MESSAGES
288 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800289 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700290#endif
291 return DEAD_OBJECT;
292 }
293
294#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800295 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700296#endif
297 return OK;
298}
299
300status_t InputChannel::receiveMessage(InputMessage* msg) {
301 ssize_t nRead;
302 do {
303 nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
304 } while (nRead == -1 && errno == EINTR);
305
306 if (nRead < 0) {
307 int error = errno;
308#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800309 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700310#endif
311 if (error == EAGAIN || error == EWOULDBLOCK) {
312 return WOULD_BLOCK;
313 }
314 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
315 return DEAD_OBJECT;
316 }
317 return -error;
318 }
319
320 if (nRead == 0) { // check for EOF
321#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800322 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700323#endif
324 return DEAD_OBJECT;
325 }
326
327 if (!msg->isValid(nRead)) {
328#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800329 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700330#endif
331 return BAD_VALUE;
332 }
333
334#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800335 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700336#endif
337 return OK;
338}
339
340sp<InputChannel> InputChannel::dup() const {
341 int fd = ::dup(getFd());
Yi Kong5bed83b2018-07-17 12:53:47 -0700342 return fd >= 0 ? new InputChannel(getName(), fd) : nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700343}
344
345
Robert Carr3720ed02018-08-08 16:08:27 -0700346status_t InputChannel::write(Parcel& out) const {
347 status_t s = out.writeString8(String8(getName().c_str()));
348
349 if (s != OK) {
350 return s;
351 }
Robert Carr803535b2018-08-02 16:38:15 -0700352 s = out.writeStrongBinder(mToken);
353 if (s != OK) {
354 return s;
355 }
Robert Carr3720ed02018-08-08 16:08:27 -0700356
357 s = out.writeDupFileDescriptor(getFd());
358
359 return s;
360}
361
362status_t InputChannel::read(const Parcel& from) {
363 mName = from.readString8();
Robert Carr803535b2018-08-02 16:38:15 -0700364 mToken = from.readStrongBinder();
Robert Carr3720ed02018-08-08 16:08:27 -0700365
366 int rawFd = from.readFileDescriptor();
367 setFd(::dup(rawFd));
368
369 if (mFd < 0) {
370 return BAD_VALUE;
371 }
372
373 return OK;
374}
375
Robert Carr803535b2018-08-02 16:38:15 -0700376sp<IBinder> InputChannel::getToken() const {
377 return mToken;
378}
379
380void InputChannel::setToken(const sp<IBinder>& token) {
381 if (mToken != nullptr) {
382 ALOGE("Assigning InputChannel (%s) a second handle?", mName.c_str());
383 }
384 mToken = token;
385}
386
Jeff Brown5912f952013-07-01 19:10:31 -0700387// --- InputPublisher ---
388
389InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
390 mChannel(channel) {
391}
392
393InputPublisher::~InputPublisher() {
394}
395
396status_t InputPublisher::publishKeyEvent(
397 uint32_t seq,
398 int32_t deviceId,
399 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100400 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700401 int32_t action,
402 int32_t flags,
403 int32_t keyCode,
404 int32_t scanCode,
405 int32_t metaState,
406 int32_t repeatCount,
407 nsecs_t downTime,
408 nsecs_t eventTime) {
409#if DEBUG_TRANSPORT_ACTIONS
410 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
411 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700412 "downTime=%" PRId64 ", eventTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800413 mChannel->getName().c_str(), seq,
Jeff Brown5912f952013-07-01 19:10:31 -0700414 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
415 downTime, eventTime);
416#endif
417
418 if (!seq) {
419 ALOGE("Attempted to publish a key event with sequence number 0.");
420 return BAD_VALUE;
421 }
422
423 InputMessage msg;
424 msg.header.type = InputMessage::TYPE_KEY;
425 msg.body.key.seq = seq;
426 msg.body.key.deviceId = deviceId;
427 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100428 msg.body.key.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700429 msg.body.key.action = action;
430 msg.body.key.flags = flags;
431 msg.body.key.keyCode = keyCode;
432 msg.body.key.scanCode = scanCode;
433 msg.body.key.metaState = metaState;
434 msg.body.key.repeatCount = repeatCount;
435 msg.body.key.downTime = downTime;
436 msg.body.key.eventTime = eventTime;
437 return mChannel->sendMessage(&msg);
438}
439
440status_t InputPublisher::publishMotionEvent(
441 uint32_t seq,
442 int32_t deviceId,
443 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700444 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700445 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100446 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700447 int32_t flags,
448 int32_t edgeFlags,
449 int32_t metaState,
450 int32_t buttonState,
451 float xOffset,
452 float yOffset,
453 float xPrecision,
454 float yPrecision,
455 nsecs_t downTime,
456 nsecs_t eventTime,
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100457 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700458 const PointerProperties* pointerProperties,
459 const PointerCoords* pointerCoords) {
460#if DEBUG_TRANSPORT_ACTIONS
461 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800462 "displayId=%" PRId32 ", "
Michael Wright7b159c92015-05-14 14:48:03 +0100463 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
464 "metaState=0x%x, buttonState=0x%x, xOffset=%f, yOffset=%f, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700465 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
Michael Wright63ff3a82014-06-10 13:03:17 -0700466 "pointerCount=%" PRIu32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800467 mChannel->getName().c_str(), seq,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800468 deviceId, source, displayId, action, actionButton, flags, edgeFlags, metaState,
469 buttonState, xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime,
470 pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700471#endif
472
473 if (!seq) {
474 ALOGE("Attempted to publish a motion event with sequence number 0.");
475 return BAD_VALUE;
476 }
477
478 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700479 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800480 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700481 return BAD_VALUE;
482 }
483
484 InputMessage msg;
485 msg.header.type = InputMessage::TYPE_MOTION;
486 msg.body.motion.seq = seq;
487 msg.body.motion.deviceId = deviceId;
488 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700489 msg.body.motion.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700490 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100491 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700492 msg.body.motion.flags = flags;
493 msg.body.motion.edgeFlags = edgeFlags;
494 msg.body.motion.metaState = metaState;
495 msg.body.motion.buttonState = buttonState;
496 msg.body.motion.xOffset = xOffset;
497 msg.body.motion.yOffset = yOffset;
498 msg.body.motion.xPrecision = xPrecision;
499 msg.body.motion.yPrecision = yPrecision;
500 msg.body.motion.downTime = downTime;
501 msg.body.motion.eventTime = eventTime;
502 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100503 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700504 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
505 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
506 }
507 return mChannel->sendMessage(&msg);
508}
509
510status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
511#if DEBUG_TRANSPORT_ACTIONS
512 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800513 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700514#endif
515
516 InputMessage msg;
517 status_t result = mChannel->receiveMessage(&msg);
518 if (result) {
519 *outSeq = 0;
520 *outHandled = false;
521 return result;
522 }
523 if (msg.header.type != InputMessage::TYPE_FINISHED) {
524 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800525 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700526 return UNKNOWN_ERROR;
527 }
528 *outSeq = msg.body.finished.seq;
529 *outHandled = msg.body.finished.handled;
530 return OK;
531}
532
533// --- InputConsumer ---
534
535InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
536 mResampleTouch(isTouchResamplingEnabled()),
537 mChannel(channel), mMsgDeferred(false) {
538}
539
540InputConsumer::~InputConsumer() {
541}
542
543bool InputConsumer::isTouchResamplingEnabled() {
544 char value[PROPERTY_VALUE_MAX];
Yi Kong5bed83b2018-07-17 12:53:47 -0700545 int length = property_get("ro.input.noresample", value, nullptr);
Jeff Brown5912f952013-07-01 19:10:31 -0700546 if (length > 0) {
Michael Wrightad526f82013-10-10 18:54:12 -0700547 if (!strcmp("1", value)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700548 return false;
549 }
Michael Wrightad526f82013-10-10 18:54:12 -0700550 if (strcmp("0", value)) {
551 ALOGD("Unrecognized property value for 'ro.input.noresample'. "
Jeff Brown5912f952013-07-01 19:10:31 -0700552 "Use '1' or '0'.");
553 }
554 }
555 return true;
556}
557
558status_t InputConsumer::consume(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800559 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700560#if DEBUG_TRANSPORT_ACTIONS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700561 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800562 mChannel->getName().c_str(), consumeBatches ? "true" : "false", frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700563#endif
564
565 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700566 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700567
568 // Fetch the next input message.
569 // Loop until an event can be returned or no additional events are received.
570 while (!*outEvent) {
571 if (mMsgDeferred) {
572 // mMsg contains a valid input message from the previous call to consume
573 // that has not yet been processed.
574 mMsgDeferred = false;
575 } else {
576 // Receive a fresh message.
577 status_t result = mChannel->receiveMessage(&mMsg);
578 if (result) {
579 // Consume the next batched event unless batches are being held for later.
580 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800581 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700582 if (*outEvent) {
583#if DEBUG_TRANSPORT_ACTIONS
584 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800585 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700586#endif
587 break;
588 }
589 }
590 return result;
591 }
592 }
593
594 switch (mMsg.header.type) {
595 case InputMessage::TYPE_KEY: {
596 KeyEvent* keyEvent = factory->createKeyEvent();
597 if (!keyEvent) return NO_MEMORY;
598
599 initializeKeyEvent(keyEvent, &mMsg);
600 *outSeq = mMsg.body.key.seq;
601 *outEvent = keyEvent;
602#if DEBUG_TRANSPORT_ACTIONS
603 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800604 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700605#endif
606 break;
607 }
608
gaoshange3e11a72017-08-08 16:11:31 +0800609 case InputMessage::TYPE_MOTION: {
Jeff Brown5912f952013-07-01 19:10:31 -0700610 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
611 if (batchIndex >= 0) {
612 Batch& batch = mBatches.editItemAt(batchIndex);
613 if (canAddSample(batch, &mMsg)) {
614 batch.samples.push(mMsg);
615#if DEBUG_TRANSPORT_ACTIONS
616 ALOGD("channel '%s' consumer ~ appended to batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800617 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700618#endif
619 break;
620 } else {
621 // We cannot append to the batch in progress, so we need to consume
622 // the previous batch right now and defer the new message until later.
623 mMsgDeferred = true;
624 status_t result = consumeSamples(factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800625 batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700626 mBatches.removeAt(batchIndex);
627 if (result) {
628 return result;
629 }
630#if DEBUG_TRANSPORT_ACTIONS
631 ALOGD("channel '%s' consumer ~ consumed batch event and "
632 "deferred current event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800633 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700634#endif
635 break;
636 }
637 }
638
639 // Start a new batch if needed.
640 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
641 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
642 mBatches.push();
643 Batch& batch = mBatches.editTop();
644 batch.samples.push(mMsg);
645#if DEBUG_TRANSPORT_ACTIONS
646 ALOGD("channel '%s' consumer ~ started batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800647 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700648#endif
649 break;
650 }
651
652 MotionEvent* motionEvent = factory->createMotionEvent();
653 if (! motionEvent) return NO_MEMORY;
654
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100655 updateTouchState(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700656 initializeMotionEvent(motionEvent, &mMsg);
657 *outSeq = mMsg.body.motion.seq;
658 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800659
Jeff Brown5912f952013-07-01 19:10:31 -0700660#if DEBUG_TRANSPORT_ACTIONS
661 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800662 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700663#endif
664 break;
665 }
666
667 default:
668 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800669 mChannel->getName().c_str(), mMsg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700670 return UNKNOWN_ERROR;
671 }
672 }
673 return OK;
674}
675
676status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800677 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700678 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700679 for (size_t i = mBatches.size(); i > 0; ) {
680 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700681 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700682 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800683 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700684 mBatches.removeAt(i);
685 return result;
686 }
687
Michael Wright32232172013-10-21 12:05:22 -0700688 nsecs_t sampleTime = frameTime;
689 if (mResampleTouch) {
690 sampleTime -= RESAMPLE_LATENCY;
691 }
Jeff Brown5912f952013-07-01 19:10:31 -0700692 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
693 if (split < 0) {
694 continue;
695 }
696
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800697 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700698 const InputMessage* next;
699 if (batch.samples.isEmpty()) {
700 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700701 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700702 } else {
703 next = &batch.samples.itemAt(0);
704 }
Michael Wright32232172013-10-21 12:05:22 -0700705 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700706 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
707 }
708 return result;
709 }
710
711 return WOULD_BLOCK;
712}
713
714status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800715 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700716 MotionEvent* motionEvent = factory->createMotionEvent();
717 if (! motionEvent) return NO_MEMORY;
718
719 uint32_t chain = 0;
720 for (size_t i = 0; i < count; i++) {
721 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100722 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700723 if (i) {
724 SeqChain seqChain;
725 seqChain.seq = msg.body.motion.seq;
726 seqChain.chain = chain;
727 mSeqChains.push(seqChain);
728 addSample(motionEvent, &msg);
729 } else {
730 initializeMotionEvent(motionEvent, &msg);
731 }
732 chain = msg.body.motion.seq;
733 }
734 batch.samples.removeItemsAt(0, count);
735
736 *outSeq = chain;
737 *outEvent = motionEvent;
738 return OK;
739}
740
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100741void InputConsumer::updateTouchState(InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700742 if (!mResampleTouch ||
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100743 !(msg.body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700744 return;
745 }
746
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100747 int32_t deviceId = msg.body.motion.deviceId;
748 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700749
750 // Update the touch state history to incorporate the new input message.
751 // If the message is in the past relative to the most recently produced resampled
752 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100753 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700754 case AMOTION_EVENT_ACTION_DOWN: {
755 ssize_t index = findTouchState(deviceId, source);
756 if (index < 0) {
757 mTouchStates.push();
758 index = mTouchStates.size() - 1;
759 }
760 TouchState& touchState = mTouchStates.editItemAt(index);
761 touchState.initialize(deviceId, source);
762 touchState.addHistory(msg);
763 break;
764 }
765
766 case AMOTION_EVENT_ACTION_MOVE: {
767 ssize_t index = findTouchState(deviceId, source);
768 if (index >= 0) {
769 TouchState& touchState = mTouchStates.editItemAt(index);
770 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800771 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700772 }
773 break;
774 }
775
776 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
777 ssize_t index = findTouchState(deviceId, source);
778 if (index >= 0) {
779 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100780 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700781 rewriteMessage(touchState, msg);
782 }
783 break;
784 }
785
786 case AMOTION_EVENT_ACTION_POINTER_UP: {
787 ssize_t index = findTouchState(deviceId, source);
788 if (index >= 0) {
789 TouchState& touchState = mTouchStates.editItemAt(index);
790 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100791 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700792 }
793 break;
794 }
795
796 case AMOTION_EVENT_ACTION_SCROLL: {
797 ssize_t index = findTouchState(deviceId, source);
798 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800799 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700800 rewriteMessage(touchState, msg);
801 }
802 break;
803 }
804
805 case AMOTION_EVENT_ACTION_UP:
806 case AMOTION_EVENT_ACTION_CANCEL: {
807 ssize_t index = findTouchState(deviceId, source);
808 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800809 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700810 rewriteMessage(touchState, msg);
811 mTouchStates.removeAt(index);
812 }
813 break;
814 }
815 }
816}
817
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800818/**
819 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
820 *
821 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
822 * is in the past relative to msg and the past two events do not contain identical coordinates),
823 * then invalidate the lastResample data for that pointer.
824 * If the two past events have identical coordinates, then lastResample data for that pointer will
825 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
826 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
827 * not equal to x0 is received.
828 */
829void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100830 nsecs_t eventTime = msg.body.motion.eventTime;
831 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
832 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700833 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100834 if (eventTime < state.lastResample.eventTime ||
835 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800836 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
837 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700838#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100839 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
840 resampleCoords.getX(), resampleCoords.getY(),
841 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700842#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800843 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
844 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
845 } else {
846 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100847 }
Jeff Brown5912f952013-07-01 19:10:31 -0700848 }
849 }
850}
851
852void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
853 const InputMessage* next) {
854 if (!mResampleTouch
855 || !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
856 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
857 return;
858 }
859
860 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
861 if (index < 0) {
862#if DEBUG_RESAMPLING
863 ALOGD("Not resampled, no touch state for device.");
864#endif
865 return;
866 }
867
868 TouchState& touchState = mTouchStates.editItemAt(index);
869 if (touchState.historySize < 1) {
870#if DEBUG_RESAMPLING
871 ALOGD("Not resampled, no history for device.");
872#endif
873 return;
874 }
875
876 // Ensure that the current sample has all of the pointers that need to be reported.
877 const History* current = touchState.getHistory(0);
878 size_t pointerCount = event->getPointerCount();
879 for (size_t i = 0; i < pointerCount; i++) {
880 uint32_t id = event->getPointerId(i);
881 if (!current->idBits.hasBit(id)) {
882#if DEBUG_RESAMPLING
883 ALOGD("Not resampled, missing id %d", id);
884#endif
885 return;
886 }
887 }
888
889 // Find the data to use for resampling.
890 const History* other;
891 History future;
892 float alpha;
893 if (next) {
894 // Interpolate between current sample and future sample.
895 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100896 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700897 other = &future;
898 nsecs_t delta = future.eventTime - current->eventTime;
899 if (delta < RESAMPLE_MIN_DELTA) {
900#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100901 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700902#endif
903 return;
904 }
905 alpha = float(sampleTime - current->eventTime) / delta;
906 } else if (touchState.historySize >= 2) {
907 // Extrapolate future sample using current sample and past sample.
908 // So other->eventTime <= current->eventTime <= sampleTime.
909 other = touchState.getHistory(1);
910 nsecs_t delta = current->eventTime - other->eventTime;
911 if (delta < RESAMPLE_MIN_DELTA) {
912#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100913 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700914#endif
915 return;
916 } else if (delta > RESAMPLE_MAX_DELTA) {
917#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100918 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700919#endif
920 return;
921 }
922 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
923 if (sampleTime > maxPredict) {
924#if DEBUG_RESAMPLING
925 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100926 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700927 sampleTime - current->eventTime, maxPredict - current->eventTime);
928#endif
929 sampleTime = maxPredict;
930 }
931 alpha = float(current->eventTime - sampleTime) / delta;
932 } else {
933#if DEBUG_RESAMPLING
934 ALOGD("Not resampled, insufficient data.");
935#endif
936 return;
937 }
938
939 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800940 History oldLastResample;
941 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700942 touchState.lastResample.eventTime = sampleTime;
943 touchState.lastResample.idBits.clear();
944 for (size_t i = 0; i < pointerCount; i++) {
945 uint32_t id = event->getPointerId(i);
946 touchState.lastResample.idToIndex[id] = i;
947 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800948 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
949 // We maintain the previously resampled value for this pointer (stored in
950 // oldLastResample) when the coordinates for this pointer haven't changed since then.
951 // This way we don't introduce artificial jitter when pointers haven't actually moved.
952
953 // We know here that the coordinates for the pointer haven't changed because we
954 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
955 // lastResample in place becasue the mapping from pointer ID to index may have changed.
956 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
957 continue;
958 }
959
Jeff Brown5912f952013-07-01 19:10:31 -0700960 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
961 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800962 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700963 if (other->idBits.hasBit(id)
964 && shouldResampleTool(event->getToolType(i))) {
965 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700966 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
967 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
968 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
969 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
970#if DEBUG_RESAMPLING
971 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
972 "other (%0.3f, %0.3f), alpha %0.3f",
973 id, resampledCoords.getX(), resampledCoords.getY(),
974 currentCoords.getX(), currentCoords.getY(),
975 otherCoords.getX(), otherCoords.getY(),
976 alpha);
977#endif
978 } else {
Jeff Brown5912f952013-07-01 19:10:31 -0700979#if DEBUG_RESAMPLING
980 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
981 id, resampledCoords.getX(), resampledCoords.getY(),
982 currentCoords.getX(), currentCoords.getY());
983#endif
984 }
985 }
986
987 event->addSample(sampleTime, touchState.lastResample.pointers);
988}
989
990bool InputConsumer::shouldResampleTool(int32_t toolType) {
991 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
992 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
993}
994
995status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
996#if DEBUG_TRANSPORT_ACTIONS
997 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800998 mChannel->getName().c_str(), seq, handled ? "true" : "false");
Jeff Brown5912f952013-07-01 19:10:31 -0700999#endif
1000
1001 if (!seq) {
1002 ALOGE("Attempted to send a finished signal with sequence number 0.");
1003 return BAD_VALUE;
1004 }
1005
1006 // Send finished signals for the batch sequence chain first.
1007 size_t seqChainCount = mSeqChains.size();
1008 if (seqChainCount) {
1009 uint32_t currentSeq = seq;
1010 uint32_t chainSeqs[seqChainCount];
1011 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001012 for (size_t i = seqChainCount; i > 0; ) {
1013 i--;
Jeff Brown5912f952013-07-01 19:10:31 -07001014 const SeqChain& seqChain = mSeqChains.itemAt(i);
1015 if (seqChain.seq == currentSeq) {
1016 currentSeq = seqChain.chain;
1017 chainSeqs[chainIndex++] = currentSeq;
1018 mSeqChains.removeAt(i);
1019 }
1020 }
1021 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001022 while (!status && chainIndex > 0) {
1023 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001024 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1025 }
1026 if (status) {
1027 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001028 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001029 SeqChain seqChain;
1030 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1031 seqChain.chain = chainSeqs[chainIndex];
1032 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001033 if (!chainIndex) break;
1034 chainIndex--;
1035 }
Jeff Brown5912f952013-07-01 19:10:31 -07001036 return status;
1037 }
1038 }
1039
1040 // Send finished signal for the last message in the batch.
1041 return sendUnchainedFinishedSignal(seq, handled);
1042}
1043
1044status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1045 InputMessage msg;
1046 msg.header.type = InputMessage::TYPE_FINISHED;
1047 msg.body.finished.seq = seq;
1048 msg.body.finished.handled = handled;
1049 return mChannel->sendMessage(&msg);
1050}
1051
1052bool InputConsumer::hasDeferredEvent() const {
1053 return mMsgDeferred;
1054}
1055
1056bool InputConsumer::hasPendingBatch() const {
1057 return !mBatches.isEmpty();
1058}
1059
1060ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1061 for (size_t i = 0; i < mBatches.size(); i++) {
1062 const Batch& batch = mBatches.itemAt(i);
1063 const InputMessage& head = batch.samples.itemAt(0);
1064 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1065 return i;
1066 }
1067 }
1068 return -1;
1069}
1070
1071ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1072 for (size_t i = 0; i < mTouchStates.size(); i++) {
1073 const TouchState& touchState = mTouchStates.itemAt(i);
1074 if (touchState.deviceId == deviceId && touchState.source == source) {
1075 return i;
1076 }
1077 }
1078 return -1;
1079}
1080
1081void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
1082 event->initialize(
1083 msg->body.key.deviceId,
1084 msg->body.key.source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001085 msg->body.key.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001086 msg->body.key.action,
1087 msg->body.key.flags,
1088 msg->body.key.keyCode,
1089 msg->body.key.scanCode,
1090 msg->body.key.metaState,
1091 msg->body.key.repeatCount,
1092 msg->body.key.downTime,
1093 msg->body.key.eventTime);
1094}
1095
1096void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001097 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001098 PointerProperties pointerProperties[pointerCount];
1099 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001100 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001101 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1102 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1103 }
1104
1105 event->initialize(
1106 msg->body.motion.deviceId,
1107 msg->body.motion.source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001108 msg->body.motion.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001109 msg->body.motion.action,
Michael Wright7b159c92015-05-14 14:48:03 +01001110 msg->body.motion.actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -07001111 msg->body.motion.flags,
1112 msg->body.motion.edgeFlags,
1113 msg->body.motion.metaState,
1114 msg->body.motion.buttonState,
1115 msg->body.motion.xOffset,
1116 msg->body.motion.yOffset,
1117 msg->body.motion.xPrecision,
1118 msg->body.motion.yPrecision,
1119 msg->body.motion.downTime,
1120 msg->body.motion.eventTime,
1121 pointerCount,
1122 pointerProperties,
1123 pointerCoords);
1124}
1125
1126void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001127 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001128 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001129 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001130 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1131 }
1132
1133 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1134 event->addSample(msg->body.motion.eventTime, pointerCoords);
1135}
1136
1137bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1138 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001139 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001140 if (head.body.motion.pointerCount != pointerCount
1141 || head.body.motion.action != msg->body.motion.action) {
1142 return false;
1143 }
1144 for (size_t i = 0; i < pointerCount; i++) {
1145 if (head.body.motion.pointers[i].properties
1146 != msg->body.motion.pointers[i].properties) {
1147 return false;
1148 }
1149 }
1150 return true;
1151}
1152
1153ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1154 size_t numSamples = batch.samples.size();
1155 size_t index = 0;
1156 while (index < numSamples
1157 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1158 index += 1;
1159 }
1160 return ssize_t(index) - 1;
1161}
1162
1163} // namespace android