blob: 7f83da523f2344d6c80ae2b37d2abde9ded6603e [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
22
23#include <errno.h>
24#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070025#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070026#include <math.h>
27#include <sys/types.h>
28#include <sys/socket.h>
29#include <unistd.h>
30
31#include <cutils/log.h>
32#include <cutils/properties.h>
33#include <input/InputTransport.h>
34
35
36namespace 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
103InputChannel::InputChannel(const String8& name, int fd) :
104 mName(name), mFd(fd) {
105#if DEBUG_CHANNEL_LIFECYCLE
106 ALOGD("Input channel constructed: name='%s', fd=%d",
107 mName.string(), fd);
108#endif
109
110 int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
111 LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
112 "non-blocking. errno=%d", mName.string(), errno);
113}
114
115InputChannel::~InputChannel() {
116#if DEBUG_CHANNEL_LIFECYCLE
117 ALOGD("Input channel destroyed: name='%s', fd=%d",
118 mName.string(), mFd);
119#endif
120
121 ::close(mFd);
122}
123
124status_t InputChannel::openInputChannelPair(const String8& name,
125 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
126 int sockets[2];
127 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
128 status_t result = -errno;
129 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
130 name.string(), errno);
131 outServerChannel.clear();
132 outClientChannel.clear();
133 return result;
134 }
135
136 int bufferSize = SOCKET_BUFFER_SIZE;
137 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
138 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
139 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
140 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
141
142 String8 serverChannelName = name;
143 serverChannelName.append(" (server)");
144 outServerChannel = new InputChannel(serverChannelName, sockets[0]);
145
146 String8 clientChannelName = name;
147 clientChannelName.append(" (client)");
148 outClientChannel = new InputChannel(clientChannelName, sockets[1]);
149 return OK;
150}
151
152status_t InputChannel::sendMessage(const InputMessage* msg) {
153 size_t msgLength = msg->size();
154 ssize_t nWrite;
155 do {
156 nWrite = ::send(mFd, msg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
157 } while (nWrite == -1 && errno == EINTR);
158
159 if (nWrite < 0) {
160 int error = errno;
161#if DEBUG_CHANNEL_MESSAGES
162 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.string(),
163 msg->header.type, error);
164#endif
165 if (error == EAGAIN || error == EWOULDBLOCK) {
166 return WOULD_BLOCK;
167 }
168 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
169 return DEAD_OBJECT;
170 }
171 return -error;
172 }
173
174 if (size_t(nWrite) != msgLength) {
175#if DEBUG_CHANNEL_MESSAGES
176 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
177 mName.string(), msg->header.type);
178#endif
179 return DEAD_OBJECT;
180 }
181
182#if DEBUG_CHANNEL_MESSAGES
183 ALOGD("channel '%s' ~ sent message of type %d", mName.string(), msg->header.type);
184#endif
185 return OK;
186}
187
188status_t InputChannel::receiveMessage(InputMessage* msg) {
189 ssize_t nRead;
190 do {
191 nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
192 } while (nRead == -1 && errno == EINTR);
193
194 if (nRead < 0) {
195 int error = errno;
196#if DEBUG_CHANNEL_MESSAGES
197 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.string(), errno);
198#endif
199 if (error == EAGAIN || error == EWOULDBLOCK) {
200 return WOULD_BLOCK;
201 }
202 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
203 return DEAD_OBJECT;
204 }
205 return -error;
206 }
207
208 if (nRead == 0) { // check for EOF
209#if DEBUG_CHANNEL_MESSAGES
210 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.string());
211#endif
212 return DEAD_OBJECT;
213 }
214
215 if (!msg->isValid(nRead)) {
216#if DEBUG_CHANNEL_MESSAGES
217 ALOGD("channel '%s' ~ received invalid message", mName.string());
218#endif
219 return BAD_VALUE;
220 }
221
222#if DEBUG_CHANNEL_MESSAGES
223 ALOGD("channel '%s' ~ received message of type %d", mName.string(), msg->header.type);
224#endif
225 return OK;
226}
227
228sp<InputChannel> InputChannel::dup() const {
229 int fd = ::dup(getFd());
230 return fd >= 0 ? new InputChannel(getName(), fd) : NULL;
231}
232
233
234// --- InputPublisher ---
235
236InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
237 mChannel(channel) {
238}
239
240InputPublisher::~InputPublisher() {
241}
242
243status_t InputPublisher::publishKeyEvent(
244 uint32_t seq,
245 int32_t deviceId,
246 int32_t source,
247 int32_t action,
248 int32_t flags,
249 int32_t keyCode,
250 int32_t scanCode,
251 int32_t metaState,
252 int32_t repeatCount,
253 nsecs_t downTime,
254 nsecs_t eventTime) {
255#if DEBUG_TRANSPORT_ACTIONS
256 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
257 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
258 "downTime=%lld, eventTime=%lld",
259 mChannel->getName().string(), seq,
260 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
261 downTime, eventTime);
262#endif
263
264 if (!seq) {
265 ALOGE("Attempted to publish a key event with sequence number 0.");
266 return BAD_VALUE;
267 }
268
269 InputMessage msg;
270 msg.header.type = InputMessage::TYPE_KEY;
271 msg.body.key.seq = seq;
272 msg.body.key.deviceId = deviceId;
273 msg.body.key.source = source;
274 msg.body.key.action = action;
275 msg.body.key.flags = flags;
276 msg.body.key.keyCode = keyCode;
277 msg.body.key.scanCode = scanCode;
278 msg.body.key.metaState = metaState;
279 msg.body.key.repeatCount = repeatCount;
280 msg.body.key.downTime = downTime;
281 msg.body.key.eventTime = eventTime;
282 return mChannel->sendMessage(&msg);
283}
284
285status_t InputPublisher::publishMotionEvent(
286 uint32_t seq,
287 int32_t deviceId,
288 int32_t source,
289 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100290 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700291 int32_t flags,
292 int32_t edgeFlags,
293 int32_t metaState,
294 int32_t buttonState,
295 float xOffset,
296 float yOffset,
297 float xPrecision,
298 float yPrecision,
299 nsecs_t downTime,
300 nsecs_t eventTime,
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100301 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700302 const PointerProperties* pointerProperties,
303 const PointerCoords* pointerCoords) {
304#if DEBUG_TRANSPORT_ACTIONS
305 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100306 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
307 "metaState=0x%x, buttonState=0x%x, xOffset=%f, yOffset=%f, "
Jeff Brown5912f952013-07-01 19:10:31 -0700308 "xPrecision=%f, yPrecision=%f, downTime=%lld, eventTime=%lld, "
Michael Wright63ff3a82014-06-10 13:03:17 -0700309 "pointerCount=%" PRIu32,
Jeff Brown5912f952013-07-01 19:10:31 -0700310 mChannel->getName().string(), seq,
Michael Wright7b159c92015-05-14 14:48:03 +0100311 deviceId, source, action, actionButton, flags, edgeFlags, metaState, buttonState,
Jeff Brown5912f952013-07-01 19:10:31 -0700312 xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
313#endif
314
315 if (!seq) {
316 ALOGE("Attempted to publish a motion event with sequence number 0.");
317 return BAD_VALUE;
318 }
319
320 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700321 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Jeff Brown5912f952013-07-01 19:10:31 -0700322 mChannel->getName().string(), pointerCount);
323 return BAD_VALUE;
324 }
325
326 InputMessage msg;
327 msg.header.type = InputMessage::TYPE_MOTION;
328 msg.body.motion.seq = seq;
329 msg.body.motion.deviceId = deviceId;
330 msg.body.motion.source = source;
331 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100332 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700333 msg.body.motion.flags = flags;
334 msg.body.motion.edgeFlags = edgeFlags;
335 msg.body.motion.metaState = metaState;
336 msg.body.motion.buttonState = buttonState;
337 msg.body.motion.xOffset = xOffset;
338 msg.body.motion.yOffset = yOffset;
339 msg.body.motion.xPrecision = xPrecision;
340 msg.body.motion.yPrecision = yPrecision;
341 msg.body.motion.downTime = downTime;
342 msg.body.motion.eventTime = eventTime;
343 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100344 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700345 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
346 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
347 }
348 return mChannel->sendMessage(&msg);
349}
350
351status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
352#if DEBUG_TRANSPORT_ACTIONS
353 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
354 mChannel->getName().string());
355#endif
356
357 InputMessage msg;
358 status_t result = mChannel->receiveMessage(&msg);
359 if (result) {
360 *outSeq = 0;
361 *outHandled = false;
362 return result;
363 }
364 if (msg.header.type != InputMessage::TYPE_FINISHED) {
365 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
366 mChannel->getName().string(), msg.header.type);
367 return UNKNOWN_ERROR;
368 }
369 *outSeq = msg.body.finished.seq;
370 *outHandled = msg.body.finished.handled;
371 return OK;
372}
373
374// --- InputConsumer ---
375
376InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
377 mResampleTouch(isTouchResamplingEnabled()),
378 mChannel(channel), mMsgDeferred(false) {
379}
380
381InputConsumer::~InputConsumer() {
382}
383
384bool InputConsumer::isTouchResamplingEnabled() {
385 char value[PROPERTY_VALUE_MAX];
Michael Wrightad526f82013-10-10 18:54:12 -0700386 int length = property_get("ro.input.noresample", value, NULL);
Jeff Brown5912f952013-07-01 19:10:31 -0700387 if (length > 0) {
Michael Wrightad526f82013-10-10 18:54:12 -0700388 if (!strcmp("1", value)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700389 return false;
390 }
Michael Wrightad526f82013-10-10 18:54:12 -0700391 if (strcmp("0", value)) {
392 ALOGD("Unrecognized property value for 'ro.input.noresample'. "
Jeff Brown5912f952013-07-01 19:10:31 -0700393 "Use '1' or '0'.");
394 }
395 }
396 return true;
397}
398
399status_t InputConsumer::consume(InputEventFactoryInterface* factory,
400 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
401#if DEBUG_TRANSPORT_ACTIONS
402 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%lld",
403 mChannel->getName().string(), consumeBatches ? "true" : "false", frameTime);
404#endif
405
406 *outSeq = 0;
407 *outEvent = NULL;
408
409 // Fetch the next input message.
410 // Loop until an event can be returned or no additional events are received.
411 while (!*outEvent) {
412 if (mMsgDeferred) {
413 // mMsg contains a valid input message from the previous call to consume
414 // that has not yet been processed.
415 mMsgDeferred = false;
416 } else {
417 // Receive a fresh message.
418 status_t result = mChannel->receiveMessage(&mMsg);
419 if (result) {
420 // Consume the next batched event unless batches are being held for later.
421 if (consumeBatches || result != WOULD_BLOCK) {
422 result = consumeBatch(factory, frameTime, outSeq, outEvent);
423 if (*outEvent) {
424#if DEBUG_TRANSPORT_ACTIONS
425 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
426 mChannel->getName().string(), *outSeq);
427#endif
428 break;
429 }
430 }
431 return result;
432 }
433 }
434
435 switch (mMsg.header.type) {
436 case InputMessage::TYPE_KEY: {
437 KeyEvent* keyEvent = factory->createKeyEvent();
438 if (!keyEvent) return NO_MEMORY;
439
440 initializeKeyEvent(keyEvent, &mMsg);
441 *outSeq = mMsg.body.key.seq;
442 *outEvent = keyEvent;
443#if DEBUG_TRANSPORT_ACTIONS
444 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
445 mChannel->getName().string(), *outSeq);
446#endif
447 break;
448 }
449
450 case AINPUT_EVENT_TYPE_MOTION: {
451 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
452 if (batchIndex >= 0) {
453 Batch& batch = mBatches.editItemAt(batchIndex);
454 if (canAddSample(batch, &mMsg)) {
455 batch.samples.push(mMsg);
456#if DEBUG_TRANSPORT_ACTIONS
457 ALOGD("channel '%s' consumer ~ appended to batch event",
458 mChannel->getName().string());
459#endif
460 break;
461 } else {
462 // We cannot append to the batch in progress, so we need to consume
463 // the previous batch right now and defer the new message until later.
464 mMsgDeferred = true;
465 status_t result = consumeSamples(factory,
466 batch, batch.samples.size(), outSeq, outEvent);
467 mBatches.removeAt(batchIndex);
468 if (result) {
469 return result;
470 }
471#if DEBUG_TRANSPORT_ACTIONS
472 ALOGD("channel '%s' consumer ~ consumed batch event and "
473 "deferred current event, seq=%u",
474 mChannel->getName().string(), *outSeq);
475#endif
476 break;
477 }
478 }
479
480 // Start a new batch if needed.
481 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
482 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
483 mBatches.push();
484 Batch& batch = mBatches.editTop();
485 batch.samples.push(mMsg);
486#if DEBUG_TRANSPORT_ACTIONS
487 ALOGD("channel '%s' consumer ~ started batch event",
488 mChannel->getName().string());
489#endif
490 break;
491 }
492
493 MotionEvent* motionEvent = factory->createMotionEvent();
494 if (! motionEvent) return NO_MEMORY;
495
496 updateTouchState(&mMsg);
497 initializeMotionEvent(motionEvent, &mMsg);
498 *outSeq = mMsg.body.motion.seq;
499 *outEvent = motionEvent;
500#if DEBUG_TRANSPORT_ACTIONS
501 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
502 mChannel->getName().string(), *outSeq);
503#endif
504 break;
505 }
506
507 default:
508 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
509 mChannel->getName().string(), mMsg.header.type);
510 return UNKNOWN_ERROR;
511 }
512 }
513 return OK;
514}
515
516status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
517 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
518 status_t result;
519 for (size_t i = mBatches.size(); i-- > 0; ) {
520 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700521 if (frameTime < 0) {
Jeff Brown5912f952013-07-01 19:10:31 -0700522 result = consumeSamples(factory, batch, batch.samples.size(),
523 outSeq, outEvent);
524 mBatches.removeAt(i);
525 return result;
526 }
527
Michael Wright32232172013-10-21 12:05:22 -0700528 nsecs_t sampleTime = frameTime;
529 if (mResampleTouch) {
530 sampleTime -= RESAMPLE_LATENCY;
531 }
Jeff Brown5912f952013-07-01 19:10:31 -0700532 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
533 if (split < 0) {
534 continue;
535 }
536
537 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
538 const InputMessage* next;
539 if (batch.samples.isEmpty()) {
540 mBatches.removeAt(i);
541 next = NULL;
542 } else {
543 next = &batch.samples.itemAt(0);
544 }
Michael Wright32232172013-10-21 12:05:22 -0700545 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700546 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
547 }
548 return result;
549 }
550
551 return WOULD_BLOCK;
552}
553
554status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
555 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
556 MotionEvent* motionEvent = factory->createMotionEvent();
557 if (! motionEvent) return NO_MEMORY;
558
559 uint32_t chain = 0;
560 for (size_t i = 0; i < count; i++) {
561 InputMessage& msg = batch.samples.editItemAt(i);
562 updateTouchState(&msg);
563 if (i) {
564 SeqChain seqChain;
565 seqChain.seq = msg.body.motion.seq;
566 seqChain.chain = chain;
567 mSeqChains.push(seqChain);
568 addSample(motionEvent, &msg);
569 } else {
570 initializeMotionEvent(motionEvent, &msg);
571 }
572 chain = msg.body.motion.seq;
573 }
574 batch.samples.removeItemsAt(0, count);
575
576 *outSeq = chain;
577 *outEvent = motionEvent;
578 return OK;
579}
580
581void InputConsumer::updateTouchState(InputMessage* msg) {
582 if (!mResampleTouch ||
583 !(msg->body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
584 return;
585 }
586
587 int32_t deviceId = msg->body.motion.deviceId;
588 int32_t source = msg->body.motion.source;
589 nsecs_t eventTime = msg->body.motion.eventTime;
590
591 // Update the touch state history to incorporate the new input message.
592 // If the message is in the past relative to the most recently produced resampled
593 // touch, then use the resampled time and coordinates instead.
594 switch (msg->body.motion.action & AMOTION_EVENT_ACTION_MASK) {
595 case AMOTION_EVENT_ACTION_DOWN: {
596 ssize_t index = findTouchState(deviceId, source);
597 if (index < 0) {
598 mTouchStates.push();
599 index = mTouchStates.size() - 1;
600 }
601 TouchState& touchState = mTouchStates.editItemAt(index);
602 touchState.initialize(deviceId, source);
603 touchState.addHistory(msg);
604 break;
605 }
606
607 case AMOTION_EVENT_ACTION_MOVE: {
608 ssize_t index = findTouchState(deviceId, source);
609 if (index >= 0) {
610 TouchState& touchState = mTouchStates.editItemAt(index);
611 touchState.addHistory(msg);
612 if (eventTime < touchState.lastResample.eventTime) {
613 rewriteMessage(touchState, msg);
614 } else {
615 touchState.lastResample.idBits.clear();
616 }
617 }
618 break;
619 }
620
621 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
622 ssize_t index = findTouchState(deviceId, source);
623 if (index >= 0) {
624 TouchState& touchState = mTouchStates.editItemAt(index);
625 touchState.lastResample.idBits.clearBit(msg->body.motion.getActionId());
626 rewriteMessage(touchState, msg);
627 }
628 break;
629 }
630
631 case AMOTION_EVENT_ACTION_POINTER_UP: {
632 ssize_t index = findTouchState(deviceId, source);
633 if (index >= 0) {
634 TouchState& touchState = mTouchStates.editItemAt(index);
635 rewriteMessage(touchState, msg);
636 touchState.lastResample.idBits.clearBit(msg->body.motion.getActionId());
637 }
638 break;
639 }
640
641 case AMOTION_EVENT_ACTION_SCROLL: {
642 ssize_t index = findTouchState(deviceId, source);
643 if (index >= 0) {
644 const TouchState& touchState = mTouchStates.itemAt(index);
645 rewriteMessage(touchState, msg);
646 }
647 break;
648 }
649
650 case AMOTION_EVENT_ACTION_UP:
651 case AMOTION_EVENT_ACTION_CANCEL: {
652 ssize_t index = findTouchState(deviceId, source);
653 if (index >= 0) {
654 const TouchState& touchState = mTouchStates.itemAt(index);
655 rewriteMessage(touchState, msg);
656 mTouchStates.removeAt(index);
657 }
658 break;
659 }
660 }
661}
662
663void InputConsumer::rewriteMessage(const TouchState& state, InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100664 for (uint32_t i = 0; i < msg->body.motion.pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700665 uint32_t id = msg->body.motion.pointers[i].properties.id;
666 if (state.lastResample.idBits.hasBit(id)) {
667 PointerCoords& msgCoords = msg->body.motion.pointers[i].coords;
668 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
669#if DEBUG_RESAMPLING
670 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
671 resampleCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
672 resampleCoords.getAxisValue(AMOTION_EVENT_AXIS_Y),
673 msgCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
674 msgCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
675#endif
676 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
677 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
678 }
679 }
680}
681
682void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
683 const InputMessage* next) {
684 if (!mResampleTouch
685 || !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
686 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
687 return;
688 }
689
690 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
691 if (index < 0) {
692#if DEBUG_RESAMPLING
693 ALOGD("Not resampled, no touch state for device.");
694#endif
695 return;
696 }
697
698 TouchState& touchState = mTouchStates.editItemAt(index);
699 if (touchState.historySize < 1) {
700#if DEBUG_RESAMPLING
701 ALOGD("Not resampled, no history for device.");
702#endif
703 return;
704 }
705
706 // Ensure that the current sample has all of the pointers that need to be reported.
707 const History* current = touchState.getHistory(0);
708 size_t pointerCount = event->getPointerCount();
709 for (size_t i = 0; i < pointerCount; i++) {
710 uint32_t id = event->getPointerId(i);
711 if (!current->idBits.hasBit(id)) {
712#if DEBUG_RESAMPLING
713 ALOGD("Not resampled, missing id %d", id);
714#endif
715 return;
716 }
717 }
718
719 // Find the data to use for resampling.
720 const History* other;
721 History future;
722 float alpha;
723 if (next) {
724 // Interpolate between current sample and future sample.
725 // So current->eventTime <= sampleTime <= future.eventTime.
726 future.initializeFrom(next);
727 other = &future;
728 nsecs_t delta = future.eventTime - current->eventTime;
729 if (delta < RESAMPLE_MIN_DELTA) {
730#if DEBUG_RESAMPLING
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700731 ALOGD("Not resampled, delta time is too small: %lld ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700732#endif
733 return;
734 }
735 alpha = float(sampleTime - current->eventTime) / delta;
736 } else if (touchState.historySize >= 2) {
737 // Extrapolate future sample using current sample and past sample.
738 // So other->eventTime <= current->eventTime <= sampleTime.
739 other = touchState.getHistory(1);
740 nsecs_t delta = current->eventTime - other->eventTime;
741 if (delta < RESAMPLE_MIN_DELTA) {
742#if DEBUG_RESAMPLING
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700743 ALOGD("Not resampled, delta time is too small: %lld ns.", delta);
744#endif
745 return;
746 } else if (delta > RESAMPLE_MAX_DELTA) {
747#if DEBUG_RESAMPLING
748 ALOGD("Not resampled, delta time is too large: %lld ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700749#endif
750 return;
751 }
752 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
753 if (sampleTime > maxPredict) {
754#if DEBUG_RESAMPLING
755 ALOGD("Sample time is too far in the future, adjusting prediction "
756 "from %lld to %lld ns.",
757 sampleTime - current->eventTime, maxPredict - current->eventTime);
758#endif
759 sampleTime = maxPredict;
760 }
761 alpha = float(current->eventTime - sampleTime) / delta;
762 } else {
763#if DEBUG_RESAMPLING
764 ALOGD("Not resampled, insufficient data.");
765#endif
766 return;
767 }
768
769 // Resample touch coordinates.
770 touchState.lastResample.eventTime = sampleTime;
771 touchState.lastResample.idBits.clear();
772 for (size_t i = 0; i < pointerCount; i++) {
773 uint32_t id = event->getPointerId(i);
774 touchState.lastResample.idToIndex[id] = i;
775 touchState.lastResample.idBits.markBit(id);
776 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
777 const PointerCoords& currentCoords = current->getPointerById(id);
778 if (other->idBits.hasBit(id)
779 && shouldResampleTool(event->getToolType(i))) {
780 const PointerCoords& otherCoords = other->getPointerById(id);
781 resampledCoords.copyFrom(currentCoords);
782 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
783 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
784 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
785 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
786#if DEBUG_RESAMPLING
787 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
788 "other (%0.3f, %0.3f), alpha %0.3f",
789 id, resampledCoords.getX(), resampledCoords.getY(),
790 currentCoords.getX(), currentCoords.getY(),
791 otherCoords.getX(), otherCoords.getY(),
792 alpha);
793#endif
794 } else {
795 resampledCoords.copyFrom(currentCoords);
796#if DEBUG_RESAMPLING
797 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
798 id, resampledCoords.getX(), resampledCoords.getY(),
799 currentCoords.getX(), currentCoords.getY());
800#endif
801 }
802 }
803
804 event->addSample(sampleTime, touchState.lastResample.pointers);
805}
806
807bool InputConsumer::shouldResampleTool(int32_t toolType) {
808 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
809 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
810}
811
812status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
813#if DEBUG_TRANSPORT_ACTIONS
814 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
815 mChannel->getName().string(), seq, handled ? "true" : "false");
816#endif
817
818 if (!seq) {
819 ALOGE("Attempted to send a finished signal with sequence number 0.");
820 return BAD_VALUE;
821 }
822
823 // Send finished signals for the batch sequence chain first.
824 size_t seqChainCount = mSeqChains.size();
825 if (seqChainCount) {
826 uint32_t currentSeq = seq;
827 uint32_t chainSeqs[seqChainCount];
828 size_t chainIndex = 0;
829 for (size_t i = seqChainCount; i-- > 0; ) {
830 const SeqChain& seqChain = mSeqChains.itemAt(i);
831 if (seqChain.seq == currentSeq) {
832 currentSeq = seqChain.chain;
833 chainSeqs[chainIndex++] = currentSeq;
834 mSeqChains.removeAt(i);
835 }
836 }
837 status_t status = OK;
838 while (!status && chainIndex-- > 0) {
839 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
840 }
841 if (status) {
842 // An error occurred so at least one signal was not sent, reconstruct the chain.
843 do {
844 SeqChain seqChain;
845 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
846 seqChain.chain = chainSeqs[chainIndex];
847 mSeqChains.push(seqChain);
848 } while (chainIndex-- > 0);
849 return status;
850 }
851 }
852
853 // Send finished signal for the last message in the batch.
854 return sendUnchainedFinishedSignal(seq, handled);
855}
856
857status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
858 InputMessage msg;
859 msg.header.type = InputMessage::TYPE_FINISHED;
860 msg.body.finished.seq = seq;
861 msg.body.finished.handled = handled;
862 return mChannel->sendMessage(&msg);
863}
864
865bool InputConsumer::hasDeferredEvent() const {
866 return mMsgDeferred;
867}
868
869bool InputConsumer::hasPendingBatch() const {
870 return !mBatches.isEmpty();
871}
872
873ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
874 for (size_t i = 0; i < mBatches.size(); i++) {
875 const Batch& batch = mBatches.itemAt(i);
876 const InputMessage& head = batch.samples.itemAt(0);
877 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
878 return i;
879 }
880 }
881 return -1;
882}
883
884ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
885 for (size_t i = 0; i < mTouchStates.size(); i++) {
886 const TouchState& touchState = mTouchStates.itemAt(i);
887 if (touchState.deviceId == deviceId && touchState.source == source) {
888 return i;
889 }
890 }
891 return -1;
892}
893
894void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
895 event->initialize(
896 msg->body.key.deviceId,
897 msg->body.key.source,
898 msg->body.key.action,
899 msg->body.key.flags,
900 msg->body.key.keyCode,
901 msg->body.key.scanCode,
902 msg->body.key.metaState,
903 msg->body.key.repeatCount,
904 msg->body.key.downTime,
905 msg->body.key.eventTime);
906}
907
908void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100909 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -0700910 PointerProperties pointerProperties[pointerCount];
911 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100912 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700913 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
914 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
915 }
916
917 event->initialize(
918 msg->body.motion.deviceId,
919 msg->body.motion.source,
920 msg->body.motion.action,
Michael Wright7b159c92015-05-14 14:48:03 +0100921 msg->body.motion.actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700922 msg->body.motion.flags,
923 msg->body.motion.edgeFlags,
924 msg->body.motion.metaState,
925 msg->body.motion.buttonState,
926 msg->body.motion.xOffset,
927 msg->body.motion.yOffset,
928 msg->body.motion.xPrecision,
929 msg->body.motion.yPrecision,
930 msg->body.motion.downTime,
931 msg->body.motion.eventTime,
932 pointerCount,
933 pointerProperties,
934 pointerCoords);
935}
936
937void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100938 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -0700939 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100940 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700941 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
942 }
943
944 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
945 event->addSample(msg->body.motion.eventTime, pointerCoords);
946}
947
948bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
949 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100950 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -0700951 if (head.body.motion.pointerCount != pointerCount
952 || head.body.motion.action != msg->body.motion.action) {
953 return false;
954 }
955 for (size_t i = 0; i < pointerCount; i++) {
956 if (head.body.motion.pointers[i].properties
957 != msg->body.motion.pointers[i].properties) {
958 return false;
959 }
960 }
961 return true;
962}
963
964ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
965 size_t numSamples = batch.samples.size();
966 size_t index = 0;
967 while (index < numSamples
968 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
969 index += 1;
970 }
971 return ssize_t(index) - 1;
972}
973
974} // namespace android