blob: 91ab008161036c9aca664dedb08ccb5737ee6293 [file] [log] [blame]
Jeff Brown5912f952013-07-01 19:10:31 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// Provides a shared memory transport for input events.
5//
6#define LOG_TAG "InputTransport"
7
8//#define LOG_NDEBUG 0
9
10// Log debug messages about channel messages (send message, receive message)
11#define DEBUG_CHANNEL_MESSAGES 0
12
13// Log debug messages whenever InputChannel objects are created/destroyed
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -070014static constexpr bool DEBUG_CHANNEL_LIFECYCLE = false;
Jeff Brown5912f952013-07-01 19:10:31 -070015
16// Log debug messages about transport actions
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080017static constexpr bool DEBUG_TRANSPORT_ACTIONS = false;
Jeff Brown5912f952013-07-01 19:10:31 -070018
19// Log debug messages about touch event resampling
20#define DEBUG_RESAMPLING 0
21
Jeff Brown5912f952013-07-01 19:10:31 -070022#include <errno.h>
23#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070024#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070025#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070026#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070027#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070028#include <unistd.h>
29
Michael Wright3dd60e22019-03-27 22:06:44 +000030#include <android-base/stringprintf.h>
31#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070032#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080033#include <ftl/enum.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000035#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070036
Jeff Brown5912f952013-07-01 19:10:31 -070037#include <input/InputTransport.h>
38
Michael Wright3dd60e22019-03-27 22:06:44 +000039using android::base::StringPrintf;
40
Jeff Brown5912f952013-07-01 19:10:31 -070041namespace android {
42
43// Socket buffer size. The default is typically about 128KB, which is much larger than
44// we really need. So we make it smaller. It just needs to be big enough to hold
45// a few dozen large multi-finger motion events in the case where an application gets
46// behind processing touches.
47static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
48
49// Nanoseconds per milliseconds.
50static const nsecs_t NANOS_PER_MS = 1000000;
51
52// Latency added during resampling. A few milliseconds doesn't hurt much but
53// reduces the impact of mispredicted touch positions.
54static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
55
56// Minimum time difference between consecutive samples before attempting to resample.
57static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
58
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070059// Maximum time difference between consecutive samples before attempting to resample
60// by extrapolation.
61static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
62
Jeff Brown5912f952013-07-01 19:10:31 -070063// Maximum time to predict forward from the last known state, to avoid predicting too
64// far into the future. This time is further bounded by 50% of the last time delta.
65static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
66
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -060067/**
68 * System property for enabling / disabling touch resampling.
69 * Resampling extrapolates / interpolates the reported touch event coordinates to better
70 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
71 * Resampling is not needed (and should be disabled) on hardware that already
72 * has touch events triggered by VSYNC.
73 * Set to "1" to enable resampling (default).
74 * Set to "0" to disable resampling.
75 * Resampling is enabled by default.
76 */
77static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
78
Jeff Brown5912f952013-07-01 19:10:31 -070079template<typename T>
80inline static T min(const T& a, const T& b) {
81 return a < b ? a : b;
82}
83
84inline static float lerp(float a, float b, float alpha) {
85 return a + alpha * (b - a);
86}
87
Siarhei Vishniakou128eab12019-05-23 10:25:59 +080088inline static bool isPointerEvent(int32_t source) {
89 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
90}
91
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080092inline static const char* toString(bool value) {
93 return value ? "true" : "false";
94}
95
Jeff Brown5912f952013-07-01 19:10:31 -070096// --- InputMessage ---
97
98bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +000099 if (size() != actualSize) {
100 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
101 return false;
102 }
103
104 switch (header.type) {
105 case Type::KEY:
106 return true;
107 case Type::MOTION: {
108 const bool valid =
109 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
110 if (!valid) {
111 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
112 }
113 return valid;
114 }
115 case Type::FINISHED:
116 case Type::FOCUS:
117 case Type::CAPTURE:
118 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700119 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000120 return true;
121 case Type::TIMELINE: {
122 const nsecs_t gpuCompletedTime =
123 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
124 const nsecs_t presentTime =
125 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
126 const bool valid = presentTime > gpuCompletedTime;
127 if (!valid) {
128 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
129 " presentTime = %" PRId64,
130 gpuCompletedTime, presentTime);
131 }
132 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700133 }
134 }
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000135 ALOGE("Invalid message type: %" PRIu32, header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700136 return false;
137}
138
139size_t InputMessage::size() const {
140 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700141 case Type::KEY:
142 return sizeof(Header) + body.key.size();
143 case Type::MOTION:
144 return sizeof(Header) + body.motion.size();
145 case Type::FINISHED:
146 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800147 case Type::FOCUS:
148 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800149 case Type::CAPTURE:
150 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800151 case Type::DRAG:
152 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000153 case Type::TIMELINE:
154 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700155 case Type::TOUCH_MODE:
156 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700157 }
158 return sizeof(Header);
159}
160
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800161/**
162 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
163 * memory to zero, then only copy the valid bytes on a per-field basis.
164 */
165void InputMessage::getSanitizedCopy(InputMessage* msg) const {
166 memset(msg, 0, sizeof(*msg));
167
168 // Write the header
169 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500170 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800171
172 // Write the body
173 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700174 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800175 // int32_t eventId
176 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800177 // nsecs_t eventTime
178 msg->body.key.eventTime = body.key.eventTime;
179 // int32_t deviceId
180 msg->body.key.deviceId = body.key.deviceId;
181 // int32_t source
182 msg->body.key.source = body.key.source;
183 // int32_t displayId
184 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600185 // std::array<uint8_t, 32> hmac
186 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800187 // int32_t action
188 msg->body.key.action = body.key.action;
189 // int32_t flags
190 msg->body.key.flags = body.key.flags;
191 // int32_t keyCode
192 msg->body.key.keyCode = body.key.keyCode;
193 // int32_t scanCode
194 msg->body.key.scanCode = body.key.scanCode;
195 // int32_t metaState
196 msg->body.key.metaState = body.key.metaState;
197 // int32_t repeatCount
198 msg->body.key.repeatCount = body.key.repeatCount;
199 // nsecs_t downTime
200 msg->body.key.downTime = body.key.downTime;
201 break;
202 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700203 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800204 // int32_t eventId
205 msg->body.motion.eventId = body.motion.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800206 // nsecs_t eventTime
207 msg->body.motion.eventTime = body.motion.eventTime;
208 // int32_t deviceId
209 msg->body.motion.deviceId = body.motion.deviceId;
210 // int32_t source
211 msg->body.motion.source = body.motion.source;
212 // int32_t displayId
213 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600214 // std::array<uint8_t, 32> hmac
215 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800216 // int32_t action
217 msg->body.motion.action = body.motion.action;
218 // int32_t actionButton
219 msg->body.motion.actionButton = body.motion.actionButton;
220 // int32_t flags
221 msg->body.motion.flags = body.motion.flags;
222 // int32_t metaState
223 msg->body.motion.metaState = body.motion.metaState;
224 // int32_t buttonState
225 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800226 // MotionClassification classification
227 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800228 // int32_t edgeFlags
229 msg->body.motion.edgeFlags = body.motion.edgeFlags;
230 // nsecs_t downTime
231 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700232
233 msg->body.motion.dsdx = body.motion.dsdx;
234 msg->body.motion.dtdx = body.motion.dtdx;
235 msg->body.motion.dtdy = body.motion.dtdy;
236 msg->body.motion.dsdy = body.motion.dsdy;
237 msg->body.motion.tx = body.motion.tx;
238 msg->body.motion.ty = body.motion.ty;
239
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800240 // float xPrecision
241 msg->body.motion.xPrecision = body.motion.xPrecision;
242 // float yPrecision
243 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700244 // float xCursorPosition
245 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
246 // float yCursorPosition
247 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Evan Rosky09576692021-07-01 12:22:09 -0700248 // uint32_t displayOrientation
249 msg->body.motion.displayOrientation = body.motion.displayOrientation;
250 // int32_t displayWidth
Evan Rosky84f07f02021-04-16 10:42:42 -0700251 msg->body.motion.displayWidth = body.motion.displayWidth;
Evan Rosky09576692021-07-01 12:22:09 -0700252 // int32_t displayHeight
Evan Rosky84f07f02021-04-16 10:42:42 -0700253 msg->body.motion.displayHeight = body.motion.displayHeight;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800254 // uint32_t pointerCount
255 msg->body.motion.pointerCount = body.motion.pointerCount;
256 //struct Pointer pointers[MAX_POINTERS]
257 for (size_t i = 0; i < body.motion.pointerCount; i++) {
258 // PointerProperties properties
259 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
260 msg->body.motion.pointers[i].properties.toolType =
261 body.motion.pointers[i].properties.toolType,
262 // PointerCoords coords
263 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
264 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
265 memcpy(&msg->body.motion.pointers[i].coords.values[0],
266 &body.motion.pointers[i].coords.values[0],
267 count * (sizeof(body.motion.pointers[i].coords.values[0])));
268 }
269 break;
270 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700271 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800272 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000273 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800274 break;
275 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800276 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800277 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800278 msg->body.focus.hasFocus = body.focus.hasFocus;
279 msg->body.focus.inTouchMode = body.focus.inTouchMode;
280 break;
281 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800282 case InputMessage::Type::CAPTURE: {
283 msg->body.capture.eventId = body.capture.eventId;
284 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
285 break;
286 }
arthurhung7632c332020-12-30 16:58:01 +0800287 case InputMessage::Type::DRAG: {
288 msg->body.drag.eventId = body.drag.eventId;
289 msg->body.drag.x = body.drag.x;
290 msg->body.drag.y = body.drag.y;
291 msg->body.drag.isExiting = body.drag.isExiting;
292 break;
293 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000294 case InputMessage::Type::TIMELINE: {
295 msg->body.timeline.eventId = body.timeline.eventId;
296 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
297 break;
298 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700299 case InputMessage::Type::TOUCH_MODE: {
300 msg->body.touchMode.eventId = body.touchMode.eventId;
301 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
302 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800303 }
304}
Jeff Brown5912f952013-07-01 19:10:31 -0700305
306// --- InputChannel ---
307
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500308std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500309 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700310 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
311 if (result != 0) {
312 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
313 strerror(errno));
314 return nullptr;
315 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500316 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500317 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700318}
319
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500320InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
321 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700322 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500323 ALOGD("Input channel constructed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700324 }
Jeff Brown5912f952013-07-01 19:10:31 -0700325}
326
327InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700328 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500329 ALOGD("Input channel destroyed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700330 }
Robert Carr3720ed02018-08-08 16:08:27 -0700331}
332
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800333status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500334 std::unique_ptr<InputChannel>& outServerChannel,
335 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700336 int sockets[2];
337 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
338 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000339 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
340 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500341 outServerChannel.reset();
342 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700343 return result;
344 }
345
346 int bufferSize = SOCKET_BUFFER_SIZE;
347 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
348 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
349 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
350 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
351
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700352 sp<IBinder> token = new BBinder();
353
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700354 std::string serverChannelName = name + " (server)";
355 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700356 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700357
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700358 std::string clientChannelName = name + " (client)";
359 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700360 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700361 return OK;
362}
363
364status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800365 const size_t msgLength = msg->size();
366 InputMessage cleanMsg;
367 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700368 ssize_t nWrite;
369 do {
Chris Ye0783e992020-06-02 21:34:49 -0700370 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700371 } while (nWrite == -1 && errno == EINTR);
372
373 if (nWrite < 0) {
374 int error = errno;
375#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800376 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
377 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700378#endif
379 if (error == EAGAIN || error == EWOULDBLOCK) {
380 return WOULD_BLOCK;
381 }
382 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
383 return DEAD_OBJECT;
384 }
385 return -error;
386 }
387
388 if (size_t(nWrite) != msgLength) {
389#if DEBUG_CHANNEL_MESSAGES
390 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800391 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700392#endif
393 return DEAD_OBJECT;
394 }
395
396#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800397 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700398#endif
399 return OK;
400}
401
402status_t InputChannel::receiveMessage(InputMessage* msg) {
403 ssize_t nRead;
404 do {
Chris Ye0783e992020-06-02 21:34:49 -0700405 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700406 } while (nRead == -1 && errno == EINTR);
407
408 if (nRead < 0) {
409 int error = errno;
410#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800411 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700412#endif
413 if (error == EAGAIN || error == EWOULDBLOCK) {
414 return WOULD_BLOCK;
415 }
416 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
417 return DEAD_OBJECT;
418 }
419 return -error;
420 }
421
422 if (nRead == 0) { // check for EOF
423#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800424 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700425#endif
426 return DEAD_OBJECT;
427 }
428
429 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000430 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700431 return BAD_VALUE;
432 }
433
434#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800435 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700436#endif
437 return OK;
438}
439
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500440std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700441 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700442 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700443}
444
Garfield Tan15601662020-09-22 15:32:38 -0700445void InputChannel::copyTo(InputChannel& outChannel) const {
446 outChannel.mName = getName();
447 outChannel.mFd = dupFd();
448 outChannel.mToken = getConnectionToken();
449}
450
Chris Ye0783e992020-06-02 21:34:49 -0700451status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500452 if (parcel == nullptr) {
453 ALOGE("%s: Null parcel", __func__);
454 return BAD_VALUE;
455 }
456 return parcel->writeStrongBinder(mToken)
457 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700458}
459
Chris Ye0783e992020-06-02 21:34:49 -0700460status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500461 if (parcel == nullptr) {
462 ALOGE("%s: Null parcel", __func__);
463 return BAD_VALUE;
464 }
465 mToken = parcel->readStrongBinder();
466 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700467}
468
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700469sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500470 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700471}
472
Garfield Tan15601662020-09-22 15:32:38 -0700473base::unique_fd InputChannel::dupFd() const {
474 android::base::unique_fd newFd(::dup(getFd()));
475 if (!newFd.ok()) {
476 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
477 strerror(errno));
478 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
479 // If this process is out of file descriptors, then throwing that might end up exploding
480 // on the other side of a binder call, which isn't really helpful.
481 // Better to just crash here and hope that the FD leak is slow.
482 // Other failures could be client errors, so we still propagate those back to the caller.
483 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
484 getName().c_str());
485 return {};
486 }
487 return newFd;
488}
489
Jeff Brown5912f952013-07-01 19:10:31 -0700490// --- InputPublisher ---
491
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500492InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700493
494InputPublisher::~InputPublisher() {
495}
496
Garfield Tan1c7bc862020-01-28 13:24:04 -0800497status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
498 int32_t source, int32_t displayId,
499 std::array<uint8_t, 32> hmac, int32_t action,
500 int32_t flags, int32_t keyCode, int32_t scanCode,
501 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
502 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000503 if (ATRACE_ENABLED()) {
504 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
505 mChannel->getName().c_str(), keyCode);
506 ATRACE_NAME(message.c_str());
507 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800508 if (DEBUG_TRANSPORT_ACTIONS) {
509 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
510 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
511 "downTime=%" PRId64 ", eventTime=%" PRId64,
512 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
513 metaState, repeatCount, downTime, eventTime);
514 }
Jeff Brown5912f952013-07-01 19:10:31 -0700515
516 if (!seq) {
517 ALOGE("Attempted to publish a key event with sequence number 0.");
518 return BAD_VALUE;
519 }
520
521 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700522 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500523 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800524 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700525 msg.body.key.deviceId = deviceId;
526 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100527 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700528 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700529 msg.body.key.action = action;
530 msg.body.key.flags = flags;
531 msg.body.key.keyCode = keyCode;
532 msg.body.key.scanCode = scanCode;
533 msg.body.key.metaState = metaState;
534 msg.body.key.repeatCount = repeatCount;
535 msg.body.key.downTime = downTime;
536 msg.body.key.eventTime = eventTime;
537 return mChannel->sendMessage(&msg);
538}
539
540status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800541 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600542 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
543 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700544 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Evan Rosky09576692021-07-01 12:22:09 -0700545 float yPrecision, float xCursorPosition, float yCursorPosition, uint32_t displayOrientation,
546 int32_t displayWidth, int32_t displayHeight, nsecs_t downTime, nsecs_t eventTime,
547 uint32_t pointerCount, const PointerProperties* pointerProperties,
548 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000549 if (ATRACE_ENABLED()) {
550 std::string message = StringPrintf(
551 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
552 mChannel->getName().c_str(), action);
553 ATRACE_NAME(message.c_str());
554 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800555 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700556 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700557 transform.dump(transformString, "transform", " ");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800558 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
559 "displayId=%" PRId32 ", "
560 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700561 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800562 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700563 "pointerCount=%" PRIu32 " \n%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800564 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
565 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700566 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
567 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800568 }
Jeff Brown5912f952013-07-01 19:10:31 -0700569
570 if (!seq) {
571 ALOGE("Attempted to publish a motion event with sequence number 0.");
572 return BAD_VALUE;
573 }
574
575 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700576 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800577 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700578 return BAD_VALUE;
579 }
580
581 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700582 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500583 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800584 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700585 msg.body.motion.deviceId = deviceId;
586 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700587 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700588 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700589 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100590 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700591 msg.body.motion.flags = flags;
592 msg.body.motion.edgeFlags = edgeFlags;
593 msg.body.motion.metaState = metaState;
594 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800595 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700596 msg.body.motion.dsdx = transform.dsdx();
597 msg.body.motion.dtdx = transform.dtdx();
598 msg.body.motion.dtdy = transform.dtdy();
599 msg.body.motion.dsdy = transform.dsdy();
600 msg.body.motion.tx = transform.tx();
601 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700602 msg.body.motion.xPrecision = xPrecision;
603 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700604 msg.body.motion.xCursorPosition = xCursorPosition;
605 msg.body.motion.yCursorPosition = yCursorPosition;
Evan Rosky09576692021-07-01 12:22:09 -0700606 msg.body.motion.displayOrientation = displayOrientation;
Evan Rosky84f07f02021-04-16 10:42:42 -0700607 msg.body.motion.displayWidth = displayWidth;
608 msg.body.motion.displayHeight = displayHeight;
Jeff Brown5912f952013-07-01 19:10:31 -0700609 msg.body.motion.downTime = downTime;
610 msg.body.motion.eventTime = eventTime;
611 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100612 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700613 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
614 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
615 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700616
Jeff Brown5912f952013-07-01 19:10:31 -0700617 return mChannel->sendMessage(&msg);
618}
619
Garfield Tan1c7bc862020-01-28 13:24:04 -0800620status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
621 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800622 if (ATRACE_ENABLED()) {
623 std::string message =
624 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
625 mChannel->getName().c_str(), toString(hasFocus),
626 toString(inTouchMode));
627 ATRACE_NAME(message.c_str());
628 }
629
630 InputMessage msg;
631 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500632 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800633 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000634 msg.body.focus.hasFocus = hasFocus;
635 msg.body.focus.inTouchMode = inTouchMode;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800636 return mChannel->sendMessage(&msg);
637}
638
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800639status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
640 bool pointerCaptureEnabled) {
641 if (ATRACE_ENABLED()) {
642 std::string message =
643 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
644 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
645 ATRACE_NAME(message.c_str());
646 }
647
648 InputMessage msg;
649 msg.header.type = InputMessage::Type::CAPTURE;
650 msg.header.seq = seq;
651 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000652 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800653 return mChannel->sendMessage(&msg);
654}
655
arthurhung7632c332020-12-30 16:58:01 +0800656status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
657 bool isExiting) {
658 if (ATRACE_ENABLED()) {
659 std::string message =
660 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
661 mChannel->getName().c_str(), x, y, toString(isExiting));
662 ATRACE_NAME(message.c_str());
663 }
664
665 InputMessage msg;
666 msg.header.type = InputMessage::Type::DRAG;
667 msg.header.seq = seq;
668 msg.body.drag.eventId = eventId;
669 msg.body.drag.isExiting = isExiting;
670 msg.body.drag.x = x;
671 msg.body.drag.y = y;
672 return mChannel->sendMessage(&msg);
673}
674
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700675status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
676 if (ATRACE_ENABLED()) {
677 std::string message =
678 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
679 mChannel->getName().c_str(), toString(isInTouchMode));
680 ATRACE_NAME(message.c_str());
681 }
682
683 InputMessage msg;
684 msg.header.type = InputMessage::Type::TOUCH_MODE;
685 msg.header.seq = seq;
686 msg.body.touchMode.eventId = eventId;
687 msg.body.touchMode.isInTouchMode = isInTouchMode;
688 return mChannel->sendMessage(&msg);
689}
690
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000691android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800692 if (DEBUG_TRANSPORT_ACTIONS) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000693 ALOGD("channel '%s' publisher ~ %s", mChannel->getName().c_str(), __func__);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800694 }
Jeff Brown5912f952013-07-01 19:10:31 -0700695
696 InputMessage msg;
697 status_t result = mChannel->receiveMessage(&msg);
698 if (result) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000699 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700700 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000701 if (msg.header.type == InputMessage::Type::FINISHED) {
702 return Finished{
703 .seq = msg.header.seq,
704 .handled = msg.body.finished.handled,
705 .consumeTime = msg.body.finished.consumeTime,
706 };
Jeff Brown5912f952013-07-01 19:10:31 -0700707 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000708
709 if (msg.header.type == InputMessage::Type::TIMELINE) {
710 return Timeline{
711 .inputEventId = msg.body.timeline.eventId,
712 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
713 };
714 }
715
716 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800717 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000718 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700719}
720
721// --- InputConsumer ---
722
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500723InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
724 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700725
726InputConsumer::~InputConsumer() {
727}
728
729bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600730 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700731}
732
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800733status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
734 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800735 if (DEBUG_TRANSPORT_ACTIONS) {
736 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
737 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
738 }
Jeff Brown5912f952013-07-01 19:10:31 -0700739
740 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700741 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700742
743 // Fetch the next input message.
744 // Loop until an event can be returned or no additional events are received.
745 while (!*outEvent) {
746 if (mMsgDeferred) {
747 // mMsg contains a valid input message from the previous call to consume
748 // that has not yet been processed.
749 mMsgDeferred = false;
750 } else {
751 // Receive a fresh message.
752 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000753 if (result == OK) {
754 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
755 }
Jeff Brown5912f952013-07-01 19:10:31 -0700756 if (result) {
757 // Consume the next batched event unless batches are being held for later.
758 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800759 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700760 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800761 if (DEBUG_TRANSPORT_ACTIONS) {
762 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
763 mChannel->getName().c_str(), *outSeq);
764 }
Jeff Brown5912f952013-07-01 19:10:31 -0700765 break;
766 }
767 }
768 return result;
769 }
770 }
771
772 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700773 case InputMessage::Type::KEY: {
774 KeyEvent* keyEvent = factory->createKeyEvent();
775 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700776
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700777 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500778 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700779 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800780 if (DEBUG_TRANSPORT_ACTIONS) {
781 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
782 mChannel->getName().c_str(), *outSeq);
783 }
Jeff Brown5912f952013-07-01 19:10:31 -0700784 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700785 }
Jeff Brown5912f952013-07-01 19:10:31 -0700786
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700787 case InputMessage::Type::MOTION: {
788 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
789 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500790 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700791 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500792 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800793 if (DEBUG_TRANSPORT_ACTIONS) {
794 ALOGD("channel '%s' consumer ~ appended to batch event",
795 mChannel->getName().c_str());
796 }
Jeff Brown5912f952013-07-01 19:10:31 -0700797 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700798 } else if (isPointerEvent(mMsg.body.motion.source) &&
799 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
800 // No need to process events that we are going to cancel anyways
801 const size_t count = batch.samples.size();
802 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500803 const InputMessage& msg = batch.samples[i];
804 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700805 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500806 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
807 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700808 } else {
809 // We cannot append to the batch in progress, so we need to consume
810 // the previous batch right now and defer the new message until later.
811 mMsgDeferred = true;
812 status_t result = consumeSamples(factory, batch, batch.samples.size(),
813 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500814 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700815 if (result) {
816 return result;
817 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800818 if (DEBUG_TRANSPORT_ACTIONS) {
819 ALOGD("channel '%s' consumer ~ consumed batch event and "
820 "deferred current event, seq=%u",
821 mChannel->getName().c_str(), *outSeq);
822 }
Jeff Brown5912f952013-07-01 19:10:31 -0700823 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700824 }
Jeff Brown5912f952013-07-01 19:10:31 -0700825 }
Jeff Brown5912f952013-07-01 19:10:31 -0700826
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800827 // Start a new batch if needed.
828 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
829 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500830 Batch batch;
831 batch.samples.push_back(mMsg);
832 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800833 if (DEBUG_TRANSPORT_ACTIONS) {
834 ALOGD("channel '%s' consumer ~ started batch event",
835 mChannel->getName().c_str());
836 }
837 break;
838 }
Jeff Brown5912f952013-07-01 19:10:31 -0700839
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800840 MotionEvent* motionEvent = factory->createMotionEvent();
841 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700842
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800843 updateTouchState(mMsg);
844 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500845 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800846 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800847
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800848 if (DEBUG_TRANSPORT_ACTIONS) {
849 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
850 mChannel->getName().c_str(), *outSeq);
851 }
852 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700853 }
Jeff Brown5912f952013-07-01 19:10:31 -0700854
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000855 case InputMessage::Type::FINISHED:
856 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000857 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
858 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800859 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800860 break;
861 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800862
863 case InputMessage::Type::FOCUS: {
864 FocusEvent* focusEvent = factory->createFocusEvent();
865 if (!focusEvent) return NO_MEMORY;
866
867 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500868 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800869 *outEvent = focusEvent;
870 break;
871 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800872
873 case InputMessage::Type::CAPTURE: {
874 CaptureEvent* captureEvent = factory->createCaptureEvent();
875 if (!captureEvent) return NO_MEMORY;
876
877 initializeCaptureEvent(captureEvent, &mMsg);
878 *outSeq = mMsg.header.seq;
879 *outEvent = captureEvent;
880 break;
881 }
arthurhung7632c332020-12-30 16:58:01 +0800882
883 case InputMessage::Type::DRAG: {
884 DragEvent* dragEvent = factory->createDragEvent();
885 if (!dragEvent) return NO_MEMORY;
886
887 initializeDragEvent(dragEvent, &mMsg);
888 *outSeq = mMsg.header.seq;
889 *outEvent = dragEvent;
890 break;
891 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700892
893 case InputMessage::Type::TOUCH_MODE: {
894 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
895 if (!touchModeEvent) return NO_MEMORY;
896
897 initializeTouchModeEvent(touchModeEvent, &mMsg);
898 *outSeq = mMsg.header.seq;
899 *outEvent = touchModeEvent;
900 break;
901 }
Jeff Brown5912f952013-07-01 19:10:31 -0700902 }
903 }
904 return OK;
905}
906
907status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800908 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700909 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700910 for (size_t i = mBatches.size(); i > 0; ) {
911 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500912 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700913 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800914 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500915 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700916 return result;
917 }
918
Michael Wright32232172013-10-21 12:05:22 -0700919 nsecs_t sampleTime = frameTime;
920 if (mResampleTouch) {
921 sampleTime -= RESAMPLE_LATENCY;
922 }
Jeff Brown5912f952013-07-01 19:10:31 -0700923 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
924 if (split < 0) {
925 continue;
926 }
927
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800928 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700929 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500930 if (batch.samples.empty()) {
931 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700932 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700933 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500934 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700935 }
Michael Wright32232172013-10-21 12:05:22 -0700936 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700937 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
938 }
939 return result;
940 }
941
942 return WOULD_BLOCK;
943}
944
945status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800946 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700947 MotionEvent* motionEvent = factory->createMotionEvent();
948 if (! motionEvent) return NO_MEMORY;
949
950 uint32_t chain = 0;
951 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500952 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100953 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700954 if (i) {
955 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500956 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700957 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500958 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700959 addSample(motionEvent, &msg);
960 } else {
961 initializeMotionEvent(motionEvent, &msg);
962 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500963 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700964 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500965 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700966
967 *outSeq = chain;
968 *outEvent = motionEvent;
969 return OK;
970}
971
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100972void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800973 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700974 return;
975 }
976
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100977 int32_t deviceId = msg.body.motion.deviceId;
978 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700979
980 // Update the touch state history to incorporate the new input message.
981 // If the message is in the past relative to the most recently produced resampled
982 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100983 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700984 case AMOTION_EVENT_ACTION_DOWN: {
985 ssize_t index = findTouchState(deviceId, source);
986 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500987 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700988 index = mTouchStates.size() - 1;
989 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500990 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700991 touchState.initialize(deviceId, source);
992 touchState.addHistory(msg);
993 break;
994 }
995
996 case AMOTION_EVENT_ACTION_MOVE: {
997 ssize_t index = findTouchState(deviceId, source);
998 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500999 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001000 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001001 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001002 }
1003 break;
1004 }
1005
1006 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1007 ssize_t index = findTouchState(deviceId, source);
1008 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001009 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001010 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001011 rewriteMessage(touchState, msg);
1012 }
1013 break;
1014 }
1015
1016 case AMOTION_EVENT_ACTION_POINTER_UP: {
1017 ssize_t index = findTouchState(deviceId, source);
1018 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001019 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001020 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001021 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001022 }
1023 break;
1024 }
1025
1026 case AMOTION_EVENT_ACTION_SCROLL: {
1027 ssize_t index = findTouchState(deviceId, source);
1028 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001029 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001030 rewriteMessage(touchState, msg);
1031 }
1032 break;
1033 }
1034
1035 case AMOTION_EVENT_ACTION_UP:
1036 case AMOTION_EVENT_ACTION_CANCEL: {
1037 ssize_t index = findTouchState(deviceId, source);
1038 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001039 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001040 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001041 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001042 }
1043 break;
1044 }
1045 }
1046}
1047
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001048/**
1049 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1050 *
1051 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1052 * is in the past relative to msg and the past two events do not contain identical coordinates),
1053 * then invalidate the lastResample data for that pointer.
1054 * If the two past events have identical coordinates, then lastResample data for that pointer will
1055 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1056 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1057 * not equal to x0 is received.
1058 */
1059void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001060 nsecs_t eventTime = msg.body.motion.eventTime;
1061 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1062 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001063 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001064 if (eventTime < state.lastResample.eventTime ||
1065 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001066 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1067 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001068#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001069 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1070 resampleCoords.getX(), resampleCoords.getY(),
1071 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001072#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001073 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1074 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
1075 } else {
1076 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001077 }
Jeff Brown5912f952013-07-01 19:10:31 -07001078 }
1079 }
1080}
1081
1082void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1083 const InputMessage* next) {
1084 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001085 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001086 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1087 return;
1088 }
1089
1090 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1091 if (index < 0) {
1092#if DEBUG_RESAMPLING
1093 ALOGD("Not resampled, no touch state for device.");
1094#endif
1095 return;
1096 }
1097
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001098 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001099 if (touchState.historySize < 1) {
1100#if DEBUG_RESAMPLING
1101 ALOGD("Not resampled, no history for device.");
1102#endif
1103 return;
1104 }
1105
1106 // Ensure that the current sample has all of the pointers that need to be reported.
1107 const History* current = touchState.getHistory(0);
1108 size_t pointerCount = event->getPointerCount();
1109 for (size_t i = 0; i < pointerCount; i++) {
1110 uint32_t id = event->getPointerId(i);
1111 if (!current->idBits.hasBit(id)) {
1112#if DEBUG_RESAMPLING
1113 ALOGD("Not resampled, missing id %d", id);
1114#endif
1115 return;
1116 }
1117 }
1118
1119 // Find the data to use for resampling.
1120 const History* other;
1121 History future;
1122 float alpha;
1123 if (next) {
1124 // Interpolate between current sample and future sample.
1125 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001126 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001127 other = &future;
1128 nsecs_t delta = future.eventTime - current->eventTime;
1129 if (delta < RESAMPLE_MIN_DELTA) {
1130#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001131 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001132#endif
1133 return;
1134 }
1135 alpha = float(sampleTime - current->eventTime) / delta;
1136 } else if (touchState.historySize >= 2) {
1137 // Extrapolate future sample using current sample and past sample.
1138 // So other->eventTime <= current->eventTime <= sampleTime.
1139 other = touchState.getHistory(1);
1140 nsecs_t delta = current->eventTime - other->eventTime;
1141 if (delta < RESAMPLE_MIN_DELTA) {
1142#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001143 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001144#endif
1145 return;
1146 } else if (delta > RESAMPLE_MAX_DELTA) {
1147#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001148 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001149#endif
1150 return;
1151 }
1152 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1153 if (sampleTime > maxPredict) {
1154#if DEBUG_RESAMPLING
1155 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001156 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001157 sampleTime - current->eventTime, maxPredict - current->eventTime);
1158#endif
1159 sampleTime = maxPredict;
1160 }
1161 alpha = float(current->eventTime - sampleTime) / delta;
1162 } else {
1163#if DEBUG_RESAMPLING
1164 ALOGD("Not resampled, insufficient data.");
1165#endif
1166 return;
1167 }
1168
1169 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001170 History oldLastResample;
1171 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001172 touchState.lastResample.eventTime = sampleTime;
1173 touchState.lastResample.idBits.clear();
1174 for (size_t i = 0; i < pointerCount; i++) {
1175 uint32_t id = event->getPointerId(i);
1176 touchState.lastResample.idToIndex[id] = i;
1177 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001178 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1179 // We maintain the previously resampled value for this pointer (stored in
1180 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1181 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1182
1183 // We know here that the coordinates for the pointer haven't changed because we
1184 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1185 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1186 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1187 continue;
1188 }
1189
Jeff Brown5912f952013-07-01 19:10:31 -07001190 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1191 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001192 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001193 if (other->idBits.hasBit(id)
1194 && shouldResampleTool(event->getToolType(i))) {
1195 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001196 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1197 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1198 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1199 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1200#if DEBUG_RESAMPLING
1201 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1202 "other (%0.3f, %0.3f), alpha %0.3f",
1203 id, resampledCoords.getX(), resampledCoords.getY(),
1204 currentCoords.getX(), currentCoords.getY(),
1205 otherCoords.getX(), otherCoords.getY(),
1206 alpha);
1207#endif
1208 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001209#if DEBUG_RESAMPLING
1210 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1211 id, resampledCoords.getX(), resampledCoords.getY(),
1212 currentCoords.getX(), currentCoords.getY());
1213#endif
1214 }
1215 }
1216
1217 event->addSample(sampleTime, touchState.lastResample.pointers);
1218}
1219
1220bool InputConsumer::shouldResampleTool(int32_t toolType) {
1221 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1222 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1223}
1224
1225status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001226 if (DEBUG_TRANSPORT_ACTIONS) {
1227 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1228 mChannel->getName().c_str(), seq, toString(handled));
1229 }
Jeff Brown5912f952013-07-01 19:10:31 -07001230
1231 if (!seq) {
1232 ALOGE("Attempted to send a finished signal with sequence number 0.");
1233 return BAD_VALUE;
1234 }
1235
1236 // Send finished signals for the batch sequence chain first.
1237 size_t seqChainCount = mSeqChains.size();
1238 if (seqChainCount) {
1239 uint32_t currentSeq = seq;
1240 uint32_t chainSeqs[seqChainCount];
1241 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001242 for (size_t i = seqChainCount; i > 0; ) {
1243 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001244 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001245 if (seqChain.seq == currentSeq) {
1246 currentSeq = seqChain.chain;
1247 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001248 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001249 }
1250 }
1251 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001252 while (!status && chainIndex > 0) {
1253 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001254 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1255 }
1256 if (status) {
1257 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001258 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001259 SeqChain seqChain;
1260 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1261 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001262 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001263 if (!chainIndex) break;
1264 chainIndex--;
1265 }
Jeff Brown5912f952013-07-01 19:10:31 -07001266 return status;
1267 }
1268 }
1269
1270 // Send finished signal for the last message in the batch.
1271 return sendUnchainedFinishedSignal(seq, handled);
1272}
1273
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001274status_t InputConsumer::sendTimeline(int32_t inputEventId,
1275 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
1276 if (DEBUG_TRANSPORT_ACTIONS) {
1277 ALOGD("channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1278 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1279 mChannel->getName().c_str(), inputEventId,
1280 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1281 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
1282 }
1283
1284 InputMessage msg;
1285 msg.header.type = InputMessage::Type::TIMELINE;
1286 msg.header.seq = 0;
1287 msg.body.timeline.eventId = inputEventId;
1288 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1289 return mChannel->sendMessage(&msg);
1290}
1291
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001292nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1293 auto it = mConsumeTimes.find(seq);
1294 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1295 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1296 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1297 seq);
1298 return it->second;
1299}
1300
1301void InputConsumer::popConsumeTime(uint32_t seq) {
1302 mConsumeTimes.erase(seq);
1303}
1304
Jeff Brown5912f952013-07-01 19:10:31 -07001305status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1306 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001307 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001308 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001309 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001310 msg.body.finished.consumeTime = getConsumeTime(seq);
1311 status_t result = mChannel->sendMessage(&msg);
1312 if (result == OK) {
1313 // Remove the consume time if the socket write succeeded. We will not need to ack this
1314 // message anymore. If the socket write did not succeed, we will try again and will still
1315 // need consume time.
1316 popConsumeTime(seq);
1317 }
1318 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001319}
1320
1321bool InputConsumer::hasDeferredEvent() const {
1322 return mMsgDeferred;
1323}
1324
1325bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001326 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001327}
1328
Arthur Hungc7812be2020-02-27 22:40:27 +08001329int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001330 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001331 return AINPUT_SOURCE_CLASS_NONE;
1332 }
1333
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001334 const Batch& batch = mBatches[0];
1335 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001336 return head.body.motion.source;
1337}
1338
Jeff Brown5912f952013-07-01 19:10:31 -07001339ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1340 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001341 const Batch& batch = mBatches[i];
1342 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001343 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1344 return i;
1345 }
1346 }
1347 return -1;
1348}
1349
1350ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1351 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001352 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001353 if (touchState.deviceId == deviceId && touchState.source == source) {
1354 return i;
1355 }
1356 }
1357 return -1;
1358}
1359
1360void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001361 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001362 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1363 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1364 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1365 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001366}
1367
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001368void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001369 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus,
1370 msg->body.focus.inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001371}
1372
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001373void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001374 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001375}
1376
arthurhung7632c332020-12-30 16:58:01 +08001377void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1378 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1379 msg->body.drag.isExiting);
1380}
1381
Jeff Brown5912f952013-07-01 19:10:31 -07001382void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001383 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001384 PointerProperties pointerProperties[pointerCount];
1385 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001386 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001387 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1388 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1389 }
1390
chaviw9eaa22c2020-07-01 16:21:27 -07001391 ui::Transform transform;
1392 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1393 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001394 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1395 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1396 msg->body.motion.actionButton, msg->body.motion.flags,
1397 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001398 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1399 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1400 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07001401 msg->body.motion.displayOrientation, msg->body.motion.displayWidth,
1402 msg->body.motion.displayHeight, msg->body.motion.downTime,
1403 msg->body.motion.eventTime, pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001404}
1405
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001406void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1407 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1408}
1409
Jeff Brown5912f952013-07-01 19:10:31 -07001410void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001411 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001412 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001413 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001414 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1415 }
1416
1417 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1418 event->addSample(msg->body.motion.eventTime, pointerCoords);
1419}
1420
1421bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001422 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001423 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001424 if (head.body.motion.pointerCount != pointerCount
1425 || head.body.motion.action != msg->body.motion.action) {
1426 return false;
1427 }
1428 for (size_t i = 0; i < pointerCount; i++) {
1429 if (head.body.motion.pointers[i].properties
1430 != msg->body.motion.pointers[i].properties) {
1431 return false;
1432 }
1433 }
1434 return true;
1435}
1436
1437ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1438 size_t numSamples = batch.samples.size();
1439 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001440 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001441 index += 1;
1442 }
1443 return ssize_t(index) - 1;
1444}
1445
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001446std::string InputConsumer::dump() const {
1447 std::string out;
1448 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1449 out = out + "mChannel = " + mChannel->getName() + "\n";
1450 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1451 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001452 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001453 }
1454 out += "Batches:\n";
1455 for (const Batch& batch : mBatches) {
1456 out += " Batch:\n";
1457 for (const InputMessage& msg : batch.samples) {
1458 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001459 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001460 switch (msg.header.type) {
1461 case InputMessage::Type::KEY: {
1462 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1463 KeyEvent::actionToString(
1464 msg.body.key.action),
1465 msg.body.key.keyCode);
1466 break;
1467 }
1468 case InputMessage::Type::MOTION: {
1469 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1470 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1471 const float x = msg.body.motion.pointers[i].coords.getX();
1472 const float y = msg.body.motion.pointers[i].coords.getY();
1473 out += android::base::StringPrintf("\n Pointer %" PRIu32
1474 " : x=%.1f y=%.1f",
1475 i, x, y);
1476 }
1477 break;
1478 }
1479 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001480 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1481 toString(msg.body.finished.handled),
1482 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001483 break;
1484 }
1485 case InputMessage::Type::FOCUS: {
1486 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1487 toString(msg.body.focus.hasFocus),
1488 toString(msg.body.focus.inTouchMode));
1489 break;
1490 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001491 case InputMessage::Type::CAPTURE: {
1492 out += android::base::StringPrintf("hasCapture=%s",
1493 toString(msg.body.capture
1494 .pointerCaptureEnabled));
1495 break;
1496 }
arthurhung7632c332020-12-30 16:58:01 +08001497 case InputMessage::Type::DRAG: {
1498 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1499 msg.body.drag.x, msg.body.drag.y,
1500 toString(msg.body.drag.isExiting));
1501 break;
1502 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001503 case InputMessage::Type::TIMELINE: {
1504 const nsecs_t gpuCompletedTime =
1505 msg.body.timeline
1506 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1507 const nsecs_t presentTime =
1508 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1509 out += android::base::StringPrintf("inputEventId=%" PRId32
1510 ", gpuCompletedTime=%" PRId64
1511 ", presentTime=%" PRId64,
1512 msg.body.timeline.eventId, gpuCompletedTime,
1513 presentTime);
1514 break;
1515 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001516 case InputMessage::Type::TOUCH_MODE: {
1517 out += android::base::StringPrintf("isInTouchMode=%s",
1518 toString(msg.body.touchMode.isInTouchMode));
1519 break;
1520 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001521 }
1522 out += "\n";
1523 }
1524 }
1525 if (mBatches.empty()) {
1526 out += " <empty>\n";
1527 }
1528 out += "mSeqChains:\n";
1529 for (const SeqChain& chain : mSeqChains) {
1530 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1531 chain.chain);
1532 }
1533 if (mSeqChains.empty()) {
1534 out += " <empty>\n";
1535 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001536 out += "mConsumeTimes:\n";
1537 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1538 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1539 consumeTime);
1540 }
1541 if (mConsumeTimes.empty()) {
1542 out += " <empty>\n";
1543 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001544 return out;
1545}
1546
Jeff Brown5912f952013-07-01 19:10:31 -07001547} // namespace android