2 // Copyright 2010 The Android Open Source Project
4 // Provides a shared memory transport for input events.
6 #define LOG_TAG "InputTransport"
10 // Log debug messages about channel messages (send message, receive message)
11 #define DEBUG_CHANNEL_MESSAGES 0
13 // Log debug messages whenever InputChannel objects are created/destroyed
14 #define DEBUG_CHANNEL_LIFECYCLE 0
16 // Log debug messages about transport actions
17 #define DEBUG_TRANSPORT_ACTIONS 0
19 // Log debug messages about touch event resampling
20 #define DEBUG_RESAMPLING 0
26 #include <sys/socket.h>
27 #include <sys/types.h>
30 #include <cutils/properties.h>
33 #include <input/InputTransport.h>
37 // Socket buffer size. The default is typically about 128KB, which is much larger than
38 // we really need. So we make it smaller. It just needs to be big enough to hold
39 // a few dozen large multi-finger motion events in the case where an application gets
40 // behind processing touches.
41 static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
43 // Nanoseconds per milliseconds.
44 static const nsecs_t NANOS_PER_MS = 1000000;
46 // Latency added during resampling. A few milliseconds doesn't hurt much but
47 // reduces the impact of mispredicted touch positions.
48 static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
50 // Minimum time difference between consecutive samples before attempting to resample.
51 static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
53 // Maximum time difference between consecutive samples before attempting to resample
55 static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
57 // Maximum time to predict forward from the last known state, to avoid predicting too
58 // far into the future. This time is further bounded by 50% of the last time delta.
59 static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
62 inline static T min(const T& a, const T& b) {
66 inline static float lerp(float a, float b, float alpha) {
67 return a + alpha * (b - a);
70 // --- InputMessage ---
72 bool InputMessage::isValid(size_t actualSize) const {
73 if (size() == actualSize) {
74 switch (header.type) {
78 return body.motion.pointerCount > 0
79 && body.motion.pointerCount <= MAX_POINTERS;
87 size_t InputMessage::size() const {
88 switch (header.type) {
90 return sizeof(Header) + body.key.size();
92 return sizeof(Header) + body.motion.size();
94 return sizeof(Header) + body.finished.size();
96 return sizeof(Header);
100 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
101 * memory to zero, then only copy the valid bytes on a per-field basis.
103 void InputMessage::getSanitizedCopy(InputMessage* msg) const {
104 memset(msg, 0, sizeof(*msg));
107 msg->header.type = header.type;
110 switch(header.type) {
111 case InputMessage::TYPE_KEY: {
113 msg->body.key.seq = body.key.seq;
115 msg->body.key.eventTime = body.key.eventTime;
117 msg->body.key.deviceId = body.key.deviceId;
119 msg->body.key.source = body.key.source;
121 msg->body.key.displayId = body.key.displayId;
123 msg->body.key.action = body.key.action;
125 msg->body.key.flags = body.key.flags;
127 msg->body.key.keyCode = body.key.keyCode;
129 msg->body.key.scanCode = body.key.scanCode;
131 msg->body.key.metaState = body.key.metaState;
132 // int32_t repeatCount
133 msg->body.key.repeatCount = body.key.repeatCount;
135 msg->body.key.downTime = body.key.downTime;
138 case InputMessage::TYPE_MOTION: {
140 msg->body.motion.seq = body.motion.seq;
142 msg->body.motion.eventTime = body.motion.eventTime;
144 msg->body.motion.deviceId = body.motion.deviceId;
146 msg->body.motion.source = body.motion.source;
148 msg->body.motion.displayId = body.motion.displayId;
150 msg->body.motion.action = body.motion.action;
151 // int32_t actionButton
152 msg->body.motion.actionButton = body.motion.actionButton;
154 msg->body.motion.flags = body.motion.flags;
156 msg->body.motion.metaState = body.motion.metaState;
157 // int32_t buttonState
158 msg->body.motion.buttonState = body.motion.buttonState;
160 msg->body.motion.edgeFlags = body.motion.edgeFlags;
162 msg->body.motion.downTime = body.motion.downTime;
164 msg->body.motion.xOffset = body.motion.xOffset;
166 msg->body.motion.yOffset = body.motion.yOffset;
168 msg->body.motion.xPrecision = body.motion.xPrecision;
170 msg->body.motion.yPrecision = body.motion.yPrecision;
171 // uint32_t pointerCount
172 msg->body.motion.pointerCount = body.motion.pointerCount;
173 //struct Pointer pointers[MAX_POINTERS]
174 for (size_t i = 0; i < body.motion.pointerCount; i++) {
175 // PointerProperties properties
176 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
177 msg->body.motion.pointers[i].properties.toolType =
178 body.motion.pointers[i].properties.toolType,
179 // PointerCoords coords
180 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
181 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
182 memcpy(&msg->body.motion.pointers[i].coords.values[0],
183 &body.motion.pointers[i].coords.values[0],
184 count * (sizeof(body.motion.pointers[i].coords.values[0])));
188 case InputMessage::TYPE_FINISHED: {
189 msg->body.finished.seq = body.finished.seq;
190 msg->body.finished.handled = body.finished.handled;
194 LOG_FATAL("Unexpected message type %i", header.type);
200 // --- InputChannel ---
202 InputChannel::InputChannel(const String8& name, int fd) :
203 mName(name), mFd(fd) {
204 #if DEBUG_CHANNEL_LIFECYCLE
205 ALOGD("Input channel constructed: name='%s', fd=%d",
209 int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
210 LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
211 "non-blocking. errno=%d", mName.string(), errno);
214 InputChannel::~InputChannel() {
215 #if DEBUG_CHANNEL_LIFECYCLE
216 ALOGD("Input channel destroyed: name='%s', fd=%d",
217 mName.string(), mFd);
223 status_t InputChannel::openInputChannelPair(const String8& name,
224 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
226 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
227 status_t result = -errno;
228 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
229 name.string(), errno);
230 outServerChannel.clear();
231 outClientChannel.clear();
235 int bufferSize = SOCKET_BUFFER_SIZE;
236 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
237 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
238 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
239 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
241 String8 serverChannelName = name;
242 serverChannelName.append(" (server)");
243 outServerChannel = new InputChannel(serverChannelName, sockets[0]);
245 String8 clientChannelName = name;
246 clientChannelName.append(" (client)");
247 outClientChannel = new InputChannel(clientChannelName, sockets[1]);
251 status_t InputChannel::sendMessage(const InputMessage* msg) {
252 const size_t msgLength = msg->size();
253 InputMessage cleanMsg;
254 msg->getSanitizedCopy(&cleanMsg);
257 nWrite = ::send(mFd, &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
258 } while (nWrite == -1 && errno == EINTR);
262 #if DEBUG_CHANNEL_MESSAGES
263 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.string(),
264 msg->header.type, error);
266 if (error == EAGAIN || error == EWOULDBLOCK) {
269 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
275 if (size_t(nWrite) != msgLength) {
276 #if DEBUG_CHANNEL_MESSAGES
277 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
278 mName.string(), msg->header.type);
283 #if DEBUG_CHANNEL_MESSAGES
284 ALOGD("channel '%s' ~ sent message of type %d", mName.string(), msg->header.type);
289 status_t InputChannel::receiveMessage(InputMessage* msg) {
292 nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
293 } while (nRead == -1 && errno == EINTR);
297 #if DEBUG_CHANNEL_MESSAGES
298 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.string(), errno);
300 if (error == EAGAIN || error == EWOULDBLOCK) {
303 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
309 if (nRead == 0) { // check for EOF
310 #if DEBUG_CHANNEL_MESSAGES
311 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.string());
316 if (!msg->isValid(nRead)) {
317 #if DEBUG_CHANNEL_MESSAGES
318 ALOGD("channel '%s' ~ received invalid message", mName.string());
323 #if DEBUG_CHANNEL_MESSAGES
324 ALOGD("channel '%s' ~ received message of type %d", mName.string(), msg->header.type);
329 sp<InputChannel> InputChannel::dup() const {
330 int fd = ::dup(getFd());
331 return fd >= 0 ? new InputChannel(getName(), fd) : NULL;
335 // --- InputPublisher ---
337 InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
341 InputPublisher::~InputPublisher() {
344 status_t InputPublisher::publishKeyEvent(
356 #if DEBUG_TRANSPORT_ACTIONS
357 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
358 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
359 "downTime=%lld, eventTime=%lld",
360 mChannel->getName().string(), seq,
361 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
362 downTime, eventTime);
366 ALOGE("Attempted to publish a key event with sequence number 0.");
371 msg.header.type = InputMessage::TYPE_KEY;
372 msg.body.key.seq = seq;
373 msg.body.key.deviceId = deviceId;
374 msg.body.key.source = source;
375 msg.body.key.action = action;
376 msg.body.key.flags = flags;
377 msg.body.key.keyCode = keyCode;
378 msg.body.key.scanCode = scanCode;
379 msg.body.key.metaState = metaState;
380 msg.body.key.repeatCount = repeatCount;
381 msg.body.key.downTime = downTime;
382 msg.body.key.eventTime = eventTime;
383 return mChannel->sendMessage(&msg);
386 status_t InputPublisher::publishMotionEvent(
392 int32_t actionButton,
403 uint32_t pointerCount,
404 const PointerProperties* pointerProperties,
405 const PointerCoords* pointerCoords) {
406 #if DEBUG_TRANSPORT_ACTIONS
407 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
408 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
409 "metaState=0x%x, buttonState=0x%x, xOffset=%f, yOffset=%f, "
410 "xPrecision=%f, yPrecision=%f, downTime=%lld, eventTime=%lld, "
411 "pointerCount=%" PRIu32,
412 mChannel->getName().string(), seq,
413 deviceId, source, action, actionButton, flags, edgeFlags, metaState, buttonState,
414 xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
418 ALOGE("Attempted to publish a motion event with sequence number 0.");
422 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
423 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
424 mChannel->getName().string(), pointerCount);
429 msg.header.type = InputMessage::TYPE_MOTION;
430 msg.body.motion.seq = seq;
431 msg.body.motion.deviceId = deviceId;
432 msg.body.motion.source = source;
433 msg.body.motion.displayId = displayId;
434 msg.body.motion.action = action;
435 msg.body.motion.actionButton = actionButton;
436 msg.body.motion.flags = flags;
437 msg.body.motion.edgeFlags = edgeFlags;
438 msg.body.motion.metaState = metaState;
439 msg.body.motion.buttonState = buttonState;
440 msg.body.motion.xOffset = xOffset;
441 msg.body.motion.yOffset = yOffset;
442 msg.body.motion.xPrecision = xPrecision;
443 msg.body.motion.yPrecision = yPrecision;
444 msg.body.motion.downTime = downTime;
445 msg.body.motion.eventTime = eventTime;
446 msg.body.motion.pointerCount = pointerCount;
447 for (uint32_t i = 0; i < pointerCount; i++) {
448 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
449 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
451 return mChannel->sendMessage(&msg);
454 status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
455 #if DEBUG_TRANSPORT_ACTIONS
456 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
457 mChannel->getName().string());
461 status_t result = mChannel->receiveMessage(&msg);
467 if (msg.header.type != InputMessage::TYPE_FINISHED) {
468 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
469 mChannel->getName().string(), msg.header.type);
470 return UNKNOWN_ERROR;
472 *outSeq = msg.body.finished.seq;
473 *outHandled = msg.body.finished.handled;
477 // --- InputConsumer ---
479 InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
480 mResampleTouch(isTouchResamplingEnabled()),
481 mChannel(channel), mMsgDeferred(false) {
484 InputConsumer::~InputConsumer() {
487 bool InputConsumer::isTouchResamplingEnabled() {
488 char value[PROPERTY_VALUE_MAX];
489 int length = property_get("ro.input.noresample", value, NULL);
491 if (!strcmp("1", value)) {
494 if (strcmp("0", value)) {
495 ALOGD("Unrecognized property value for 'ro.input.noresample'. "
502 status_t InputConsumer::consume(InputEventFactoryInterface* factory,
503 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent,
504 int32_t* displayId) {
505 #if DEBUG_TRANSPORT_ACTIONS
506 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%lld",
507 mChannel->getName().string(), consumeBatches ? "true" : "false", frameTime);
512 *displayId = -1; // Invalid display.
514 // Fetch the next input message.
515 // Loop until an event can be returned or no additional events are received.
518 // mMsg contains a valid input message from the previous call to consume
519 // that has not yet been processed.
520 mMsgDeferred = false;
522 // Receive a fresh message.
523 status_t result = mChannel->receiveMessage(&mMsg);
525 // Consume the next batched event unless batches are being held for later.
526 if (consumeBatches || result != WOULD_BLOCK) {
527 result = consumeBatch(factory, frameTime, outSeq, outEvent, displayId);
529 #if DEBUG_TRANSPORT_ACTIONS
530 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
531 mChannel->getName().string(), *outSeq);
540 switch (mMsg.header.type) {
541 case InputMessage::TYPE_KEY: {
542 KeyEvent* keyEvent = factory->createKeyEvent();
543 if (!keyEvent) return NO_MEMORY;
545 initializeKeyEvent(keyEvent, &mMsg);
546 *outSeq = mMsg.body.key.seq;
547 *outEvent = keyEvent;
548 #if DEBUG_TRANSPORT_ACTIONS
549 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
550 mChannel->getName().string(), *outSeq);
555 case AINPUT_EVENT_TYPE_MOTION: {
556 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
557 if (batchIndex >= 0) {
558 Batch& batch = mBatches.editItemAt(batchIndex);
559 if (canAddSample(batch, &mMsg)) {
560 batch.samples.push(mMsg);
561 #if DEBUG_TRANSPORT_ACTIONS
562 ALOGD("channel '%s' consumer ~ appended to batch event",
563 mChannel->getName().string());
567 // We cannot append to the batch in progress, so we need to consume
568 // the previous batch right now and defer the new message until later.
570 status_t result = consumeSamples(factory,
571 batch, batch.samples.size(), outSeq, outEvent, displayId);
572 mBatches.removeAt(batchIndex);
576 #if DEBUG_TRANSPORT_ACTIONS
577 ALOGD("channel '%s' consumer ~ consumed batch event and "
578 "deferred current event, seq=%u",
579 mChannel->getName().string(), *outSeq);
585 // Start a new batch if needed.
586 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
587 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
589 Batch& batch = mBatches.editTop();
590 batch.samples.push(mMsg);
591 #if DEBUG_TRANSPORT_ACTIONS
592 ALOGD("channel '%s' consumer ~ started batch event",
593 mChannel->getName().string());
598 MotionEvent* motionEvent = factory->createMotionEvent();
599 if (! motionEvent) return NO_MEMORY;
601 updateTouchState(mMsg);
602 initializeMotionEvent(motionEvent, &mMsg);
603 *outSeq = mMsg.body.motion.seq;
604 *outEvent = motionEvent;
605 *displayId = mMsg.body.motion.displayId;
606 #if DEBUG_TRANSPORT_ACTIONS
607 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
608 mChannel->getName().string(), *outSeq);
614 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
615 mChannel->getName().string(), mMsg.header.type);
616 return UNKNOWN_ERROR;
622 status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
623 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId) {
625 for (size_t i = mBatches.size(); i > 0; ) {
627 Batch& batch = mBatches.editItemAt(i);
629 result = consumeSamples(factory, batch, batch.samples.size(),
630 outSeq, outEvent, displayId);
631 mBatches.removeAt(i);
635 nsecs_t sampleTime = frameTime;
636 if (mResampleTouch) {
637 sampleTime -= RESAMPLE_LATENCY;
639 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
644 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent, displayId);
645 const InputMessage* next;
646 if (batch.samples.isEmpty()) {
647 mBatches.removeAt(i);
650 next = &batch.samples.itemAt(0);
652 if (!result && mResampleTouch) {
653 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
661 status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
662 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId) {
663 MotionEvent* motionEvent = factory->createMotionEvent();
664 if (! motionEvent) return NO_MEMORY;
667 for (size_t i = 0; i < count; i++) {
668 InputMessage& msg = batch.samples.editItemAt(i);
669 updateTouchState(msg);
672 seqChain.seq = msg.body.motion.seq;
673 seqChain.chain = chain;
674 mSeqChains.push(seqChain);
675 addSample(motionEvent, &msg);
677 *displayId = msg.body.motion.displayId;
678 initializeMotionEvent(motionEvent, &msg);
680 chain = msg.body.motion.seq;
682 batch.samples.removeItemsAt(0, count);
685 *outEvent = motionEvent;
689 void InputConsumer::updateTouchState(InputMessage& msg) {
690 if (!mResampleTouch ||
691 !(msg.body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
695 int32_t deviceId = msg.body.motion.deviceId;
696 int32_t source = msg.body.motion.source;
698 // Update the touch state history to incorporate the new input message.
699 // If the message is in the past relative to the most recently produced resampled
700 // touch, then use the resampled time and coordinates instead.
701 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
702 case AMOTION_EVENT_ACTION_DOWN: {
703 ssize_t index = findTouchState(deviceId, source);
706 index = mTouchStates.size() - 1;
708 TouchState& touchState = mTouchStates.editItemAt(index);
709 touchState.initialize(deviceId, source);
710 touchState.addHistory(msg);
714 case AMOTION_EVENT_ACTION_MOVE: {
715 ssize_t index = findTouchState(deviceId, source);
717 TouchState& touchState = mTouchStates.editItemAt(index);
718 touchState.addHistory(msg);
719 bool messageRewritten = rewriteMessage(touchState, msg);
720 if (!messageRewritten) {
721 touchState.lastResample.idBits.clear();
727 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
728 ssize_t index = findTouchState(deviceId, source);
730 TouchState& touchState = mTouchStates.editItemAt(index);
731 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
732 rewriteMessage(touchState, msg);
737 case AMOTION_EVENT_ACTION_POINTER_UP: {
738 ssize_t index = findTouchState(deviceId, source);
740 TouchState& touchState = mTouchStates.editItemAt(index);
741 rewriteMessage(touchState, msg);
742 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
747 case AMOTION_EVENT_ACTION_SCROLL: {
748 ssize_t index = findTouchState(deviceId, source);
750 const TouchState& touchState = mTouchStates.itemAt(index);
751 rewriteMessage(touchState, msg);
756 case AMOTION_EVENT_ACTION_UP:
757 case AMOTION_EVENT_ACTION_CANCEL: {
758 ssize_t index = findTouchState(deviceId, source);
760 const TouchState& touchState = mTouchStates.itemAt(index);
761 rewriteMessage(touchState, msg);
762 mTouchStates.removeAt(index);
769 bool InputConsumer::rewriteMessage(const TouchState& state, InputMessage& msg) {
770 bool messageRewritten = false;
771 nsecs_t eventTime = msg.body.motion.eventTime;
772 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
773 uint32_t id = msg.body.motion.pointers[i].properties.id;
774 if (state.lastResample.idBits.hasBit(id)) {
775 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
776 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
777 if (eventTime < state.lastResample.eventTime ||
778 state.recentCoordinatesAreIdentical(id)) {
779 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
780 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
782 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
783 resampleCoords.getX(), resampleCoords.getY(),
784 msgCoords.getX(), msgCoords.getY());
786 messageRewritten = true;
790 return messageRewritten;
793 void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
794 const InputMessage* next) {
796 || !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
797 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
801 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
804 ALOGD("Not resampled, no touch state for device.");
809 TouchState& touchState = mTouchStates.editItemAt(index);
810 if (touchState.historySize < 1) {
812 ALOGD("Not resampled, no history for device.");
817 // Ensure that the current sample has all of the pointers that need to be reported.
818 // Also ensure that the past two "real" touch events do not contain duplicate coordinates
819 const History* current = touchState.getHistory(0);
820 size_t pointerCount = event->getPointerCount();
821 for (size_t i = 0; i < pointerCount; i++) {
822 uint32_t id = event->getPointerId(i);
823 if (!current->idBits.hasBit(id)) {
825 ALOGD("Not resampled, missing id %d", id);
829 if (touchState.recentCoordinatesAreIdentical(id)) {
831 ALOGD("Not resampled, past two historical events have duplicate coordinates");
837 // Find the data to use for resampling.
838 const History* other;
842 // Interpolate between current sample and future sample.
843 // So current->eventTime <= sampleTime <= future.eventTime.
844 future.initializeFrom(*next);
846 nsecs_t delta = future.eventTime - current->eventTime;
847 if (delta < RESAMPLE_MIN_DELTA) {
849 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
853 alpha = float(sampleTime - current->eventTime) / delta;
854 } else if (touchState.historySize >= 2) {
855 // Extrapolate future sample using current sample and past sample.
856 // So other->eventTime <= current->eventTime <= sampleTime.
857 other = touchState.getHistory(1);
858 nsecs_t delta = current->eventTime - other->eventTime;
859 if (delta < RESAMPLE_MIN_DELTA) {
861 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
864 } else if (delta > RESAMPLE_MAX_DELTA) {
866 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
870 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
871 if (sampleTime > maxPredict) {
873 ALOGD("Sample time is too far in the future, adjusting prediction "
874 "from %" PRId64 " to %" PRId64 " ns.",
875 sampleTime - current->eventTime, maxPredict - current->eventTime);
877 sampleTime = maxPredict;
879 alpha = float(current->eventTime - sampleTime) / delta;
882 ALOGD("Not resampled, insufficient data.");
887 // Resample touch coordinates.
888 touchState.lastResample.eventTime = sampleTime;
889 touchState.lastResample.idBits.clear();
890 for (size_t i = 0; i < pointerCount; i++) {
891 uint32_t id = event->getPointerId(i);
892 touchState.lastResample.idToIndex[id] = i;
893 touchState.lastResample.idBits.markBit(id);
894 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
895 const PointerCoords& currentCoords = current->getPointerById(id);
896 if (other->idBits.hasBit(id)
897 && shouldResampleTool(event->getToolType(i))) {
898 const PointerCoords& otherCoords = other->getPointerById(id);
899 resampledCoords.copyFrom(currentCoords);
900 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
901 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
902 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
903 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
905 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
906 "other (%0.3f, %0.3f), alpha %0.3f",
907 id, resampledCoords.getX(), resampledCoords.getY(),
908 currentCoords.getX(), currentCoords.getY(),
909 otherCoords.getX(), otherCoords.getY(),
913 resampledCoords.copyFrom(currentCoords);
915 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
916 id, resampledCoords.getX(), resampledCoords.getY(),
917 currentCoords.getX(), currentCoords.getY());
922 event->addSample(sampleTime, touchState.lastResample.pointers);
925 bool InputConsumer::shouldResampleTool(int32_t toolType) {
926 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
927 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
930 status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
931 #if DEBUG_TRANSPORT_ACTIONS
932 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
933 mChannel->getName().string(), seq, handled ? "true" : "false");
937 ALOGE("Attempted to send a finished signal with sequence number 0.");
941 // Send finished signals for the batch sequence chain first.
942 size_t seqChainCount = mSeqChains.size();
944 uint32_t currentSeq = seq;
945 uint32_t chainSeqs[seqChainCount];
946 size_t chainIndex = 0;
947 for (size_t i = seqChainCount; i > 0; ) {
949 const SeqChain& seqChain = mSeqChains.itemAt(i);
950 if (seqChain.seq == currentSeq) {
951 currentSeq = seqChain.chain;
952 chainSeqs[chainIndex++] = currentSeq;
953 mSeqChains.removeAt(i);
956 status_t status = OK;
957 while (!status && chainIndex > 0) {
959 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
962 // An error occurred so at least one signal was not sent, reconstruct the chain.
965 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
966 seqChain.chain = chainSeqs[chainIndex];
967 mSeqChains.push(seqChain);
968 if (!chainIndex) break;
975 // Send finished signal for the last message in the batch.
976 return sendUnchainedFinishedSignal(seq, handled);
979 status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
981 msg.header.type = InputMessage::TYPE_FINISHED;
982 msg.body.finished.seq = seq;
983 msg.body.finished.handled = handled;
984 return mChannel->sendMessage(&msg);
987 bool InputConsumer::hasDeferredEvent() const {
991 bool InputConsumer::hasPendingBatch() const {
992 return !mBatches.isEmpty();
995 ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
996 for (size_t i = 0; i < mBatches.size(); i++) {
997 const Batch& batch = mBatches.itemAt(i);
998 const InputMessage& head = batch.samples.itemAt(0);
999 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1006 ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1007 for (size_t i = 0; i < mTouchStates.size(); i++) {
1008 const TouchState& touchState = mTouchStates.itemAt(i);
1009 if (touchState.deviceId == deviceId && touchState.source == source) {
1016 void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
1018 msg->body.key.deviceId,
1019 msg->body.key.source,
1020 msg->body.key.action,
1021 msg->body.key.flags,
1022 msg->body.key.keyCode,
1023 msg->body.key.scanCode,
1024 msg->body.key.metaState,
1025 msg->body.key.repeatCount,
1026 msg->body.key.downTime,
1027 msg->body.key.eventTime);
1030 void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
1031 uint32_t pointerCount = msg->body.motion.pointerCount;
1032 PointerProperties pointerProperties[pointerCount];
1033 PointerCoords pointerCoords[pointerCount];
1034 for (uint32_t i = 0; i < pointerCount; i++) {
1035 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1036 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1040 msg->body.motion.deviceId,
1041 msg->body.motion.source,
1042 msg->body.motion.action,
1043 msg->body.motion.actionButton,
1044 msg->body.motion.flags,
1045 msg->body.motion.edgeFlags,
1046 msg->body.motion.metaState,
1047 msg->body.motion.buttonState,
1048 msg->body.motion.xOffset,
1049 msg->body.motion.yOffset,
1050 msg->body.motion.xPrecision,
1051 msg->body.motion.yPrecision,
1052 msg->body.motion.downTime,
1053 msg->body.motion.eventTime,
1059 void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
1060 uint32_t pointerCount = msg->body.motion.pointerCount;
1061 PointerCoords pointerCoords[pointerCount];
1062 for (uint32_t i = 0; i < pointerCount; i++) {
1063 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1066 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1067 event->addSample(msg->body.motion.eventTime, pointerCoords);
1070 bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1071 const InputMessage& head = batch.samples.itemAt(0);
1072 uint32_t pointerCount = msg->body.motion.pointerCount;
1073 if (head.body.motion.pointerCount != pointerCount
1074 || head.body.motion.action != msg->body.motion.action) {
1077 for (size_t i = 0; i < pointerCount; i++) {
1078 if (head.body.motion.pointers[i].properties
1079 != msg->body.motion.pointers[i].properties) {
1086 ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1087 size_t numSamples = batch.samples.size();
1089 while (index < numSamples
1090 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1093 return ssize_t(index) - 1;
1096 } // namespace android