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