blob: c18739a84a6c7646fd12632252e7a979ec56e1e2 [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
Jeff Brown5912f952013-07-01 19:10:31 -070033#include <input/InputTransport.h>
34
Jeff Brown5912f952013-07-01 19:10:31 -070035namespace android {
36
37// Socket buffer size. The default is typically about 128KB, which is much larger than
38// we really need. So we make it smaller. It just needs to be big enough to hold
39// a few dozen large multi-finger motion events in the case where an application gets
40// behind processing touches.
41static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
42
43// Nanoseconds per milliseconds.
44static const nsecs_t NANOS_PER_MS = 1000000;
45
46// Latency added during resampling. A few milliseconds doesn't hurt much but
47// reduces the impact of mispredicted touch positions.
48static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
49
50// Minimum time difference between consecutive samples before attempting to resample.
51static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
52
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070053// Maximum time difference between consecutive samples before attempting to resample
54// by extrapolation.
55static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
56
Jeff Brown5912f952013-07-01 19:10:31 -070057// Maximum time to predict forward from the last known state, to avoid predicting too
58// far into the future. This time is further bounded by 50% of the last time delta.
59static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
60
61template<typename T>
62inline static T min(const T& a, const T& b) {
63 return a < b ? a : b;
64}
65
66inline static float lerp(float a, float b, float alpha) {
67 return a + alpha * (b - a);
68}
69
70// --- InputMessage ---
71
72bool InputMessage::isValid(size_t actualSize) const {
73 if (size() == actualSize) {
74 switch (header.type) {
75 case TYPE_KEY:
76 return true;
77 case TYPE_MOTION:
78 return body.motion.pointerCount > 0
79 && body.motion.pointerCount <= MAX_POINTERS;
80 case TYPE_FINISHED:
81 return true;
82 }
83 }
84 return false;
85}
86
87size_t InputMessage::size() const {
88 switch (header.type) {
89 case TYPE_KEY:
90 return sizeof(Header) + body.key.size();
91 case TYPE_MOTION:
92 return sizeof(Header) + body.motion.size();
93 case TYPE_FINISHED:
94 return sizeof(Header) + body.finished.size();
95 }
96 return sizeof(Header);
97}
98
Siarhei Vishniakoucb2f0ce2018-11-16 22:18:53 -080099/**
100 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
101 * memory to zero, then only copy the valid bytes on a per-field basis.
102 */
103void InputMessage::getSanitizedCopy(InputMessage* msg) const {
104 memset(msg, 0, sizeof(*msg));
105
106 // Write the header
107 msg->header.type = header.type;
108
109 // Write the body
110 switch(header.type) {
111 case InputMessage::TYPE_KEY: {
112 // uint32_t seq
113 msg->body.key.seq = body.key.seq;
114 // nsecs_t eventTime
115 msg->body.key.eventTime = body.key.eventTime;
116 // int32_t deviceId
117 msg->body.key.deviceId = body.key.deviceId;
118 // int32_t source
119 msg->body.key.source = body.key.source;
120 // int32_t action
121 msg->body.key.action = body.key.action;
122 // int32_t flags
123 msg->body.key.flags = body.key.flags;
124 // int32_t keyCode
125 msg->body.key.keyCode = body.key.keyCode;
126 // int32_t scanCode
127 msg->body.key.scanCode = body.key.scanCode;
128 // int32_t metaState
129 msg->body.key.metaState = body.key.metaState;
130 // int32_t repeatCount
131 msg->body.key.repeatCount = body.key.repeatCount;
132 // nsecs_t downTime
133 msg->body.key.downTime = body.key.downTime;
134 break;
135 }
136 case InputMessage::TYPE_MOTION: {
137 // uint32_t seq
138 msg->body.motion.seq = body.motion.seq;
139 // nsecs_t eventTime
140 msg->body.motion.eventTime = body.motion.eventTime;
141 // int32_t deviceId
142 msg->body.motion.deviceId = body.motion.deviceId;
143 // int32_t source
144 msg->body.motion.source = body.motion.source;
145 // int32_t action
146 msg->body.motion.action = body.motion.action;
147 // int32_t actionButton
148 msg->body.motion.actionButton = body.motion.actionButton;
149 // int32_t flags
150 msg->body.motion.flags = body.motion.flags;
151 // int32_t metaState
152 msg->body.motion.metaState = body.motion.metaState;
153 // int32_t buttonState
154 msg->body.motion.buttonState = body.motion.buttonState;
155 // int32_t edgeFlags
156 msg->body.motion.edgeFlags = body.motion.edgeFlags;
157 // nsecs_t downTime
158 msg->body.motion.downTime = body.motion.downTime;
159 // float xOffset
160 msg->body.motion.xOffset = body.motion.xOffset;
161 // float yOffset
162 msg->body.motion.yOffset = body.motion.yOffset;
163 // float xPrecision
164 msg->body.motion.xPrecision = body.motion.xPrecision;
165 // float yPrecision
166 msg->body.motion.yPrecision = body.motion.yPrecision;
167 // uint32_t pointerCount
168 msg->body.motion.pointerCount = body.motion.pointerCount;
169 //struct Pointer pointers[MAX_POINTERS]
170 for (size_t i = 0; i < body.motion.pointerCount; i++) {
171 // PointerProperties properties
172 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
173 msg->body.motion.pointers[i].properties.toolType =
174 body.motion.pointers[i].properties.toolType,
175 // PointerCoords coords
176 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
177 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
178 memcpy(&msg->body.motion.pointers[i].coords.values[0],
179 &body.motion.pointers[i].coords.values[0],
180 count * (sizeof(body.motion.pointers[i].coords.values[0])));
181 }
182 break;
183 }
184 case InputMessage::TYPE_FINISHED: {
185 msg->body.finished.seq = body.finished.seq;
186 msg->body.finished.handled = body.finished.handled;
187 break;
188 }
189 default: {
190 LOG_FATAL("Unexpected message type %i", header.type);
191 break;
192 }
193 }
194}
Jeff Brown5912f952013-07-01 19:10:31 -0700195
196// --- InputChannel ---
197
198InputChannel::InputChannel(const String8& name, int fd) :
199 mName(name), mFd(fd) {
200#if DEBUG_CHANNEL_LIFECYCLE
201 ALOGD("Input channel constructed: name='%s', fd=%d",
202 mName.string(), fd);
203#endif
204
205 int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
206 LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
207 "non-blocking. errno=%d", mName.string(), errno);
208}
209
210InputChannel::~InputChannel() {
211#if DEBUG_CHANNEL_LIFECYCLE
212 ALOGD("Input channel destroyed: name='%s', fd=%d",
213 mName.string(), mFd);
214#endif
215
216 ::close(mFd);
217}
218
219status_t InputChannel::openInputChannelPair(const String8& name,
220 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
221 int sockets[2];
222 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
223 status_t result = -errno;
224 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
225 name.string(), errno);
226 outServerChannel.clear();
227 outClientChannel.clear();
228 return result;
229 }
230
231 int bufferSize = SOCKET_BUFFER_SIZE;
232 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
233 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
234 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
235 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
236
237 String8 serverChannelName = name;
238 serverChannelName.append(" (server)");
239 outServerChannel = new InputChannel(serverChannelName, sockets[0]);
240
241 String8 clientChannelName = name;
242 clientChannelName.append(" (client)");
243 outClientChannel = new InputChannel(clientChannelName, sockets[1]);
244 return OK;
245}
246
247status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakoucb2f0ce2018-11-16 22:18:53 -0800248 const size_t msgLength = msg->size();
249 InputMessage cleanMsg;
250 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700251 ssize_t nWrite;
252 do {
Siarhei Vishniakoucb2f0ce2018-11-16 22:18:53 -0800253 nWrite = ::send(mFd, &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700254 } while (nWrite == -1 && errno == EINTR);
255
256 if (nWrite < 0) {
257 int error = errno;
258#if DEBUG_CHANNEL_MESSAGES
259 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.string(),
260 msg->header.type, error);
261#endif
262 if (error == EAGAIN || error == EWOULDBLOCK) {
263 return WOULD_BLOCK;
264 }
265 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
266 return DEAD_OBJECT;
267 }
268 return -error;
269 }
270
271 if (size_t(nWrite) != msgLength) {
272#if DEBUG_CHANNEL_MESSAGES
273 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
274 mName.string(), msg->header.type);
275#endif
276 return DEAD_OBJECT;
277 }
278
279#if DEBUG_CHANNEL_MESSAGES
280 ALOGD("channel '%s' ~ sent message of type %d", mName.string(), msg->header.type);
281#endif
282 return OK;
283}
284
285status_t InputChannel::receiveMessage(InputMessage* msg) {
286 ssize_t nRead;
287 do {
288 nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
289 } while (nRead == -1 && errno == EINTR);
290
291 if (nRead < 0) {
292 int error = errno;
293#if DEBUG_CHANNEL_MESSAGES
294 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.string(), errno);
295#endif
296 if (error == EAGAIN || error == EWOULDBLOCK) {
297 return WOULD_BLOCK;
298 }
299 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
300 return DEAD_OBJECT;
301 }
302 return -error;
303 }
304
305 if (nRead == 0) { // check for EOF
306#if DEBUG_CHANNEL_MESSAGES
307 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.string());
308#endif
309 return DEAD_OBJECT;
310 }
311
312 if (!msg->isValid(nRead)) {
313#if DEBUG_CHANNEL_MESSAGES
314 ALOGD("channel '%s' ~ received invalid message", mName.string());
315#endif
316 return BAD_VALUE;
317 }
318
319#if DEBUG_CHANNEL_MESSAGES
320 ALOGD("channel '%s' ~ received message of type %d", mName.string(), msg->header.type);
321#endif
322 return OK;
323}
324
325sp<InputChannel> InputChannel::dup() const {
326 int fd = ::dup(getFd());
327 return fd >= 0 ? new InputChannel(getName(), fd) : NULL;
328}
329
330
331// --- InputPublisher ---
332
333InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
334 mChannel(channel) {
335}
336
337InputPublisher::~InputPublisher() {
338}
339
340status_t InputPublisher::publishKeyEvent(
341 uint32_t seq,
342 int32_t deviceId,
343 int32_t source,
344 int32_t action,
345 int32_t flags,
346 int32_t keyCode,
347 int32_t scanCode,
348 int32_t metaState,
349 int32_t repeatCount,
350 nsecs_t downTime,
351 nsecs_t eventTime) {
352#if DEBUG_TRANSPORT_ACTIONS
353 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
354 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
355 "downTime=%lld, eventTime=%lld",
356 mChannel->getName().string(), seq,
357 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
358 downTime, eventTime);
359#endif
360
361 if (!seq) {
362 ALOGE("Attempted to publish a key event with sequence number 0.");
363 return BAD_VALUE;
364 }
365
366 InputMessage msg;
367 msg.header.type = InputMessage::TYPE_KEY;
368 msg.body.key.seq = seq;
369 msg.body.key.deviceId = deviceId;
370 msg.body.key.source = source;
371 msg.body.key.action = action;
372 msg.body.key.flags = flags;
373 msg.body.key.keyCode = keyCode;
374 msg.body.key.scanCode = scanCode;
375 msg.body.key.metaState = metaState;
376 msg.body.key.repeatCount = repeatCount;
377 msg.body.key.downTime = downTime;
378 msg.body.key.eventTime = eventTime;
379 return mChannel->sendMessage(&msg);
380}
381
382status_t InputPublisher::publishMotionEvent(
383 uint32_t seq,
384 int32_t deviceId,
385 int32_t source,
386 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100387 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700388 int32_t flags,
389 int32_t edgeFlags,
390 int32_t metaState,
391 int32_t buttonState,
392 float xOffset,
393 float yOffset,
394 float xPrecision,
395 float yPrecision,
396 nsecs_t downTime,
397 nsecs_t eventTime,
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100398 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700399 const PointerProperties* pointerProperties,
400 const PointerCoords* pointerCoords) {
401#if DEBUG_TRANSPORT_ACTIONS
402 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100403 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
404 "metaState=0x%x, buttonState=0x%x, xOffset=%f, yOffset=%f, "
Jeff Brown5912f952013-07-01 19:10:31 -0700405 "xPrecision=%f, yPrecision=%f, downTime=%lld, eventTime=%lld, "
Michael Wright63ff3a82014-06-10 13:03:17 -0700406 "pointerCount=%" PRIu32,
Jeff Brown5912f952013-07-01 19:10:31 -0700407 mChannel->getName().string(), seq,
Michael Wright7b159c92015-05-14 14:48:03 +0100408 deviceId, source, action, actionButton, flags, edgeFlags, metaState, buttonState,
Jeff Brown5912f952013-07-01 19:10:31 -0700409 xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
410#endif
411
412 if (!seq) {
413 ALOGE("Attempted to publish a motion event with sequence number 0.");
414 return BAD_VALUE;
415 }
416
417 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700418 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Jeff Brown5912f952013-07-01 19:10:31 -0700419 mChannel->getName().string(), pointerCount);
420 return BAD_VALUE;
421 }
422
423 InputMessage msg;
424 msg.header.type = InputMessage::TYPE_MOTION;
425 msg.body.motion.seq = seq;
426 msg.body.motion.deviceId = deviceId;
427 msg.body.motion.source = source;
428 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100429 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700430 msg.body.motion.flags = flags;
431 msg.body.motion.edgeFlags = edgeFlags;
432 msg.body.motion.metaState = metaState;
433 msg.body.motion.buttonState = buttonState;
434 msg.body.motion.xOffset = xOffset;
435 msg.body.motion.yOffset = yOffset;
436 msg.body.motion.xPrecision = xPrecision;
437 msg.body.motion.yPrecision = yPrecision;
438 msg.body.motion.downTime = downTime;
439 msg.body.motion.eventTime = eventTime;
440 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100441 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700442 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
443 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
444 }
445 return mChannel->sendMessage(&msg);
446}
447
448status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
449#if DEBUG_TRANSPORT_ACTIONS
450 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
451 mChannel->getName().string());
452#endif
453
454 InputMessage msg;
455 status_t result = mChannel->receiveMessage(&msg);
456 if (result) {
457 *outSeq = 0;
458 *outHandled = false;
459 return result;
460 }
461 if (msg.header.type != InputMessage::TYPE_FINISHED) {
462 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
463 mChannel->getName().string(), msg.header.type);
464 return UNKNOWN_ERROR;
465 }
466 *outSeq = msg.body.finished.seq;
467 *outHandled = msg.body.finished.handled;
468 return OK;
469}
470
471// --- InputConsumer ---
472
473InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
474 mResampleTouch(isTouchResamplingEnabled()),
475 mChannel(channel), mMsgDeferred(false) {
476}
477
478InputConsumer::~InputConsumer() {
479}
480
481bool InputConsumer::isTouchResamplingEnabled() {
482 char value[PROPERTY_VALUE_MAX];
Michael Wrightad526f82013-10-10 18:54:12 -0700483 int length = property_get("ro.input.noresample", value, NULL);
Jeff Brown5912f952013-07-01 19:10:31 -0700484 if (length > 0) {
Michael Wrightad526f82013-10-10 18:54:12 -0700485 if (!strcmp("1", value)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700486 return false;
487 }
Michael Wrightad526f82013-10-10 18:54:12 -0700488 if (strcmp("0", value)) {
489 ALOGD("Unrecognized property value for 'ro.input.noresample'. "
Jeff Brown5912f952013-07-01 19:10:31 -0700490 "Use '1' or '0'.");
491 }
492 }
493 return true;
494}
495
496status_t InputConsumer::consume(InputEventFactoryInterface* factory,
497 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
498#if DEBUG_TRANSPORT_ACTIONS
499 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%lld",
500 mChannel->getName().string(), consumeBatches ? "true" : "false", frameTime);
501#endif
502
503 *outSeq = 0;
504 *outEvent = NULL;
505
506 // Fetch the next input message.
507 // Loop until an event can be returned or no additional events are received.
508 while (!*outEvent) {
509 if (mMsgDeferred) {
510 // mMsg contains a valid input message from the previous call to consume
511 // that has not yet been processed.
512 mMsgDeferred = false;
513 } else {
514 // Receive a fresh message.
515 status_t result = mChannel->receiveMessage(&mMsg);
516 if (result) {
517 // Consume the next batched event unless batches are being held for later.
518 if (consumeBatches || result != WOULD_BLOCK) {
519 result = consumeBatch(factory, frameTime, outSeq, outEvent);
520 if (*outEvent) {
521#if DEBUG_TRANSPORT_ACTIONS
522 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
523 mChannel->getName().string(), *outSeq);
524#endif
525 break;
526 }
527 }
528 return result;
529 }
530 }
531
532 switch (mMsg.header.type) {
533 case InputMessage::TYPE_KEY: {
534 KeyEvent* keyEvent = factory->createKeyEvent();
535 if (!keyEvent) return NO_MEMORY;
536
537 initializeKeyEvent(keyEvent, &mMsg);
538 *outSeq = mMsg.body.key.seq;
539 *outEvent = keyEvent;
540#if DEBUG_TRANSPORT_ACTIONS
541 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
542 mChannel->getName().string(), *outSeq);
543#endif
544 break;
545 }
546
547 case AINPUT_EVENT_TYPE_MOTION: {
548 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
549 if (batchIndex >= 0) {
550 Batch& batch = mBatches.editItemAt(batchIndex);
551 if (canAddSample(batch, &mMsg)) {
552 batch.samples.push(mMsg);
553#if DEBUG_TRANSPORT_ACTIONS
554 ALOGD("channel '%s' consumer ~ appended to batch event",
555 mChannel->getName().string());
556#endif
557 break;
558 } else {
559 // We cannot append to the batch in progress, so we need to consume
560 // the previous batch right now and defer the new message until later.
561 mMsgDeferred = true;
562 status_t result = consumeSamples(factory,
563 batch, batch.samples.size(), outSeq, outEvent);
564 mBatches.removeAt(batchIndex);
565 if (result) {
566 return result;
567 }
568#if DEBUG_TRANSPORT_ACTIONS
569 ALOGD("channel '%s' consumer ~ consumed batch event and "
570 "deferred current event, seq=%u",
571 mChannel->getName().string(), *outSeq);
572#endif
573 break;
574 }
575 }
576
577 // Start a new batch if needed.
578 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
579 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
580 mBatches.push();
581 Batch& batch = mBatches.editTop();
582 batch.samples.push(mMsg);
583#if DEBUG_TRANSPORT_ACTIONS
584 ALOGD("channel '%s' consumer ~ started batch event",
585 mChannel->getName().string());
586#endif
587 break;
588 }
589
590 MotionEvent* motionEvent = factory->createMotionEvent();
591 if (! motionEvent) return NO_MEMORY;
592
593 updateTouchState(&mMsg);
594 initializeMotionEvent(motionEvent, &mMsg);
595 *outSeq = mMsg.body.motion.seq;
596 *outEvent = motionEvent;
597#if DEBUG_TRANSPORT_ACTIONS
598 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
599 mChannel->getName().string(), *outSeq);
600#endif
601 break;
602 }
603
604 default:
605 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
606 mChannel->getName().string(), mMsg.header.type);
607 return UNKNOWN_ERROR;
608 }
609 }
610 return OK;
611}
612
613status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
614 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
615 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700616 for (size_t i = mBatches.size(); i > 0; ) {
617 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700618 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700619 if (frameTime < 0) {
Jeff Brown5912f952013-07-01 19:10:31 -0700620 result = consumeSamples(factory, batch, batch.samples.size(),
621 outSeq, outEvent);
622 mBatches.removeAt(i);
623 return result;
624 }
625
Michael Wright32232172013-10-21 12:05:22 -0700626 nsecs_t sampleTime = frameTime;
627 if (mResampleTouch) {
628 sampleTime -= RESAMPLE_LATENCY;
629 }
Jeff Brown5912f952013-07-01 19:10:31 -0700630 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
631 if (split < 0) {
632 continue;
633 }
634
635 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
636 const InputMessage* next;
637 if (batch.samples.isEmpty()) {
638 mBatches.removeAt(i);
639 next = NULL;
640 } else {
641 next = &batch.samples.itemAt(0);
642 }
Michael Wright32232172013-10-21 12:05:22 -0700643 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700644 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
645 }
646 return result;
647 }
648
649 return WOULD_BLOCK;
650}
651
652status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
653 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
654 MotionEvent* motionEvent = factory->createMotionEvent();
655 if (! motionEvent) return NO_MEMORY;
656
657 uint32_t chain = 0;
658 for (size_t i = 0; i < count; i++) {
659 InputMessage& msg = batch.samples.editItemAt(i);
660 updateTouchState(&msg);
661 if (i) {
662 SeqChain seqChain;
663 seqChain.seq = msg.body.motion.seq;
664 seqChain.chain = chain;
665 mSeqChains.push(seqChain);
666 addSample(motionEvent, &msg);
667 } else {
668 initializeMotionEvent(motionEvent, &msg);
669 }
670 chain = msg.body.motion.seq;
671 }
672 batch.samples.removeItemsAt(0, count);
673
674 *outSeq = chain;
675 *outEvent = motionEvent;
676 return OK;
677}
678
679void InputConsumer::updateTouchState(InputMessage* msg) {
680 if (!mResampleTouch ||
681 !(msg->body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
682 return;
683 }
684
685 int32_t deviceId = msg->body.motion.deviceId;
686 int32_t source = msg->body.motion.source;
687 nsecs_t eventTime = msg->body.motion.eventTime;
688
689 // Update the touch state history to incorporate the new input message.
690 // If the message is in the past relative to the most recently produced resampled
691 // touch, then use the resampled time and coordinates instead.
692 switch (msg->body.motion.action & AMOTION_EVENT_ACTION_MASK) {
693 case AMOTION_EVENT_ACTION_DOWN: {
694 ssize_t index = findTouchState(deviceId, source);
695 if (index < 0) {
696 mTouchStates.push();
697 index = mTouchStates.size() - 1;
698 }
699 TouchState& touchState = mTouchStates.editItemAt(index);
700 touchState.initialize(deviceId, source);
701 touchState.addHistory(msg);
702 break;
703 }
704
705 case AMOTION_EVENT_ACTION_MOVE: {
706 ssize_t index = findTouchState(deviceId, source);
707 if (index >= 0) {
708 TouchState& touchState = mTouchStates.editItemAt(index);
709 touchState.addHistory(msg);
710 if (eventTime < touchState.lastResample.eventTime) {
711 rewriteMessage(touchState, msg);
712 } else {
713 touchState.lastResample.idBits.clear();
714 }
715 }
716 break;
717 }
718
719 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
720 ssize_t index = findTouchState(deviceId, source);
721 if (index >= 0) {
722 TouchState& touchState = mTouchStates.editItemAt(index);
723 touchState.lastResample.idBits.clearBit(msg->body.motion.getActionId());
724 rewriteMessage(touchState, msg);
725 }
726 break;
727 }
728
729 case AMOTION_EVENT_ACTION_POINTER_UP: {
730 ssize_t index = findTouchState(deviceId, source);
731 if (index >= 0) {
732 TouchState& touchState = mTouchStates.editItemAt(index);
733 rewriteMessage(touchState, msg);
734 touchState.lastResample.idBits.clearBit(msg->body.motion.getActionId());
735 }
736 break;
737 }
738
739 case AMOTION_EVENT_ACTION_SCROLL: {
740 ssize_t index = findTouchState(deviceId, source);
741 if (index >= 0) {
742 const TouchState& touchState = mTouchStates.itemAt(index);
743 rewriteMessage(touchState, msg);
744 }
745 break;
746 }
747
748 case AMOTION_EVENT_ACTION_UP:
749 case AMOTION_EVENT_ACTION_CANCEL: {
750 ssize_t index = findTouchState(deviceId, source);
751 if (index >= 0) {
752 const TouchState& touchState = mTouchStates.itemAt(index);
753 rewriteMessage(touchState, msg);
754 mTouchStates.removeAt(index);
755 }
756 break;
757 }
758 }
759}
760
761void InputConsumer::rewriteMessage(const TouchState& state, InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100762 for (uint32_t i = 0; i < msg->body.motion.pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700763 uint32_t id = msg->body.motion.pointers[i].properties.id;
764 if (state.lastResample.idBits.hasBit(id)) {
765 PointerCoords& msgCoords = msg->body.motion.pointers[i].coords;
766 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
767#if DEBUG_RESAMPLING
768 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
769 resampleCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
770 resampleCoords.getAxisValue(AMOTION_EVENT_AXIS_Y),
771 msgCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
772 msgCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
773#endif
774 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
775 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
776 }
777 }
778}
779
780void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
781 const InputMessage* next) {
782 if (!mResampleTouch
783 || !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
784 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
785 return;
786 }
787
788 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
789 if (index < 0) {
790#if DEBUG_RESAMPLING
791 ALOGD("Not resampled, no touch state for device.");
792#endif
793 return;
794 }
795
796 TouchState& touchState = mTouchStates.editItemAt(index);
797 if (touchState.historySize < 1) {
798#if DEBUG_RESAMPLING
799 ALOGD("Not resampled, no history for device.");
800#endif
801 return;
802 }
803
804 // Ensure that the current sample has all of the pointers that need to be reported.
805 const History* current = touchState.getHistory(0);
806 size_t pointerCount = event->getPointerCount();
807 for (size_t i = 0; i < pointerCount; i++) {
808 uint32_t id = event->getPointerId(i);
809 if (!current->idBits.hasBit(id)) {
810#if DEBUG_RESAMPLING
811 ALOGD("Not resampled, missing id %d", id);
812#endif
813 return;
814 }
815 }
816
817 // Find the data to use for resampling.
818 const History* other;
819 History future;
820 float alpha;
821 if (next) {
822 // Interpolate between current sample and future sample.
823 // So current->eventTime <= sampleTime <= future.eventTime.
824 future.initializeFrom(next);
825 other = &future;
826 nsecs_t delta = future.eventTime - current->eventTime;
827 if (delta < RESAMPLE_MIN_DELTA) {
828#if DEBUG_RESAMPLING
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700829 ALOGD("Not resampled, delta time is too small: %lld ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700830#endif
831 return;
832 }
833 alpha = float(sampleTime - current->eventTime) / delta;
834 } else if (touchState.historySize >= 2) {
835 // Extrapolate future sample using current sample and past sample.
836 // So other->eventTime <= current->eventTime <= sampleTime.
837 other = touchState.getHistory(1);
838 nsecs_t delta = current->eventTime - other->eventTime;
839 if (delta < RESAMPLE_MIN_DELTA) {
840#if DEBUG_RESAMPLING
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700841 ALOGD("Not resampled, delta time is too small: %lld ns.", delta);
842#endif
843 return;
844 } else if (delta > RESAMPLE_MAX_DELTA) {
845#if DEBUG_RESAMPLING
846 ALOGD("Not resampled, delta time is too large: %lld ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700847#endif
848 return;
849 }
850 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
851 if (sampleTime > maxPredict) {
852#if DEBUG_RESAMPLING
853 ALOGD("Sample time is too far in the future, adjusting prediction "
854 "from %lld to %lld ns.",
855 sampleTime - current->eventTime, maxPredict - current->eventTime);
856#endif
857 sampleTime = maxPredict;
858 }
859 alpha = float(current->eventTime - sampleTime) / delta;
860 } else {
861#if DEBUG_RESAMPLING
862 ALOGD("Not resampled, insufficient data.");
863#endif
864 return;
865 }
866
867 // Resample touch coordinates.
868 touchState.lastResample.eventTime = sampleTime;
869 touchState.lastResample.idBits.clear();
870 for (size_t i = 0; i < pointerCount; i++) {
871 uint32_t id = event->getPointerId(i);
872 touchState.lastResample.idToIndex[id] = i;
873 touchState.lastResample.idBits.markBit(id);
874 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
875 const PointerCoords& currentCoords = current->getPointerById(id);
876 if (other->idBits.hasBit(id)
877 && shouldResampleTool(event->getToolType(i))) {
878 const PointerCoords& otherCoords = other->getPointerById(id);
879 resampledCoords.copyFrom(currentCoords);
880 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
881 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
882 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
883 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
884#if DEBUG_RESAMPLING
885 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
886 "other (%0.3f, %0.3f), alpha %0.3f",
887 id, resampledCoords.getX(), resampledCoords.getY(),
888 currentCoords.getX(), currentCoords.getY(),
889 otherCoords.getX(), otherCoords.getY(),
890 alpha);
891#endif
892 } else {
893 resampledCoords.copyFrom(currentCoords);
894#if DEBUG_RESAMPLING
895 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
896 id, resampledCoords.getX(), resampledCoords.getY(),
897 currentCoords.getX(), currentCoords.getY());
898#endif
899 }
900 }
901
902 event->addSample(sampleTime, touchState.lastResample.pointers);
903}
904
905bool InputConsumer::shouldResampleTool(int32_t toolType) {
906 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
907 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
908}
909
910status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
911#if DEBUG_TRANSPORT_ACTIONS
912 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
913 mChannel->getName().string(), seq, handled ? "true" : "false");
914#endif
915
916 if (!seq) {
917 ALOGE("Attempted to send a finished signal with sequence number 0.");
918 return BAD_VALUE;
919 }
920
921 // Send finished signals for the batch sequence chain first.
922 size_t seqChainCount = mSeqChains.size();
923 if (seqChainCount) {
924 uint32_t currentSeq = seq;
925 uint32_t chainSeqs[seqChainCount];
926 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -0700927 for (size_t i = seqChainCount; i > 0; ) {
928 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700929 const SeqChain& seqChain = mSeqChains.itemAt(i);
930 if (seqChain.seq == currentSeq) {
931 currentSeq = seqChain.chain;
932 chainSeqs[chainIndex++] = currentSeq;
933 mSeqChains.removeAt(i);
934 }
935 }
936 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -0700937 while (!status && chainIndex > 0) {
938 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -0700939 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
940 }
941 if (status) {
942 // An error occurred so at least one signal was not sent, reconstruct the chain.
943 do {
944 SeqChain seqChain;
945 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
946 seqChain.chain = chainSeqs[chainIndex];
947 mSeqChains.push(seqChain);
Dan Austin1faef802015-09-22 14:28:07 -0700948 if (chainIndex != 0) {
949 chainIndex--;
950 }
951 } while (chainIndex > 0);
Jeff Brown5912f952013-07-01 19:10:31 -0700952 return status;
953 }
954 }
955
956 // Send finished signal for the last message in the batch.
957 return sendUnchainedFinishedSignal(seq, handled);
958}
959
960status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
961 InputMessage msg;
962 msg.header.type = InputMessage::TYPE_FINISHED;
963 msg.body.finished.seq = seq;
964 msg.body.finished.handled = handled;
965 return mChannel->sendMessage(&msg);
966}
967
968bool InputConsumer::hasDeferredEvent() const {
969 return mMsgDeferred;
970}
971
972bool InputConsumer::hasPendingBatch() const {
973 return !mBatches.isEmpty();
974}
975
976ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
977 for (size_t i = 0; i < mBatches.size(); i++) {
978 const Batch& batch = mBatches.itemAt(i);
979 const InputMessage& head = batch.samples.itemAt(0);
980 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
981 return i;
982 }
983 }
984 return -1;
985}
986
987ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
988 for (size_t i = 0; i < mTouchStates.size(); i++) {
989 const TouchState& touchState = mTouchStates.itemAt(i);
990 if (touchState.deviceId == deviceId && touchState.source == source) {
991 return i;
992 }
993 }
994 return -1;
995}
996
997void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
998 event->initialize(
999 msg->body.key.deviceId,
1000 msg->body.key.source,
1001 msg->body.key.action,
1002 msg->body.key.flags,
1003 msg->body.key.keyCode,
1004 msg->body.key.scanCode,
1005 msg->body.key.metaState,
1006 msg->body.key.repeatCount,
1007 msg->body.key.downTime,
1008 msg->body.key.eventTime);
1009}
1010
1011void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001012 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001013 PointerProperties pointerProperties[pointerCount];
1014 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001015 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001016 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1017 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1018 }
1019
1020 event->initialize(
1021 msg->body.motion.deviceId,
1022 msg->body.motion.source,
1023 msg->body.motion.action,
Michael Wright7b159c92015-05-14 14:48:03 +01001024 msg->body.motion.actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -07001025 msg->body.motion.flags,
1026 msg->body.motion.edgeFlags,
1027 msg->body.motion.metaState,
1028 msg->body.motion.buttonState,
1029 msg->body.motion.xOffset,
1030 msg->body.motion.yOffset,
1031 msg->body.motion.xPrecision,
1032 msg->body.motion.yPrecision,
1033 msg->body.motion.downTime,
1034 msg->body.motion.eventTime,
1035 pointerCount,
1036 pointerProperties,
1037 pointerCoords);
1038}
1039
1040void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001041 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001042 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001043 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001044 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1045 }
1046
1047 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1048 event->addSample(msg->body.motion.eventTime, pointerCoords);
1049}
1050
1051bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1052 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001053 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001054 if (head.body.motion.pointerCount != pointerCount
1055 || head.body.motion.action != msg->body.motion.action) {
1056 return false;
1057 }
1058 for (size_t i = 0; i < pointerCount; i++) {
1059 if (head.body.motion.pointers[i].properties
1060 != msg->body.motion.pointers[i].properties) {
1061 return false;
1062 }
1063 }
1064 return true;
1065}
1066
1067ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1068 size_t numSamples = batch.samples.size();
1069 size_t index = 0;
1070 while (index < numSamples
1071 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1072 index += 1;
1073 }
1074 return ssize_t(index) - 1;
1075}
1076
1077} // namespace android