InputTransport.cpp 33 KB

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