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