blob: 32444f9092a123272c572cdbb0309473aa9bea9a [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
100
101// --- InputChannel ---
102
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800103InputChannel::InputChannel(const std::string& name, int fd) :
Robert Carr3720ed02018-08-08 16:08:27 -0700104 mName(name) {
Jeff Brown5912f952013-07-01 19:10:31 -0700105#if DEBUG_CHANNEL_LIFECYCLE
106 ALOGD("Input channel constructed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800107 mName.c_str(), fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700108#endif
109
Robert Carr3720ed02018-08-08 16:08:27 -0700110 setFd(fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700111}
112
113InputChannel::~InputChannel() {
114#if DEBUG_CHANNEL_LIFECYCLE
115 ALOGD("Input channel destroyed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800116 mName.c_str(), mFd);
Jeff Brown5912f952013-07-01 19:10:31 -0700117#endif
118
119 ::close(mFd);
120}
121
Robert Carr3720ed02018-08-08 16:08:27 -0700122void InputChannel::setFd(int fd) {
123 if (mFd > 0) {
124 ::close(mFd);
125 }
126 mFd = fd;
127 if (mFd > 0) {
128 int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
129 LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
130 "non-blocking. errno=%d", mName.c_str(), errno);
131 }
132}
133
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800134status_t InputChannel::openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700135 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
136 int sockets[2];
137 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
138 status_t result = -errno;
139 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800140 name.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700141 outServerChannel.clear();
142 outClientChannel.clear();
143 return result;
144 }
145
146 int bufferSize = SOCKET_BUFFER_SIZE;
147 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
148 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
149 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
150 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
151
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800152 std::string serverChannelName = name;
153 serverChannelName += " (server)";
Jeff Brown5912f952013-07-01 19:10:31 -0700154 outServerChannel = new InputChannel(serverChannelName, sockets[0]);
155
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800156 std::string clientChannelName = name;
157 clientChannelName += " (client)";
Jeff Brown5912f952013-07-01 19:10:31 -0700158 outClientChannel = new InputChannel(clientChannelName, sockets[1]);
159 return OK;
160}
161
162status_t InputChannel::sendMessage(const InputMessage* msg) {
163 size_t msgLength = msg->size();
164 ssize_t nWrite;
165 do {
166 nWrite = ::send(mFd, msg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
167 } while (nWrite == -1 && errno == EINTR);
168
169 if (nWrite < 0) {
170 int error = errno;
171#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800172 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.c_str(),
Jeff Brown5912f952013-07-01 19:10:31 -0700173 msg->header.type, error);
174#endif
175 if (error == EAGAIN || error == EWOULDBLOCK) {
176 return WOULD_BLOCK;
177 }
178 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
179 return DEAD_OBJECT;
180 }
181 return -error;
182 }
183
184 if (size_t(nWrite) != msgLength) {
185#if DEBUG_CHANNEL_MESSAGES
186 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800187 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700188#endif
189 return DEAD_OBJECT;
190 }
191
192#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800193 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700194#endif
195 return OK;
196}
197
198status_t InputChannel::receiveMessage(InputMessage* msg) {
199 ssize_t nRead;
200 do {
201 nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
202 } while (nRead == -1 && errno == EINTR);
203
204 if (nRead < 0) {
205 int error = errno;
206#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800207 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700208#endif
209 if (error == EAGAIN || error == EWOULDBLOCK) {
210 return WOULD_BLOCK;
211 }
212 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
213 return DEAD_OBJECT;
214 }
215 return -error;
216 }
217
218 if (nRead == 0) { // check for EOF
219#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700221#endif
222 return DEAD_OBJECT;
223 }
224
225 if (!msg->isValid(nRead)) {
226#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800227 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700228#endif
229 return BAD_VALUE;
230 }
231
232#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700234#endif
235 return OK;
236}
237
238sp<InputChannel> InputChannel::dup() const {
239 int fd = ::dup(getFd());
Yi Kong5bed83b2018-07-17 12:53:47 -0700240 return fd >= 0 ? new InputChannel(getName(), fd) : nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700241}
242
243
Robert Carr3720ed02018-08-08 16:08:27 -0700244status_t InputChannel::write(Parcel& out) const {
245 status_t s = out.writeString8(String8(getName().c_str()));
246
247 if (s != OK) {
248 return s;
249 }
250
251 s = out.writeDupFileDescriptor(getFd());
252
253 return s;
254}
255
256status_t InputChannel::read(const Parcel& from) {
257 mName = from.readString8();
258
259 int rawFd = from.readFileDescriptor();
260 setFd(::dup(rawFd));
261
262 if (mFd < 0) {
263 return BAD_VALUE;
264 }
265
266 return OK;
267}
268
Jeff Brown5912f952013-07-01 19:10:31 -0700269// --- InputPublisher ---
270
271InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
272 mChannel(channel) {
273}
274
275InputPublisher::~InputPublisher() {
276}
277
278status_t InputPublisher::publishKeyEvent(
279 uint32_t seq,
280 int32_t deviceId,
281 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100282 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700283 int32_t action,
284 int32_t flags,
285 int32_t keyCode,
286 int32_t scanCode,
287 int32_t metaState,
288 int32_t repeatCount,
289 nsecs_t downTime,
290 nsecs_t eventTime) {
291#if DEBUG_TRANSPORT_ACTIONS
292 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
293 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700294 "downTime=%" PRId64 ", eventTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800295 mChannel->getName().c_str(), seq,
Jeff Brown5912f952013-07-01 19:10:31 -0700296 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
297 downTime, eventTime);
298#endif
299
300 if (!seq) {
301 ALOGE("Attempted to publish a key event with sequence number 0.");
302 return BAD_VALUE;
303 }
304
305 InputMessage msg;
306 msg.header.type = InputMessage::TYPE_KEY;
307 msg.body.key.seq = seq;
308 msg.body.key.deviceId = deviceId;
309 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100310 msg.body.key.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700311 msg.body.key.action = action;
312 msg.body.key.flags = flags;
313 msg.body.key.keyCode = keyCode;
314 msg.body.key.scanCode = scanCode;
315 msg.body.key.metaState = metaState;
316 msg.body.key.repeatCount = repeatCount;
317 msg.body.key.downTime = downTime;
318 msg.body.key.eventTime = eventTime;
319 return mChannel->sendMessage(&msg);
320}
321
322status_t InputPublisher::publishMotionEvent(
323 uint32_t seq,
324 int32_t deviceId,
325 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700326 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700327 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100328 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700329 int32_t flags,
330 int32_t edgeFlags,
331 int32_t metaState,
332 int32_t buttonState,
333 float xOffset,
334 float yOffset,
335 float xPrecision,
336 float yPrecision,
337 nsecs_t downTime,
338 nsecs_t eventTime,
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100339 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700340 const PointerProperties* pointerProperties,
341 const PointerCoords* pointerCoords) {
342#if DEBUG_TRANSPORT_ACTIONS
343 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800344 "displayId=%" PRId32 ", "
Michael Wright7b159c92015-05-14 14:48:03 +0100345 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
346 "metaState=0x%x, buttonState=0x%x, xOffset=%f, yOffset=%f, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700347 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
Michael Wright63ff3a82014-06-10 13:03:17 -0700348 "pointerCount=%" PRIu32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800349 mChannel->getName().c_str(), seq,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800350 deviceId, source, displayId, action, actionButton, flags, edgeFlags, metaState,
351 buttonState, xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime,
352 pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700353#endif
354
355 if (!seq) {
356 ALOGE("Attempted to publish a motion event with sequence number 0.");
357 return BAD_VALUE;
358 }
359
360 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700361 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800362 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700363 return BAD_VALUE;
364 }
365
366 InputMessage msg;
367 msg.header.type = InputMessage::TYPE_MOTION;
368 msg.body.motion.seq = seq;
369 msg.body.motion.deviceId = deviceId;
370 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700371 msg.body.motion.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700372 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100373 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700374 msg.body.motion.flags = flags;
375 msg.body.motion.edgeFlags = edgeFlags;
376 msg.body.motion.metaState = metaState;
377 msg.body.motion.buttonState = buttonState;
378 msg.body.motion.xOffset = xOffset;
379 msg.body.motion.yOffset = yOffset;
380 msg.body.motion.xPrecision = xPrecision;
381 msg.body.motion.yPrecision = yPrecision;
382 msg.body.motion.downTime = downTime;
383 msg.body.motion.eventTime = eventTime;
384 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100385 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700386 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
387 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
388 }
389 return mChannel->sendMessage(&msg);
390}
391
392status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
393#if DEBUG_TRANSPORT_ACTIONS
394 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800395 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700396#endif
397
398 InputMessage msg;
399 status_t result = mChannel->receiveMessage(&msg);
400 if (result) {
401 *outSeq = 0;
402 *outHandled = false;
403 return result;
404 }
405 if (msg.header.type != InputMessage::TYPE_FINISHED) {
406 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800407 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700408 return UNKNOWN_ERROR;
409 }
410 *outSeq = msg.body.finished.seq;
411 *outHandled = msg.body.finished.handled;
412 return OK;
413}
414
415// --- InputConsumer ---
416
417InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
418 mResampleTouch(isTouchResamplingEnabled()),
419 mChannel(channel), mMsgDeferred(false) {
420}
421
422InputConsumer::~InputConsumer() {
423}
424
425bool InputConsumer::isTouchResamplingEnabled() {
426 char value[PROPERTY_VALUE_MAX];
Yi Kong5bed83b2018-07-17 12:53:47 -0700427 int length = property_get("ro.input.noresample", value, nullptr);
Jeff Brown5912f952013-07-01 19:10:31 -0700428 if (length > 0) {
Michael Wrightad526f82013-10-10 18:54:12 -0700429 if (!strcmp("1", value)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700430 return false;
431 }
Michael Wrightad526f82013-10-10 18:54:12 -0700432 if (strcmp("0", value)) {
433 ALOGD("Unrecognized property value for 'ro.input.noresample'. "
Jeff Brown5912f952013-07-01 19:10:31 -0700434 "Use '1' or '0'.");
435 }
436 }
437 return true;
438}
439
440status_t InputConsumer::consume(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800441 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700442#if DEBUG_TRANSPORT_ACTIONS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700443 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800444 mChannel->getName().c_str(), consumeBatches ? "true" : "false", frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700445#endif
446
447 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700448 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700449
450 // Fetch the next input message.
451 // Loop until an event can be returned or no additional events are received.
452 while (!*outEvent) {
453 if (mMsgDeferred) {
454 // mMsg contains a valid input message from the previous call to consume
455 // that has not yet been processed.
456 mMsgDeferred = false;
457 } else {
458 // Receive a fresh message.
459 status_t result = mChannel->receiveMessage(&mMsg);
460 if (result) {
461 // Consume the next batched event unless batches are being held for later.
462 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800463 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700464 if (*outEvent) {
465#if DEBUG_TRANSPORT_ACTIONS
466 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800467 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700468#endif
469 break;
470 }
471 }
472 return result;
473 }
474 }
475
476 switch (mMsg.header.type) {
477 case InputMessage::TYPE_KEY: {
478 KeyEvent* keyEvent = factory->createKeyEvent();
479 if (!keyEvent) return NO_MEMORY;
480
481 initializeKeyEvent(keyEvent, &mMsg);
482 *outSeq = mMsg.body.key.seq;
483 *outEvent = keyEvent;
484#if DEBUG_TRANSPORT_ACTIONS
485 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800486 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700487#endif
488 break;
489 }
490
gaoshange3e11a72017-08-08 16:11:31 +0800491 case InputMessage::TYPE_MOTION: {
Jeff Brown5912f952013-07-01 19:10:31 -0700492 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
493 if (batchIndex >= 0) {
494 Batch& batch = mBatches.editItemAt(batchIndex);
495 if (canAddSample(batch, &mMsg)) {
496 batch.samples.push(mMsg);
497#if DEBUG_TRANSPORT_ACTIONS
498 ALOGD("channel '%s' consumer ~ appended to batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800499 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700500#endif
501 break;
502 } else {
503 // We cannot append to the batch in progress, so we need to consume
504 // the previous batch right now and defer the new message until later.
505 mMsgDeferred = true;
506 status_t result = consumeSamples(factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800507 batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700508 mBatches.removeAt(batchIndex);
509 if (result) {
510 return result;
511 }
512#if DEBUG_TRANSPORT_ACTIONS
513 ALOGD("channel '%s' consumer ~ consumed batch event and "
514 "deferred current event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800515 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700516#endif
517 break;
518 }
519 }
520
521 // Start a new batch if needed.
522 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
523 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
524 mBatches.push();
525 Batch& batch = mBatches.editTop();
526 batch.samples.push(mMsg);
527#if DEBUG_TRANSPORT_ACTIONS
528 ALOGD("channel '%s' consumer ~ started batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800529 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700530#endif
531 break;
532 }
533
534 MotionEvent* motionEvent = factory->createMotionEvent();
535 if (! motionEvent) return NO_MEMORY;
536
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100537 updateTouchState(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700538 initializeMotionEvent(motionEvent, &mMsg);
539 *outSeq = mMsg.body.motion.seq;
540 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800541
Jeff Brown5912f952013-07-01 19:10:31 -0700542#if DEBUG_TRANSPORT_ACTIONS
543 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800544 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700545#endif
546 break;
547 }
548
549 default:
550 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800551 mChannel->getName().c_str(), mMsg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700552 return UNKNOWN_ERROR;
553 }
554 }
555 return OK;
556}
557
558status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800559 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700560 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700561 for (size_t i = mBatches.size(); i > 0; ) {
562 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700563 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700564 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800565 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700566 mBatches.removeAt(i);
567 return result;
568 }
569
Michael Wright32232172013-10-21 12:05:22 -0700570 nsecs_t sampleTime = frameTime;
571 if (mResampleTouch) {
572 sampleTime -= RESAMPLE_LATENCY;
573 }
Jeff Brown5912f952013-07-01 19:10:31 -0700574 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
575 if (split < 0) {
576 continue;
577 }
578
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800579 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700580 const InputMessage* next;
581 if (batch.samples.isEmpty()) {
582 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700583 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700584 } else {
585 next = &batch.samples.itemAt(0);
586 }
Michael Wright32232172013-10-21 12:05:22 -0700587 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700588 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
589 }
590 return result;
591 }
592
593 return WOULD_BLOCK;
594}
595
596status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800597 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700598 MotionEvent* motionEvent = factory->createMotionEvent();
599 if (! motionEvent) return NO_MEMORY;
600
601 uint32_t chain = 0;
602 for (size_t i = 0; i < count; i++) {
603 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100604 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700605 if (i) {
606 SeqChain seqChain;
607 seqChain.seq = msg.body.motion.seq;
608 seqChain.chain = chain;
609 mSeqChains.push(seqChain);
610 addSample(motionEvent, &msg);
611 } else {
612 initializeMotionEvent(motionEvent, &msg);
613 }
614 chain = msg.body.motion.seq;
615 }
616 batch.samples.removeItemsAt(0, count);
617
618 *outSeq = chain;
619 *outEvent = motionEvent;
620 return OK;
621}
622
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100623void InputConsumer::updateTouchState(InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700624 if (!mResampleTouch ||
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100625 !(msg.body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700626 return;
627 }
628
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100629 int32_t deviceId = msg.body.motion.deviceId;
630 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700631
632 // Update the touch state history to incorporate the new input message.
633 // If the message is in the past relative to the most recently produced resampled
634 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100635 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700636 case AMOTION_EVENT_ACTION_DOWN: {
637 ssize_t index = findTouchState(deviceId, source);
638 if (index < 0) {
639 mTouchStates.push();
640 index = mTouchStates.size() - 1;
641 }
642 TouchState& touchState = mTouchStates.editItemAt(index);
643 touchState.initialize(deviceId, source);
644 touchState.addHistory(msg);
645 break;
646 }
647
648 case AMOTION_EVENT_ACTION_MOVE: {
649 ssize_t index = findTouchState(deviceId, source);
650 if (index >= 0) {
651 TouchState& touchState = mTouchStates.editItemAt(index);
652 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800653 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700654 }
655 break;
656 }
657
658 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
659 ssize_t index = findTouchState(deviceId, source);
660 if (index >= 0) {
661 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100662 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700663 rewriteMessage(touchState, msg);
664 }
665 break;
666 }
667
668 case AMOTION_EVENT_ACTION_POINTER_UP: {
669 ssize_t index = findTouchState(deviceId, source);
670 if (index >= 0) {
671 TouchState& touchState = mTouchStates.editItemAt(index);
672 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100673 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700674 }
675 break;
676 }
677
678 case AMOTION_EVENT_ACTION_SCROLL: {
679 ssize_t index = findTouchState(deviceId, source);
680 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800681 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700682 rewriteMessage(touchState, msg);
683 }
684 break;
685 }
686
687 case AMOTION_EVENT_ACTION_UP:
688 case AMOTION_EVENT_ACTION_CANCEL: {
689 ssize_t index = findTouchState(deviceId, source);
690 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800691 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700692 rewriteMessage(touchState, msg);
693 mTouchStates.removeAt(index);
694 }
695 break;
696 }
697 }
698}
699
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800700/**
701 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
702 *
703 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
704 * is in the past relative to msg and the past two events do not contain identical coordinates),
705 * then invalidate the lastResample data for that pointer.
706 * If the two past events have identical coordinates, then lastResample data for that pointer will
707 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
708 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
709 * not equal to x0 is received.
710 */
711void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100712 nsecs_t eventTime = msg.body.motion.eventTime;
713 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
714 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700715 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100716 if (eventTime < state.lastResample.eventTime ||
717 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800718 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
719 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700720#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100721 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
722 resampleCoords.getX(), resampleCoords.getY(),
723 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700724#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800725 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
726 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
727 } else {
728 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100729 }
Jeff Brown5912f952013-07-01 19:10:31 -0700730 }
731 }
732}
733
734void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
735 const InputMessage* next) {
736 if (!mResampleTouch
737 || !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
738 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
739 return;
740 }
741
742 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
743 if (index < 0) {
744#if DEBUG_RESAMPLING
745 ALOGD("Not resampled, no touch state for device.");
746#endif
747 return;
748 }
749
750 TouchState& touchState = mTouchStates.editItemAt(index);
751 if (touchState.historySize < 1) {
752#if DEBUG_RESAMPLING
753 ALOGD("Not resampled, no history for device.");
754#endif
755 return;
756 }
757
758 // Ensure that the current sample has all of the pointers that need to be reported.
759 const History* current = touchState.getHistory(0);
760 size_t pointerCount = event->getPointerCount();
761 for (size_t i = 0; i < pointerCount; i++) {
762 uint32_t id = event->getPointerId(i);
763 if (!current->idBits.hasBit(id)) {
764#if DEBUG_RESAMPLING
765 ALOGD("Not resampled, missing id %d", id);
766#endif
767 return;
768 }
769 }
770
771 // Find the data to use for resampling.
772 const History* other;
773 History future;
774 float alpha;
775 if (next) {
776 // Interpolate between current sample and future sample.
777 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100778 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700779 other = &future;
780 nsecs_t delta = future.eventTime - current->eventTime;
781 if (delta < RESAMPLE_MIN_DELTA) {
782#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100783 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700784#endif
785 return;
786 }
787 alpha = float(sampleTime - current->eventTime) / delta;
788 } else if (touchState.historySize >= 2) {
789 // Extrapolate future sample using current sample and past sample.
790 // So other->eventTime <= current->eventTime <= sampleTime.
791 other = touchState.getHistory(1);
792 nsecs_t delta = current->eventTime - other->eventTime;
793 if (delta < RESAMPLE_MIN_DELTA) {
794#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100795 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700796#endif
797 return;
798 } else if (delta > RESAMPLE_MAX_DELTA) {
799#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100800 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700801#endif
802 return;
803 }
804 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
805 if (sampleTime > maxPredict) {
806#if DEBUG_RESAMPLING
807 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100808 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700809 sampleTime - current->eventTime, maxPredict - current->eventTime);
810#endif
811 sampleTime = maxPredict;
812 }
813 alpha = float(current->eventTime - sampleTime) / delta;
814 } else {
815#if DEBUG_RESAMPLING
816 ALOGD("Not resampled, insufficient data.");
817#endif
818 return;
819 }
820
821 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800822 History oldLastResample;
823 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700824 touchState.lastResample.eventTime = sampleTime;
825 touchState.lastResample.idBits.clear();
826 for (size_t i = 0; i < pointerCount; i++) {
827 uint32_t id = event->getPointerId(i);
828 touchState.lastResample.idToIndex[id] = i;
829 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800830 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
831 // We maintain the previously resampled value for this pointer (stored in
832 // oldLastResample) when the coordinates for this pointer haven't changed since then.
833 // This way we don't introduce artificial jitter when pointers haven't actually moved.
834
835 // We know here that the coordinates for the pointer haven't changed because we
836 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
837 // lastResample in place becasue the mapping from pointer ID to index may have changed.
838 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
839 continue;
840 }
841
Jeff Brown5912f952013-07-01 19:10:31 -0700842 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
843 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800844 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700845 if (other->idBits.hasBit(id)
846 && shouldResampleTool(event->getToolType(i))) {
847 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700848 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
849 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
850 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
851 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
852#if DEBUG_RESAMPLING
853 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
854 "other (%0.3f, %0.3f), alpha %0.3f",
855 id, resampledCoords.getX(), resampledCoords.getY(),
856 currentCoords.getX(), currentCoords.getY(),
857 otherCoords.getX(), otherCoords.getY(),
858 alpha);
859#endif
860 } else {
Jeff Brown5912f952013-07-01 19:10:31 -0700861#if DEBUG_RESAMPLING
862 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
863 id, resampledCoords.getX(), resampledCoords.getY(),
864 currentCoords.getX(), currentCoords.getY());
865#endif
866 }
867 }
868
869 event->addSample(sampleTime, touchState.lastResample.pointers);
870}
871
872bool InputConsumer::shouldResampleTool(int32_t toolType) {
873 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
874 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
875}
876
877status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
878#if DEBUG_TRANSPORT_ACTIONS
879 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800880 mChannel->getName().c_str(), seq, handled ? "true" : "false");
Jeff Brown5912f952013-07-01 19:10:31 -0700881#endif
882
883 if (!seq) {
884 ALOGE("Attempted to send a finished signal with sequence number 0.");
885 return BAD_VALUE;
886 }
887
888 // Send finished signals for the batch sequence chain first.
889 size_t seqChainCount = mSeqChains.size();
890 if (seqChainCount) {
891 uint32_t currentSeq = seq;
892 uint32_t chainSeqs[seqChainCount];
893 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -0700894 for (size_t i = seqChainCount; i > 0; ) {
895 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700896 const SeqChain& seqChain = mSeqChains.itemAt(i);
897 if (seqChain.seq == currentSeq) {
898 currentSeq = seqChain.chain;
899 chainSeqs[chainIndex++] = currentSeq;
900 mSeqChains.removeAt(i);
901 }
902 }
903 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -0700904 while (!status && chainIndex > 0) {
905 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -0700906 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
907 }
908 if (status) {
909 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +0800910 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -0700911 SeqChain seqChain;
912 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
913 seqChain.chain = chainSeqs[chainIndex];
914 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +0800915 if (!chainIndex) break;
916 chainIndex--;
917 }
Jeff Brown5912f952013-07-01 19:10:31 -0700918 return status;
919 }
920 }
921
922 // Send finished signal for the last message in the batch.
923 return sendUnchainedFinishedSignal(seq, handled);
924}
925
926status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
927 InputMessage msg;
928 msg.header.type = InputMessage::TYPE_FINISHED;
929 msg.body.finished.seq = seq;
930 msg.body.finished.handled = handled;
931 return mChannel->sendMessage(&msg);
932}
933
934bool InputConsumer::hasDeferredEvent() const {
935 return mMsgDeferred;
936}
937
938bool InputConsumer::hasPendingBatch() const {
939 return !mBatches.isEmpty();
940}
941
942ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
943 for (size_t i = 0; i < mBatches.size(); i++) {
944 const Batch& batch = mBatches.itemAt(i);
945 const InputMessage& head = batch.samples.itemAt(0);
946 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
947 return i;
948 }
949 }
950 return -1;
951}
952
953ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
954 for (size_t i = 0; i < mTouchStates.size(); i++) {
955 const TouchState& touchState = mTouchStates.itemAt(i);
956 if (touchState.deviceId == deviceId && touchState.source == source) {
957 return i;
958 }
959 }
960 return -1;
961}
962
963void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
964 event->initialize(
965 msg->body.key.deviceId,
966 msg->body.key.source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100967 msg->body.key.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700968 msg->body.key.action,
969 msg->body.key.flags,
970 msg->body.key.keyCode,
971 msg->body.key.scanCode,
972 msg->body.key.metaState,
973 msg->body.key.repeatCount,
974 msg->body.key.downTime,
975 msg->body.key.eventTime);
976}
977
978void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100979 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -0700980 PointerProperties pointerProperties[pointerCount];
981 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100982 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700983 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
984 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
985 }
986
987 event->initialize(
988 msg->body.motion.deviceId,
989 msg->body.motion.source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800990 msg->body.motion.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700991 msg->body.motion.action,
Michael Wright7b159c92015-05-14 14:48:03 +0100992 msg->body.motion.actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700993 msg->body.motion.flags,
994 msg->body.motion.edgeFlags,
995 msg->body.motion.metaState,
996 msg->body.motion.buttonState,
997 msg->body.motion.xOffset,
998 msg->body.motion.yOffset,
999 msg->body.motion.xPrecision,
1000 msg->body.motion.yPrecision,
1001 msg->body.motion.downTime,
1002 msg->body.motion.eventTime,
1003 pointerCount,
1004 pointerProperties,
1005 pointerCoords);
1006}
1007
1008void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001009 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001010 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001011 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001012 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1013 }
1014
1015 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1016 event->addSample(msg->body.motion.eventTime, pointerCoords);
1017}
1018
1019bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1020 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001021 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001022 if (head.body.motion.pointerCount != pointerCount
1023 || head.body.motion.action != msg->body.motion.action) {
1024 return false;
1025 }
1026 for (size_t i = 0; i < pointerCount; i++) {
1027 if (head.body.motion.pointers[i].properties
1028 != msg->body.motion.pointers[i].properties) {
1029 return false;
1030 }
1031 }
1032 return true;
1033}
1034
1035ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1036 size_t numSamples = batch.samples.size();
1037 size_t index = 0;
1038 while (index < numSamples
1039 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1040 index += 1;
1041 }
1042 return ssize_t(index) - 1;
1043}
1044
1045} // namespace android