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